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 52
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
| fuzzy_diff
stringlengths 16
3.18k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0d59cf159d9c5f6c64c49cc7ef3cef8feaf5452d
|
templatetags/coltrane.py
|
templatetags/coltrane.py
|
from django.db.models import get_model
from django import template
from django.contrib.comments.models import Comment, FreeComment
from coltrane.models import Entry, Link
register = template.Library()
class LatestFeaturedNode(template.Node):
def __init__(self, varname):
self.varname = varname
def render(self, context):
context[self.varname] = Entry.live.latest_featured()
return ''
def do_latest_featured(parser, token):
"""
Retrieves the latest featured Entry and stores it in a specified
context variable.
Syntax::
{% get_latest_featured_entry as [varname] %}
Example::
{% get_latest_featured_entry as latest_featured_entry %}
"""
bits = token.contents.split()
if len(bits) != 3:
raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
if bits[1] != 'as':
raise template.TemplateSyntaxError("first argument to '%s' tag must be 'as'" % bits[0])
return LatestFeaturedNode(bits[2])
register.tag('get_latest_featured_entry', do_latest_featured)
|
from django.db.models import get_model
from django import template
from django.contrib.comments.models import Comment, FreeComment
from template_utils.templatetags.generic_content import GenericContentNode
from coltrane.models import Entry, Link
register = template.Library()
class LatestFeaturedNode(GenericContentNode):
def _get_query_set(self):
if self._queryset is not None:
self._queryset = self._queryset.filter(featured__exact=True)
def do_featured_entries(parser, token):
"""
Retrieves the latest ``num`` featured entries and stores them in a
specified context variable.
Syntax::
{% get_featured_entries [num] as [varname] %}
Example::
{% get_featured_entries 5 as featured_entries %}
"""
bits = token.contents.split()
if len(bits) != 4:
raise template.TemplateSyntaxError("'%s' tag takes three arguments" % bits[0])
if bits[2] != 'as':
raise template.TemplateSyntaxError("second argument to '%s' tag must be 'as'" % bits[0])
return LatestFeaturedNode('coltrane.entry', bits[1], bits[3])
def do_featured_entry(parser, token):
"""
Retrieves the latest featured Entry and stores it in a specified
context variable.
Syntax::
{% get_featured_entry as [varname] %}
Example::
{% get_featured_entry as featured_entry %}
"""
bits = token.contents.split()
if len(bits) != 3:
raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
if bits[1] != 'as':
raise template.TemplateSyntaxError("first argument to '%s' tag must be 'as'" % bits[0])
return LatestFeaturedNode('coltrane.entry', 1, bits[2])
register.tag('get_featured_entries', do_featured_entries)
register.tag('get_featured_entry', do_featured_entry)
|
Refactor LatestFeaturedNode to use GenericContentNode and accept a configurable number of entries to fetch
|
Refactor LatestFeaturedNode to use GenericContentNode and accept a configurable number of entries to fetch
git-svn-id: 9770886a22906f523ce26b0ad22db0fc46e41232@54 5f8205a5-902a-0410-8b63-8f478ce83d95
|
Python
|
bsd-3-clause
|
clones/django-coltrane,mafix/coltrane-blog
|
from django.db.models import get_model
from django import template
from django.contrib.comments.models import Comment, FreeComment
+ from template_utils.templatetags.generic_content import GenericContentNode
+
from coltrane.models import Entry, Link
register = template.Library()
- class LatestFeaturedNode(template.Node):
+ class LatestFeaturedNode(GenericContentNode):
+ def _get_query_set(self):
+ if self._queryset is not None:
+ self._queryset = self._queryset.filter(featured__exact=True)
- def __init__(self, varname):
- self.varname = varname
-
- def render(self, context):
- context[self.varname] = Entry.live.latest_featured()
- return ''
+ def do_featured_entries(parser, token):
+ """
+ Retrieves the latest ``num`` featured entries and stores them in a
+ specified context variable.
+
+ Syntax::
+
+ {% get_featured_entries [num] as [varname] %}
+
+ Example::
+
+ {% get_featured_entries 5 as featured_entries %}
+
+ """
+ bits = token.contents.split()
+ if len(bits) != 4:
+ raise template.TemplateSyntaxError("'%s' tag takes three arguments" % bits[0])
+ if bits[2] != 'as':
+ raise template.TemplateSyntaxError("second argument to '%s' tag must be 'as'" % bits[0])
+ return LatestFeaturedNode('coltrane.entry', bits[1], bits[3])
+
- def do_latest_featured(parser, token):
+ def do_featured_entry(parser, token):
"""
Retrieves the latest featured Entry and stores it in a specified
context variable.
Syntax::
- {% get_latest_featured_entry as [varname] %}
+ {% get_featured_entry as [varname] %}
Example::
- {% get_latest_featured_entry as latest_featured_entry %}
+ {% get_featured_entry as featured_entry %}
"""
bits = token.contents.split()
if len(bits) != 3:
raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
if bits[1] != 'as':
raise template.TemplateSyntaxError("first argument to '%s' tag must be 'as'" % bits[0])
- return LatestFeaturedNode(bits[2])
+ return LatestFeaturedNode('coltrane.entry', 1, bits[2])
+ register.tag('get_featured_entries', do_featured_entries)
- register.tag('get_latest_featured_entry', do_latest_featured)
+ register.tag('get_featured_entry', do_featured_entry)
|
Refactor LatestFeaturedNode to use GenericContentNode and accept a configurable number of entries to fetch
|
## Code Before:
from django.db.models import get_model
from django import template
from django.contrib.comments.models import Comment, FreeComment
from coltrane.models import Entry, Link
register = template.Library()
class LatestFeaturedNode(template.Node):
def __init__(self, varname):
self.varname = varname
def render(self, context):
context[self.varname] = Entry.live.latest_featured()
return ''
def do_latest_featured(parser, token):
"""
Retrieves the latest featured Entry and stores it in a specified
context variable.
Syntax::
{% get_latest_featured_entry as [varname] %}
Example::
{% get_latest_featured_entry as latest_featured_entry %}
"""
bits = token.contents.split()
if len(bits) != 3:
raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
if bits[1] != 'as':
raise template.TemplateSyntaxError("first argument to '%s' tag must be 'as'" % bits[0])
return LatestFeaturedNode(bits[2])
register.tag('get_latest_featured_entry', do_latest_featured)
## Instruction:
Refactor LatestFeaturedNode to use GenericContentNode and accept a configurable number of entries to fetch
## Code After:
from django.db.models import get_model
from django import template
from django.contrib.comments.models import Comment, FreeComment
from template_utils.templatetags.generic_content import GenericContentNode
from coltrane.models import Entry, Link
register = template.Library()
class LatestFeaturedNode(GenericContentNode):
def _get_query_set(self):
if self._queryset is not None:
self._queryset = self._queryset.filter(featured__exact=True)
def do_featured_entries(parser, token):
"""
Retrieves the latest ``num`` featured entries and stores them in a
specified context variable.
Syntax::
{% get_featured_entries [num] as [varname] %}
Example::
{% get_featured_entries 5 as featured_entries %}
"""
bits = token.contents.split()
if len(bits) != 4:
raise template.TemplateSyntaxError("'%s' tag takes three arguments" % bits[0])
if bits[2] != 'as':
raise template.TemplateSyntaxError("second argument to '%s' tag must be 'as'" % bits[0])
return LatestFeaturedNode('coltrane.entry', bits[1], bits[3])
def do_featured_entry(parser, token):
"""
Retrieves the latest featured Entry and stores it in a specified
context variable.
Syntax::
{% get_featured_entry as [varname] %}
Example::
{% get_featured_entry as featured_entry %}
"""
bits = token.contents.split()
if len(bits) != 3:
raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
if bits[1] != 'as':
raise template.TemplateSyntaxError("first argument to '%s' tag must be 'as'" % bits[0])
return LatestFeaturedNode('coltrane.entry', 1, bits[2])
register.tag('get_featured_entries', do_featured_entries)
register.tag('get_featured_entry', do_featured_entry)
|
...
from django.contrib.comments.models import Comment, FreeComment
from template_utils.templatetags.generic_content import GenericContentNode
from coltrane.models import Entry, Link
...
class LatestFeaturedNode(GenericContentNode):
def _get_query_set(self):
if self._queryset is not None:
self._queryset = self._queryset.filter(featured__exact=True)
...
def do_featured_entries(parser, token):
"""
Retrieves the latest ``num`` featured entries and stores them in a
specified context variable.
Syntax::
{% get_featured_entries [num] as [varname] %}
Example::
{% get_featured_entries 5 as featured_entries %}
"""
bits = token.contents.split()
if len(bits) != 4:
raise template.TemplateSyntaxError("'%s' tag takes three arguments" % bits[0])
if bits[2] != 'as':
raise template.TemplateSyntaxError("second argument to '%s' tag must be 'as'" % bits[0])
return LatestFeaturedNode('coltrane.entry', bits[1], bits[3])
def do_featured_entry(parser, token):
"""
...
{% get_featured_entry as [varname] %}
...
{% get_featured_entry as featured_entry %}
...
raise template.TemplateSyntaxError("first argument to '%s' tag must be 'as'" % bits[0])
return LatestFeaturedNode('coltrane.entry', 1, bits[2])
register.tag('get_featured_entries', do_featured_entries)
register.tag('get_featured_entry', do_featured_entry)
...
|
ed09a3ded286cc4d5623c17e65b2d40ef55ccee7
|
valohai_yaml/parsing.py
|
valohai_yaml/parsing.py
|
from typing import IO, Union
from valohai_yaml.objs import Config
from .utils import read_yaml
def parse(yaml: Union[dict, list, bytes, str, IO], validate: bool = True) -> Config:
"""
Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:param validate: Whether to validate the data before attempting to parse it.
:return: Config object
"""
data = read_yaml(yaml)
if validate: # pragma: no branch
from .validation import validate as do_validate
do_validate(data, raise_exc=True)
return Config.parse(data)
|
from typing import IO, Union
from valohai_yaml.objs import Config
from .utils import read_yaml
def parse(yaml: Union[dict, list, bytes, str, IO], validate: bool = True) -> Config:
"""
Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:param validate: Whether to validate the data before attempting to parse it.
:return: Config object
"""
data = read_yaml(yaml)
if data is None: # empty file
return Config()
if validate: # pragma: no branch
from .validation import validate as do_validate
do_validate(data, raise_exc=True)
return Config.parse(data)
|
Handle empty YAML files in parse()
|
Handle empty YAML files in parse()
Refs valohai/valohai-cli#170
|
Python
|
mit
|
valohai/valohai-yaml
|
from typing import IO, Union
from valohai_yaml.objs import Config
from .utils import read_yaml
def parse(yaml: Union[dict, list, bytes, str, IO], validate: bool = True) -> Config:
"""
Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:param validate: Whether to validate the data before attempting to parse it.
:return: Config object
"""
data = read_yaml(yaml)
+ if data is None: # empty file
+ return Config()
if validate: # pragma: no branch
from .validation import validate as do_validate
do_validate(data, raise_exc=True)
return Config.parse(data)
|
Handle empty YAML files in parse()
|
## Code Before:
from typing import IO, Union
from valohai_yaml.objs import Config
from .utils import read_yaml
def parse(yaml: Union[dict, list, bytes, str, IO], validate: bool = True) -> Config:
"""
Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:param validate: Whether to validate the data before attempting to parse it.
:return: Config object
"""
data = read_yaml(yaml)
if validate: # pragma: no branch
from .validation import validate as do_validate
do_validate(data, raise_exc=True)
return Config.parse(data)
## Instruction:
Handle empty YAML files in parse()
## Code After:
from typing import IO, Union
from valohai_yaml.objs import Config
from .utils import read_yaml
def parse(yaml: Union[dict, list, bytes, str, IO], validate: bool = True) -> Config:
"""
Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:param validate: Whether to validate the data before attempting to parse it.
:return: Config object
"""
data = read_yaml(yaml)
if data is None: # empty file
return Config()
if validate: # pragma: no branch
from .validation import validate as do_validate
do_validate(data, raise_exc=True)
return Config.parse(data)
|
# ... existing code ...
data = read_yaml(yaml)
if data is None: # empty file
return Config()
if validate: # pragma: no branch
# ... rest of the code ...
|
df2d43e8ae84af605b845b3cbbb9c318f300e4e9
|
server.py
|
server.py
|
import subprocess
import sys
from flask import Flask, request
app = Flask(__name__)
SPASS=sys.argv[1] if len(sys.argv) > 1 else '/usr/local/bin/spass'
def call_spass(name, master):
p = subprocess.Popen([
SPASS,
'get',
name],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True)
try:
out, err = p.communicate(bytes('%s\n' % master, 'utf8'), timeout=5)
except subprocess.TimeoutExpired:
p.kill()
return 'Error: spass process timedout'
return out if p.returncode == 0 else err
@app.route('/getpwd', methods=['POST'])
def getpwd():
return call_spass(request.form['name'], request.form['master'])
@app.route('/')
def index():
return app.send_static_file('index.html')
if __name__ == '__main__':
app.run()
|
import logging
import subprocess
import sys
from flask import Flask, request
app = Flask(__name__)
SPASS=sys.argv[1] if len(sys.argv) > 1 else '/usr/local/bin/spass'
@app.before_first_request
def setup():
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
def call_spass(name, master):
p = subprocess.Popen([
SPASS,
'get',
name],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True)
try:
out, err = p.communicate(bytes('%s\n' % master, 'utf8'), timeout=5)
except subprocess.TimeoutExpired:
p.kill()
return 'Error: spass process timedout'
return (out if p.returncode == 0 else err), p.returncode
@app.route('/getpwd', methods=['POST'])
def getpwd():
val, code = call_spass(request.form['name'], request.form['master'])
app.logger.info('%s %s %d', request.remote_addr, request.form['name'], code)
return val
@app.route('/')
def index():
return app.send_static_file('index.html')
if __name__ == '__main__':
app.run()
|
Add logging for requested password and result
|
Add logging for requested password and result
|
Python
|
mit
|
iburinoc/spass-server,iburinoc/spass-server
|
+ import logging
import subprocess
import sys
from flask import Flask, request
app = Flask(__name__)
SPASS=sys.argv[1] if len(sys.argv) > 1 else '/usr/local/bin/spass'
+
+ @app.before_first_request
+ def setup():
+ app.logger.addHandler(logging.StreamHandler())
+ app.logger.setLevel(logging.INFO)
def call_spass(name, master):
p = subprocess.Popen([
SPASS,
'get',
name],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True)
try:
out, err = p.communicate(bytes('%s\n' % master, 'utf8'), timeout=5)
except subprocess.TimeoutExpired:
p.kill()
return 'Error: spass process timedout'
- return out if p.returncode == 0 else err
+ return (out if p.returncode == 0 else err), p.returncode
@app.route('/getpwd', methods=['POST'])
def getpwd():
- return call_spass(request.form['name'], request.form['master'])
+ val, code = call_spass(request.form['name'], request.form['master'])
+ app.logger.info('%s %s %d', request.remote_addr, request.form['name'], code)
+ return val
@app.route('/')
def index():
return app.send_static_file('index.html')
if __name__ == '__main__':
app.run()
|
Add logging for requested password and result
|
## Code Before:
import subprocess
import sys
from flask import Flask, request
app = Flask(__name__)
SPASS=sys.argv[1] if len(sys.argv) > 1 else '/usr/local/bin/spass'
def call_spass(name, master):
p = subprocess.Popen([
SPASS,
'get',
name],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True)
try:
out, err = p.communicate(bytes('%s\n' % master, 'utf8'), timeout=5)
except subprocess.TimeoutExpired:
p.kill()
return 'Error: spass process timedout'
return out if p.returncode == 0 else err
@app.route('/getpwd', methods=['POST'])
def getpwd():
return call_spass(request.form['name'], request.form['master'])
@app.route('/')
def index():
return app.send_static_file('index.html')
if __name__ == '__main__':
app.run()
## Instruction:
Add logging for requested password and result
## Code After:
import logging
import subprocess
import sys
from flask import Flask, request
app = Flask(__name__)
SPASS=sys.argv[1] if len(sys.argv) > 1 else '/usr/local/bin/spass'
@app.before_first_request
def setup():
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
def call_spass(name, master):
p = subprocess.Popen([
SPASS,
'get',
name],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True)
try:
out, err = p.communicate(bytes('%s\n' % master, 'utf8'), timeout=5)
except subprocess.TimeoutExpired:
p.kill()
return 'Error: spass process timedout'
return (out if p.returncode == 0 else err), p.returncode
@app.route('/getpwd', methods=['POST'])
def getpwd():
val, code = call_spass(request.form['name'], request.form['master'])
app.logger.info('%s %s %d', request.remote_addr, request.form['name'], code)
return val
@app.route('/')
def index():
return app.send_static_file('index.html')
if __name__ == '__main__':
app.run()
|
// ... existing code ...
import logging
import subprocess
// ... modified code ...
SPASS=sys.argv[1] if len(sys.argv) > 1 else '/usr/local/bin/spass'
@app.before_first_request
def setup():
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
...
return (out if p.returncode == 0 else err), p.returncode
...
def getpwd():
val, code = call_spass(request.form['name'], request.form['master'])
app.logger.info('%s %s %d', request.remote_addr, request.form['name'], code)
return val
// ... rest of the code ...
|
fd2c03b2e6f48dac071b813b20cc2f70a2658f24
|
tests/test_path_paths.py
|
tests/test_path_paths.py
|
import nose
from nose.tools import raises
import dpath.path
import dpath.exceptions
import dpath.options
@raises(dpath.exceptions.InvalidKeyName)
def test_path_paths_invalid_keyname():
tdict = {
"I/contain/the/separator": 0
}
for x in dpath.path.paths(tdict):
pass
@raises(dpath.exceptions.InvalidKeyName)
def test_path_paths_empty_key_disallowed():
tdict = {
"Empty": {
"": {
"Key": ""
}
}
}
for x in dpath.path.paths(tdict):
pass
def test_path_paths_empty_key_allowed():
tdict = {
"Empty": {
"": {
"Key": ""
}
}
}
parts=[]
dpath.options.ALLOW_EMPTY_STRING_KEYS=True
for x in dpath.path.paths(tdict, dirs=False, leaves=True):
path = x
for x in path[:-1]:
parts.append(x[0])
dpath.options.ALLOW_EMPTY_STRING_KEYS=False
print "/".join(parts)
assert("/".join(parts) == "Empty//Key")
def test_path_paths_int_keys():
dpath.path.validate([
['I', dict],
['am', dict],
['path', dict],
[0, dict],
['of', dict],
[2, int]
])
|
import nose
from nose.tools import raises
import dpath.path
import dpath.exceptions
import dpath.options
@raises(dpath.exceptions.InvalidKeyName)
def test_path_paths_invalid_keyname():
tdict = {
"I/contain/the/separator": 0
}
for x in dpath.path.paths(tdict):
pass
@raises(dpath.exceptions.InvalidKeyName)
def test_path_paths_empty_key_disallowed():
tdict = {
"Empty": {
"": {
"Key": ""
}
}
}
for x in dpath.path.paths(tdict):
pass
def test_path_paths_empty_key_allowed():
tdict = {
"Empty": {
"": {
"Key": ""
}
}
}
parts=[]
dpath.options.ALLOW_EMPTY_STRING_KEYS=True
for x in dpath.path.paths(tdict, dirs=False, leaves=True):
path = x
for x in path[:-1]:
parts.append(x[0])
dpath.options.ALLOW_EMPTY_STRING_KEYS=False
assert("/".join(parts) == "Empty//Key")
def test_path_paths_int_keys():
dpath.path.validate([
['I', dict],
['am', dict],
['path', dict],
[0, dict],
['of', dict],
[2, int]
])
|
Print statement was breaking python 3 builds
|
Print statement was breaking python 3 builds
|
Python
|
mit
|
akesterson/dpath-python,calebcase/dpath-python,benthomasson/dpath-python,lexhung/dpath-python,pombredanne/dpath-python
|
import nose
from nose.tools import raises
import dpath.path
import dpath.exceptions
import dpath.options
@raises(dpath.exceptions.InvalidKeyName)
def test_path_paths_invalid_keyname():
tdict = {
"I/contain/the/separator": 0
}
for x in dpath.path.paths(tdict):
pass
@raises(dpath.exceptions.InvalidKeyName)
def test_path_paths_empty_key_disallowed():
tdict = {
"Empty": {
"": {
"Key": ""
}
}
}
for x in dpath.path.paths(tdict):
pass
def test_path_paths_empty_key_allowed():
tdict = {
"Empty": {
"": {
"Key": ""
}
}
}
parts=[]
dpath.options.ALLOW_EMPTY_STRING_KEYS=True
for x in dpath.path.paths(tdict, dirs=False, leaves=True):
path = x
for x in path[:-1]:
parts.append(x[0])
dpath.options.ALLOW_EMPTY_STRING_KEYS=False
- print "/".join(parts)
assert("/".join(parts) == "Empty//Key")
def test_path_paths_int_keys():
dpath.path.validate([
['I', dict],
['am', dict],
['path', dict],
[0, dict],
['of', dict],
[2, int]
])
|
Print statement was breaking python 3 builds
|
## Code Before:
import nose
from nose.tools import raises
import dpath.path
import dpath.exceptions
import dpath.options
@raises(dpath.exceptions.InvalidKeyName)
def test_path_paths_invalid_keyname():
tdict = {
"I/contain/the/separator": 0
}
for x in dpath.path.paths(tdict):
pass
@raises(dpath.exceptions.InvalidKeyName)
def test_path_paths_empty_key_disallowed():
tdict = {
"Empty": {
"": {
"Key": ""
}
}
}
for x in dpath.path.paths(tdict):
pass
def test_path_paths_empty_key_allowed():
tdict = {
"Empty": {
"": {
"Key": ""
}
}
}
parts=[]
dpath.options.ALLOW_EMPTY_STRING_KEYS=True
for x in dpath.path.paths(tdict, dirs=False, leaves=True):
path = x
for x in path[:-1]:
parts.append(x[0])
dpath.options.ALLOW_EMPTY_STRING_KEYS=False
print "/".join(parts)
assert("/".join(parts) == "Empty//Key")
def test_path_paths_int_keys():
dpath.path.validate([
['I', dict],
['am', dict],
['path', dict],
[0, dict],
['of', dict],
[2, int]
])
## Instruction:
Print statement was breaking python 3 builds
## Code After:
import nose
from nose.tools import raises
import dpath.path
import dpath.exceptions
import dpath.options
@raises(dpath.exceptions.InvalidKeyName)
def test_path_paths_invalid_keyname():
tdict = {
"I/contain/the/separator": 0
}
for x in dpath.path.paths(tdict):
pass
@raises(dpath.exceptions.InvalidKeyName)
def test_path_paths_empty_key_disallowed():
tdict = {
"Empty": {
"": {
"Key": ""
}
}
}
for x in dpath.path.paths(tdict):
pass
def test_path_paths_empty_key_allowed():
tdict = {
"Empty": {
"": {
"Key": ""
}
}
}
parts=[]
dpath.options.ALLOW_EMPTY_STRING_KEYS=True
for x in dpath.path.paths(tdict, dirs=False, leaves=True):
path = x
for x in path[:-1]:
parts.append(x[0])
dpath.options.ALLOW_EMPTY_STRING_KEYS=False
assert("/".join(parts) == "Empty//Key")
def test_path_paths_int_keys():
dpath.path.validate([
['I', dict],
['am', dict],
['path', dict],
[0, dict],
['of', dict],
[2, int]
])
|
...
dpath.options.ALLOW_EMPTY_STRING_KEYS=False
assert("/".join(parts) == "Empty//Key")
...
|
b2657fd84c0d8fd4e1188a649bb2595651b83adb
|
kazoo/handlers/util.py
|
kazoo/handlers/util.py
|
try:
from gevent import monkey
[start_new_thread] = monkey.get_original('thread', ['start_new_thread'])
except ImportError:
from thread import start_new_thread
def thread(func):
"""Thread decorator
Takes a function and spawns it as a daemon thread using the
real OS thread regardless of monkey patching.
"""
start_new_thread(func, ())
|
from __future__ import absolute_import
try:
from gevent._threading import start_new_thread
except ImportError:
from thread import start_new_thread
def thread(func):
"""Thread decorator
Takes a function and spawns it as a daemon thread using the
real OS thread regardless of monkey patching.
"""
start_new_thread(func, ())
|
Make sure we use proper gevent with absolute import, pull the start_new_thread directly out.
|
Make sure we use proper gevent with absolute import, pull the start_new_thread directly out.
|
Python
|
apache-2.0
|
harlowja/kazoo,pombredanne/kazoo,rockerbox/kazoo,AlexanderplUs/kazoo,harlowja/kazoo,pombredanne/kazoo,rgs1/kazoo,Asana/kazoo,jacksontj/kazoo,kormat/kazoo,rackerlabs/kazoo,bsanders/kazoo,tempbottle/kazoo,python-zk/kazoo,rockerbox/kazoo,jacksontj/kazoo,rackerlabs/kazoo,python-zk/kazoo,rgs1/kazoo,tempbottle/kazoo,AlexanderplUs/kazoo,max0d41/kazoo,kormat/kazoo,max0d41/kazoo,bsanders/kazoo
|
+ from __future__ import absolute_import
+
try:
+ from gevent._threading import start_new_thread
- from gevent import monkey
- [start_new_thread] = monkey.get_original('thread', ['start_new_thread'])
except ImportError:
from thread import start_new_thread
def thread(func):
"""Thread decorator
Takes a function and spawns it as a daemon thread using the
real OS thread regardless of monkey patching.
"""
start_new_thread(func, ())
|
Make sure we use proper gevent with absolute import, pull the start_new_thread directly out.
|
## Code Before:
try:
from gevent import monkey
[start_new_thread] = monkey.get_original('thread', ['start_new_thread'])
except ImportError:
from thread import start_new_thread
def thread(func):
"""Thread decorator
Takes a function and spawns it as a daemon thread using the
real OS thread regardless of monkey patching.
"""
start_new_thread(func, ())
## Instruction:
Make sure we use proper gevent with absolute import, pull the start_new_thread directly out.
## Code After:
from __future__ import absolute_import
try:
from gevent._threading import start_new_thread
except ImportError:
from thread import start_new_thread
def thread(func):
"""Thread decorator
Takes a function and spawns it as a daemon thread using the
real OS thread regardless of monkey patching.
"""
start_new_thread(func, ())
|
...
from __future__ import absolute_import
try:
from gevent._threading import start_new_thread
except ImportError:
...
|
dfdb824eb1327a270e1c167e2ed5e161026858ea
|
antxetamedia/multimedia/handlers.py
|
antxetamedia/multimedia/handlers.py
|
from boto.s3.connection import S3Connection
from boto.s3.bucket import Bucket
from boto.exception import S3ResponseError, S3CreateError
from django.conf import settings
def upload(user, passwd, bucket, metadata, key, fd):
conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False)
while bucket.endswith('-'):
bucket = bucket[:-1]
try:
bucket = conn.get_bucket(bucket)
except S3ResponseError:
try:
bucket = conn.create_bucket(bucket, headers=metadata)
except (S3ResponseError, UnicodeDecodeError):
bucket = conn.create_bucket(bucket)
except S3CreateError as e:
if e.status == 409:
bucket = Bucket(conn, bucket)
key = bucket.new_key(key)
try:
key.set_contents_from_file(fd)
except S3ResponseError:
key.set_contents_from_file(fd)
return key.generate_url(0).split('?')[0]
|
from boto.s3.connection import S3Connection
from boto.s3.bucket import Bucket
from boto.exception import S3ResponseError, S3CreateError
from django.conf import settings
def upload(user, passwd, bucket, metadata, key, fd):
conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False)
while bucket.endswith('-'):
bucket = bucket[:-1]
try:
bucket = conn.get_bucket(bucket)
except S3ResponseError:
try:
bucket = conn.create_bucket(bucket, headers=metadata)
except S3CreateError as e:
if e.status == 409:
bucket = Bucket(conn, bucket)
key = bucket.new_key(key)
try:
key.set_contents_from_file(fd)
except S3ResponseError:
key.set_contents_from_file(fd)
return key.generate_url(0).split('?')[0]
|
Break lowdly on unicode errors
|
Break lowdly on unicode errors
|
Python
|
agpl-3.0
|
GISAElkartea/antxetamedia,GISAElkartea/antxetamedia,GISAElkartea/antxetamedia
|
from boto.s3.connection import S3Connection
from boto.s3.bucket import Bucket
from boto.exception import S3ResponseError, S3CreateError
from django.conf import settings
def upload(user, passwd, bucket, metadata, key, fd):
conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False)
while bucket.endswith('-'):
bucket = bucket[:-1]
try:
bucket = conn.get_bucket(bucket)
except S3ResponseError:
try:
bucket = conn.create_bucket(bucket, headers=metadata)
- except (S3ResponseError, UnicodeDecodeError):
- bucket = conn.create_bucket(bucket)
except S3CreateError as e:
if e.status == 409:
bucket = Bucket(conn, bucket)
key = bucket.new_key(key)
try:
key.set_contents_from_file(fd)
except S3ResponseError:
key.set_contents_from_file(fd)
return key.generate_url(0).split('?')[0]
|
Break lowdly on unicode errors
|
## Code Before:
from boto.s3.connection import S3Connection
from boto.s3.bucket import Bucket
from boto.exception import S3ResponseError, S3CreateError
from django.conf import settings
def upload(user, passwd, bucket, metadata, key, fd):
conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False)
while bucket.endswith('-'):
bucket = bucket[:-1]
try:
bucket = conn.get_bucket(bucket)
except S3ResponseError:
try:
bucket = conn.create_bucket(bucket, headers=metadata)
except (S3ResponseError, UnicodeDecodeError):
bucket = conn.create_bucket(bucket)
except S3CreateError as e:
if e.status == 409:
bucket = Bucket(conn, bucket)
key = bucket.new_key(key)
try:
key.set_contents_from_file(fd)
except S3ResponseError:
key.set_contents_from_file(fd)
return key.generate_url(0).split('?')[0]
## Instruction:
Break lowdly on unicode errors
## Code After:
from boto.s3.connection import S3Connection
from boto.s3.bucket import Bucket
from boto.exception import S3ResponseError, S3CreateError
from django.conf import settings
def upload(user, passwd, bucket, metadata, key, fd):
conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False)
while bucket.endswith('-'):
bucket = bucket[:-1]
try:
bucket = conn.get_bucket(bucket)
except S3ResponseError:
try:
bucket = conn.create_bucket(bucket, headers=metadata)
except S3CreateError as e:
if e.status == 409:
bucket = Bucket(conn, bucket)
key = bucket.new_key(key)
try:
key.set_contents_from_file(fd)
except S3ResponseError:
key.set_contents_from_file(fd)
return key.generate_url(0).split('?')[0]
|
...
bucket = conn.create_bucket(bucket, headers=metadata)
except S3CreateError as e:
...
|
29c437e15f7793886c80b71ca6764184caff2597
|
readthedocs/oauth/management/commands/load_project_remote_repo_relation.py
|
readthedocs/oauth/management/commands/load_project_remote_repo_relation.py
|
import json
from django.core.management.base import BaseCommand
from readthedocs.oauth.models import RemoteRepository
class Command(BaseCommand):
help = "Load Project and RemoteRepository Relationship from JSON file"
def add_arguments(self, parser):
# File path of the json file containing relationship data
parser.add_argument(
'--file',
required=True,
nargs=1,
type=str,
help='File path of the json file containing relationship data.',
)
def handle(self, *args, **options):
file = options.get('file')[0]
try:
# Load data from the json file
with open(file, 'r') as f:
data = json.load(f)
except Exception as e:
self.stdout.write(
self.style.ERROR(
f'Exception occurred while trying to load the file "{file}". '
f'Exception: {e}.'
)
)
return
for item in data:
try:
RemoteRepository.objects.filter(
remote_id=item['remote_id']
).update(project_id=item['project_id'])
except Exception as e:
self.stdout.write(
self.style.ERROR(
f"Exception occurred while trying to update {item['slug']}'s "
f"relationship with {item['html_url']}, "
f"username: {item['username']}, Exception: {e}."
)
)
|
import json
from django.core.management.base import BaseCommand
from readthedocs.oauth.models import RemoteRepository
class Command(BaseCommand):
help = "Load Project and RemoteRepository Relationship from JSON file"
def add_arguments(self, parser):
# File path of the json file containing relationship data
parser.add_argument(
'--file',
required=True,
nargs=1,
type=str,
help='File path of the json file containing relationship data.',
)
def handle(self, *args, **options):
file = options.get('file')[0]
try:
# Load data from the json file
with open(file, 'r') as f:
data = json.load(f)
except Exception as e:
self.stdout.write(
self.style.ERROR(
f'Exception occurred while trying to load the file "{file}". '
f'Exception: {e}.'
)
)
return
for item in data:
try:
update_count = RemoteRepository.objects.filter(
remote_id=item['remote_id']
).update(project_id=item['project_id'])
if update_count < 1:
self.stdout.write(
self.style.ERROR(
f"Could not update {item['slug']}'s "
f"relationship with {item['html_url']}, "
f"remote_id {item['remote_id']}, "
f"username: {item['username']}."
)
)
except Exception as e:
self.stdout.write(
self.style.ERROR(
f"Exception occurred while trying to update {item['slug']}'s "
f"relationship with {item['html_url']}, "
f"username: {item['username']}, Exception: {e}."
)
)
|
Check if the remote_repo was updated or not and log error
|
Check if the remote_repo was updated or not and log error
|
Python
|
mit
|
rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org
|
import json
from django.core.management.base import BaseCommand
from readthedocs.oauth.models import RemoteRepository
class Command(BaseCommand):
help = "Load Project and RemoteRepository Relationship from JSON file"
def add_arguments(self, parser):
# File path of the json file containing relationship data
parser.add_argument(
'--file',
required=True,
nargs=1,
type=str,
help='File path of the json file containing relationship data.',
)
def handle(self, *args, **options):
file = options.get('file')[0]
try:
# Load data from the json file
with open(file, 'r') as f:
data = json.load(f)
except Exception as e:
self.stdout.write(
self.style.ERROR(
f'Exception occurred while trying to load the file "{file}". '
f'Exception: {e}.'
)
)
return
for item in data:
try:
- RemoteRepository.objects.filter(
+ update_count = RemoteRepository.objects.filter(
remote_id=item['remote_id']
).update(project_id=item['project_id'])
+
+ if update_count < 1:
+ self.stdout.write(
+ self.style.ERROR(
+ f"Could not update {item['slug']}'s "
+ f"relationship with {item['html_url']}, "
+ f"remote_id {item['remote_id']}, "
+ f"username: {item['username']}."
+ )
+ )
except Exception as e:
self.stdout.write(
self.style.ERROR(
f"Exception occurred while trying to update {item['slug']}'s "
f"relationship with {item['html_url']}, "
f"username: {item['username']}, Exception: {e}."
)
)
|
Check if the remote_repo was updated or not and log error
|
## Code Before:
import json
from django.core.management.base import BaseCommand
from readthedocs.oauth.models import RemoteRepository
class Command(BaseCommand):
help = "Load Project and RemoteRepository Relationship from JSON file"
def add_arguments(self, parser):
# File path of the json file containing relationship data
parser.add_argument(
'--file',
required=True,
nargs=1,
type=str,
help='File path of the json file containing relationship data.',
)
def handle(self, *args, **options):
file = options.get('file')[0]
try:
# Load data from the json file
with open(file, 'r') as f:
data = json.load(f)
except Exception as e:
self.stdout.write(
self.style.ERROR(
f'Exception occurred while trying to load the file "{file}". '
f'Exception: {e}.'
)
)
return
for item in data:
try:
RemoteRepository.objects.filter(
remote_id=item['remote_id']
).update(project_id=item['project_id'])
except Exception as e:
self.stdout.write(
self.style.ERROR(
f"Exception occurred while trying to update {item['slug']}'s "
f"relationship with {item['html_url']}, "
f"username: {item['username']}, Exception: {e}."
)
)
## Instruction:
Check if the remote_repo was updated or not and log error
## Code After:
import json
from django.core.management.base import BaseCommand
from readthedocs.oauth.models import RemoteRepository
class Command(BaseCommand):
help = "Load Project and RemoteRepository Relationship from JSON file"
def add_arguments(self, parser):
# File path of the json file containing relationship data
parser.add_argument(
'--file',
required=True,
nargs=1,
type=str,
help='File path of the json file containing relationship data.',
)
def handle(self, *args, **options):
file = options.get('file')[0]
try:
# Load data from the json file
with open(file, 'r') as f:
data = json.load(f)
except Exception as e:
self.stdout.write(
self.style.ERROR(
f'Exception occurred while trying to load the file "{file}". '
f'Exception: {e}.'
)
)
return
for item in data:
try:
update_count = RemoteRepository.objects.filter(
remote_id=item['remote_id']
).update(project_id=item['project_id'])
if update_count < 1:
self.stdout.write(
self.style.ERROR(
f"Could not update {item['slug']}'s "
f"relationship with {item['html_url']}, "
f"remote_id {item['remote_id']}, "
f"username: {item['username']}."
)
)
except Exception as e:
self.stdout.write(
self.style.ERROR(
f"Exception occurred while trying to update {item['slug']}'s "
f"relationship with {item['html_url']}, "
f"username: {item['username']}, Exception: {e}."
)
)
|
# ... existing code ...
try:
update_count = RemoteRepository.objects.filter(
remote_id=item['remote_id']
# ... modified code ...
).update(project_id=item['project_id'])
if update_count < 1:
self.stdout.write(
self.style.ERROR(
f"Could not update {item['slug']}'s "
f"relationship with {item['html_url']}, "
f"remote_id {item['remote_id']}, "
f"username: {item['username']}."
)
)
# ... rest of the code ...
|
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()
|
...
else:
contract = Contract()
contract.publisher = source.publisher
...
|
fc123442727ae25f03c5aa8d2fa7bc6fae388ae2
|
thecure/levels/level1.py
|
thecure/levels/level1.py
|
from thecure.levels.base import Level
from thecure.sprites import Direction, InfectedHuman
class Level1(Level):
name = 'level1'
start_pos = (900, 6200)
def setup(self):
boy = InfectedHuman('boy1')
self.main_layer.add(boy)
boy.move_to(300, 160)
boy.set_direction(Direction.DOWN)
girl = InfectedHuman('girl1')
self.main_layer.add(girl)
girl.move_to(470, 200)
girl.set_direction(Direction.LEFT)
def draw_bg(self, surface):
surface.fill((237, 243, 255))
|
from thecure.levels.base import Level
from thecure.sprites import Direction, InfectedHuman
class Level1(Level):
name = 'level1'
start_pos = (900, 6200)
def setup(self):
boy = InfectedHuman('boy1')
self.main_layer.add(boy)
boy.move_to(1536, 5696)
boy.set_direction(Direction.DOWN)
girl = InfectedHuman('girl1')
self.main_layer.add(girl)
girl.move_to(1536, 5824)
girl.set_direction(Direction.UP)
def draw_bg(self, surface):
surface.fill((237, 243, 255))
|
Move the kids onto the field.
|
Move the kids onto the field.
|
Python
|
mit
|
chipx86/the-cure
|
from thecure.levels.base import Level
from thecure.sprites import Direction, InfectedHuman
class Level1(Level):
name = 'level1'
start_pos = (900, 6200)
def setup(self):
boy = InfectedHuman('boy1')
self.main_layer.add(boy)
- boy.move_to(300, 160)
+ boy.move_to(1536, 5696)
boy.set_direction(Direction.DOWN)
girl = InfectedHuman('girl1')
self.main_layer.add(girl)
- girl.move_to(470, 200)
+ girl.move_to(1536, 5824)
- girl.set_direction(Direction.LEFT)
+ girl.set_direction(Direction.UP)
def draw_bg(self, surface):
surface.fill((237, 243, 255))
|
Move the kids onto the field.
|
## Code Before:
from thecure.levels.base import Level
from thecure.sprites import Direction, InfectedHuman
class Level1(Level):
name = 'level1'
start_pos = (900, 6200)
def setup(self):
boy = InfectedHuman('boy1')
self.main_layer.add(boy)
boy.move_to(300, 160)
boy.set_direction(Direction.DOWN)
girl = InfectedHuman('girl1')
self.main_layer.add(girl)
girl.move_to(470, 200)
girl.set_direction(Direction.LEFT)
def draw_bg(self, surface):
surface.fill((237, 243, 255))
## Instruction:
Move the kids onto the field.
## Code After:
from thecure.levels.base import Level
from thecure.sprites import Direction, InfectedHuman
class Level1(Level):
name = 'level1'
start_pos = (900, 6200)
def setup(self):
boy = InfectedHuman('boy1')
self.main_layer.add(boy)
boy.move_to(1536, 5696)
boy.set_direction(Direction.DOWN)
girl = InfectedHuman('girl1')
self.main_layer.add(girl)
girl.move_to(1536, 5824)
girl.set_direction(Direction.UP)
def draw_bg(self, surface):
surface.fill((237, 243, 255))
|
// ... existing code ...
self.main_layer.add(boy)
boy.move_to(1536, 5696)
boy.set_direction(Direction.DOWN)
// ... modified code ...
self.main_layer.add(girl)
girl.move_to(1536, 5824)
girl.set_direction(Direction.UP)
// ... rest of the code ...
|
3f909cdfba61719dfa0a860aeba1e418fe740f33
|
indra/__init__.py
|
indra/__init__.py
|
from __future__ import print_function, unicode_literals
import logging
import os
import sys
__version__ = '1.10.0'
__all__ = ['assemblers', 'belief', 'databases', 'explanation', 'literature',
'mechlinker', 'preassembler', 'sources', 'tools', 'util']
logging.basicConfig(format='%(levelname)s: [%(asctime)s] indra/%(name)s - %(message)s',
level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
# Suppress INFO-level logging from some dependencies
logging.getLogger('requests').setLevel(logging.ERROR)
logging.getLogger('urllib3').setLevel(logging.ERROR)
logging.getLogger('rdflib').setLevel(logging.ERROR)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
# This is specifically to suppress lib2to3 logging from networkx
import lib2to3.pgen2.driver
class Lib2to3LoggingModuleShim(object):
def getLogger(self):
return logging.getLogger('lib2to3')
lib2to3.pgen2.driver.logging = Lib2to3LoggingModuleShim()
logging.getLogger('lib2to3').setLevel(logging.ERROR)
logger = logging.getLogger('indra')
from .config import get_config, has_config
|
from __future__ import print_function, unicode_literals
import logging
import os
import sys
__version__ = '1.10.0'
__all__ = ['assemblers', 'belief', 'databases', 'explanation', 'literature',
'mechlinker', 'preassembler', 'sources', 'tools', 'util']
logging.basicConfig(format=('%(levelname)s: [%(asctime)s] %(name)s'
' - %(message)s'),
level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
# Suppress INFO-level logging from some dependencies
logging.getLogger('requests').setLevel(logging.ERROR)
logging.getLogger('urllib3').setLevel(logging.ERROR)
logging.getLogger('rdflib').setLevel(logging.ERROR)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
# This is specifically to suppress lib2to3 logging from networkx
import lib2to3.pgen2.driver
class Lib2to3LoggingModuleShim(object):
def getLogger(self):
return logging.getLogger('lib2to3')
lib2to3.pgen2.driver.logging = Lib2to3LoggingModuleShim()
logging.getLogger('lib2to3').setLevel(logging.ERROR)
logger = logging.getLogger('indra')
from .config import get_config, has_config
|
Remove indra prefix from logger
|
Remove indra prefix from logger
|
Python
|
bsd-2-clause
|
bgyori/indra,bgyori/indra,johnbachman/indra,pvtodorov/indra,sorgerlab/indra,bgyori/indra,pvtodorov/indra,johnbachman/belpy,sorgerlab/belpy,sorgerlab/belpy,sorgerlab/belpy,sorgerlab/indra,johnbachman/indra,johnbachman/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/belpy,johnbachman/belpy,pvtodorov/indra
|
from __future__ import print_function, unicode_literals
import logging
import os
import sys
__version__ = '1.10.0'
__all__ = ['assemblers', 'belief', 'databases', 'explanation', 'literature',
'mechlinker', 'preassembler', 'sources', 'tools', 'util']
- logging.basicConfig(format='%(levelname)s: [%(asctime)s] indra/%(name)s - %(message)s',
+ logging.basicConfig(format=('%(levelname)s: [%(asctime)s] %(name)s'
+ ' - %(message)s'),
level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
# Suppress INFO-level logging from some dependencies
logging.getLogger('requests').setLevel(logging.ERROR)
logging.getLogger('urllib3').setLevel(logging.ERROR)
logging.getLogger('rdflib').setLevel(logging.ERROR)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
# This is specifically to suppress lib2to3 logging from networkx
import lib2to3.pgen2.driver
class Lib2to3LoggingModuleShim(object):
def getLogger(self):
return logging.getLogger('lib2to3')
lib2to3.pgen2.driver.logging = Lib2to3LoggingModuleShim()
logging.getLogger('lib2to3').setLevel(logging.ERROR)
logger = logging.getLogger('indra')
from .config import get_config, has_config
|
Remove indra prefix from logger
|
## Code Before:
from __future__ import print_function, unicode_literals
import logging
import os
import sys
__version__ = '1.10.0'
__all__ = ['assemblers', 'belief', 'databases', 'explanation', 'literature',
'mechlinker', 'preassembler', 'sources', 'tools', 'util']
logging.basicConfig(format='%(levelname)s: [%(asctime)s] indra/%(name)s - %(message)s',
level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
# Suppress INFO-level logging from some dependencies
logging.getLogger('requests').setLevel(logging.ERROR)
logging.getLogger('urllib3').setLevel(logging.ERROR)
logging.getLogger('rdflib').setLevel(logging.ERROR)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
# This is specifically to suppress lib2to3 logging from networkx
import lib2to3.pgen2.driver
class Lib2to3LoggingModuleShim(object):
def getLogger(self):
return logging.getLogger('lib2to3')
lib2to3.pgen2.driver.logging = Lib2to3LoggingModuleShim()
logging.getLogger('lib2to3').setLevel(logging.ERROR)
logger = logging.getLogger('indra')
from .config import get_config, has_config
## Instruction:
Remove indra prefix from logger
## Code After:
from __future__ import print_function, unicode_literals
import logging
import os
import sys
__version__ = '1.10.0'
__all__ = ['assemblers', 'belief', 'databases', 'explanation', 'literature',
'mechlinker', 'preassembler', 'sources', 'tools', 'util']
logging.basicConfig(format=('%(levelname)s: [%(asctime)s] %(name)s'
' - %(message)s'),
level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
# Suppress INFO-level logging from some dependencies
logging.getLogger('requests').setLevel(logging.ERROR)
logging.getLogger('urllib3').setLevel(logging.ERROR)
logging.getLogger('rdflib').setLevel(logging.ERROR)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
# This is specifically to suppress lib2to3 logging from networkx
import lib2to3.pgen2.driver
class Lib2to3LoggingModuleShim(object):
def getLogger(self):
return logging.getLogger('lib2to3')
lib2to3.pgen2.driver.logging = Lib2to3LoggingModuleShim()
logging.getLogger('lib2to3').setLevel(logging.ERROR)
logger = logging.getLogger('indra')
from .config import get_config, has_config
|
# ... existing code ...
logging.basicConfig(format=('%(levelname)s: [%(asctime)s] %(name)s'
' - %(message)s'),
level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
# ... rest of the code ...
|
f627a76e8dac96282b0a9f76eeda8c7db70cc030
|
telemetry/telemetry/internal/actions/javascript_click.py
|
telemetry/telemetry/internal/actions/javascript_click.py
|
from telemetry.internal.actions import page_action
class ClickElementAction(page_action.ElementPageAction):
def RunAction(self, tab):
code = '''
function(element, errorMsg) {
if (!element) {
throw Error('Cannot find element: ' + errorMsg);
}
element.click();
}'''
# Click handler that plays media or requests fullscreen may not take
# effects without user_gesture set to True.
self.EvaluateCallback(tab, code)
|
from telemetry.internal.actions import page_action
class ClickElementAction(page_action.ElementPageAction):
def RunAction(self, tab):
code = '''
function(element, errorMsg) {
if (!element) {
throw Error('Cannot find element: ' + errorMsg);
}
element.click();
}'''
# Click handler that plays media or requests fullscreen may not take
# effects without user_gesture set to True.
self.EvaluateCallback(tab, code, user_gesture=True)
|
Fix a regression where the user_gesture bit isn't set for ClickElement.
|
Fix a regression where the user_gesture bit isn't set for ClickElement.
The regrssion was introduced in
https://chromium-review.googlesource.com/c/catapult/+/1335627
Once this rolls into Chromium, I'll add a chromium side test to prevent
it from regress again in the future.
Bug: chromium:885912
TEST=manual
[email protected],[email protected]
Change-Id: Ic1c7e83a3e7d7318baa81531925dab07db9450ca
Reviewed-on: https://chromium-review.googlesource.com/c/1476957
Reviewed-by: Caleb Rouleau <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
|
Python
|
bsd-3-clause
|
catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult
|
from telemetry.internal.actions import page_action
class ClickElementAction(page_action.ElementPageAction):
def RunAction(self, tab):
code = '''
function(element, errorMsg) {
if (!element) {
throw Error('Cannot find element: ' + errorMsg);
}
element.click();
}'''
# Click handler that plays media or requests fullscreen may not take
# effects without user_gesture set to True.
- self.EvaluateCallback(tab, code)
+ self.EvaluateCallback(tab, code, user_gesture=True)
|
Fix a regression where the user_gesture bit isn't set for ClickElement.
|
## Code Before:
from telemetry.internal.actions import page_action
class ClickElementAction(page_action.ElementPageAction):
def RunAction(self, tab):
code = '''
function(element, errorMsg) {
if (!element) {
throw Error('Cannot find element: ' + errorMsg);
}
element.click();
}'''
# Click handler that plays media or requests fullscreen may not take
# effects without user_gesture set to True.
self.EvaluateCallback(tab, code)
## Instruction:
Fix a regression where the user_gesture bit isn't set for ClickElement.
## Code After:
from telemetry.internal.actions import page_action
class ClickElementAction(page_action.ElementPageAction):
def RunAction(self, tab):
code = '''
function(element, errorMsg) {
if (!element) {
throw Error('Cannot find element: ' + errorMsg);
}
element.click();
}'''
# Click handler that plays media or requests fullscreen may not take
# effects without user_gesture set to True.
self.EvaluateCallback(tab, code, user_gesture=True)
|
// ... existing code ...
# effects without user_gesture set to True.
self.EvaluateCallback(tab, code, user_gesture=True)
// ... rest of the code ...
|
498ab0c125180ba89987e797d0094adc02019a8f
|
numba/exttypes/utils.py
|
numba/exttypes/utils.py
|
"Simple utilities related to extension types"
#------------------------------------------------------------------------
# Read state from extension types
#------------------------------------------------------------------------
def get_attributes_type(py_class):
"Return the attribute struct type of the numba extension type"
return py_class.__numba_struct_type
def get_vtab_type(py_class):
"Return the type of the virtual method table of the numba extension type"
return py_class.__numba_vtab_type
def get_method_pointers(py_class):
"Return [(method_name, method_pointer)] given a numba extension type"
return getattr(py_class, '__numba_method_pointers', None)
#------------------------------------------------------------------------
# Type checking
#------------------------------------------------------------------------
def is_numba_class(py_class):
return hasattr(py_class, '__numba_struct_type')
|
"Simple utilities related to extension types"
#------------------------------------------------------------------------
# Read state from extension types
#------------------------------------------------------------------------
def get_attributes_type(py_class):
"Return the attribute struct type of the numba extension type"
return py_class.__numba_struct_type
def get_vtab_type(py_class):
"Return the type of the virtual method table of the numba extension type"
return py_class.__numba_vtab_type
def get_method_pointers(py_class):
"Return [(method_name, method_pointer)] given a numba extension type"
return getattr(py_class, '__numba_method_pointers', None)
#------------------------------------------------------------------------
# Type checking
#------------------------------------------------------------------------
def is_numba_class(py_class):
return hasattr(py_class, '__numba_struct_type')
def get_numba_bases(py_class):
for base in py_class.__mro__:
if is_numba_class(base):
yield base
|
Add utility to iterate over numba base classes
|
Add utility to iterate over numba base classes
|
Python
|
bsd-2-clause
|
jriehl/numba,cpcloud/numba,stuartarchibald/numba,numba/numba,GaZ3ll3/numba,pombredanne/numba,ssarangi/numba,ssarangi/numba,gdementen/numba,gmarkall/numba,pitrou/numba,shiquanwang/numba,numba/numba,seibert/numba,pitrou/numba,sklam/numba,shiquanwang/numba,IntelLabs/numba,seibert/numba,gdementen/numba,stuartarchibald/numba,stonebig/numba,stonebig/numba,cpcloud/numba,ssarangi/numba,GaZ3ll3/numba,gdementen/numba,stefanseefeld/numba,numba/numba,pombredanne/numba,gmarkall/numba,IntelLabs/numba,sklam/numba,numba/numba,cpcloud/numba,numba/numba,IntelLabs/numba,seibert/numba,pitrou/numba,ssarangi/numba,stonebig/numba,gdementen/numba,ssarangi/numba,jriehl/numba,cpcloud/numba,IntelLabs/numba,stefanseefeld/numba,stuartarchibald/numba,pombredanne/numba,stefanseefeld/numba,jriehl/numba,stonebig/numba,jriehl/numba,stuartarchibald/numba,sklam/numba,gmarkall/numba,gdementen/numba,IntelLabs/numba,pombredanne/numba,stefanseefeld/numba,pombredanne/numba,pitrou/numba,GaZ3ll3/numba,GaZ3ll3/numba,gmarkall/numba,jriehl/numba,pitrou/numba,seibert/numba,shiquanwang/numba,sklam/numba,gmarkall/numba,sklam/numba,seibert/numba,GaZ3ll3/numba,cpcloud/numba,stefanseefeld/numba,stuartarchibald/numba,stonebig/numba
|
"Simple utilities related to extension types"
#------------------------------------------------------------------------
# Read state from extension types
#------------------------------------------------------------------------
def get_attributes_type(py_class):
"Return the attribute struct type of the numba extension type"
return py_class.__numba_struct_type
def get_vtab_type(py_class):
"Return the type of the virtual method table of the numba extension type"
return py_class.__numba_vtab_type
def get_method_pointers(py_class):
"Return [(method_name, method_pointer)] given a numba extension type"
return getattr(py_class, '__numba_method_pointers', None)
#------------------------------------------------------------------------
# Type checking
#------------------------------------------------------------------------
def is_numba_class(py_class):
return hasattr(py_class, '__numba_struct_type')
+
+ def get_numba_bases(py_class):
+ for base in py_class.__mro__:
+ if is_numba_class(base):
+ yield base
|
Add utility to iterate over numba base classes
|
## Code Before:
"Simple utilities related to extension types"
#------------------------------------------------------------------------
# Read state from extension types
#------------------------------------------------------------------------
def get_attributes_type(py_class):
"Return the attribute struct type of the numba extension type"
return py_class.__numba_struct_type
def get_vtab_type(py_class):
"Return the type of the virtual method table of the numba extension type"
return py_class.__numba_vtab_type
def get_method_pointers(py_class):
"Return [(method_name, method_pointer)] given a numba extension type"
return getattr(py_class, '__numba_method_pointers', None)
#------------------------------------------------------------------------
# Type checking
#------------------------------------------------------------------------
def is_numba_class(py_class):
return hasattr(py_class, '__numba_struct_type')
## Instruction:
Add utility to iterate over numba base classes
## Code After:
"Simple utilities related to extension types"
#------------------------------------------------------------------------
# Read state from extension types
#------------------------------------------------------------------------
def get_attributes_type(py_class):
"Return the attribute struct type of the numba extension type"
return py_class.__numba_struct_type
def get_vtab_type(py_class):
"Return the type of the virtual method table of the numba extension type"
return py_class.__numba_vtab_type
def get_method_pointers(py_class):
"Return [(method_name, method_pointer)] given a numba extension type"
return getattr(py_class, '__numba_method_pointers', None)
#------------------------------------------------------------------------
# Type checking
#------------------------------------------------------------------------
def is_numba_class(py_class):
return hasattr(py_class, '__numba_struct_type')
def get_numba_bases(py_class):
for base in py_class.__mro__:
if is_numba_class(base):
yield base
|
// ... existing code ...
return hasattr(py_class, '__numba_struct_type')
def get_numba_bases(py_class):
for base in py_class.__mro__:
if is_numba_class(base):
yield base
// ... rest of the code ...
|
f48a9f088e383eb77c40b0196552590dc654cea7
|
test/mbed_gt_cli.py
|
test/mbed_gt_cli.py
|
import unittest
from mbed_greentea import mbed_greentea_cli
class GreenteaCliFunctionality(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_print_version(self):
version = mbed_greentea_cli.print_version(verbose=False)
a, b, c = version.split('.')
self.assertEqual(a.isdigit(), True)
self.assertEqual(b.isdigit(), True)
self.assertEqual(c.isdigit(), True)
if __name__ == '__main__':
unittest.main()
|
import unittest
from mbed_greentea import mbed_greentea_cli
class GreenteaCliFunctionality(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_get_greentea_version(self):
version = mbed_greentea_cli.get_greentea_version()
self.assertIs(type(version), str)
a, b, c = version.split('.')
self.assertEqual(a.isdigit(), True)
self.assertEqual(b.isdigit(), True)
self.assertEqual(c.isdigit(), True)
def get_hello_string(self):
version = mbed_greentea_cli.get_greentea_version()
hello_string = mbed_greentea_cli.get_hello_string()
self.assertIs(type(version), str)
self.assertIs(type(hello_string), str)
self.assertIn(version, hello_string)
if __name__ == '__main__':
unittest.main()
|
Add unit tests to mbed-greentea version printing API
|
Add unit tests to mbed-greentea version printing API
|
Python
|
apache-2.0
|
ARMmbed/greentea
|
import unittest
from mbed_greentea import mbed_greentea_cli
class GreenteaCliFunctionality(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
- def test_print_version(self):
+ def test_get_greentea_version(self):
- version = mbed_greentea_cli.print_version(verbose=False)
+ version = mbed_greentea_cli.get_greentea_version()
+
+ self.assertIs(type(version), str)
+
a, b, c = version.split('.')
+
self.assertEqual(a.isdigit(), True)
self.assertEqual(b.isdigit(), True)
self.assertEqual(c.isdigit(), True)
+
+ def get_hello_string(self):
+ version = mbed_greentea_cli.get_greentea_version()
+ hello_string = mbed_greentea_cli.get_hello_string()
+
+ self.assertIs(type(version), str)
+ self.assertIs(type(hello_string), str)
+ self.assertIn(version, hello_string)
if __name__ == '__main__':
unittest.main()
|
Add unit tests to mbed-greentea version printing API
|
## Code Before:
import unittest
from mbed_greentea import mbed_greentea_cli
class GreenteaCliFunctionality(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_print_version(self):
version = mbed_greentea_cli.print_version(verbose=False)
a, b, c = version.split('.')
self.assertEqual(a.isdigit(), True)
self.assertEqual(b.isdigit(), True)
self.assertEqual(c.isdigit(), True)
if __name__ == '__main__':
unittest.main()
## Instruction:
Add unit tests to mbed-greentea version printing API
## Code After:
import unittest
from mbed_greentea import mbed_greentea_cli
class GreenteaCliFunctionality(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_get_greentea_version(self):
version = mbed_greentea_cli.get_greentea_version()
self.assertIs(type(version), str)
a, b, c = version.split('.')
self.assertEqual(a.isdigit(), True)
self.assertEqual(b.isdigit(), True)
self.assertEqual(c.isdigit(), True)
def get_hello_string(self):
version = mbed_greentea_cli.get_greentea_version()
hello_string = mbed_greentea_cli.get_hello_string()
self.assertIs(type(version), str)
self.assertIs(type(hello_string), str)
self.assertIn(version, hello_string)
if __name__ == '__main__':
unittest.main()
|
...
def test_get_greentea_version(self):
version = mbed_greentea_cli.get_greentea_version()
self.assertIs(type(version), str)
a, b, c = version.split('.')
self.assertEqual(a.isdigit(), True)
...
def get_hello_string(self):
version = mbed_greentea_cli.get_greentea_version()
hello_string = mbed_greentea_cli.get_hello_string()
self.assertIs(type(version), str)
self.assertIs(type(hello_string), str)
self.assertIn(version, hello_string)
...
|
d3f09baf1e1de0272e1a579a207f685feb6c673f
|
common/mixins.py
|
common/mixins.py
|
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.text import slugify
class TimestampMixin(models.Model):
"""Mixin for date and timestamp. Inherits django's models.Model."""
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class SlugifyMixin():
"""
Slugify specific field and pass as value to slug field in the model.
This mixin helps in solving the problem of having case insensitive duplicates
by creating a slug and ensuring uniqueness.
Model field to be slugified should be passed as a string into a variable
called slugify_field.
Slug field in the model should be named slug.
"""
def clean(self):
if hasattr(self, 'slugify_field') and hasattr(self, 'slug'):
self.slug = slugify(getattr(self, self.slugify_field))
if self.__class__.objects.filter(slug=self.slug).exists():
raise ValidationError("This object already exists.")
def save(self, *args, **kwargs):
self.clean()
return super().save(*args, **kwargs)
|
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
class TimestampMixin(models.Model):
"""Mixin for date and timestamp. Inherits django's models.Model."""
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class SlugifyMixin():
"""
Slugify specific field and pass as value to slug field in the model.
This mixin helps in solving the problem of having case insensitive duplicates
by creating a slug and ensuring uniqueness.
Model field to be slugified should be passed as a string into a variable
called slugify_field.
Slug field in the model should be named slug.
"""
def clean(self):
if hasattr(self, 'slugify_field') and hasattr(self, 'slug'):
slugify_field_value = getattr(self, self.slugify_field)
self.slug = slugify(slugify_field_value)
if self.__class__.objects.filter(slug=self.slug).exists():
raise ValidationError(_("Entry with {0} - {1} already exists.".format(
self.slugify_field, slugify_field_value)))
def save(self, *args, **kwargs):
self.clean()
return super().save(*args, **kwargs)
|
Return user-friendly error message for SlugifyMixin class
|
Return user-friendly error message for SlugifyMixin class
|
Python
|
mit
|
teamtaverna/core
|
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.text import slugify
+ from django.utils.translation import ugettext_lazy as _
class TimestampMixin(models.Model):
"""Mixin for date and timestamp. Inherits django's models.Model."""
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class SlugifyMixin():
"""
Slugify specific field and pass as value to slug field in the model.
This mixin helps in solving the problem of having case insensitive duplicates
by creating a slug and ensuring uniqueness.
Model field to be slugified should be passed as a string into a variable
called slugify_field.
Slug field in the model should be named slug.
"""
def clean(self):
if hasattr(self, 'slugify_field') and hasattr(self, 'slug'):
- self.slug = slugify(getattr(self, self.slugify_field))
+ slugify_field_value = getattr(self, self.slugify_field)
+ self.slug = slugify(slugify_field_value)
if self.__class__.objects.filter(slug=self.slug).exists():
- raise ValidationError("This object already exists.")
+ raise ValidationError(_("Entry with {0} - {1} already exists.".format(
+ self.slugify_field, slugify_field_value)))
def save(self, *args, **kwargs):
self.clean()
return super().save(*args, **kwargs)
|
Return user-friendly error message for SlugifyMixin class
|
## Code Before:
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.text import slugify
class TimestampMixin(models.Model):
"""Mixin for date and timestamp. Inherits django's models.Model."""
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class SlugifyMixin():
"""
Slugify specific field and pass as value to slug field in the model.
This mixin helps in solving the problem of having case insensitive duplicates
by creating a slug and ensuring uniqueness.
Model field to be slugified should be passed as a string into a variable
called slugify_field.
Slug field in the model should be named slug.
"""
def clean(self):
if hasattr(self, 'slugify_field') and hasattr(self, 'slug'):
self.slug = slugify(getattr(self, self.slugify_field))
if self.__class__.objects.filter(slug=self.slug).exists():
raise ValidationError("This object already exists.")
def save(self, *args, **kwargs):
self.clean()
return super().save(*args, **kwargs)
## Instruction:
Return user-friendly error message for SlugifyMixin class
## Code After:
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
class TimestampMixin(models.Model):
"""Mixin for date and timestamp. Inherits django's models.Model."""
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class SlugifyMixin():
"""
Slugify specific field and pass as value to slug field in the model.
This mixin helps in solving the problem of having case insensitive duplicates
by creating a slug and ensuring uniqueness.
Model field to be slugified should be passed as a string into a variable
called slugify_field.
Slug field in the model should be named slug.
"""
def clean(self):
if hasattr(self, 'slugify_field') and hasattr(self, 'slug'):
slugify_field_value = getattr(self, self.slugify_field)
self.slug = slugify(slugify_field_value)
if self.__class__.objects.filter(slug=self.slug).exists():
raise ValidationError(_("Entry with {0} - {1} already exists.".format(
self.slugify_field, slugify_field_value)))
def save(self, *args, **kwargs):
self.clean()
return super().save(*args, **kwargs)
|
// ... existing code ...
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
// ... modified code ...
if hasattr(self, 'slugify_field') and hasattr(self, 'slug'):
slugify_field_value = getattr(self, self.slugify_field)
self.slug = slugify(slugify_field_value)
...
if self.__class__.objects.filter(slug=self.slug).exists():
raise ValidationError(_("Entry with {0} - {1} already exists.".format(
self.slugify_field, slugify_field_value)))
// ... rest of the code ...
|
f6a974a1dc5337e482fe6fcac402597735892567
|
saleor/delivery/__init__.py
|
saleor/delivery/__init__.py
|
from __future__ import unicode_literals
from django.conf import settings
from prices import Price
from satchless.item import Item
class BaseDelivery(Item):
def __init__(self, delivery_group):
self.group = delivery_group
def get_price_per_item(self, **kwargs):
return Price(0, currency=settings.SATCHLESS_DEFAULT_CURRENCY)
class DummyShipping(BaseDelivery):
def __unicode__(self):
return 'Dummy shipping'
def get_price_per_item(self, **kwargs):
weight = sum(line.product.weight for line in self.group)
qty = sum(line.quantity for line in self.group)
return Price(qty * weight,
currency=settings.SATCHLESS_DEFAULT_CURRENCY)
class DigitalDelivery(BaseDelivery):
def __unicode__(self):
return 'Digital delivery'
|
from __future__ import unicode_literals
from re import sub
from django.conf import settings
from prices import Price
from satchless.item import ItemSet
from ..cart import ShippedGroup
class BaseDelivery(ItemSet):
group = None
def __init__(self, delivery_group):
self.group = delivery_group
def __iter__(self):
return iter(self.group)
def get_delivery_total(self, **kwargs):
return Price(0, currency=settings.SATCHLESS_DEFAULT_CURRENCY)
def get_total_with_delivery(self):
return self.group.get_total() + self.get_delivery_total()
@property
def name(self):
'''
Returns undescored version of class name
'''
name = type(self).__name__
name = sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\1', name)
return name.lower().strip('_')
class DummyShipping(BaseDelivery):
address = None
def __init__(self, delivery_group, address):
self.address = address
super(DummyShipping, self).__init__(delivery_group)
def __unicode__(self):
return 'Dummy shipping'
def get_delivery_total(self, **kwargs):
weight = sum(line.product.weight for line in self.group)
qty = sum(line.quantity for line in self.group)
return Price(qty * weight,
currency=settings.SATCHLESS_DEFAULT_CURRENCY)
class DigitalDelivery(BaseDelivery):
email = None
def __init__(self, delivery_group, email):
self.email = email
super(DigitalDelivery, self).__init__(delivery_group)
def __unicode__(self):
return 'Digital delivery'
def get_delivery_methods_for_group(group, **kwargs):
if isinstance(group, ShippedGroup):
yield DummyShipping(group, kwargs['address'])
else:
yield DigitalDelivery(group, kwargs['email'])
|
Use the delivery classes as proxy for items groups
|
Use the delivery classes as proxy for items groups
|
Python
|
bsd-3-clause
|
Drekscott/Motlaesaleor,taedori81/saleor,rchav/vinerack,maferelo/saleor,rodrigozn/CW-Shop,dashmug/saleor,taedori81/saleor,laosunhust/saleor,laosunhust/saleor,car3oon/saleor,mociepka/saleor,hongquan/saleor,arth-co/saleor,taedori81/saleor,car3oon/saleor,spartonia/saleor,dashmug/saleor,hongquan/saleor,hongquan/saleor,car3oon/saleor,avorio/saleor,rchav/vinerack,spartonia/saleor,dashmug/saleor,arth-co/saleor,maferelo/saleor,paweltin/saleor,spartonia/saleor,taedori81/saleor,KenMutemi/saleor,avorio/saleor,arth-co/saleor,josesanch/saleor,Drekscott/Motlaesaleor,josesanch/saleor,KenMutemi/saleor,HyperManTT/ECommerceSaleor,tfroehlich82/saleor,avorio/saleor,jreigel/saleor,paweltin/saleor,tfroehlich82/saleor,rodrigozn/CW-Shop,UITools/saleor,josesanch/saleor,itbabu/saleor,rchav/vinerack,HyperManTT/ECommerceSaleor,spartonia/saleor,UITools/saleor,UITools/saleor,jreigel/saleor,itbabu/saleor,arth-co/saleor,KenMutemi/saleor,tfroehlich82/saleor,mociepka/saleor,Drekscott/Motlaesaleor,HyperManTT/ECommerceSaleor,paweltin/saleor,Drekscott/Motlaesaleor,maferelo/saleor,laosunhust/saleor,avorio/saleor,mociepka/saleor,itbabu/saleor,paweltin/saleor,laosunhust/saleor,jreigel/saleor,rodrigozn/CW-Shop,UITools/saleor,UITools/saleor
|
from __future__ import unicode_literals
+ from re import sub
from django.conf import settings
from prices import Price
- from satchless.item import Item
+ from satchless.item import ItemSet
+
+ from ..cart import ShippedGroup
- class BaseDelivery(Item):
+ class BaseDelivery(ItemSet):
+
+ group = None
def __init__(self, delivery_group):
self.group = delivery_group
+ def __iter__(self):
+ return iter(self.group)
+
- def get_price_per_item(self, **kwargs):
+ def get_delivery_total(self, **kwargs):
return Price(0, currency=settings.SATCHLESS_DEFAULT_CURRENCY)
+
+ def get_total_with_delivery(self):
+ return self.group.get_total() + self.get_delivery_total()
+
+ @property
+ def name(self):
+ '''
+ Returns undescored version of class name
+ '''
+ name = type(self).__name__
+ name = sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\1', name)
+ return name.lower().strip('_')
class DummyShipping(BaseDelivery):
+ address = None
+
+ def __init__(self, delivery_group, address):
+ self.address = address
+ super(DummyShipping, self).__init__(delivery_group)
+
def __unicode__(self):
return 'Dummy shipping'
- def get_price_per_item(self, **kwargs):
+ def get_delivery_total(self, **kwargs):
weight = sum(line.product.weight for line in self.group)
qty = sum(line.quantity for line in self.group)
return Price(qty * weight,
currency=settings.SATCHLESS_DEFAULT_CURRENCY)
class DigitalDelivery(BaseDelivery):
+ email = None
+
+ def __init__(self, delivery_group, email):
+ self.email = email
+ super(DigitalDelivery, self).__init__(delivery_group)
+
def __unicode__(self):
return 'Digital delivery'
+
+ def get_delivery_methods_for_group(group, **kwargs):
+ if isinstance(group, ShippedGroup):
+ yield DummyShipping(group, kwargs['address'])
+ else:
+ yield DigitalDelivery(group, kwargs['email'])
+
|
Use the delivery classes as proxy for items groups
|
## Code Before:
from __future__ import unicode_literals
from django.conf import settings
from prices import Price
from satchless.item import Item
class BaseDelivery(Item):
def __init__(self, delivery_group):
self.group = delivery_group
def get_price_per_item(self, **kwargs):
return Price(0, currency=settings.SATCHLESS_DEFAULT_CURRENCY)
class DummyShipping(BaseDelivery):
def __unicode__(self):
return 'Dummy shipping'
def get_price_per_item(self, **kwargs):
weight = sum(line.product.weight for line in self.group)
qty = sum(line.quantity for line in self.group)
return Price(qty * weight,
currency=settings.SATCHLESS_DEFAULT_CURRENCY)
class DigitalDelivery(BaseDelivery):
def __unicode__(self):
return 'Digital delivery'
## Instruction:
Use the delivery classes as proxy for items groups
## Code After:
from __future__ import unicode_literals
from re import sub
from django.conf import settings
from prices import Price
from satchless.item import ItemSet
from ..cart import ShippedGroup
class BaseDelivery(ItemSet):
group = None
def __init__(self, delivery_group):
self.group = delivery_group
def __iter__(self):
return iter(self.group)
def get_delivery_total(self, **kwargs):
return Price(0, currency=settings.SATCHLESS_DEFAULT_CURRENCY)
def get_total_with_delivery(self):
return self.group.get_total() + self.get_delivery_total()
@property
def name(self):
'''
Returns undescored version of class name
'''
name = type(self).__name__
name = sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\1', name)
return name.lower().strip('_')
class DummyShipping(BaseDelivery):
address = None
def __init__(self, delivery_group, address):
self.address = address
super(DummyShipping, self).__init__(delivery_group)
def __unicode__(self):
return 'Dummy shipping'
def get_delivery_total(self, **kwargs):
weight = sum(line.product.weight for line in self.group)
qty = sum(line.quantity for line in self.group)
return Price(qty * weight,
currency=settings.SATCHLESS_DEFAULT_CURRENCY)
class DigitalDelivery(BaseDelivery):
email = None
def __init__(self, delivery_group, email):
self.email = email
super(DigitalDelivery, self).__init__(delivery_group)
def __unicode__(self):
return 'Digital delivery'
def get_delivery_methods_for_group(group, **kwargs):
if isinstance(group, ShippedGroup):
yield DummyShipping(group, kwargs['address'])
else:
yield DigitalDelivery(group, kwargs['email'])
|
# ... existing code ...
from __future__ import unicode_literals
from re import sub
# ... modified code ...
from prices import Price
from satchless.item import ItemSet
from ..cart import ShippedGroup
...
class BaseDelivery(ItemSet):
group = None
...
def __iter__(self):
return iter(self.group)
def get_delivery_total(self, **kwargs):
return Price(0, currency=settings.SATCHLESS_DEFAULT_CURRENCY)
def get_total_with_delivery(self):
return self.group.get_total() + self.get_delivery_total()
@property
def name(self):
'''
Returns undescored version of class name
'''
name = type(self).__name__
name = sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\1', name)
return name.lower().strip('_')
...
address = None
def __init__(self, delivery_group, address):
self.address = address
super(DummyShipping, self).__init__(delivery_group)
def __unicode__(self):
...
def get_delivery_total(self, **kwargs):
weight = sum(line.product.weight for line in self.group)
...
email = None
def __init__(self, delivery_group, email):
self.email = email
super(DigitalDelivery, self).__init__(delivery_group)
def __unicode__(self):
...
return 'Digital delivery'
def get_delivery_methods_for_group(group, **kwargs):
if isinstance(group, ShippedGroup):
yield DummyShipping(group, kwargs['address'])
else:
yield DigitalDelivery(group, kwargs['email'])
# ... rest of the code ...
|
ef7910d259f3a7d025e95ad69345da457a777b90
|
myvoice/urls.py
|
myvoice/urls.py
|
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('myvoice.core.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^broadcast/', include('broadcast.urls')),
url(r'^groups/', include('groups.urls')),
url(r'^decisiontree/', include('decisiontree.urls')),
url(r'^pbf/', include('myvoice.pbf.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^', include('myvoice.core.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^broadcast/', include('broadcast.urls')),
url(r'^groups/', include('groups.urls')),
url(r'^decisiontree/', include('decisiontree.urls')),
url(r'^pbf/', include('myvoice.pbf.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
Use Django 1.7 syntax for URLs
|
Use Django 1.7 syntax for URLs
|
Python
|
bsd-2-clause
|
myvoice-nigeria/myvoice,myvoice-nigeria/myvoice,myvoice-nigeria/myvoice,myvoice-nigeria/myvoice
|
from django.conf import settings
- from django.conf.urls import patterns, include, url
+ from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
- urlpatterns = patterns('',
+ urlpatterns = [
url(r'^', include('myvoice.core.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^broadcast/', include('broadcast.urls')),
url(r'^groups/', include('groups.urls')),
url(r'^decisiontree/', include('decisiontree.urls')),
url(r'^pbf/', include('myvoice.pbf.urls')),
- ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
+ ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
Use Django 1.7 syntax for URLs
|
## Code Before:
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('myvoice.core.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^broadcast/', include('broadcast.urls')),
url(r'^groups/', include('groups.urls')),
url(r'^decisiontree/', include('decisiontree.urls')),
url(r'^pbf/', include('myvoice.pbf.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
## Instruction:
Use Django 1.7 syntax for URLs
## Code After:
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^', include('myvoice.core.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^broadcast/', include('broadcast.urls')),
url(r'^groups/', include('groups.urls')),
url(r'^decisiontree/', include('decisiontree.urls')),
url(r'^pbf/', include('myvoice.pbf.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
...
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
...
urlpatterns = [
url(r'^', include('myvoice.core.urls')),
...
url(r'^pbf/', include('myvoice.pbf.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
...
|
3170407aaaeffbc76e31e5fc78d4dacd008e27d2
|
backbone_calendar/ajax/mixins.py
|
backbone_calendar/ajax/mixins.py
|
from django import http
from django.utils import simplejson as json
class JSONResponseMixin(object):
context_variable = 'object_list'
def render_to_response(self, context):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context))
def dispatch(self, *args, **kwargs):
return super(JSONResponseMixin, self).dispatch(*args, **kwargs)
def post(self, *args, **kwargs):
return self.get(self, *args, **kwargs)
def get_json_response(self, content, **httpresponse_kwargs):
"Construct an `HttpResponse` object."
return http.HttpResponse(content,
content_type='application/json',
**httpresponse_kwargs)
def convert_context_to_json(self, context):
"Convert the context dictionary into a JSON object"
# Note: This is *EXTREMELY* naive; in reality, you'll need
# to do much more complex handling to ensure that arbitrary
# objects -- such as Django model instances or querysets
# -- can be serialized as JSON.
if self.context_variable is not None:
return json.dumps(context.get(self.context_variable, None))
return json.dumps(context)
|
import json
from django import http
class JSONResponseMixin(object):
context_variable = 'object_list'
def render_to_response(self, context):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context))
def dispatch(self, *args, **kwargs):
return super(JSONResponseMixin, self).dispatch(*args, **kwargs)
def post(self, *args, **kwargs):
return self.get(self, *args, **kwargs)
def get_json_response(self, content, **httpresponse_kwargs):
"Construct an `HttpResponse` object."
return http.HttpResponse(content,
content_type='application/json',
**httpresponse_kwargs)
def convert_context_to_json(self, context):
"Convert the context dictionary into a JSON object"
# Note: This is *EXTREMELY* naive; in reality, you'll need
# to do much more complex handling to ensure that arbitrary
# objects -- such as Django model instances or querysets
# -- can be serialized as JSON.
if self.context_variable is not None:
return json.dumps(context.get(self.context_variable, None))
return json.dumps(context)
|
Use json and not simplejson
|
Use json and not simplejson
|
Python
|
agpl-3.0
|
rezometz/django-backbone-calendar,rezometz/django-backbone-calendar,rezometz/django-backbone-calendar
|
+ import json
+
from django import http
- from django.utils import simplejson as json
class JSONResponseMixin(object):
context_variable = 'object_list'
def render_to_response(self, context):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context))
def dispatch(self, *args, **kwargs):
return super(JSONResponseMixin, self).dispatch(*args, **kwargs)
def post(self, *args, **kwargs):
return self.get(self, *args, **kwargs)
def get_json_response(self, content, **httpresponse_kwargs):
"Construct an `HttpResponse` object."
return http.HttpResponse(content,
content_type='application/json',
**httpresponse_kwargs)
def convert_context_to_json(self, context):
"Convert the context dictionary into a JSON object"
# Note: This is *EXTREMELY* naive; in reality, you'll need
# to do much more complex handling to ensure that arbitrary
# objects -- such as Django model instances or querysets
# -- can be serialized as JSON.
if self.context_variable is not None:
return json.dumps(context.get(self.context_variable, None))
return json.dumps(context)
|
Use json and not simplejson
|
## Code Before:
from django import http
from django.utils import simplejson as json
class JSONResponseMixin(object):
context_variable = 'object_list'
def render_to_response(self, context):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context))
def dispatch(self, *args, **kwargs):
return super(JSONResponseMixin, self).dispatch(*args, **kwargs)
def post(self, *args, **kwargs):
return self.get(self, *args, **kwargs)
def get_json_response(self, content, **httpresponse_kwargs):
"Construct an `HttpResponse` object."
return http.HttpResponse(content,
content_type='application/json',
**httpresponse_kwargs)
def convert_context_to_json(self, context):
"Convert the context dictionary into a JSON object"
# Note: This is *EXTREMELY* naive; in reality, you'll need
# to do much more complex handling to ensure that arbitrary
# objects -- such as Django model instances or querysets
# -- can be serialized as JSON.
if self.context_variable is not None:
return json.dumps(context.get(self.context_variable, None))
return json.dumps(context)
## Instruction:
Use json and not simplejson
## Code After:
import json
from django import http
class JSONResponseMixin(object):
context_variable = 'object_list'
def render_to_response(self, context):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context))
def dispatch(self, *args, **kwargs):
return super(JSONResponseMixin, self).dispatch(*args, **kwargs)
def post(self, *args, **kwargs):
return self.get(self, *args, **kwargs)
def get_json_response(self, content, **httpresponse_kwargs):
"Construct an `HttpResponse` object."
return http.HttpResponse(content,
content_type='application/json',
**httpresponse_kwargs)
def convert_context_to_json(self, context):
"Convert the context dictionary into a JSON object"
# Note: This is *EXTREMELY* naive; in reality, you'll need
# to do much more complex handling to ensure that arbitrary
# objects -- such as Django model instances or querysets
# -- can be serialized as JSON.
if self.context_variable is not None:
return json.dumps(context.get(self.context_variable, None))
return json.dumps(context)
|
// ... existing code ...
import json
from django import http
// ... rest of the code ...
|
c78d9c63238b5535b1881f4eee54700f5a138b04
|
lupa/__init__.py
|
lupa/__init__.py
|
def _try_import_with_global_library_symbols():
try:
import DLFCN
dlopen_flags = DLFCN.RTLD_NOW | DLFCN.RTLD_GLOBAL
except ImportError:
import ctypes
dlopen_flags = ctypes.RTLD_GLOBAL
import sys
old_flags = sys.getdlopenflags()
try:
sys.setdlopenflags(dlopen_flags)
import lupa._lupa
finally:
sys.setdlopenflags(old_flags)
try:
_try_import_with_global_library_symbols()
except:
pass
del _try_import_with_global_library_symbols
# the following is all that should stay in the namespace:
from lupa._lupa import *
try:
from lupa.version import __version__
except ImportError:
pass
|
from __future__ import absolute_import
# We need to enable global symbol visibility for lupa in order to
# support binary module loading in Lua. If we can enable it here, we
# do it temporarily.
def _try_import_with_global_library_symbols():
try:
from os import RTLD_NOW, RTLD_GLOBAL
except ImportError:
from DLFCN import RTLD_NOW, RTLD_GLOBAL # Py2.7
dlopen_flags = RTLD_NOW | RTLD_GLOBAL
import sys
old_flags = sys.getdlopenflags()
try:
sys.setdlopenflags(dlopen_flags)
import lupa._lupa
finally:
sys.setdlopenflags(old_flags)
try:
_try_import_with_global_library_symbols()
except:
pass
del _try_import_with_global_library_symbols
# the following is all that should stay in the namespace:
from lupa._lupa import *
try:
from lupa.version import __version__
except ImportError:
pass
|
Use "os.RTLD_*" flags in Py3, as "DLFCN.*" is only the right thing to use in Py2.
|
Use "os.RTLD_*" flags in Py3, as "DLFCN.*" is only the right thing to use in Py2.
|
Python
|
mit
|
pombredanne/lupa,pombredanne/lupa
|
+ from __future__ import absolute_import
+
+
+ # We need to enable global symbol visibility for lupa in order to
+ # support binary module loading in Lua. If we can enable it here, we
+ # do it temporarily.
def _try_import_with_global_library_symbols():
try:
+ from os import RTLD_NOW, RTLD_GLOBAL
- import DLFCN
- dlopen_flags = DLFCN.RTLD_NOW | DLFCN.RTLD_GLOBAL
except ImportError:
- import ctypes
- dlopen_flags = ctypes.RTLD_GLOBAL
+ from DLFCN import RTLD_NOW, RTLD_GLOBAL # Py2.7
+ dlopen_flags = RTLD_NOW | RTLD_GLOBAL
import sys
old_flags = sys.getdlopenflags()
try:
sys.setdlopenflags(dlopen_flags)
import lupa._lupa
finally:
sys.setdlopenflags(old_flags)
try:
_try_import_with_global_library_symbols()
except:
pass
del _try_import_with_global_library_symbols
# the following is all that should stay in the namespace:
from lupa._lupa import *
try:
from lupa.version import __version__
except ImportError:
pass
|
Use "os.RTLD_*" flags in Py3, as "DLFCN.*" is only the right thing to use in Py2.
|
## Code Before:
def _try_import_with_global_library_symbols():
try:
import DLFCN
dlopen_flags = DLFCN.RTLD_NOW | DLFCN.RTLD_GLOBAL
except ImportError:
import ctypes
dlopen_flags = ctypes.RTLD_GLOBAL
import sys
old_flags = sys.getdlopenflags()
try:
sys.setdlopenflags(dlopen_flags)
import lupa._lupa
finally:
sys.setdlopenflags(old_flags)
try:
_try_import_with_global_library_symbols()
except:
pass
del _try_import_with_global_library_symbols
# the following is all that should stay in the namespace:
from lupa._lupa import *
try:
from lupa.version import __version__
except ImportError:
pass
## Instruction:
Use "os.RTLD_*" flags in Py3, as "DLFCN.*" is only the right thing to use in Py2.
## Code After:
from __future__ import absolute_import
# We need to enable global symbol visibility for lupa in order to
# support binary module loading in Lua. If we can enable it here, we
# do it temporarily.
def _try_import_with_global_library_symbols():
try:
from os import RTLD_NOW, RTLD_GLOBAL
except ImportError:
from DLFCN import RTLD_NOW, RTLD_GLOBAL # Py2.7
dlopen_flags = RTLD_NOW | RTLD_GLOBAL
import sys
old_flags = sys.getdlopenflags()
try:
sys.setdlopenflags(dlopen_flags)
import lupa._lupa
finally:
sys.setdlopenflags(old_flags)
try:
_try_import_with_global_library_symbols()
except:
pass
del _try_import_with_global_library_symbols
# the following is all that should stay in the namespace:
from lupa._lupa import *
try:
from lupa.version import __version__
except ImportError:
pass
|
// ... existing code ...
from __future__ import absolute_import
# We need to enable global symbol visibility for lupa in order to
# support binary module loading in Lua. If we can enable it here, we
# do it temporarily.
// ... modified code ...
try:
from os import RTLD_NOW, RTLD_GLOBAL
except ImportError:
from DLFCN import RTLD_NOW, RTLD_GLOBAL # Py2.7
dlopen_flags = RTLD_NOW | RTLD_GLOBAL
// ... rest of the code ...
|
ae2f1014bbe83d64f17fee6a9ebd2c12cdc9a1bf
|
app/main/errors.py
|
app/main/errors.py
|
from flask import render_template
from app.main import main
@main.app_errorhandler(400)
def bad_request(e):
return render_template("errors/500.html",
**main.config['BASE_TEMPLATE_DATA']), 400
@main.app_errorhandler(404)
def page_not_found(e):
return render_template("errors/404.html",
**main.config['BASE_TEMPLATE_DATA']), 404
@main.app_errorhandler(500)
def exception(e):
return render_template("errors/500.html",
**main.config['BASE_TEMPLATE_DATA']), 500
@main.app_errorhandler(503)
def service_unavailable(e):
return render_template("errors/500.html",
**main.config['BASE_TEMPLATE_DATA']), 503
|
from flask import render_template
from app.main import main
from dmutils.apiclient import APIError
@main.app_errorhandler(APIError)
def api_error(e):
return _render_error_template(e.status_code)
@main.app_errorhandler(400)
def bad_request(e):
return _render_error_template(400)
@main.app_errorhandler(404)
def page_not_found(e):
return _render_error_template(404)
@main.app_errorhandler(500)
def exception(e):
return _render_error_template(500)
@main.app_errorhandler(503)
def service_unavailable(e):
return _render_error_template(503)
def _render_error_template(status_code):
return render_template(
_get_template(status_code),
**main.config['BASE_TEMPLATE_DATA']
), status_code
def _get_template(status_code):
if status_code == 404:
return "errors/404.html"
else:
return "errors/500.html"
|
Add APIError flask error handler
|
Add APIError flask error handler
This is modelled after the similar change in the supplier frontend
https://github.com/alphagov/digitalmarketplace-supplier-frontend/commit/233f8840d55cadb9fb7fe60ff12c53b0f59f23a5
|
Python
|
mit
|
alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend
|
from flask import render_template
from app.main import main
+ from dmutils.apiclient import APIError
+
+
+ @main.app_errorhandler(APIError)
+ def api_error(e):
+ return _render_error_template(e.status_code)
@main.app_errorhandler(400)
def bad_request(e):
+ return _render_error_template(400)
- return render_template("errors/500.html",
- **main.config['BASE_TEMPLATE_DATA']), 400
@main.app_errorhandler(404)
def page_not_found(e):
+ return _render_error_template(404)
- return render_template("errors/404.html",
- **main.config['BASE_TEMPLATE_DATA']), 404
@main.app_errorhandler(500)
def exception(e):
+ return _render_error_template(500)
- return render_template("errors/500.html",
- **main.config['BASE_TEMPLATE_DATA']), 500
@main.app_errorhandler(503)
def service_unavailable(e):
+ return _render_error_template(503)
- return render_template("errors/500.html",
- **main.config['BASE_TEMPLATE_DATA']), 503
+
+ def _render_error_template(status_code):
+ return render_template(
+ _get_template(status_code),
+ **main.config['BASE_TEMPLATE_DATA']
+ ), status_code
+
+
+ def _get_template(status_code):
+ if status_code == 404:
+ return "errors/404.html"
+ else:
+ return "errors/500.html"
+
|
Add APIError flask error handler
|
## Code Before:
from flask import render_template
from app.main import main
@main.app_errorhandler(400)
def bad_request(e):
return render_template("errors/500.html",
**main.config['BASE_TEMPLATE_DATA']), 400
@main.app_errorhandler(404)
def page_not_found(e):
return render_template("errors/404.html",
**main.config['BASE_TEMPLATE_DATA']), 404
@main.app_errorhandler(500)
def exception(e):
return render_template("errors/500.html",
**main.config['BASE_TEMPLATE_DATA']), 500
@main.app_errorhandler(503)
def service_unavailable(e):
return render_template("errors/500.html",
**main.config['BASE_TEMPLATE_DATA']), 503
## Instruction:
Add APIError flask error handler
## Code After:
from flask import render_template
from app.main import main
from dmutils.apiclient import APIError
@main.app_errorhandler(APIError)
def api_error(e):
return _render_error_template(e.status_code)
@main.app_errorhandler(400)
def bad_request(e):
return _render_error_template(400)
@main.app_errorhandler(404)
def page_not_found(e):
return _render_error_template(404)
@main.app_errorhandler(500)
def exception(e):
return _render_error_template(500)
@main.app_errorhandler(503)
def service_unavailable(e):
return _render_error_template(503)
def _render_error_template(status_code):
return render_template(
_get_template(status_code),
**main.config['BASE_TEMPLATE_DATA']
), status_code
def _get_template(status_code):
if status_code == 404:
return "errors/404.html"
else:
return "errors/500.html"
|
...
from app.main import main
from dmutils.apiclient import APIError
@main.app_errorhandler(APIError)
def api_error(e):
return _render_error_template(e.status_code)
...
def bad_request(e):
return _render_error_template(400)
...
def page_not_found(e):
return _render_error_template(404)
...
def exception(e):
return _render_error_template(500)
...
def service_unavailable(e):
return _render_error_template(503)
def _render_error_template(status_code):
return render_template(
_get_template(status_code),
**main.config['BASE_TEMPLATE_DATA']
), status_code
def _get_template(status_code):
if status_code == 404:
return "errors/404.html"
else:
return "errors/500.html"
...
|
28bf565f30a6d9b25bd6bc24ce5958a98a106161
|
mpi/__init__.py
|
mpi/__init__.py
|
from mpi4py import MPI
comm = MPI.COMM_WORLD
def get_host():
return MPI.Get_processor_name()
def get_rank():
return comm.Get_rank()
def finalize():
return MPI.Finalize()
|
from mpi4py import MPI
comm = MPI.COMM_WORLD
def get_host():
return MPI.Get_processor_name()
def get_rank():
return comm.Get_rank()
def host_rank_mapping():
"""Get host to rank mapping
Return dictionary mapping ranks to host
"""
d = {}
for (host, rank) in comm.allgather((get_host(), get_rank())):
if host not in d:
d[host] = []
d[host].append(rank)
return d
def finalize():
return MPI.Finalize()
|
Add function to get the host-rank mapping of mpi tasks
|
Add function to get the host-rank mapping of mpi tasks
|
Python
|
mit
|
IanLee1521/utilities
|
from mpi4py import MPI
comm = MPI.COMM_WORLD
def get_host():
return MPI.Get_processor_name()
def get_rank():
return comm.Get_rank()
+ def host_rank_mapping():
+ """Get host to rank mapping
+
+ Return dictionary mapping ranks to host
+ """
+ d = {}
+ for (host, rank) in comm.allgather((get_host(), get_rank())):
+ if host not in d:
+ d[host] = []
+ d[host].append(rank)
+ return d
+
+
def finalize():
return MPI.Finalize()
|
Add function to get the host-rank mapping of mpi tasks
|
## Code Before:
from mpi4py import MPI
comm = MPI.COMM_WORLD
def get_host():
return MPI.Get_processor_name()
def get_rank():
return comm.Get_rank()
def finalize():
return MPI.Finalize()
## Instruction:
Add function to get the host-rank mapping of mpi tasks
## Code After:
from mpi4py import MPI
comm = MPI.COMM_WORLD
def get_host():
return MPI.Get_processor_name()
def get_rank():
return comm.Get_rank()
def host_rank_mapping():
"""Get host to rank mapping
Return dictionary mapping ranks to host
"""
d = {}
for (host, rank) in comm.allgather((get_host(), get_rank())):
if host not in d:
d[host] = []
d[host].append(rank)
return d
def finalize():
return MPI.Finalize()
|
// ... existing code ...
def host_rank_mapping():
"""Get host to rank mapping
Return dictionary mapping ranks to host
"""
d = {}
for (host, rank) in comm.allgather((get_host(), get_rank())):
if host not in d:
d[host] = []
d[host].append(rank)
return d
def finalize():
// ... rest of the code ...
|
f6bff4e5360ba2c0379c129a111d333ee718c1d3
|
datafeeds/usfirst_event_teams_parser.py
|
datafeeds/usfirst_event_teams_parser.py
|
import re
from BeautifulSoup import BeautifulSoup
from datafeeds.parser_base import ParserBase
class UsfirstEventTeamsParser(ParserBase):
@classmethod
def parse(self, html):
"""
Find what Teams are attending an Event, and return their team_numbers.
"""
teamRe = re.compile(r'whats-going-on/team/FRC/[A-Za-z0-9=&;\-:]*?">\d+')
teamNumberRe = re.compile(r'\d+$')
tpidRe = re.compile(r'\d+')
teams = list()
for teamResult in teamRe.findall(html):
team = dict()
team["team_number"] = int(teamNumberRe.findall(teamResult)[0])
team["first_tpid"] = int(tpidRe.findall(teamResult)[0])
teams.append(team)
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)
more_pages = soup.find('a', {'title': 'Go to next page'}) is not None
return teams, more_pages
|
import re
from BeautifulSoup import BeautifulSoup
from datafeeds.parser_base import ParserBase
class UsfirstEventTeamsParser(ParserBase):
@classmethod
def parse(self, html):
"""
Find what Teams are attending an Event, and return their team_numbers.
"""
teamRe = re.compile(r'whats-going-on\/team\/(\d*)\?ProgramCode=FRC">(\d*)')
teams = list()
for first_tpid, team_number in teamRe.findall(html):
team = dict()
team["first_tpid"] = int(first_tpid)
team["team_number"] = int(team_number)
teams.append(team)
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)
more_pages = soup.find('a', {'title': 'Go to next page'}) is not None
return teams, more_pages
|
Fix event teams parser for new format
|
Fix event teams parser for new format
|
Python
|
mit
|
the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,nwalters512/the-blue-alliance,bdaroz/the-blue-alliance,1fish2/the-blue-alliance,synth3tk/the-blue-alliance,jaredhasenklein/the-blue-alliance,bdaroz/the-blue-alliance,nwalters512/the-blue-alliance,tsteward/the-blue-alliance,jaredhasenklein/the-blue-alliance,the-blue-alliance/the-blue-alliance,the-blue-alliance/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,fangeugene/the-blue-alliance,bvisness/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,synth3tk/the-blue-alliance,josephbisch/the-blue-alliance,phil-lopreiato/the-blue-alliance,nwalters512/the-blue-alliance,bdaroz/the-blue-alliance,josephbisch/the-blue-alliance,the-blue-alliance/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,bdaroz/the-blue-alliance,tsteward/the-blue-alliance,1fish2/the-blue-alliance,bvisness/the-blue-alliance,jaredhasenklein/the-blue-alliance,bvisness/the-blue-alliance,the-blue-alliance/the-blue-alliance,1fish2/the-blue-alliance,synth3tk/the-blue-alliance,tsteward/the-blue-alliance,tsteward/the-blue-alliance,1fish2/the-blue-alliance,nwalters512/the-blue-alliance,bdaroz/the-blue-alliance,1fish2/the-blue-alliance,synth3tk/the-blue-alliance,josephbisch/the-blue-alliance,bvisness/the-blue-alliance,phil-lopreiato/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,phil-lopreiato/the-blue-alliance,phil-lopreiato/the-blue-alliance,jaredhasenklein/the-blue-alliance,bvisness/the-blue-alliance,josephbisch/the-blue-alliance,verycumbersome/the-blue-alliance,josephbisch/the-blue-alliance,the-blue-alliance/the-blue-alliance,tsteward/the-blue-alliance,1fish2/the-blue-alliance,phil-lopreiato/the-blue-alliance,nwalters512/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,josephbisch/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,fangeugene/the-blue-alliance,bvisness/the-blue-alliance,phil-lopreiato/the-blue-alliance,verycumbersome/the-blue-alliance,verycumbersome/the-blue-alliance
|
import re
from BeautifulSoup import BeautifulSoup
from datafeeds.parser_base import ParserBase
class UsfirstEventTeamsParser(ParserBase):
@classmethod
def parse(self, html):
"""
Find what Teams are attending an Event, and return their team_numbers.
"""
+ teamRe = re.compile(r'whats-going-on\/team\/(\d*)\?ProgramCode=FRC">(\d*)')
- teamRe = re.compile(r'whats-going-on/team/FRC/[A-Za-z0-9=&;\-:]*?">\d+')
- teamNumberRe = re.compile(r'\d+$')
- tpidRe = re.compile(r'\d+')
teams = list()
- for teamResult in teamRe.findall(html):
+ for first_tpid, team_number in teamRe.findall(html):
team = dict()
+ team["first_tpid"] = int(first_tpid)
- team["team_number"] = int(teamNumberRe.findall(teamResult)[0])
+ team["team_number"] = int(team_number)
- team["first_tpid"] = int(tpidRe.findall(teamResult)[0])
teams.append(team)
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)
more_pages = soup.find('a', {'title': 'Go to next page'}) is not None
return teams, more_pages
|
Fix event teams parser for new format
|
## Code Before:
import re
from BeautifulSoup import BeautifulSoup
from datafeeds.parser_base import ParserBase
class UsfirstEventTeamsParser(ParserBase):
@classmethod
def parse(self, html):
"""
Find what Teams are attending an Event, and return their team_numbers.
"""
teamRe = re.compile(r'whats-going-on/team/FRC/[A-Za-z0-9=&;\-:]*?">\d+')
teamNumberRe = re.compile(r'\d+$')
tpidRe = re.compile(r'\d+')
teams = list()
for teamResult in teamRe.findall(html):
team = dict()
team["team_number"] = int(teamNumberRe.findall(teamResult)[0])
team["first_tpid"] = int(tpidRe.findall(teamResult)[0])
teams.append(team)
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)
more_pages = soup.find('a', {'title': 'Go to next page'}) is not None
return teams, more_pages
## Instruction:
Fix event teams parser for new format
## Code After:
import re
from BeautifulSoup import BeautifulSoup
from datafeeds.parser_base import ParserBase
class UsfirstEventTeamsParser(ParserBase):
@classmethod
def parse(self, html):
"""
Find what Teams are attending an Event, and return their team_numbers.
"""
teamRe = re.compile(r'whats-going-on\/team\/(\d*)\?ProgramCode=FRC">(\d*)')
teams = list()
for first_tpid, team_number in teamRe.findall(html):
team = dict()
team["first_tpid"] = int(first_tpid)
team["team_number"] = int(team_number)
teams.append(team)
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)
more_pages = soup.find('a', {'title': 'Go to next page'}) is not None
return teams, more_pages
|
...
teamRe = re.compile(r'whats-going-on\/team\/(\d*)\?ProgramCode=FRC">(\d*)')
...
teams = list()
for first_tpid, team_number in teamRe.findall(html):
team = dict()
team["first_tpid"] = int(first_tpid)
team["team_number"] = int(team_number)
teams.append(team)
...
|
2d4016d8e4245a6e85c2bbea012d13471718b1b0
|
journal/views.py
|
journal/views.py
|
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from .models import Entry
from .serializers import EntrySerializer
@method_decorator(csrf_exempt, name='dispatch')
class RestView(View):
def get(self, request):
last = request.GET.get('last', None)
if last is None:
entries = Entry.objects.all()
else:
last_entry = Entry.objects.get(uuid=last)
entries = Entry.objects.filter(id__gt=last_entry.id)
serializer = EntrySerializer(entries, many=True)
return JsonResponse({'entries': serializer.data})
@csrf_exempt
def put(self, request):
body = JSONParser().parse(request)
serializer = EntrySerializer(data=body['entries'], many=True)
if serializer.is_valid():
serializer.save()
return JsonResponse({}, status=201)
return JsonResponse(serializer.errors, status=400)
|
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from .models import Entry
from .serializers import EntrySerializer
@method_decorator(csrf_exempt, name='dispatch')
class RestView(View):
def get(self, request):
last = request.GET.get('last', None)
tag = request.GET.get('tag', None)
entries = Entry.objects.filter(tag=tag)
if last is not None:
last_entry = entries.get(uuid=last)
entries = entries.filter(id__gt=last_entry.id)
serializer = EntrySerializer(entries, many=True)
return JsonResponse({'entries': serializer.data})
@csrf_exempt
def put(self, request):
tag = request.GET.get('tag', None)
body = JSONParser().parse(request)
serializer = EntrySerializer(data=body['entries'], many=True)
if serializer.is_valid():
serializer.save(tag=tag)
return JsonResponse({}, status=201)
return JsonResponse(serializer.errors, status=400)
|
Add a way to specific tag.
|
Add a way to specific tag.
|
Python
|
agpl-3.0
|
etesync/journal-manager
|
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from .models import Entry
from .serializers import EntrySerializer
@method_decorator(csrf_exempt, name='dispatch')
class RestView(View):
def get(self, request):
last = request.GET.get('last', None)
+ tag = request.GET.get('tag', None)
+ entries = Entry.objects.filter(tag=tag)
- if last is None:
+ if last is not None:
- entries = Entry.objects.all()
- else:
- last_entry = Entry.objects.get(uuid=last)
+ last_entry = entries.get(uuid=last)
- entries = Entry.objects.filter(id__gt=last_entry.id)
+ entries = entries.filter(id__gt=last_entry.id)
serializer = EntrySerializer(entries, many=True)
return JsonResponse({'entries': serializer.data})
@csrf_exempt
def put(self, request):
+ tag = request.GET.get('tag', None)
body = JSONParser().parse(request)
serializer = EntrySerializer(data=body['entries'], many=True)
if serializer.is_valid():
- serializer.save()
+ serializer.save(tag=tag)
return JsonResponse({}, status=201)
return JsonResponse(serializer.errors, status=400)
|
Add a way to specific tag.
|
## Code Before:
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from .models import Entry
from .serializers import EntrySerializer
@method_decorator(csrf_exempt, name='dispatch')
class RestView(View):
def get(self, request):
last = request.GET.get('last', None)
if last is None:
entries = Entry.objects.all()
else:
last_entry = Entry.objects.get(uuid=last)
entries = Entry.objects.filter(id__gt=last_entry.id)
serializer = EntrySerializer(entries, many=True)
return JsonResponse({'entries': serializer.data})
@csrf_exempt
def put(self, request):
body = JSONParser().parse(request)
serializer = EntrySerializer(data=body['entries'], many=True)
if serializer.is_valid():
serializer.save()
return JsonResponse({}, status=201)
return JsonResponse(serializer.errors, status=400)
## Instruction:
Add a way to specific tag.
## Code After:
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from .models import Entry
from .serializers import EntrySerializer
@method_decorator(csrf_exempt, name='dispatch')
class RestView(View):
def get(self, request):
last = request.GET.get('last', None)
tag = request.GET.get('tag', None)
entries = Entry.objects.filter(tag=tag)
if last is not None:
last_entry = entries.get(uuid=last)
entries = entries.filter(id__gt=last_entry.id)
serializer = EntrySerializer(entries, many=True)
return JsonResponse({'entries': serializer.data})
@csrf_exempt
def put(self, request):
tag = request.GET.get('tag', None)
body = JSONParser().parse(request)
serializer = EntrySerializer(data=body['entries'], many=True)
if serializer.is_valid():
serializer.save(tag=tag)
return JsonResponse({}, status=201)
return JsonResponse(serializer.errors, status=400)
|
// ... existing code ...
last = request.GET.get('last', None)
tag = request.GET.get('tag', None)
entries = Entry.objects.filter(tag=tag)
if last is not None:
last_entry = entries.get(uuid=last)
entries = entries.filter(id__gt=last_entry.id)
// ... modified code ...
def put(self, request):
tag = request.GET.get('tag', None)
body = JSONParser().parse(request)
...
if serializer.is_valid():
serializer.save(tag=tag)
return JsonResponse({}, status=201)
// ... rest of the code ...
|
6cfc9de7fe8fd048a75845a69bdeefc7c742bae4
|
oneall/django_oneall/management/commands/emaillogin.py
|
oneall/django_oneall/management/commands/emaillogin.py
|
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from ...auth import EmailTokenAuthBackend
class Command(BaseCommand):
help = "E-mail login without sending the actual e-mail."
def add_arguments(self, parser):
parser.add_argument('email', type=str)
def handle(self, email, **options):
if '@' not in email:
self.stderr.write("Failed. E-mail is mandatory.")
return 1
query_string = EmailTokenAuthBackend().issue(email)
self.stdout.write("Complete login with: %s?%s" % (reverse('oneall-login'), query_string))
|
from django.core.mail import EmailMessage
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from ...auth import EmailTokenAuthBackend
class Command(BaseCommand):
help = "Issues an e-mail login token."
def add_arguments(self, parser):
parser.add_argument('-s', '--send', dest='send', action='store_true',
help="Actually e-mail the token instead of only displaying it.")
parser.add_argument('email', type=str)
def handle(self, email, send, **options):
if '@' not in email:
self.stderr.write("Failed. E-mail is mandatory.")
return
query_string = EmailTokenAuthBackend().issue(email)
msg = "Complete login with: %s?%s" % (reverse('oneall-login'), query_string)
self.stdout.write(msg)
if send:
mail = EmailMessage()
mail.to = [email]
mail.subject = 'Login Test'
mail.body = msg
try:
sent = mail.send()
self.stdout.write("Sent %d message." % sent)
except ConnectionError as e:
self.stderr.write(str(e))
|
Add the possibility of testing SMTP from the command-line.
|
Add the possibility of testing SMTP from the command-line.
|
Python
|
mit
|
leandigo/django-oneall,ckot/django-oneall,leandigo/django-oneall,ckot/django-oneall
|
+ from django.core.mail import EmailMessage
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from ...auth import EmailTokenAuthBackend
class Command(BaseCommand):
- help = "E-mail login without sending the actual e-mail."
+ help = "Issues an e-mail login token."
def add_arguments(self, parser):
+ parser.add_argument('-s', '--send', dest='send', action='store_true',
+ help="Actually e-mail the token instead of only displaying it.")
parser.add_argument('email', type=str)
- def handle(self, email, **options):
+ def handle(self, email, send, **options):
if '@' not in email:
self.stderr.write("Failed. E-mail is mandatory.")
- return 1
+ return
query_string = EmailTokenAuthBackend().issue(email)
- self.stdout.write("Complete login with: %s?%s" % (reverse('oneall-login'), query_string))
+ msg = "Complete login with: %s?%s" % (reverse('oneall-login'), query_string)
+ self.stdout.write(msg)
+ if send:
+ mail = EmailMessage()
+ mail.to = [email]
+ mail.subject = 'Login Test'
+ mail.body = msg
+ try:
+ sent = mail.send()
+ self.stdout.write("Sent %d message." % sent)
+ except ConnectionError as e:
+ self.stderr.write(str(e))
|
Add the possibility of testing SMTP from the command-line.
|
## Code Before:
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from ...auth import EmailTokenAuthBackend
class Command(BaseCommand):
help = "E-mail login without sending the actual e-mail."
def add_arguments(self, parser):
parser.add_argument('email', type=str)
def handle(self, email, **options):
if '@' not in email:
self.stderr.write("Failed. E-mail is mandatory.")
return 1
query_string = EmailTokenAuthBackend().issue(email)
self.stdout.write("Complete login with: %s?%s" % (reverse('oneall-login'), query_string))
## Instruction:
Add the possibility of testing SMTP from the command-line.
## Code After:
from django.core.mail import EmailMessage
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from ...auth import EmailTokenAuthBackend
class Command(BaseCommand):
help = "Issues an e-mail login token."
def add_arguments(self, parser):
parser.add_argument('-s', '--send', dest='send', action='store_true',
help="Actually e-mail the token instead of only displaying it.")
parser.add_argument('email', type=str)
def handle(self, email, send, **options):
if '@' not in email:
self.stderr.write("Failed. E-mail is mandatory.")
return
query_string = EmailTokenAuthBackend().issue(email)
msg = "Complete login with: %s?%s" % (reverse('oneall-login'), query_string)
self.stdout.write(msg)
if send:
mail = EmailMessage()
mail.to = [email]
mail.subject = 'Login Test'
mail.body = msg
try:
sent = mail.send()
self.stdout.write("Sent %d message." % sent)
except ConnectionError as e:
self.stderr.write(str(e))
|
// ... existing code ...
from django.core.mail import EmailMessage
from django.core.management.base import BaseCommand
// ... modified code ...
class Command(BaseCommand):
help = "Issues an e-mail login token."
...
def add_arguments(self, parser):
parser.add_argument('-s', '--send', dest='send', action='store_true',
help="Actually e-mail the token instead of only displaying it.")
parser.add_argument('email', type=str)
...
def handle(self, email, send, **options):
if '@' not in email:
...
self.stderr.write("Failed. E-mail is mandatory.")
return
query_string = EmailTokenAuthBackend().issue(email)
msg = "Complete login with: %s?%s" % (reverse('oneall-login'), query_string)
self.stdout.write(msg)
if send:
mail = EmailMessage()
mail.to = [email]
mail.subject = 'Login Test'
mail.body = msg
try:
sent = mail.send()
self.stdout.write("Sent %d message." % sent)
except ConnectionError as e:
self.stderr.write(str(e))
// ... rest of the code ...
|
807e1315c2abb6c493eca575f478ce7b69173d6f
|
pajbot/eventloop.py
|
pajbot/eventloop.py
|
import logging
from irc.schedule import IScheduler
from tempora import schedule
from tempora.schedule import Scheduler
log = logging.getLogger(__name__)
# same as InvokeScheduler from the original implementation,
# but with the extra try-catch
class SafeInvokeScheduler(Scheduler):
"""
Command targets are functions to be invoked on schedule.
"""
def run(self, command):
try:
command.target()
except Exception:
# we do "exception Exception" to not catch KeyboardInterrupt and SystemExit
# (so the bot can properly quit)
log.exception("Logging an uncaught exception (main thread)")
# same as DefaultScheduler from the original implementation,
# but extends SafeInvokeScheduler instead
class SafeDefaultScheduler(SafeInvokeScheduler, IScheduler):
def execute_every(self, period, func):
self.add(schedule.PeriodicCommand.after(period, func))
def execute_at(self, when, func):
self.add(schedule.DelayedCommand.at_time(when, func))
def execute_after(self, delay, func):
self.add(schedule.DelayedCommand.after(delay, func))
|
import logging
from irc.schedule import IScheduler
from tempora import schedule
from tempora.schedule import Scheduler
log = logging.getLogger(__name__)
# same as InvokeScheduler from the original implementation,
# but with the extra try-catch
class SafeInvokeScheduler(Scheduler):
"""
Command targets are functions to be invoked on schedule.
"""
def run(self, command):
try:
command.target()
except Exception:
# we do "except Exception" to not catch KeyboardInterrupt and SystemExit (so the bot can properly quit)
log.exception("Logging an uncaught exception (main thread)")
# same as DefaultScheduler from the original implementation,
# but extends SafeInvokeScheduler instead
class SafeDefaultScheduler(SafeInvokeScheduler, IScheduler):
def execute_every(self, period, func):
self.add(schedule.PeriodicCommand.after(period, func))
def execute_at(self, when, func):
self.add(schedule.DelayedCommand.at_time(when, func))
def execute_after(self, delay, func):
self.add(schedule.DelayedCommand.after(delay, func))
|
Update comment to be a bit more helpful
|
Update comment to be a bit more helpful
|
Python
|
mit
|
pajlada/tyggbot,pajlada/tyggbot,pajlada/pajbot,pajlada/pajbot,pajlada/pajbot,pajlada/tyggbot,pajlada/tyggbot,pajlada/pajbot
|
import logging
from irc.schedule import IScheduler
from tempora import schedule
from tempora.schedule import Scheduler
log = logging.getLogger(__name__)
# same as InvokeScheduler from the original implementation,
# but with the extra try-catch
class SafeInvokeScheduler(Scheduler):
"""
Command targets are functions to be invoked on schedule.
"""
def run(self, command):
try:
command.target()
except Exception:
- # we do "exception Exception" to not catch KeyboardInterrupt and SystemExit
+ # we do "except Exception" to not catch KeyboardInterrupt and SystemExit (so the bot can properly quit)
- # (so the bot can properly quit)
log.exception("Logging an uncaught exception (main thread)")
# same as DefaultScheduler from the original implementation,
# but extends SafeInvokeScheduler instead
class SafeDefaultScheduler(SafeInvokeScheduler, IScheduler):
def execute_every(self, period, func):
self.add(schedule.PeriodicCommand.after(period, func))
def execute_at(self, when, func):
self.add(schedule.DelayedCommand.at_time(when, func))
def execute_after(self, delay, func):
self.add(schedule.DelayedCommand.after(delay, func))
|
Update comment to be a bit more helpful
|
## Code Before:
import logging
from irc.schedule import IScheduler
from tempora import schedule
from tempora.schedule import Scheduler
log = logging.getLogger(__name__)
# same as InvokeScheduler from the original implementation,
# but with the extra try-catch
class SafeInvokeScheduler(Scheduler):
"""
Command targets are functions to be invoked on schedule.
"""
def run(self, command):
try:
command.target()
except Exception:
# we do "exception Exception" to not catch KeyboardInterrupt and SystemExit
# (so the bot can properly quit)
log.exception("Logging an uncaught exception (main thread)")
# same as DefaultScheduler from the original implementation,
# but extends SafeInvokeScheduler instead
class SafeDefaultScheduler(SafeInvokeScheduler, IScheduler):
def execute_every(self, period, func):
self.add(schedule.PeriodicCommand.after(period, func))
def execute_at(self, when, func):
self.add(schedule.DelayedCommand.at_time(when, func))
def execute_after(self, delay, func):
self.add(schedule.DelayedCommand.after(delay, func))
## Instruction:
Update comment to be a bit more helpful
## Code After:
import logging
from irc.schedule import IScheduler
from tempora import schedule
from tempora.schedule import Scheduler
log = logging.getLogger(__name__)
# same as InvokeScheduler from the original implementation,
# but with the extra try-catch
class SafeInvokeScheduler(Scheduler):
"""
Command targets are functions to be invoked on schedule.
"""
def run(self, command):
try:
command.target()
except Exception:
# we do "except Exception" to not catch KeyboardInterrupt and SystemExit (so the bot can properly quit)
log.exception("Logging an uncaught exception (main thread)")
# same as DefaultScheduler from the original implementation,
# but extends SafeInvokeScheduler instead
class SafeDefaultScheduler(SafeInvokeScheduler, IScheduler):
def execute_every(self, period, func):
self.add(schedule.PeriodicCommand.after(period, func))
def execute_at(self, when, func):
self.add(schedule.DelayedCommand.at_time(when, func))
def execute_after(self, delay, func):
self.add(schedule.DelayedCommand.after(delay, func))
|
...
except Exception:
# we do "except Exception" to not catch KeyboardInterrupt and SystemExit (so the bot can properly quit)
log.exception("Logging an uncaught exception (main thread)")
...
|
1e8cc5743f32bb5f6e2e9bcbee0f78e3df357449
|
tests/test_fastpbkdf2.py
|
tests/test_fastpbkdf2.py
|
import pytest
from fastpbkdf2 import pbkdf2_hmac
def test_unsupported_algorithm():
with pytest.raises(ValueError):
pbkdf2_hmac("foo", b"password", b"salt", 1)
|
import binascii
import pytest
from fastpbkdf2 import pbkdf2_hmac
def test_unsupported_algorithm():
with pytest.raises(ValueError):
pbkdf2_hmac("foo", b"password", b"salt", 1)
@pytest.mark.parametrize("password,salt,iterations,length,derived_key", [
(b"password", b"salt",
1, 20, b"0c60c80f961f0e71f3a9b524af6012062fe037a6"),
(b"password", b"salt",
2, 20, b"ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"),
(b"password", b"salt",
4096, 20, b"4b007901b765489abead49d926f721d065a429c1"),
(b"password", b"salt",
16777216, 20, b"eefe3d61cd4da4e4e9945b3d6ba2158c2634e984"),
(b"passwordPASSWORDpassword", b"saltSALTsaltSALTsaltSALTsaltSALTsalt",
4096, 25, b"3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038"),
(b"pass\0word", b"sa\0lt",
4096, 16, b"56fa6aa75548099dcc37d7f03425e0c3"),
])
def test_with_vectors(password, salt, iterations, length, derived_key):
assert binascii.hexlify(
pbkdf2_hmac("sha1", password, salt, iterations, length)
) == derived_key
|
Add test for RFC 6070 vectors.
|
Add test for RFC 6070 vectors.
|
Python
|
apache-2.0
|
Ayrx/python-fastpbkdf2,Ayrx/python-fastpbkdf2
|
+ import binascii
+
import pytest
from fastpbkdf2 import pbkdf2_hmac
def test_unsupported_algorithm():
with pytest.raises(ValueError):
pbkdf2_hmac("foo", b"password", b"salt", 1)
+
+ @pytest.mark.parametrize("password,salt,iterations,length,derived_key", [
+ (b"password", b"salt",
+ 1, 20, b"0c60c80f961f0e71f3a9b524af6012062fe037a6"),
+ (b"password", b"salt",
+ 2, 20, b"ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"),
+ (b"password", b"salt",
+ 4096, 20, b"4b007901b765489abead49d926f721d065a429c1"),
+ (b"password", b"salt",
+ 16777216, 20, b"eefe3d61cd4da4e4e9945b3d6ba2158c2634e984"),
+ (b"passwordPASSWORDpassword", b"saltSALTsaltSALTsaltSALTsaltSALTsalt",
+ 4096, 25, b"3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038"),
+ (b"pass\0word", b"sa\0lt",
+ 4096, 16, b"56fa6aa75548099dcc37d7f03425e0c3"),
+ ])
+ def test_with_vectors(password, salt, iterations, length, derived_key):
+ assert binascii.hexlify(
+ pbkdf2_hmac("sha1", password, salt, iterations, length)
+ ) == derived_key
+
|
Add test for RFC 6070 vectors.
|
## Code Before:
import pytest
from fastpbkdf2 import pbkdf2_hmac
def test_unsupported_algorithm():
with pytest.raises(ValueError):
pbkdf2_hmac("foo", b"password", b"salt", 1)
## Instruction:
Add test for RFC 6070 vectors.
## Code After:
import binascii
import pytest
from fastpbkdf2 import pbkdf2_hmac
def test_unsupported_algorithm():
with pytest.raises(ValueError):
pbkdf2_hmac("foo", b"password", b"salt", 1)
@pytest.mark.parametrize("password,salt,iterations,length,derived_key", [
(b"password", b"salt",
1, 20, b"0c60c80f961f0e71f3a9b524af6012062fe037a6"),
(b"password", b"salt",
2, 20, b"ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"),
(b"password", b"salt",
4096, 20, b"4b007901b765489abead49d926f721d065a429c1"),
(b"password", b"salt",
16777216, 20, b"eefe3d61cd4da4e4e9945b3d6ba2158c2634e984"),
(b"passwordPASSWORDpassword", b"saltSALTsaltSALTsaltSALTsaltSALTsalt",
4096, 25, b"3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038"),
(b"pass\0word", b"sa\0lt",
4096, 16, b"56fa6aa75548099dcc37d7f03425e0c3"),
])
def test_with_vectors(password, salt, iterations, length, derived_key):
assert binascii.hexlify(
pbkdf2_hmac("sha1", password, salt, iterations, length)
) == derived_key
|
// ... existing code ...
import binascii
import pytest
// ... modified code ...
pbkdf2_hmac("foo", b"password", b"salt", 1)
@pytest.mark.parametrize("password,salt,iterations,length,derived_key", [
(b"password", b"salt",
1, 20, b"0c60c80f961f0e71f3a9b524af6012062fe037a6"),
(b"password", b"salt",
2, 20, b"ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"),
(b"password", b"salt",
4096, 20, b"4b007901b765489abead49d926f721d065a429c1"),
(b"password", b"salt",
16777216, 20, b"eefe3d61cd4da4e4e9945b3d6ba2158c2634e984"),
(b"passwordPASSWORDpassword", b"saltSALTsaltSALTsaltSALTsaltSALTsalt",
4096, 25, b"3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038"),
(b"pass\0word", b"sa\0lt",
4096, 16, b"56fa6aa75548099dcc37d7f03425e0c3"),
])
def test_with_vectors(password, salt, iterations, length, derived_key):
assert binascii.hexlify(
pbkdf2_hmac("sha1", password, salt, iterations, length)
) == derived_key
// ... rest of the code ...
|
1838a160221859a40d208bc95352b105c53edb5f
|
partner_communication_switzerland/models/res_users.py
|
partner_communication_switzerland/models/res_users.py
|
import logging
from odoo import api, models
_logger = logging.getLogger(__name__)
class ResUsers(models.Model):
_inherit = 'res.users'
@api.multi
def action_reset_password(self):
create_mode = bool(self.env.context.get('create_user'))
# Only override the rest behavior, not normal signup
if create_mode:
super(ResUsers, self).action_reset_password()
else:
config = self.env.ref(
'partner_communication_switzerland.reset_password_email')
for user in self:
self.env['partner.communication.job'].create({
'partner_id': user.partner_id.id,
'config_id': config.id
})
@api.multi
def _compute_signature_letter(self):
""" Translate country in Signature (for Compassion Switzerland) """
for user in self:
employee = user.employee_ids
signature = ''
if len(employee) == 1:
signature += employee.name + '<br/>'
if employee.department_id:
signature += employee.department_id.name + '<br/>'
signature += user.company_id.name.split(' ')[0] + ' '
signature += user.company_id.country_id.name
user.signature_letter = signature
|
import logging
from odoo import api, models
from odoo.addons.auth_signup.models.res_partner import now
_logger = logging.getLogger(__name__)
class ResUsers(models.Model):
_inherit = 'res.users'
@api.multi
def action_reset_password(self):
create_mode = bool(self.env.context.get('create_user'))
# Only override the rest behavior, not normal signup
if create_mode:
super(ResUsers, self).action_reset_password()
else:
expiration = now(days=+1)
self.mapped('partner_id').signup_prepare(
signup_type="reset", expiration=expiration)
config = self.env.ref(
'partner_communication_switzerland.reset_password_email')
for user in self:
self.env['partner.communication.job'].create({
'partner_id': user.partner_id.id,
'config_id': config.id
})
@api.multi
def _compute_signature_letter(self):
""" Translate country in Signature (for Compassion Switzerland) """
for user in self:
employee = user.employee_ids
signature = ''
if len(employee) == 1:
signature += employee.name + '<br/>'
if employee.department_id:
signature += employee.department_id.name + '<br/>'
signature += user.company_id.name.split(' ')[0] + ' '
signature += user.company_id.country_id.name
user.signature_letter = signature
|
FIX password reset method that was not resetting the password
|
FIX password reset method that was not resetting the password
|
Python
|
agpl-3.0
|
CompassionCH/compassion-switzerland,ecino/compassion-switzerland,CompassionCH/compassion-switzerland,ecino/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,ecino/compassion-switzerland,CompassionCH/compassion-switzerland
|
import logging
from odoo import api, models
+
+ from odoo.addons.auth_signup.models.res_partner import now
_logger = logging.getLogger(__name__)
class ResUsers(models.Model):
_inherit = 'res.users'
@api.multi
def action_reset_password(self):
create_mode = bool(self.env.context.get('create_user'))
# Only override the rest behavior, not normal signup
if create_mode:
super(ResUsers, self).action_reset_password()
else:
+ expiration = now(days=+1)
+ self.mapped('partner_id').signup_prepare(
+ signup_type="reset", expiration=expiration)
config = self.env.ref(
'partner_communication_switzerland.reset_password_email')
for user in self:
self.env['partner.communication.job'].create({
'partner_id': user.partner_id.id,
'config_id': config.id
})
@api.multi
def _compute_signature_letter(self):
""" Translate country in Signature (for Compassion Switzerland) """
for user in self:
employee = user.employee_ids
signature = ''
if len(employee) == 1:
signature += employee.name + '<br/>'
if employee.department_id:
signature += employee.department_id.name + '<br/>'
signature += user.company_id.name.split(' ')[0] + ' '
signature += user.company_id.country_id.name
user.signature_letter = signature
|
FIX password reset method that was not resetting the password
|
## Code Before:
import logging
from odoo import api, models
_logger = logging.getLogger(__name__)
class ResUsers(models.Model):
_inherit = 'res.users'
@api.multi
def action_reset_password(self):
create_mode = bool(self.env.context.get('create_user'))
# Only override the rest behavior, not normal signup
if create_mode:
super(ResUsers, self).action_reset_password()
else:
config = self.env.ref(
'partner_communication_switzerland.reset_password_email')
for user in self:
self.env['partner.communication.job'].create({
'partner_id': user.partner_id.id,
'config_id': config.id
})
@api.multi
def _compute_signature_letter(self):
""" Translate country in Signature (for Compassion Switzerland) """
for user in self:
employee = user.employee_ids
signature = ''
if len(employee) == 1:
signature += employee.name + '<br/>'
if employee.department_id:
signature += employee.department_id.name + '<br/>'
signature += user.company_id.name.split(' ')[0] + ' '
signature += user.company_id.country_id.name
user.signature_letter = signature
## Instruction:
FIX password reset method that was not resetting the password
## Code After:
import logging
from odoo import api, models
from odoo.addons.auth_signup.models.res_partner import now
_logger = logging.getLogger(__name__)
class ResUsers(models.Model):
_inherit = 'res.users'
@api.multi
def action_reset_password(self):
create_mode = bool(self.env.context.get('create_user'))
# Only override the rest behavior, not normal signup
if create_mode:
super(ResUsers, self).action_reset_password()
else:
expiration = now(days=+1)
self.mapped('partner_id').signup_prepare(
signup_type="reset", expiration=expiration)
config = self.env.ref(
'partner_communication_switzerland.reset_password_email')
for user in self:
self.env['partner.communication.job'].create({
'partner_id': user.partner_id.id,
'config_id': config.id
})
@api.multi
def _compute_signature_letter(self):
""" Translate country in Signature (for Compassion Switzerland) """
for user in self:
employee = user.employee_ids
signature = ''
if len(employee) == 1:
signature += employee.name + '<br/>'
if employee.department_id:
signature += employee.department_id.name + '<br/>'
signature += user.company_id.name.split(' ')[0] + ' '
signature += user.company_id.country_id.name
user.signature_letter = signature
|
// ... existing code ...
from odoo import api, models
from odoo.addons.auth_signup.models.res_partner import now
// ... modified code ...
else:
expiration = now(days=+1)
self.mapped('partner_id').signup_prepare(
signup_type="reset", expiration=expiration)
config = self.env.ref(
// ... rest of the code ...
|
3d1dba15097ac8b746c138b75fe1763aa4b8ac12
|
footballseason/urls.py
|
footballseason/urls.py
|
from django.conf.urls import url
from . import views
urlpatterns = [
# eg: /footballseason/
url(r'^$', views.index, name='index'),
# eg: /footballseason/3
url(r'^(?P<week_id>[0-9]+)/$', views.display, name='display'),
# eg: /footballseason/3/submit
url(r'^(?P<week_id>[0-9]+)/submit$', views.submit, name='submit'),
# eg: /footballseason/3/vote
url(r'^(?P<week_id>[0-9]+)/vote$', views.vote, name='vote'),
# eg: /footballseason/update
url(r'^update$', views.update, name='update'),
# eg: /footballseason/records
url(r'^records$', views.records_default, name='records_default'),
# eg: /footballseason/records/2015
url(r'^records/(?P<season>[0-9]+)$', views.records_by_season, name='records_by_season'),
# eg: /footballseason/records/2015/3
url(r'^records/(?P<season>[0-9]+)/(?P<week>[0-9]+)$', views.records_by_week, name='records_by_week'),
]
|
from django.conf.urls import url
from . import views
urlpatterns = [
# eg: /footballseason/
url(r'^$', views.index, name='index'),
# eg: /footballseason/3/
url(r'^(?P<week_id>[0-9]+)/$', views.display, name='display'),
# eg: /footballseason/3/submit/
url(r'^(?P<week_id>[0-9]+)/submit/$', views.submit, name='submit'),
# eg: /footballseason/3/vote/
url(r'^(?P<week_id>[0-9]+)/vote/$', views.vote, name='vote'),
# eg: /footballseason/update/
url(r'^update/$', views.update, name='update'),
# eg: /footballseason/records/
url(r'^records/$', views.records_default, name='records_default'),
# eg: /footballseason/records/2015/
url(r'^records/(?P<season>[0-9]+)/$', views.records_by_season, name='records_by_season'),
# eg: /footballseason/records/2015/3/
url(r'^records/(?P<season>[0-9]+)/(?P<week>[0-9]+)/$', views.records_by_week, name='records_by_week'),
]
|
Fix URLs so APPEND_SLASH works
|
Fix URLs so APPEND_SLASH works
|
Python
|
mit
|
mkokotovich/footballpicks,mkokotovich/footballpicks,mkokotovich/footballpicks,mkokotovich/footballpicks
|
from django.conf.urls import url
from . import views
urlpatterns = [
# eg: /footballseason/
url(r'^$', views.index, name='index'),
- # eg: /footballseason/3
+ # eg: /footballseason/3/
url(r'^(?P<week_id>[0-9]+)/$', views.display, name='display'),
- # eg: /footballseason/3/submit
+ # eg: /footballseason/3/submit/
- url(r'^(?P<week_id>[0-9]+)/submit$', views.submit, name='submit'),
+ url(r'^(?P<week_id>[0-9]+)/submit/$', views.submit, name='submit'),
- # eg: /footballseason/3/vote
+ # eg: /footballseason/3/vote/
- url(r'^(?P<week_id>[0-9]+)/vote$', views.vote, name='vote'),
+ url(r'^(?P<week_id>[0-9]+)/vote/$', views.vote, name='vote'),
- # eg: /footballseason/update
+ # eg: /footballseason/update/
- url(r'^update$', views.update, name='update'),
+ url(r'^update/$', views.update, name='update'),
- # eg: /footballseason/records
+ # eg: /footballseason/records/
- url(r'^records$', views.records_default, name='records_default'),
+ url(r'^records/$', views.records_default, name='records_default'),
- # eg: /footballseason/records/2015
+ # eg: /footballseason/records/2015/
- url(r'^records/(?P<season>[0-9]+)$', views.records_by_season, name='records_by_season'),
+ url(r'^records/(?P<season>[0-9]+)/$', views.records_by_season, name='records_by_season'),
- # eg: /footballseason/records/2015/3
+ # eg: /footballseason/records/2015/3/
- url(r'^records/(?P<season>[0-9]+)/(?P<week>[0-9]+)$', views.records_by_week, name='records_by_week'),
+ url(r'^records/(?P<season>[0-9]+)/(?P<week>[0-9]+)/$', views.records_by_week, name='records_by_week'),
]
|
Fix URLs so APPEND_SLASH works
|
## Code Before:
from django.conf.urls import url
from . import views
urlpatterns = [
# eg: /footballseason/
url(r'^$', views.index, name='index'),
# eg: /footballseason/3
url(r'^(?P<week_id>[0-9]+)/$', views.display, name='display'),
# eg: /footballseason/3/submit
url(r'^(?P<week_id>[0-9]+)/submit$', views.submit, name='submit'),
# eg: /footballseason/3/vote
url(r'^(?P<week_id>[0-9]+)/vote$', views.vote, name='vote'),
# eg: /footballseason/update
url(r'^update$', views.update, name='update'),
# eg: /footballseason/records
url(r'^records$', views.records_default, name='records_default'),
# eg: /footballseason/records/2015
url(r'^records/(?P<season>[0-9]+)$', views.records_by_season, name='records_by_season'),
# eg: /footballseason/records/2015/3
url(r'^records/(?P<season>[0-9]+)/(?P<week>[0-9]+)$', views.records_by_week, name='records_by_week'),
]
## Instruction:
Fix URLs so APPEND_SLASH works
## Code After:
from django.conf.urls import url
from . import views
urlpatterns = [
# eg: /footballseason/
url(r'^$', views.index, name='index'),
# eg: /footballseason/3/
url(r'^(?P<week_id>[0-9]+)/$', views.display, name='display'),
# eg: /footballseason/3/submit/
url(r'^(?P<week_id>[0-9]+)/submit/$', views.submit, name='submit'),
# eg: /footballseason/3/vote/
url(r'^(?P<week_id>[0-9]+)/vote/$', views.vote, name='vote'),
# eg: /footballseason/update/
url(r'^update/$', views.update, name='update'),
# eg: /footballseason/records/
url(r'^records/$', views.records_default, name='records_default'),
# eg: /footballseason/records/2015/
url(r'^records/(?P<season>[0-9]+)/$', views.records_by_season, name='records_by_season'),
# eg: /footballseason/records/2015/3/
url(r'^records/(?P<season>[0-9]+)/(?P<week>[0-9]+)/$', views.records_by_week, name='records_by_week'),
]
|
// ... existing code ...
# eg: /footballseason/3/
url(r'^(?P<week_id>[0-9]+)/$', views.display, name='display'),
// ... modified code ...
# eg: /footballseason/3/submit/
url(r'^(?P<week_id>[0-9]+)/submit/$', views.submit, name='submit'),
# eg: /footballseason/3/vote/
url(r'^(?P<week_id>[0-9]+)/vote/$', views.vote, name='vote'),
# eg: /footballseason/update/
url(r'^update/$', views.update, name='update'),
# eg: /footballseason/records/
url(r'^records/$', views.records_default, name='records_default'),
# eg: /footballseason/records/2015/
url(r'^records/(?P<season>[0-9]+)/$', views.records_by_season, name='records_by_season'),
# eg: /footballseason/records/2015/3/
url(r'^records/(?P<season>[0-9]+)/(?P<week>[0-9]+)/$', views.records_by_week, name='records_by_week'),
]
// ... rest of the code ...
|
0d8cd57b6d5d4755709ca853856eb14b4b63f437
|
servant.py
|
servant.py
|
import os
import sys
import zipfile
from nose import core as nose_core
if sys.argv[1] == "remove_extension":
try:
os.remove("coverage/tracer.so")
except OSError:
pass
elif sys.argv[1] == "test_with_tracer":
os.environ["COVERAGE_TEST_TRACER"] = sys.argv[2]
del sys.argv[1:3]
nose_core.main()
elif sys.argv[1] == "zip_mods":
zipfile.ZipFile("test/zipmods.zip", "w").write("test/covmodzip1.py", "covmodzip1.py")
|
import os
import sys
import zipfile
from nose import core as nose_core
if sys.argv[1] == "remove_extension":
so_names = """
tracer.so
tracer.cpython-32m.so
""".split()
for filename in so_names:
try:
os.remove(os.path.join("coverage", filename))
except OSError:
pass
elif sys.argv[1] == "test_with_tracer":
os.environ["COVERAGE_TEST_TRACER"] = sys.argv[2]
del sys.argv[1:3]
nose_core.main()
elif sys.argv[1] == "zip_mods":
zipfile.ZipFile("test/zipmods.zip", "w").write("test/covmodzip1.py", "covmodzip1.py")
|
Make tox with with py3.2: the .so is named differently there.
|
Make tox with with py3.2: the .so is named differently there.
|
Python
|
apache-2.0
|
nedbat/coveragepy,nedbat/coveragepy,larsbutler/coveragepy,larsbutler/coveragepy,blueyed/coveragepy,blueyed/coveragepy,hugovk/coveragepy,7WebPages/coveragepy,larsbutler/coveragepy,nedbat/coveragepy,hugovk/coveragepy,7WebPages/coveragepy,jayhetee/coveragepy,larsbutler/coveragepy,nedbat/coveragepy,jayhetee/coveragepy,hugovk/coveragepy,jayhetee/coveragepy,hugovk/coveragepy,blueyed/coveragepy,7WebPages/coveragepy,7WebPages/coveragepy,blueyed/coveragepy,larsbutler/coveragepy,hugovk/coveragepy,jayhetee/coveragepy,jayhetee/coveragepy,blueyed/coveragepy,nedbat/coveragepy
|
import os
import sys
import zipfile
from nose import core as nose_core
if sys.argv[1] == "remove_extension":
+ so_names = """
+ tracer.so
+ tracer.cpython-32m.so
+ """.split()
+
+ for filename in so_names:
- try:
+ try:
- os.remove("coverage/tracer.so")
+ os.remove(os.path.join("coverage", filename))
- except OSError:
+ except OSError:
- pass
+ pass
elif sys.argv[1] == "test_with_tracer":
os.environ["COVERAGE_TEST_TRACER"] = sys.argv[2]
del sys.argv[1:3]
nose_core.main()
elif sys.argv[1] == "zip_mods":
zipfile.ZipFile("test/zipmods.zip", "w").write("test/covmodzip1.py", "covmodzip1.py")
|
Make tox with with py3.2: the .so is named differently there.
|
## Code Before:
import os
import sys
import zipfile
from nose import core as nose_core
if sys.argv[1] == "remove_extension":
try:
os.remove("coverage/tracer.so")
except OSError:
pass
elif sys.argv[1] == "test_with_tracer":
os.environ["COVERAGE_TEST_TRACER"] = sys.argv[2]
del sys.argv[1:3]
nose_core.main()
elif sys.argv[1] == "zip_mods":
zipfile.ZipFile("test/zipmods.zip", "w").write("test/covmodzip1.py", "covmodzip1.py")
## Instruction:
Make tox with with py3.2: the .so is named differently there.
## Code After:
import os
import sys
import zipfile
from nose import core as nose_core
if sys.argv[1] == "remove_extension":
so_names = """
tracer.so
tracer.cpython-32m.so
""".split()
for filename in so_names:
try:
os.remove(os.path.join("coverage", filename))
except OSError:
pass
elif sys.argv[1] == "test_with_tracer":
os.environ["COVERAGE_TEST_TRACER"] = sys.argv[2]
del sys.argv[1:3]
nose_core.main()
elif sys.argv[1] == "zip_mods":
zipfile.ZipFile("test/zipmods.zip", "w").write("test/covmodzip1.py", "covmodzip1.py")
|
# ... existing code ...
if sys.argv[1] == "remove_extension":
so_names = """
tracer.so
tracer.cpython-32m.so
""".split()
for filename in so_names:
try:
os.remove(os.path.join("coverage", filename))
except OSError:
pass
# ... rest of the code ...
|
25e4730c4614a26cdecd60eb0846e69578353d2c
|
tomcrypt/__init__.py
|
tomcrypt/__init__.py
|
import os
import ctypes
# We need to manually load the _core SO the first time so that we can specify
# that it use the RTLD_GLOBAL flag. Otherwise (when not on a Mac) the runtime
# linker will not be able to resolve undefined symbols in the other modules.
_core_handle = ctypes.CDLL(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '_core.so'),
ctypes.RTLD_GLOBAL
)
class Error(ValueError):
def __init__(self, *args, **kwargs):
self.code = kwargs.get('code', -1)
ValueError.__init__(self, *args)
class LibError(Error):
pass
|
import ctypes
class Error(ValueError):
def __init__(self, *args, **kwargs):
self.code = kwargs.get('code', -1)
ValueError.__init__(self, *args)
class LibError(Error):
pass
# We need to manually load the _core the first time so that we can specify
# that it use the RTLD_GLOBAL flag. Otherwise (when not on a Mac) the runtime
# linker will not be able to resolve undefined symbols in the other modules.
# This must also be done after the above exceptions are defined so that they
# are availible to the core.
from . import _core
ctypes.PyDLL(_core.__file__, mode=ctypes.RTLD_GLOBAL)
|
Use import to locate _core
|
Linking: Use import to locate _core
Related to #8
|
Python
|
bsd-3-clause
|
mikeboers/PyTomCrypt,mikeboers/PyTomCrypt,mikeboers/PyTomCrypt
|
- import os
import ctypes
-
- # We need to manually load the _core SO the first time so that we can specify
- # that it use the RTLD_GLOBAL flag. Otherwise (when not on a Mac) the runtime
- # linker will not be able to resolve undefined symbols in the other modules.
- _core_handle = ctypes.CDLL(
- os.path.join(os.path.dirname(os.path.abspath(__file__)), '_core.so'),
- ctypes.RTLD_GLOBAL
- )
class Error(ValueError):
def __init__(self, *args, **kwargs):
self.code = kwargs.get('code', -1)
ValueError.__init__(self, *args)
class LibError(Error):
pass
+ # We need to manually load the _core the first time so that we can specify
+ # that it use the RTLD_GLOBAL flag. Otherwise (when not on a Mac) the runtime
+ # linker will not be able to resolve undefined symbols in the other modules.
+ # This must also be done after the above exceptions are defined so that they
+ # are availible to the core.
+ from . import _core
+ ctypes.PyDLL(_core.__file__, mode=ctypes.RTLD_GLOBAL)
+
|
Use import to locate _core
|
## Code Before:
import os
import ctypes
# We need to manually load the _core SO the first time so that we can specify
# that it use the RTLD_GLOBAL flag. Otherwise (when not on a Mac) the runtime
# linker will not be able to resolve undefined symbols in the other modules.
_core_handle = ctypes.CDLL(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '_core.so'),
ctypes.RTLD_GLOBAL
)
class Error(ValueError):
def __init__(self, *args, **kwargs):
self.code = kwargs.get('code', -1)
ValueError.__init__(self, *args)
class LibError(Error):
pass
## Instruction:
Use import to locate _core
## Code After:
import ctypes
class Error(ValueError):
def __init__(self, *args, **kwargs):
self.code = kwargs.get('code', -1)
ValueError.__init__(self, *args)
class LibError(Error):
pass
# We need to manually load the _core the first time so that we can specify
# that it use the RTLD_GLOBAL flag. Otherwise (when not on a Mac) the runtime
# linker will not be able to resolve undefined symbols in the other modules.
# This must also be done after the above exceptions are defined so that they
# are availible to the core.
from . import _core
ctypes.PyDLL(_core.__file__, mode=ctypes.RTLD_GLOBAL)
|
// ... existing code ...
import ctypes
// ... modified code ...
# We need to manually load the _core the first time so that we can specify
# that it use the RTLD_GLOBAL flag. Otherwise (when not on a Mac) the runtime
# linker will not be able to resolve undefined symbols in the other modules.
# This must also be done after the above exceptions are defined so that they
# are availible to the core.
from . import _core
ctypes.PyDLL(_core.__file__, mode=ctypes.RTLD_GLOBAL)
// ... rest of the code ...
|
22e16ba6e2bf7135933895162744424e89ca514d
|
article/tests/article_admin_tests.py
|
article/tests/article_admin_tests.py
|
from django.contrib.auth.models import User
from django.test import TestCase, override_settings, Client
from django.test import RequestFactory
from mock import MagicMock
from wagtail.wagtailsearch.backends.elasticsearch import Elasticsearch
from django.db import DataError, IntegrityError
from django.core.exceptions import ValidationError
from article.models import Article
from functional_tests.factory import ArticleFactory, AuthorFactory
class ArticleAdminFormTest(TestCase):
def setUp(self):
self.client = Client()
self.test_author = AuthorFactory(name='xyz', slug="xyz")
self.article = ArticleFactory(title="english_article", authors=(self.test_author,), language='en')
def login_admin(self):
User.objects.create_superuser('pari', '[email protected]', "pari")
self.client.login(username="pari", password="pari")
def test_no_article_can_be_stored_without_a_title(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"): # Slug and title fields cannot be null.
ArticleFactory(title="")
def test_article_cannot_be_stored_without_content(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"):
ArticleFactory(title='Test', content='')
def test_article_cannot_be_stored_without_language(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"):
ArticleFactory(title='Test', language='')
|
from django.contrib.auth.models import User
from django.test import TestCase, override_settings, Client
from django.test import RequestFactory
from mock import MagicMock
from wagtail.wagtailsearch.backends.elasticsearch import Elasticsearch
from django.db import DataError, IntegrityError
from django.core.exceptions import ValidationError
from article.models import Article
from functional_tests.factory import ArticleFactory, AuthorFactory
class ArticleAdminFormTest(TestCase):
def setUp(self):
self.client = Client()
self.test_author = AuthorFactory(name='xyz', slug="xyz")
self.article = ArticleFactory(title="english_article", authors=(self.test_author,), language='en')
def login_admin(self):
User.objects.create_superuser('pari', '[email protected]', "pari")
self.client.login(username="pari", password="pari")
def test_no_article_can_be_stored_without_a_title(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"): # Slug and title fields cannot be null.
ArticleFactory(title="")
def test_article_can_be_stored_without_content(self):
article = ArticleFactory(title='Test', content='')
self.assertEqual(article.title, 'Test')
def test_article_cannot_be_stored_without_language(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"):
ArticleFactory(title='Test', language='')
|
Fix test for storing article without any content
|
Fix test for storing article without any content
|
Python
|
bsd-3-clause
|
PARINetwork/pari,PARINetwork/pari,PARINetwork/pari,PARINetwork/pari
|
from django.contrib.auth.models import User
from django.test import TestCase, override_settings, Client
from django.test import RequestFactory
from mock import MagicMock
from wagtail.wagtailsearch.backends.elasticsearch import Elasticsearch
from django.db import DataError, IntegrityError
from django.core.exceptions import ValidationError
from article.models import Article
from functional_tests.factory import ArticleFactory, AuthorFactory
class ArticleAdminFormTest(TestCase):
def setUp(self):
self.client = Client()
self.test_author = AuthorFactory(name='xyz', slug="xyz")
self.article = ArticleFactory(title="english_article", authors=(self.test_author,), language='en')
def login_admin(self):
User.objects.create_superuser('pari', '[email protected]', "pari")
self.client.login(username="pari", password="pari")
def test_no_article_can_be_stored_without_a_title(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"): # Slug and title fields cannot be null.
ArticleFactory(title="")
- def test_article_cannot_be_stored_without_content(self):
+ def test_article_can_be_stored_without_content(self):
- with self.assertRaisesRegexp(ValidationError,
- "This field cannot be blank"):
- ArticleFactory(title='Test', content='')
+ article = ArticleFactory(title='Test', content='')
+ self.assertEqual(article.title, 'Test')
def test_article_cannot_be_stored_without_language(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"):
ArticleFactory(title='Test', language='')
|
Fix test for storing article without any content
|
## Code Before:
from django.contrib.auth.models import User
from django.test import TestCase, override_settings, Client
from django.test import RequestFactory
from mock import MagicMock
from wagtail.wagtailsearch.backends.elasticsearch import Elasticsearch
from django.db import DataError, IntegrityError
from django.core.exceptions import ValidationError
from article.models import Article
from functional_tests.factory import ArticleFactory, AuthorFactory
class ArticleAdminFormTest(TestCase):
def setUp(self):
self.client = Client()
self.test_author = AuthorFactory(name='xyz', slug="xyz")
self.article = ArticleFactory(title="english_article", authors=(self.test_author,), language='en')
def login_admin(self):
User.objects.create_superuser('pari', '[email protected]', "pari")
self.client.login(username="pari", password="pari")
def test_no_article_can_be_stored_without_a_title(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"): # Slug and title fields cannot be null.
ArticleFactory(title="")
def test_article_cannot_be_stored_without_content(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"):
ArticleFactory(title='Test', content='')
def test_article_cannot_be_stored_without_language(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"):
ArticleFactory(title='Test', language='')
## Instruction:
Fix test for storing article without any content
## Code After:
from django.contrib.auth.models import User
from django.test import TestCase, override_settings, Client
from django.test import RequestFactory
from mock import MagicMock
from wagtail.wagtailsearch.backends.elasticsearch import Elasticsearch
from django.db import DataError, IntegrityError
from django.core.exceptions import ValidationError
from article.models import Article
from functional_tests.factory import ArticleFactory, AuthorFactory
class ArticleAdminFormTest(TestCase):
def setUp(self):
self.client = Client()
self.test_author = AuthorFactory(name='xyz', slug="xyz")
self.article = ArticleFactory(title="english_article", authors=(self.test_author,), language='en')
def login_admin(self):
User.objects.create_superuser('pari', '[email protected]', "pari")
self.client.login(username="pari", password="pari")
def test_no_article_can_be_stored_without_a_title(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"): # Slug and title fields cannot be null.
ArticleFactory(title="")
def test_article_can_be_stored_without_content(self):
article = ArticleFactory(title='Test', content='')
self.assertEqual(article.title, 'Test')
def test_article_cannot_be_stored_without_language(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"):
ArticleFactory(title='Test', language='')
|
# ... existing code ...
def test_article_can_be_stored_without_content(self):
article = ArticleFactory(title='Test', content='')
self.assertEqual(article.title, 'Test')
# ... rest of the code ...
|
f93555f1039857d1c4ba06d3f5a95810f1f1d26e
|
devp2p/__init__.py
|
devp2p/__init__.py
|
from pkg_resources import get_distribution, DistributionNotFound
import os.path
try:
_dist = get_distribution('devp2p')
# Normalize case for Windows systems
dist_loc = os.path.normcase(_dist.location)
here = os.path.normcase(__file__)
if not here.startswith(os.path.join(dist_loc, 'devp2p')):
# not installed, but there is another version that *is*
raise DistributionNotFound
except DistributionNotFound:
__version__ = 'dirty'
else:
__version__ = _dist.version
# ########### endversion ##################
|
from pkg_resources import get_distribution, DistributionNotFound
import os.path
import subprocess
import re
GIT_DESCRIBE_RE = re.compile('^(?P<version>v\d+\.\d+\.\d+)-(?P<git>\d+-g[a-fA-F0-9]+(?:-dirty)?)$')
__version__ = None
try:
_dist = get_distribution('pyethapp')
# Normalize case for Windows systems
dist_loc = os.path.normcase(_dist.location)
here = os.path.normcase(__file__)
if not here.startswith(os.path.join(dist_loc, 'pyethapp')):
# not installed, but there is another version that *is*
raise DistributionNotFound
__version__ = _dist.version
except DistributionNotFound:
pass
if not __version__:
try:
rev = subprocess.check_output(['git', 'describe', '--tags', '--dirty'],
stderr=subprocess.STDOUT)
match = GIT_DESCRIBE_RE.match(rev)
if match:
__version__ = "{}+git-{}".format(match.group("version"), match.group("git"))
except:
pass
if not __version__:
__version__ = 'undefined'
# ########### endversion ##################
|
Use version extraction code from pyethapp / pyethereum
|
Use version extraction code from pyethapp / pyethereum
|
Python
|
mit
|
ethereum/pydevp2p,ms83/pydevp2p
|
from pkg_resources import get_distribution, DistributionNotFound
import os.path
+ import subprocess
+ import re
+
+
+ GIT_DESCRIBE_RE = re.compile('^(?P<version>v\d+\.\d+\.\d+)-(?P<git>\d+-g[a-fA-F0-9]+(?:-dirty)?)$')
+
+
+ __version__ = None
try:
- _dist = get_distribution('devp2p')
+ _dist = get_distribution('pyethapp')
# Normalize case for Windows systems
dist_loc = os.path.normcase(_dist.location)
here = os.path.normcase(__file__)
- if not here.startswith(os.path.join(dist_loc, 'devp2p')):
+ if not here.startswith(os.path.join(dist_loc, 'pyethapp')):
# not installed, but there is another version that *is*
raise DistributionNotFound
+ __version__ = _dist.version
except DistributionNotFound:
+ pass
+
+ if not __version__:
+ try:
+ rev = subprocess.check_output(['git', 'describe', '--tags', '--dirty'],
+ stderr=subprocess.STDOUT)
+ match = GIT_DESCRIBE_RE.match(rev)
+ if match:
+ __version__ = "{}+git-{}".format(match.group("version"), match.group("git"))
+ except:
+ pass
+
+ if not __version__:
- __version__ = 'dirty'
+ __version__ = 'undefined'
+
- else:
- __version__ = _dist.version
# ########### endversion ##################
|
Use version extraction code from pyethapp / pyethereum
|
## Code Before:
from pkg_resources import get_distribution, DistributionNotFound
import os.path
try:
_dist = get_distribution('devp2p')
# Normalize case for Windows systems
dist_loc = os.path.normcase(_dist.location)
here = os.path.normcase(__file__)
if not here.startswith(os.path.join(dist_loc, 'devp2p')):
# not installed, but there is another version that *is*
raise DistributionNotFound
except DistributionNotFound:
__version__ = 'dirty'
else:
__version__ = _dist.version
# ########### endversion ##################
## Instruction:
Use version extraction code from pyethapp / pyethereum
## Code After:
from pkg_resources import get_distribution, DistributionNotFound
import os.path
import subprocess
import re
GIT_DESCRIBE_RE = re.compile('^(?P<version>v\d+\.\d+\.\d+)-(?P<git>\d+-g[a-fA-F0-9]+(?:-dirty)?)$')
__version__ = None
try:
_dist = get_distribution('pyethapp')
# Normalize case for Windows systems
dist_loc = os.path.normcase(_dist.location)
here = os.path.normcase(__file__)
if not here.startswith(os.path.join(dist_loc, 'pyethapp')):
# not installed, but there is another version that *is*
raise DistributionNotFound
__version__ = _dist.version
except DistributionNotFound:
pass
if not __version__:
try:
rev = subprocess.check_output(['git', 'describe', '--tags', '--dirty'],
stderr=subprocess.STDOUT)
match = GIT_DESCRIBE_RE.match(rev)
if match:
__version__ = "{}+git-{}".format(match.group("version"), match.group("git"))
except:
pass
if not __version__:
__version__ = 'undefined'
# ########### endversion ##################
|
...
import os.path
import subprocess
import re
GIT_DESCRIBE_RE = re.compile('^(?P<version>v\d+\.\d+\.\d+)-(?P<git>\d+-g[a-fA-F0-9]+(?:-dirty)?)$')
__version__ = None
try:
_dist = get_distribution('pyethapp')
# Normalize case for Windows systems
...
here = os.path.normcase(__file__)
if not here.startswith(os.path.join(dist_loc, 'pyethapp')):
# not installed, but there is another version that *is*
...
raise DistributionNotFound
__version__ = _dist.version
except DistributionNotFound:
pass
if not __version__:
try:
rev = subprocess.check_output(['git', 'describe', '--tags', '--dirty'],
stderr=subprocess.STDOUT)
match = GIT_DESCRIBE_RE.match(rev)
if match:
__version__ = "{}+git-{}".format(match.group("version"), match.group("git"))
except:
pass
if not __version__:
__version__ = 'undefined'
# ########### endversion ##################
...
|
e09af91b45355294c16249bcd3c0bf07982cd39c
|
websaver/parsed_data/models.py
|
websaver/parsed_data/models.py
|
from django.db import models
# Create your models here.
class RatingData(models.Model):
userName = models.CharField(max_length=30)
solofpp = models.CharField(max_length=5, null=True)
duofpp = models.CharField(max_length=5, null=True)
squadfpp = models.CharField(max_length=5, null=True)
solo = models.CharField(max_length=5, null=True)
duo = models.CharField(max_length=5, null=True)
squad = models.CharField(max_length=5, null=True)
solokd = models.CharField(max_length=5, null=True)
duokd = models.CharField(max_length=5, null=True)
squadkd = models.CharField(max_length=5, null=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('created_at',)
def __str__(self):
return self.userName
|
from django.db import models
# Create your models here.
class RatingData(models.Model):
userName = models.CharField(max_length=30)
solofpp = models.CharField(max_length=5, null=True)
duofpp = models.CharField(max_length=5, null=True)
squadfpp = models.CharField(max_length=5, null=True)
solo = models.CharField(max_length=5, null=True)
duo = models.CharField(max_length=5, null=True)
squad = models.CharField(max_length=5, null=True)
solokd = models.CharField(max_length=5, null=True)
duokd = models.CharField(max_length=5, null=True)
squadkd = models.CharField(max_length=5, null=True)
solofppkd = models.CharField(max_length=5, null=True)
duofppkd = models.CharField(max_length=5, null=True)
squadfppkd = models.CharField(max_length=5, null=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('created_at',)
def __str__(self):
return self.userName
|
Add fpp k/d data to the model.
|
Add fpp k/d data to the model.
|
Python
|
mit
|
aiirohituzi/myWebCrawler,aiirohituzi/myWebCrawler,aiirohituzi/myWebCrawler
|
from django.db import models
# Create your models here.
class RatingData(models.Model):
userName = models.CharField(max_length=30)
+
solofpp = models.CharField(max_length=5, null=True)
duofpp = models.CharField(max_length=5, null=True)
squadfpp = models.CharField(max_length=5, null=True)
+
solo = models.CharField(max_length=5, null=True)
duo = models.CharField(max_length=5, null=True)
squad = models.CharField(max_length=5, null=True)
+
solokd = models.CharField(max_length=5, null=True)
duokd = models.CharField(max_length=5, null=True)
squadkd = models.CharField(max_length=5, null=True)
+
+ solofppkd = models.CharField(max_length=5, null=True)
+ duofppkd = models.CharField(max_length=5, null=True)
+ squadfppkd = models.CharField(max_length=5, null=True)
+
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('created_at',)
def __str__(self):
return self.userName
|
Add fpp k/d data to the model.
|
## Code Before:
from django.db import models
# Create your models here.
class RatingData(models.Model):
userName = models.CharField(max_length=30)
solofpp = models.CharField(max_length=5, null=True)
duofpp = models.CharField(max_length=5, null=True)
squadfpp = models.CharField(max_length=5, null=True)
solo = models.CharField(max_length=5, null=True)
duo = models.CharField(max_length=5, null=True)
squad = models.CharField(max_length=5, null=True)
solokd = models.CharField(max_length=5, null=True)
duokd = models.CharField(max_length=5, null=True)
squadkd = models.CharField(max_length=5, null=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('created_at',)
def __str__(self):
return self.userName
## Instruction:
Add fpp k/d data to the model.
## Code After:
from django.db import models
# Create your models here.
class RatingData(models.Model):
userName = models.CharField(max_length=30)
solofpp = models.CharField(max_length=5, null=True)
duofpp = models.CharField(max_length=5, null=True)
squadfpp = models.CharField(max_length=5, null=True)
solo = models.CharField(max_length=5, null=True)
duo = models.CharField(max_length=5, null=True)
squad = models.CharField(max_length=5, null=True)
solokd = models.CharField(max_length=5, null=True)
duokd = models.CharField(max_length=5, null=True)
squadkd = models.CharField(max_length=5, null=True)
solofppkd = models.CharField(max_length=5, null=True)
duofppkd = models.CharField(max_length=5, null=True)
squadfppkd = models.CharField(max_length=5, null=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('created_at',)
def __str__(self):
return self.userName
|
// ... existing code ...
userName = models.CharField(max_length=30)
solofpp = models.CharField(max_length=5, null=True)
// ... modified code ...
squadfpp = models.CharField(max_length=5, null=True)
solo = models.CharField(max_length=5, null=True)
...
squad = models.CharField(max_length=5, null=True)
solokd = models.CharField(max_length=5, null=True)
...
squadkd = models.CharField(max_length=5, null=True)
solofppkd = models.CharField(max_length=5, null=True)
duofppkd = models.CharField(max_length=5, null=True)
squadfppkd = models.CharField(max_length=5, null=True)
created_at = models.DateTimeField(auto_now_add=True)
// ... rest of the code ...
|
7ea233b7f955f7dbb291d0662fe321cddfceba80
|
mopidy/frontends/lastfm/__init__.py
|
mopidy/frontends/lastfm/__init__.py
|
from __future__ import unicode_literals
import mopidy
from mopidy import ext
from mopidy.exceptions import ExtensionError
__doc__ = """
Frontend which scrobbles the music you play to your `Last.fm
<http://www.last.fm>`_ profile.
.. note::
This frontend requires a free user account at Last.fm.
**Dependencies:**
.. literalinclude:: ../../../requirements/lastfm.txt
**Settings:**
- :attr:`mopidy.settings.LASTFM_USERNAME`
- :attr:`mopidy.settings.LASTFM_PASSWORD`
**Usage:**
The frontend is enabled by default if all dependencies are available.
"""
class Extension(ext.Extension):
name = 'Mopidy-Lastfm'
version = mopidy.__version__
def get_default_config(self):
return '[ext.lastfm]'
def validate_config(self, config):
pass
def validate_environment(self):
try:
import pylast # noqa
except ImportError as e:
raise ExtensionError('pylast library not found', e)
def get_frontend_classes(self):
from .actor import LastfmFrontend
return [LastfmFrontend]
|
from __future__ import unicode_literals
import mopidy
from mopidy import exceptions, ext
from mopidy.utils import config, formatting
default_config = """
[ext.lastfm]
# If the Last.fm extension should be enabled or not
enabled = true
# Your Last.fm username
username =
# Your Last.fm password
password =
"""
__doc__ = """
Frontend which scrobbles the music you play to your `Last.fm
<http://www.last.fm>`_ profile.
.. note::
This frontend requires a free user account at Last.fm.
**Dependencies:**
.. literalinclude:: ../../../requirements/lastfm.txt
**Default config:**
.. code-block:: ini
%(config)s
**Usage:**
The frontend is enabled by default if all dependencies are available.
""" % {'config': formatting.indent(default_config)}
class Extension(ext.Extension):
name = 'Mopidy-Lastfm'
version = mopidy.__version__
def get_default_config(self):
return default_config
def get_config_schema(self):
schema = config.ExtensionConfigSchema()
schema['username'] = config.String()
schema['password'] = config.String(secret=True)
return schema
def validate_environment(self):
try:
import pylast # noqa
except ImportError as e:
raise exceptions.ExtensionError('pylast library not found', e)
def get_frontend_classes(self):
from .actor import LastfmFrontend
return [LastfmFrontend]
|
Add default config and config schema
|
lastfm: Add default config and config schema
|
Python
|
apache-2.0
|
diandiankan/mopidy,jmarsik/mopidy,ZenithDK/mopidy,diandiankan/mopidy,bacontext/mopidy,ali/mopidy,jcass77/mopidy,quartz55/mopidy,rawdlite/mopidy,priestd09/mopidy,kingosticks/mopidy,mopidy/mopidy,bencevans/mopidy,swak/mopidy,mokieyue/mopidy,hkariti/mopidy,quartz55/mopidy,kingosticks/mopidy,vrs01/mopidy,glogiotatidis/mopidy,dbrgn/mopidy,rawdlite/mopidy,vrs01/mopidy,liamw9534/mopidy,jodal/mopidy,ali/mopidy,SuperStarPL/mopidy,pacificIT/mopidy,abarisain/mopidy,adamcik/mopidy,woutervanwijk/mopidy,ZenithDK/mopidy,ZenithDK/mopidy,adamcik/mopidy,tkem/mopidy,dbrgn/mopidy,diandiankan/mopidy,rawdlite/mopidy,mopidy/mopidy,priestd09/mopidy,glogiotatidis/mopidy,tkem/mopidy,ZenithDK/mopidy,hkariti/mopidy,rawdlite/mopidy,vrs01/mopidy,mokieyue/mopidy,jodal/mopidy,diandiankan/mopidy,SuperStarPL/mopidy,adamcik/mopidy,liamw9534/mopidy,quartz55/mopidy,pacificIT/mopidy,bencevans/mopidy,ali/mopidy,bencevans/mopidy,dbrgn/mopidy,glogiotatidis/mopidy,jmarsik/mopidy,mokieyue/mopidy,jcass77/mopidy,abarisain/mopidy,tkem/mopidy,dbrgn/mopidy,hkariti/mopidy,jmarsik/mopidy,jodal/mopidy,swak/mopidy,vrs01/mopidy,quartz55/mopidy,SuperStarPL/mopidy,SuperStarPL/mopidy,bacontext/mopidy,jmarsik/mopidy,bacontext/mopidy,mokieyue/mopidy,tkem/mopidy,swak/mopidy,priestd09/mopidy,hkariti/mopidy,woutervanwijk/mopidy,pacificIT/mopidy,ali/mopidy,bacontext/mopidy,bencevans/mopidy,mopidy/mopidy,kingosticks/mopidy,glogiotatidis/mopidy,jcass77/mopidy,swak/mopidy,pacificIT/mopidy
|
from __future__ import unicode_literals
import mopidy
- from mopidy import ext
+ from mopidy import exceptions, ext
- from mopidy.exceptions import ExtensionError
+ from mopidy.utils import config, formatting
+
+ default_config = """
+ [ext.lastfm]
+
+ # If the Last.fm extension should be enabled or not
+ enabled = true
+
+ # Your Last.fm username
+ username =
+
+ # Your Last.fm password
+ password =
+ """
__doc__ = """
Frontend which scrobbles the music you play to your `Last.fm
<http://www.last.fm>`_ profile.
.. note::
This frontend requires a free user account at Last.fm.
**Dependencies:**
.. literalinclude:: ../../../requirements/lastfm.txt
- **Settings:**
+ **Default config:**
- - :attr:`mopidy.settings.LASTFM_USERNAME`
- - :attr:`mopidy.settings.LASTFM_PASSWORD`
+ .. code-block:: ini
+
+ %(config)s
**Usage:**
The frontend is enabled by default if all dependencies are available.
- """
+ """ % {'config': formatting.indent(default_config)}
class Extension(ext.Extension):
name = 'Mopidy-Lastfm'
version = mopidy.__version__
def get_default_config(self):
- return '[ext.lastfm]'
+ return default_config
- def validate_config(self, config):
- pass
+ def get_config_schema(self):
+ schema = config.ExtensionConfigSchema()
+ schema['username'] = config.String()
+ schema['password'] = config.String(secret=True)
+ return schema
def validate_environment(self):
try:
import pylast # noqa
except ImportError as e:
- raise ExtensionError('pylast library not found', e)
+ raise exceptions.ExtensionError('pylast library not found', e)
def get_frontend_classes(self):
from .actor import LastfmFrontend
return [LastfmFrontend]
|
Add default config and config schema
|
## Code Before:
from __future__ import unicode_literals
import mopidy
from mopidy import ext
from mopidy.exceptions import ExtensionError
__doc__ = """
Frontend which scrobbles the music you play to your `Last.fm
<http://www.last.fm>`_ profile.
.. note::
This frontend requires a free user account at Last.fm.
**Dependencies:**
.. literalinclude:: ../../../requirements/lastfm.txt
**Settings:**
- :attr:`mopidy.settings.LASTFM_USERNAME`
- :attr:`mopidy.settings.LASTFM_PASSWORD`
**Usage:**
The frontend is enabled by default if all dependencies are available.
"""
class Extension(ext.Extension):
name = 'Mopidy-Lastfm'
version = mopidy.__version__
def get_default_config(self):
return '[ext.lastfm]'
def validate_config(self, config):
pass
def validate_environment(self):
try:
import pylast # noqa
except ImportError as e:
raise ExtensionError('pylast library not found', e)
def get_frontend_classes(self):
from .actor import LastfmFrontend
return [LastfmFrontend]
## Instruction:
Add default config and config schema
## Code After:
from __future__ import unicode_literals
import mopidy
from mopidy import exceptions, ext
from mopidy.utils import config, formatting
default_config = """
[ext.lastfm]
# If the Last.fm extension should be enabled or not
enabled = true
# Your Last.fm username
username =
# Your Last.fm password
password =
"""
__doc__ = """
Frontend which scrobbles the music you play to your `Last.fm
<http://www.last.fm>`_ profile.
.. note::
This frontend requires a free user account at Last.fm.
**Dependencies:**
.. literalinclude:: ../../../requirements/lastfm.txt
**Default config:**
.. code-block:: ini
%(config)s
**Usage:**
The frontend is enabled by default if all dependencies are available.
""" % {'config': formatting.indent(default_config)}
class Extension(ext.Extension):
name = 'Mopidy-Lastfm'
version = mopidy.__version__
def get_default_config(self):
return default_config
def get_config_schema(self):
schema = config.ExtensionConfigSchema()
schema['username'] = config.String()
schema['password'] = config.String(secret=True)
return schema
def validate_environment(self):
try:
import pylast # noqa
except ImportError as e:
raise exceptions.ExtensionError('pylast library not found', e)
def get_frontend_classes(self):
from .actor import LastfmFrontend
return [LastfmFrontend]
|
// ... existing code ...
import mopidy
from mopidy import exceptions, ext
from mopidy.utils import config, formatting
default_config = """
[ext.lastfm]
# If the Last.fm extension should be enabled or not
enabled = true
# Your Last.fm username
username =
# Your Last.fm password
password =
"""
// ... modified code ...
**Default config:**
.. code-block:: ini
%(config)s
...
The frontend is enabled by default if all dependencies are available.
""" % {'config': formatting.indent(default_config)}
...
def get_default_config(self):
return default_config
def get_config_schema(self):
schema = config.ExtensionConfigSchema()
schema['username'] = config.String()
schema['password'] = config.String(secret=True)
return schema
...
except ImportError as e:
raise exceptions.ExtensionError('pylast library not found', e)
// ... rest of the code ...
|
29061254e99f8e02e8285c3ebc965866c8c9d378
|
testing/chess_engine_fight.py
|
testing/chess_engine_fight.py
|
import subprocess, os, sys
if len(sys.argv) < 2:
print('Must specify file names of 2 chess engines')
for i in range(len(sys.argv)):
print(str(i) + ': ' + sys.argv[i])
sys.exit(1)
generator = './' + sys.argv[-2]
checker = './' + sys.argv[-1]
game_file = 'game.pgn'
count = 0
while True:
try:
os.remove(game_file)
except OSError:
pass
count += 1
print('Game #' + str(count))
out = subprocess.run([generator, '-random', '-random'])
if not os.path.isfile(game_file):
print('Game file not produced: ' + game_file)
print('generator = ' + generator)
print(out.returncode)
print(out.stdout)
print(out.stderr)
sys.exit()
result = subprocess.run([checker, '-confirm', game_file])
if result.returncode != 0:
print('Found discrepancy. See ' + game_file)
print('generator = ' + generator)
print('checker = ' + checker)
sys.exit()
generator, checker = checker, generator
|
import subprocess, os, sys
if len(sys.argv) < 2:
print('Must specify file names of 2 chess engines')
for i in range(len(sys.argv)):
print(str(i) + ': ' + sys.argv[i])
sys.exit(1)
generator = './' + sys.argv[-2]
checker = './' + sys.argv[-1]
game_file = 'game.pgn'
count = 0
while True:
try:
os.remove(game_file)
except OSError:
pass
if os.path.isfile(game_file):
print('Could not delete output file:', game_file)
count += 1
print('Game #' + str(count))
out = subprocess.run([generator, '-random', '-random'])
if not os.path.isfile(game_file):
print('Game file not produced: ' + game_file)
print('generator = ' + generator)
print(out.returncode)
print(out.stdout)
print(out.stderr)
sys.exit()
result = subprocess.run([checker, '-confirm', game_file])
if result.returncode != 0:
print('Found discrepancy. See ' + game_file)
print('generator = ' + generator)
print('checker = ' + checker)
sys.exit()
generator, checker = checker, generator
|
Check that engine fight files are deleted before test
|
Check that engine fight files are deleted before test
|
Python
|
mit
|
MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess
|
import subprocess, os, sys
if len(sys.argv) < 2:
print('Must specify file names of 2 chess engines')
for i in range(len(sys.argv)):
print(str(i) + ': ' + sys.argv[i])
sys.exit(1)
generator = './' + sys.argv[-2]
checker = './' + sys.argv[-1]
game_file = 'game.pgn'
count = 0
while True:
try:
os.remove(game_file)
except OSError:
pass
+
+ if os.path.isfile(game_file):
+ print('Could not delete output file:', game_file)
count += 1
print('Game #' + str(count))
out = subprocess.run([generator, '-random', '-random'])
if not os.path.isfile(game_file):
print('Game file not produced: ' + game_file)
print('generator = ' + generator)
print(out.returncode)
print(out.stdout)
print(out.stderr)
sys.exit()
result = subprocess.run([checker, '-confirm', game_file])
if result.returncode != 0:
print('Found discrepancy. See ' + game_file)
print('generator = ' + generator)
print('checker = ' + checker)
sys.exit()
generator, checker = checker, generator
|
Check that engine fight files are deleted before test
|
## Code Before:
import subprocess, os, sys
if len(sys.argv) < 2:
print('Must specify file names of 2 chess engines')
for i in range(len(sys.argv)):
print(str(i) + ': ' + sys.argv[i])
sys.exit(1)
generator = './' + sys.argv[-2]
checker = './' + sys.argv[-1]
game_file = 'game.pgn'
count = 0
while True:
try:
os.remove(game_file)
except OSError:
pass
count += 1
print('Game #' + str(count))
out = subprocess.run([generator, '-random', '-random'])
if not os.path.isfile(game_file):
print('Game file not produced: ' + game_file)
print('generator = ' + generator)
print(out.returncode)
print(out.stdout)
print(out.stderr)
sys.exit()
result = subprocess.run([checker, '-confirm', game_file])
if result.returncode != 0:
print('Found discrepancy. See ' + game_file)
print('generator = ' + generator)
print('checker = ' + checker)
sys.exit()
generator, checker = checker, generator
## Instruction:
Check that engine fight files are deleted before test
## Code After:
import subprocess, os, sys
if len(sys.argv) < 2:
print('Must specify file names of 2 chess engines')
for i in range(len(sys.argv)):
print(str(i) + ': ' + sys.argv[i])
sys.exit(1)
generator = './' + sys.argv[-2]
checker = './' + sys.argv[-1]
game_file = 'game.pgn'
count = 0
while True:
try:
os.remove(game_file)
except OSError:
pass
if os.path.isfile(game_file):
print('Could not delete output file:', game_file)
count += 1
print('Game #' + str(count))
out = subprocess.run([generator, '-random', '-random'])
if not os.path.isfile(game_file):
print('Game file not produced: ' + game_file)
print('generator = ' + generator)
print(out.returncode)
print(out.stdout)
print(out.stderr)
sys.exit()
result = subprocess.run([checker, '-confirm', game_file])
if result.returncode != 0:
print('Found discrepancy. See ' + game_file)
print('generator = ' + generator)
print('checker = ' + checker)
sys.exit()
generator, checker = checker, generator
|
# ... existing code ...
pass
if os.path.isfile(game_file):
print('Could not delete output file:', game_file)
# ... rest of the code ...
|
5f1ccd3845e198495e33748b460ef6fa9858e925
|
app/settings.py
|
app/settings.py
|
import os
EQ_RABBITMQ_URL = os.getenv('EQ_RABBITMQ_URL', 'amqp://admin:admin@localhost:5672/%2F')
EQ_RABBITMQ_QUEUE_NAME = os.getenv('EQ_RABBITMQ_QUEUE_NAME', 'eq-submissions')
EQ_RABBITMQ_TEST_QUEUE_NAME = os.getenv('EQ_RABBITMQ_TEST_QUEUE_NAME', 'eq-test')
EQ_PRODUCTION = os.getenv("EQ_PRODUCTION", 'True')
EQ_RRM_PUBLIC_KEY = os.getenv('EQ_RRM_PUBLIC_KEY')
EQ_SR_PRIVATE_KEY = os.getenv('EQ_SR_PRIVATE_KEY')
EQ_GIT_REF = os.getenv('EQ_GIT_REF', None)
EQ_NEW_RELIC_CONFIG_FILE = os.getenv('EQ_NEW_RELIC_CONFIG_FILE', './newrelic.ini')
EQ_SR_LOG_GROUP = os.getenv('EQ_SR_LOG_GROUP', os.getenv('USER') + '-local')
EQ_LOG_LEVEL = os.getenv('EQ_LOG_LEVEL', 'INFO')
|
import os
EQ_RABBITMQ_URL = os.getenv('EQ_RABBITMQ_URL', 'amqp://admin:admin@localhost:5672/%2F')
EQ_RABBITMQ_QUEUE_NAME = os.getenv('EQ_RABBITMQ_QUEUE_NAME', 'eq-submissions')
EQ_RABBITMQ_TEST_QUEUE_NAME = os.getenv('EQ_RABBITMQ_TEST_QUEUE_NAME', 'eq-test')
EQ_PRODUCTION = os.getenv("EQ_PRODUCTION", 'True')
EQ_RRM_PUBLIC_KEY = os.getenv('EQ_RRM_PUBLIC_KEY')
EQ_SR_PRIVATE_KEY = os.getenv('EQ_SR_PRIVATE_KEY')
EQ_GIT_REF = os.getenv('EQ_GIT_REF', None)
EQ_NEW_RELIC_CONFIG_FILE = os.getenv('EQ_NEW_RELIC_CONFIG_FILE', './newrelic.ini')
EQ_SR_LOG_GROUP = os.getenv('EQ_SR_LOG_GROUP', os.getenv('USER', 'UNKNOWN') + '-local')
EQ_LOG_LEVEL = os.getenv('EQ_LOG_LEVEL', 'INFO')
|
Make sure there is a default for LOG Group
|
Make sure there is a default for LOG Group
|
Python
|
mit
|
ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner
|
import os
EQ_RABBITMQ_URL = os.getenv('EQ_RABBITMQ_URL', 'amqp://admin:admin@localhost:5672/%2F')
EQ_RABBITMQ_QUEUE_NAME = os.getenv('EQ_RABBITMQ_QUEUE_NAME', 'eq-submissions')
EQ_RABBITMQ_TEST_QUEUE_NAME = os.getenv('EQ_RABBITMQ_TEST_QUEUE_NAME', 'eq-test')
EQ_PRODUCTION = os.getenv("EQ_PRODUCTION", 'True')
EQ_RRM_PUBLIC_KEY = os.getenv('EQ_RRM_PUBLIC_KEY')
EQ_SR_PRIVATE_KEY = os.getenv('EQ_SR_PRIVATE_KEY')
EQ_GIT_REF = os.getenv('EQ_GIT_REF', None)
EQ_NEW_RELIC_CONFIG_FILE = os.getenv('EQ_NEW_RELIC_CONFIG_FILE', './newrelic.ini')
- EQ_SR_LOG_GROUP = os.getenv('EQ_SR_LOG_GROUP', os.getenv('USER') + '-local')
+ EQ_SR_LOG_GROUP = os.getenv('EQ_SR_LOG_GROUP', os.getenv('USER', 'UNKNOWN') + '-local')
EQ_LOG_LEVEL = os.getenv('EQ_LOG_LEVEL', 'INFO')
|
Make sure there is a default for LOG Group
|
## Code Before:
import os
EQ_RABBITMQ_URL = os.getenv('EQ_RABBITMQ_URL', 'amqp://admin:admin@localhost:5672/%2F')
EQ_RABBITMQ_QUEUE_NAME = os.getenv('EQ_RABBITMQ_QUEUE_NAME', 'eq-submissions')
EQ_RABBITMQ_TEST_QUEUE_NAME = os.getenv('EQ_RABBITMQ_TEST_QUEUE_NAME', 'eq-test')
EQ_PRODUCTION = os.getenv("EQ_PRODUCTION", 'True')
EQ_RRM_PUBLIC_KEY = os.getenv('EQ_RRM_PUBLIC_KEY')
EQ_SR_PRIVATE_KEY = os.getenv('EQ_SR_PRIVATE_KEY')
EQ_GIT_REF = os.getenv('EQ_GIT_REF', None)
EQ_NEW_RELIC_CONFIG_FILE = os.getenv('EQ_NEW_RELIC_CONFIG_FILE', './newrelic.ini')
EQ_SR_LOG_GROUP = os.getenv('EQ_SR_LOG_GROUP', os.getenv('USER') + '-local')
EQ_LOG_LEVEL = os.getenv('EQ_LOG_LEVEL', 'INFO')
## Instruction:
Make sure there is a default for LOG Group
## Code After:
import os
EQ_RABBITMQ_URL = os.getenv('EQ_RABBITMQ_URL', 'amqp://admin:admin@localhost:5672/%2F')
EQ_RABBITMQ_QUEUE_NAME = os.getenv('EQ_RABBITMQ_QUEUE_NAME', 'eq-submissions')
EQ_RABBITMQ_TEST_QUEUE_NAME = os.getenv('EQ_RABBITMQ_TEST_QUEUE_NAME', 'eq-test')
EQ_PRODUCTION = os.getenv("EQ_PRODUCTION", 'True')
EQ_RRM_PUBLIC_KEY = os.getenv('EQ_RRM_PUBLIC_KEY')
EQ_SR_PRIVATE_KEY = os.getenv('EQ_SR_PRIVATE_KEY')
EQ_GIT_REF = os.getenv('EQ_GIT_REF', None)
EQ_NEW_RELIC_CONFIG_FILE = os.getenv('EQ_NEW_RELIC_CONFIG_FILE', './newrelic.ini')
EQ_SR_LOG_GROUP = os.getenv('EQ_SR_LOG_GROUP', os.getenv('USER', 'UNKNOWN') + '-local')
EQ_LOG_LEVEL = os.getenv('EQ_LOG_LEVEL', 'INFO')
|
...
EQ_NEW_RELIC_CONFIG_FILE = os.getenv('EQ_NEW_RELIC_CONFIG_FILE', './newrelic.ini')
EQ_SR_LOG_GROUP = os.getenv('EQ_SR_LOG_GROUP', os.getenv('USER', 'UNKNOWN') + '-local')
EQ_LOG_LEVEL = os.getenv('EQ_LOG_LEVEL', 'INFO')
...
|
61693f27510567f4f2f5af2b51f95ae465290d9a
|
tests/test_directory/test_domain.py
|
tests/test_directory/test_domain.py
|
'''
Creates all tests to serialize XMLs to xml_curl
'''
import logging
import pytest
from lxml import etree
from mock import Mock
from wirecurly.directory import Domain, User
def test_domain_no_users():
domain = Domain('wirephone.com.ar')
response = domain.todict()
assert domain.domain == 'wirephone.com.ar'
assert len(response['children']) == 0
assert not domain.users
def test_domain_1_user():
domain = Domain('wirephone.com.ar')
user = Mock(User)
domain.addUser(user)
assert domain.users
assert len(domain.users) == 1
assert domain.users[0] == user
response = domain.todict()
assert len(response['children']) == 1
assert response.get('children')[0] == user.todict()
|
'''
Creates all tests to serialize XMLs to xml_curl
'''
import logging
import pytest
from lxml import etree
from mock import Mock
from wirecurly.directory import Domain, User
def test_domain_no_users():
domain = Domain('wirephone.com.ar')
response = domain.todict()
assert domain.domain == 'wirephone.com.ar'
assert len(response['children']) == 0
assert not domain.users
def test_domain_1_user():
domain = Domain('wirephone.com.ar')
user = Mock(User)
domain.addUser(user)
assert domain.users
assert len(domain.users) == 1
assert domain.users[0] == user
response = domain.todict()
assert len(response['children']) == 1
assert response.get('children')[0] == user.todict()
def test_domain_with_group():
domain = Domain('wirephone.com.ar')
user = Mock(User)
domain.addUser(user)
domain.addUsersToGroup()
response = domain.todict()
assert response.get('children')[0]['tag'] == 'groups'
assert response.get('children')[0].get('children')[0]['tag'] == 'group'
assert response.get('children')[0].get('children')[0].get('children')[0]['tag'] == 'users'
def test_domain_with_group_name():
domain = Domain('wirephone.com.ar')
user = Mock(User)
domain.addUser(user)
domain.addUsersToGroup('group_name')
response = domain.todict()
assert response.get('children')[0].get('children')[0]['attrs']['name'] == 'group_name'
|
Add tests for addUsersToGroup function
|
Add tests for addUsersToGroup function
|
Python
|
mpl-2.0
|
IndiciumSRL/wirecurly
|
'''
Creates all tests to serialize XMLs to xml_curl
'''
import logging
import pytest
from lxml import etree
from mock import Mock
from wirecurly.directory import Domain, User
def test_domain_no_users():
domain = Domain('wirephone.com.ar')
response = domain.todict()
assert domain.domain == 'wirephone.com.ar'
assert len(response['children']) == 0
assert not domain.users
def test_domain_1_user():
domain = Domain('wirephone.com.ar')
user = Mock(User)
domain.addUser(user)
assert domain.users
assert len(domain.users) == 1
assert domain.users[0] == user
response = domain.todict()
assert len(response['children']) == 1
assert response.get('children')[0] == user.todict()
+ def test_domain_with_group():
+ domain = Domain('wirephone.com.ar')
+ user = Mock(User)
+ domain.addUser(user)
+ domain.addUsersToGroup()
+
+ response = domain.todict()
+
+ assert response.get('children')[0]['tag'] == 'groups'
+ assert response.get('children')[0].get('children')[0]['tag'] == 'group'
+ assert response.get('children')[0].get('children')[0].get('children')[0]['tag'] == 'users'
+
+ def test_domain_with_group_name():
+ domain = Domain('wirephone.com.ar')
+ user = Mock(User)
+ domain.addUser(user)
+ domain.addUsersToGroup('group_name')
+
+ response = domain.todict()
+
+ assert response.get('children')[0].get('children')[0]['attrs']['name'] == 'group_name'
|
Add tests for addUsersToGroup function
|
## Code Before:
'''
Creates all tests to serialize XMLs to xml_curl
'''
import logging
import pytest
from lxml import etree
from mock import Mock
from wirecurly.directory import Domain, User
def test_domain_no_users():
domain = Domain('wirephone.com.ar')
response = domain.todict()
assert domain.domain == 'wirephone.com.ar'
assert len(response['children']) == 0
assert not domain.users
def test_domain_1_user():
domain = Domain('wirephone.com.ar')
user = Mock(User)
domain.addUser(user)
assert domain.users
assert len(domain.users) == 1
assert domain.users[0] == user
response = domain.todict()
assert len(response['children']) == 1
assert response.get('children')[0] == user.todict()
## Instruction:
Add tests for addUsersToGroup function
## Code After:
'''
Creates all tests to serialize XMLs to xml_curl
'''
import logging
import pytest
from lxml import etree
from mock import Mock
from wirecurly.directory import Domain, User
def test_domain_no_users():
domain = Domain('wirephone.com.ar')
response = domain.todict()
assert domain.domain == 'wirephone.com.ar'
assert len(response['children']) == 0
assert not domain.users
def test_domain_1_user():
domain = Domain('wirephone.com.ar')
user = Mock(User)
domain.addUser(user)
assert domain.users
assert len(domain.users) == 1
assert domain.users[0] == user
response = domain.todict()
assert len(response['children']) == 1
assert response.get('children')[0] == user.todict()
def test_domain_with_group():
domain = Domain('wirephone.com.ar')
user = Mock(User)
domain.addUser(user)
domain.addUsersToGroup()
response = domain.todict()
assert response.get('children')[0]['tag'] == 'groups'
assert response.get('children')[0].get('children')[0]['tag'] == 'group'
assert response.get('children')[0].get('children')[0].get('children')[0]['tag'] == 'users'
def test_domain_with_group_name():
domain = Domain('wirephone.com.ar')
user = Mock(User)
domain.addUser(user)
domain.addUsersToGroup('group_name')
response = domain.todict()
assert response.get('children')[0].get('children')[0]['attrs']['name'] == 'group_name'
|
...
assert response.get('children')[0] == user.todict()
def test_domain_with_group():
domain = Domain('wirephone.com.ar')
user = Mock(User)
domain.addUser(user)
domain.addUsersToGroup()
response = domain.todict()
assert response.get('children')[0]['tag'] == 'groups'
assert response.get('children')[0].get('children')[0]['tag'] == 'group'
assert response.get('children')[0].get('children')[0].get('children')[0]['tag'] == 'users'
def test_domain_with_group_name():
domain = Domain('wirephone.com.ar')
user = Mock(User)
domain.addUser(user)
domain.addUsersToGroup('group_name')
response = domain.todict()
assert response.get('children')[0].get('children')[0]['attrs']['name'] == 'group_name'
...
|
745ec6f3dd227cc00c3db0d100b005fb6fd4d903
|
test/on_yubikey/test_cli_openpgp.py
|
test/on_yubikey/test_cli_openpgp.py
|
import unittest
from ykman.util import TRANSPORT
from .util import (DestructiveYubikeyTestCase, missing_mode, ykman_cli)
@unittest.skipIf(*missing_mode(TRANSPORT.CCID))
class TestOpenPGP(DestructiveYubikeyTestCase):
def test_openpgp_info(self):
output = ykman_cli('openpgp', 'info')
self.assertIn('OpenPGP version:', output)
def test_openpgp_reset(self):
output = ykman_cli('openpgp', 'reset', '-f')
self.assertIn(
'Success! All data has been cleared and default PINs are set.',
output)
|
import unittest
from ykman.util import TRANSPORT
from .util import (DestructiveYubikeyTestCase, missing_mode, ykman_cli)
@unittest.skipIf(*missing_mode(TRANSPORT.CCID))
class TestOpenPGP(DestructiveYubikeyTestCase):
def setUp(self):
ykman_cli('openpgp', 'reset', '-f')
def test_openpgp_info(self):
output = ykman_cli('openpgp', 'info')
self.assertIn('OpenPGP version:', output)
def test_openpgp_reset(self):
output = ykman_cli('openpgp', 'reset', '-f')
self.assertIn(
'Success! All data has been cleared and default PINs are set.',
output)
|
Reset OpenPGP applet before each test
|
Reset OpenPGP applet before each test
|
Python
|
bsd-2-clause
|
Yubico/yubikey-manager,Yubico/yubikey-manager
|
import unittest
from ykman.util import TRANSPORT
from .util import (DestructiveYubikeyTestCase, missing_mode, ykman_cli)
@unittest.skipIf(*missing_mode(TRANSPORT.CCID))
class TestOpenPGP(DestructiveYubikeyTestCase):
+
+ def setUp(self):
+ ykman_cli('openpgp', 'reset', '-f')
def test_openpgp_info(self):
output = ykman_cli('openpgp', 'info')
self.assertIn('OpenPGP version:', output)
def test_openpgp_reset(self):
output = ykman_cli('openpgp', 'reset', '-f')
self.assertIn(
'Success! All data has been cleared and default PINs are set.',
output)
|
Reset OpenPGP applet before each test
|
## Code Before:
import unittest
from ykman.util import TRANSPORT
from .util import (DestructiveYubikeyTestCase, missing_mode, ykman_cli)
@unittest.skipIf(*missing_mode(TRANSPORT.CCID))
class TestOpenPGP(DestructiveYubikeyTestCase):
def test_openpgp_info(self):
output = ykman_cli('openpgp', 'info')
self.assertIn('OpenPGP version:', output)
def test_openpgp_reset(self):
output = ykman_cli('openpgp', 'reset', '-f')
self.assertIn(
'Success! All data has been cleared and default PINs are set.',
output)
## Instruction:
Reset OpenPGP applet before each test
## Code After:
import unittest
from ykman.util import TRANSPORT
from .util import (DestructiveYubikeyTestCase, missing_mode, ykman_cli)
@unittest.skipIf(*missing_mode(TRANSPORT.CCID))
class TestOpenPGP(DestructiveYubikeyTestCase):
def setUp(self):
ykman_cli('openpgp', 'reset', '-f')
def test_openpgp_info(self):
output = ykman_cli('openpgp', 'info')
self.assertIn('OpenPGP version:', output)
def test_openpgp_reset(self):
output = ykman_cli('openpgp', 'reset', '-f')
self.assertIn(
'Success! All data has been cleared and default PINs are set.',
output)
|
# ... existing code ...
class TestOpenPGP(DestructiveYubikeyTestCase):
def setUp(self):
ykman_cli('openpgp', 'reset', '-f')
# ... rest of the code ...
|
0ae9fcccb1c67a8d9337e4ef2887fb7ea2e01d51
|
mpltools/io/core.py
|
mpltools/io/core.py
|
import os
import matplotlib.pyplot as plt
def save_all_figs(directory='./', fmt=None, default_name='untitled%i'):
"""Save all open figures.
Each figure is saved with the title of the plot, if possible.
Parameters
------------
directory : str
Path where figures are saved.
fmt : str, list of str
Image format(s) of saved figures. If None, default to rc parameter
'savefig.extension'.
default_name : str
Default filename to use if plot has no title. Must contain '%i' for the
figure number.
Examples
--------
>>> save_all_figs('plots/', fmt=['pdf','png'])
"""
for fignum in plt.get_fignums():
try:
filename = plt.figure(fignum).get_axes()[0].get_title()
if filename == '':
filename = default_name % fignum
savename = os.path.join(directory, filename)
if fmt is None:
fmt = plt.rcParams.get('savefig.extension','png')
if isinstance(fmt, basestring):
fmt = [fmt]
for a_fmt in fmt:
plt.savefig(savename + '.' + a_fmt)
print ('Saved \'%s\' '% (savename + '.' + a_fmt))
except(IndexError):
pass
|
import os
import matplotlib.pyplot as plt
def save_all_figs(directory='./', fmt=None, default_name='untitled%i'):
"""Save all open figures.
Each figure is saved with the title of the plot, if possible.
Parameters
------------
directory : str
Path where figures are saved.
fmt : str, list of str
Image format(s) of saved figures. If None, default to rc parameter
'savefig.extension'.
default_name : str
Default filename to use if plot has no title. Must contain '%i' for the
figure number.
Examples
--------
>>> save_all_figs('plots/', fmt=['pdf','png'])
"""
fmt = fmt if fmt is not None else 'png'
if isinstance(fmt, basestring):
fmt = [fmt]
for fignum in plt.get_fignums():
try:
filename = plt.figure(fignum).get_axes()[0].get_title()
if filename == '':
filename = default_name % fignum
savepath = os.path.join(directory, filename)
for a_fmt in fmt:
savename = '%s.%s' % (savepath, a_fmt)
plt.savefig(savename)
print("Saved '%s'" % savename)
except(IndexError):
pass
|
Refactor formatting of save name.
|
Refactor formatting of save name.
|
Python
|
bsd-3-clause
|
tonysyu/mpltools,matteoicardi/mpltools
|
import os
import matplotlib.pyplot as plt
def save_all_figs(directory='./', fmt=None, default_name='untitled%i'):
"""Save all open figures.
Each figure is saved with the title of the plot, if possible.
Parameters
------------
directory : str
Path where figures are saved.
fmt : str, list of str
Image format(s) of saved figures. If None, default to rc parameter
'savefig.extension'.
default_name : str
Default filename to use if plot has no title. Must contain '%i' for the
figure number.
Examples
--------
>>> save_all_figs('plots/', fmt=['pdf','png'])
"""
+ fmt = fmt if fmt is not None else 'png'
+ if isinstance(fmt, basestring):
+ fmt = [fmt]
+
for fignum in plt.get_fignums():
try:
filename = plt.figure(fignum).get_axes()[0].get_title()
-
if filename == '':
filename = default_name % fignum
- savename = os.path.join(directory, filename)
+ savepath = os.path.join(directory, filename)
-
- if fmt is None:
- fmt = plt.rcParams.get('savefig.extension','png')
-
- if isinstance(fmt, basestring):
- fmt = [fmt]
for a_fmt in fmt:
+ savename = '%s.%s' % (savepath, a_fmt)
- plt.savefig(savename + '.' + a_fmt)
+ plt.savefig(savename)
- print ('Saved \'%s\' '% (savename + '.' + a_fmt))
+ print("Saved '%s'" % savename)
except(IndexError):
pass
|
Refactor formatting of save name.
|
## Code Before:
import os
import matplotlib.pyplot as plt
def save_all_figs(directory='./', fmt=None, default_name='untitled%i'):
"""Save all open figures.
Each figure is saved with the title of the plot, if possible.
Parameters
------------
directory : str
Path where figures are saved.
fmt : str, list of str
Image format(s) of saved figures. If None, default to rc parameter
'savefig.extension'.
default_name : str
Default filename to use if plot has no title. Must contain '%i' for the
figure number.
Examples
--------
>>> save_all_figs('plots/', fmt=['pdf','png'])
"""
for fignum in plt.get_fignums():
try:
filename = plt.figure(fignum).get_axes()[0].get_title()
if filename == '':
filename = default_name % fignum
savename = os.path.join(directory, filename)
if fmt is None:
fmt = plt.rcParams.get('savefig.extension','png')
if isinstance(fmt, basestring):
fmt = [fmt]
for a_fmt in fmt:
plt.savefig(savename + '.' + a_fmt)
print ('Saved \'%s\' '% (savename + '.' + a_fmt))
except(IndexError):
pass
## Instruction:
Refactor formatting of save name.
## Code After:
import os
import matplotlib.pyplot as plt
def save_all_figs(directory='./', fmt=None, default_name='untitled%i'):
"""Save all open figures.
Each figure is saved with the title of the plot, if possible.
Parameters
------------
directory : str
Path where figures are saved.
fmt : str, list of str
Image format(s) of saved figures. If None, default to rc parameter
'savefig.extension'.
default_name : str
Default filename to use if plot has no title. Must contain '%i' for the
figure number.
Examples
--------
>>> save_all_figs('plots/', fmt=['pdf','png'])
"""
fmt = fmt if fmt is not None else 'png'
if isinstance(fmt, basestring):
fmt = [fmt]
for fignum in plt.get_fignums():
try:
filename = plt.figure(fignum).get_axes()[0].get_title()
if filename == '':
filename = default_name % fignum
savepath = os.path.join(directory, filename)
for a_fmt in fmt:
savename = '%s.%s' % (savepath, a_fmt)
plt.savefig(savename)
print("Saved '%s'" % savename)
except(IndexError):
pass
|
# ... existing code ...
"""
fmt = fmt if fmt is not None else 'png'
if isinstance(fmt, basestring):
fmt = [fmt]
for fignum in plt.get_fignums():
# ... modified code ...
filename = plt.figure(fignum).get_axes()[0].get_title()
if filename == '':
...
savepath = os.path.join(directory, filename)
...
for a_fmt in fmt:
savename = '%s.%s' % (savepath, a_fmt)
plt.savefig(savename)
print("Saved '%s'" % savename)
# ... rest of the code ...
|
df000e724ce1f307a478fcf4790404183df13610
|
_setup_database.py
|
_setup_database.py
|
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
if __name__ == '__main__':
# migrating teams from json file to database
migrate_teams(simulation=True)
# creating divisions from division configuration file
create_divisions(simulation=True)
|
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
from setup.create_players import migrate_players
if __name__ == '__main__':
# migrating teams from json file to database
migrate_teams(simulation=True)
# creating divisions from division configuration file
create_divisions(simulation=True)
# migrating players from json file to database
migrate_players(simulation=True)
|
Include player data migration in setup
|
Include player data migration in setup
|
Python
|
mit
|
leaffan/pynhldb
|
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
+ from setup.create_players import migrate_players
if __name__ == '__main__':
# migrating teams from json file to database
migrate_teams(simulation=True)
# creating divisions from division configuration file
create_divisions(simulation=True)
+ # migrating players from json file to database
+ migrate_players(simulation=True)
|
Include player data migration in setup
|
## Code Before:
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
if __name__ == '__main__':
# migrating teams from json file to database
migrate_teams(simulation=True)
# creating divisions from division configuration file
create_divisions(simulation=True)
## Instruction:
Include player data migration in setup
## Code After:
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
from setup.create_players import migrate_players
if __name__ == '__main__':
# migrating teams from json file to database
migrate_teams(simulation=True)
# creating divisions from division configuration file
create_divisions(simulation=True)
# migrating players from json file to database
migrate_players(simulation=True)
|
// ... existing code ...
from setup.create_divisions import create_divisions
from setup.create_players import migrate_players
// ... modified code ...
create_divisions(simulation=True)
# migrating players from json file to database
migrate_players(simulation=True)
// ... rest of the code ...
|
d8ce56feada64d287306d7f439ec12a42acda0d6
|
bot.py
|
bot.py
|
import tweepy
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
userid = str(input("Please input id who you want fav attack\n"))
count = input("input number you want to fav!\n")
fav = api.user_timeline(id = userid, count = count)
try:
for status in fav:
api.create_favorite(status.id_str)
except tweepy.error.TweepError as e:
if e.args[0][0]['code'] == 139:
print("You have already favorited this status! \n")
else:
print(e.reason)
finally:
print("Done!")
|
import tweepy
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
def getdata():
userid = str(input("Please input id who you want fav attack\n"))
count = input("input number you want to fav!\n")
fav = api.user_timeline(id = userid, count = count)
def main():
getdata()
try:
for status in fav:
api.create_favorite(status.id_str)
except tweepy.error.TweepError as e:
if e.args[0][0]['code'] == 139:
print("You have already favorited this status! \n")
else:
print(e.reason)
finally:
print("Done!")
if __name__ == "__main__":
main()
|
Make it more complex (((
|
Make it more complex (((
|
Python
|
mit
|
zhangyubaka/tweepy_favbot
|
import tweepy
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
+ def getdata():
- userid = str(input("Please input id who you want fav attack\n"))
+ userid = str(input("Please input id who you want fav attack\n"))
- count = input("input number you want to fav!\n")
+ count = input("input number you want to fav!\n")
+ fav = api.user_timeline(id = userid, count = count)
- fav = api.user_timeline(id = userid, count = count)
+ def main():
+ getdata()
+ try:
+ for status in fav:
+ api.create_favorite(status.id_str)
+ except tweepy.error.TweepError as e:
+ if e.args[0][0]['code'] == 139:
+ print("You have already favorited this status! \n")
+ else:
+ print(e.reason)
+ finally:
+ print("Done!")
+ if __name__ == "__main__":
+ main()
- try:
- for status in fav:
- api.create_favorite(status.id_str)
- except tweepy.error.TweepError as e:
- if e.args[0][0]['code'] == 139:
- print("You have already favorited this status! \n")
- else:
- print(e.reason)
- finally:
- print("Done!")
|
Make it more complex (((
|
## Code Before:
import tweepy
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
userid = str(input("Please input id who you want fav attack\n"))
count = input("input number you want to fav!\n")
fav = api.user_timeline(id = userid, count = count)
try:
for status in fav:
api.create_favorite(status.id_str)
except tweepy.error.TweepError as e:
if e.args[0][0]['code'] == 139:
print("You have already favorited this status! \n")
else:
print(e.reason)
finally:
print("Done!")
## Instruction:
Make it more complex (((
## Code After:
import tweepy
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
def getdata():
userid = str(input("Please input id who you want fav attack\n"))
count = input("input number you want to fav!\n")
fav = api.user_timeline(id = userid, count = count)
def main():
getdata()
try:
for status in fav:
api.create_favorite(status.id_str)
except tweepy.error.TweepError as e:
if e.args[0][0]['code'] == 139:
print("You have already favorited this status! \n")
else:
print(e.reason)
finally:
print("Done!")
if __name__ == "__main__":
main()
|
...
def getdata():
userid = str(input("Please input id who you want fav attack\n"))
count = input("input number you want to fav!\n")
fav = api.user_timeline(id = userid, count = count)
def main():
getdata()
try:
for status in fav:
api.create_favorite(status.id_str)
except tweepy.error.TweepError as e:
if e.args[0][0]['code'] == 139:
print("You have already favorited this status! \n")
else:
print(e.reason)
finally:
print("Done!")
if __name__ == "__main__":
main()
...
|
1adc660916eafe5937b96f1b5bc480185efc96ad
|
aospy_user/__init__.py
|
aospy_user/__init__.py
|
"""aospy_user: Library of user-defined aospy objects."""
from . import regions
from . import units
from . import calcs
from . import variables
from . import runs
from . import models
from . import projs
from . import obj_from_name
from .obj_from_name import (to_proj, to_model, to_run, to_var, to_region,
to_iterable)
|
"""aospy_user: Library of user-defined aospy objects."""
from aospy import (LAT_STR, LON_STR, PHALF_STR, PFULL_STR, PLEVEL_STR,
TIME_STR, TIME_STR_IDEALIZED)
from . import regions
from . import units
from . import calcs
from . import variables
from . import runs
from . import models
from . import projs
from . import obj_from_name
from .obj_from_name import (to_proj, to_model, to_run, to_var, to_region,
to_iterable)
|
Use aospy coord label constants
|
Use aospy coord label constants
|
Python
|
apache-2.0
|
spencerahill/aospy-obj-lib
|
"""aospy_user: Library of user-defined aospy objects."""
+ from aospy import (LAT_STR, LON_STR, PHALF_STR, PFULL_STR, PLEVEL_STR,
+ TIME_STR, TIME_STR_IDEALIZED)
+
from . import regions
from . import units
from . import calcs
from . import variables
from . import runs
from . import models
from . import projs
from . import obj_from_name
from .obj_from_name import (to_proj, to_model, to_run, to_var, to_region,
to_iterable)
|
Use aospy coord label constants
|
## Code Before:
"""aospy_user: Library of user-defined aospy objects."""
from . import regions
from . import units
from . import calcs
from . import variables
from . import runs
from . import models
from . import projs
from . import obj_from_name
from .obj_from_name import (to_proj, to_model, to_run, to_var, to_region,
to_iterable)
## Instruction:
Use aospy coord label constants
## Code After:
"""aospy_user: Library of user-defined aospy objects."""
from aospy import (LAT_STR, LON_STR, PHALF_STR, PFULL_STR, PLEVEL_STR,
TIME_STR, TIME_STR_IDEALIZED)
from . import regions
from . import units
from . import calcs
from . import variables
from . import runs
from . import models
from . import projs
from . import obj_from_name
from .obj_from_name import (to_proj, to_model, to_run, to_var, to_region,
to_iterable)
|
# ... existing code ...
"""aospy_user: Library of user-defined aospy objects."""
from aospy import (LAT_STR, LON_STR, PHALF_STR, PFULL_STR, PLEVEL_STR,
TIME_STR, TIME_STR_IDEALIZED)
from . import regions
# ... rest of the code ...
|
45c4f2455b453ee361cbb38ed1add996012b1c5e
|
datahelper.py
|
datahelper.py
|
from google.appengine.ext import ndb
from flask import g
from app import app
def put_later(*objs):
"""
Any ndb model instances passed to this method will be put after the flask request has been processed.
"""
for obj in objs:
if obj not in g.dirty_ndb:
g.dirty_ndb.append(obj)
@app.after_request
def store_ndb(response):
"""
Puts the contents of g.dirty_ndb
"""
try:
if g.dirty_ndb:
ndb.put_multi(g.dirty_ndb)
g.dirty_ndb = []
finally:
return response
|
from google.appengine.ext import ndb
from flask import g
from app import app
def put_later(*objs):
"""
Any ndb model instances passed to this method will be put after the flask request has been processed.
"""
for obj in objs:
if obj not in g.dirty_ndb:
g.dirty_ndb.append(obj)
@app.after_request
def store_ndb(response):
"""
Puts the contents of g.dirty_ndb
"""
if g.dirty_ndb:
ndb.put_multi(g.dirty_ndb)
g.dirty_ndb = []
return response
|
Fix bug where dirty_ndb was silently failing.
|
Fix bug where dirty_ndb was silently failing.
|
Python
|
apache-2.0
|
kkinder/GAEStarterKit,kkinder/GAEStarterKit,kkinder/GAEStarterKit
|
from google.appengine.ext import ndb
from flask import g
from app import app
def put_later(*objs):
"""
Any ndb model instances passed to this method will be put after the flask request has been processed.
"""
for obj in objs:
if obj not in g.dirty_ndb:
g.dirty_ndb.append(obj)
@app.after_request
def store_ndb(response):
"""
Puts the contents of g.dirty_ndb
"""
- try:
- if g.dirty_ndb:
+ if g.dirty_ndb:
- ndb.put_multi(g.dirty_ndb)
+ ndb.put_multi(g.dirty_ndb)
- g.dirty_ndb = []
+ g.dirty_ndb = []
- finally:
- return response
+ return response
|
Fix bug where dirty_ndb was silently failing.
|
## Code Before:
from google.appengine.ext import ndb
from flask import g
from app import app
def put_later(*objs):
"""
Any ndb model instances passed to this method will be put after the flask request has been processed.
"""
for obj in objs:
if obj not in g.dirty_ndb:
g.dirty_ndb.append(obj)
@app.after_request
def store_ndb(response):
"""
Puts the contents of g.dirty_ndb
"""
try:
if g.dirty_ndb:
ndb.put_multi(g.dirty_ndb)
g.dirty_ndb = []
finally:
return response
## Instruction:
Fix bug where dirty_ndb was silently failing.
## Code After:
from google.appengine.ext import ndb
from flask import g
from app import app
def put_later(*objs):
"""
Any ndb model instances passed to this method will be put after the flask request has been processed.
"""
for obj in objs:
if obj not in g.dirty_ndb:
g.dirty_ndb.append(obj)
@app.after_request
def store_ndb(response):
"""
Puts the contents of g.dirty_ndb
"""
if g.dirty_ndb:
ndb.put_multi(g.dirty_ndb)
g.dirty_ndb = []
return response
|
# ... existing code ...
"""
if g.dirty_ndb:
ndb.put_multi(g.dirty_ndb)
g.dirty_ndb = []
return response
# ... rest of the code ...
|
d5ad324355e0abdf0a6bdcb41e1f07224742b537
|
src/main.py
|
src/main.py
|
import sys
import game
import menu
menu.init()
menu.chooseOption()
|
import game
import menu
menu.init()
menu.chooseOption()
|
Remove needless import of sys module
|
Remove needless import of sys module
|
Python
|
mit
|
TheUnderscores/card-fight-thingy
|
-
- import sys
import game
import menu
menu.init()
menu.chooseOption()
|
Remove needless import of sys module
|
## Code Before:
import sys
import game
import menu
menu.init()
menu.chooseOption()
## Instruction:
Remove needless import of sys module
## Code After:
import game
import menu
menu.init()
menu.chooseOption()
|
...
...
|
931e2d1e8ba3fd6b129a6d74e3a1ad9984c1938a
|
benchmarks/benchmarks/bench_random.py
|
benchmarks/benchmarks/bench_random.py
|
from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
class Random(Benchmark):
params = ['normal', 'uniform', 'weibull 1', 'binomial 10 0.5',
'poisson 10']
def setup(self, name):
items = name.split()
name = items.pop(0)
params = [float(x) for x in items]
self.func = getattr(np.random, name)
self.params = tuple(params) + ((100, 100),)
def time_rng(self, name):
self.func(*self.params)
class Shuffle(Benchmark):
def setup(self):
self.a = np.arange(100000)
def time_100000(self):
np.random.shuffle(self.a)
|
from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
from numpy.lib import NumpyVersion
class Random(Benchmark):
params = ['normal', 'uniform', 'weibull 1', 'binomial 10 0.5',
'poisson 10']
def setup(self, name):
items = name.split()
name = items.pop(0)
params = [float(x) for x in items]
self.func = getattr(np.random, name)
self.params = tuple(params) + ((100, 100),)
def time_rng(self, name):
self.func(*self.params)
class Shuffle(Benchmark):
def setup(self):
self.a = np.arange(100000)
def time_100000(self):
np.random.shuffle(self.a)
class Randint(Benchmark):
def time_randint_fast(self):
"""Compare to uint32 below"""
np.random.randint(0, 2**30, size=10**5)
def time_randint_slow(self):
"""Compare to uint32 below"""
np.random.randint(0, 2**30 + 1, size=10**5)
class Randint_dtype(Benchmark):
high = {
'bool': 1,
'uint8': 2**7,
'uint16': 2**15,
'uint32': 2**31,
'uint64': 2**63
}
param_names = ['dtype']
params = ['bool', 'uint8', 'uint16', 'uint32', 'uint64']
def setup(self, name):
if NumpyVersion(np.__version__) < '1.11.0.dev0':
raise NotImplementedError
def time_randint_fast(self, name):
high = self.high[name]
np.random.randint(0, high, size=10**5, dtype=name)
def time_randint_slow(self, name):
high = self.high[name]
np.random.randint(0, high + 1, size=10**5, dtype=name)
|
Add benchmark tests for numpy.random.randint.
|
ENH: Add benchmark tests for numpy.random.randint.
This add benchmarks randint. There is one set of benchmarks for the
default dtype, 'l', that can be tracked back, and another set for the
new dtypes 'bool', 'uint8', 'uint16', 'uint32', and 'uint64'.
|
Python
|
bsd-3-clause
|
shoyer/numpy,Dapid/numpy,jakirkham/numpy,WarrenWeckesser/numpy,chatcannon/numpy,WarrenWeckesser/numpy,b-carter/numpy,anntzer/numpy,ssanderson/numpy,simongibbons/numpy,nbeaver/numpy,SiccarPoint/numpy,numpy/numpy,Eric89GXL/numpy,kiwifb/numpy,seberg/numpy,rgommers/numpy,ESSS/numpy,shoyer/numpy,anntzer/numpy,utke1/numpy,dwillmer/numpy,grlee77/numpy,ddasilva/numpy,charris/numpy,tacaswell/numpy,simongibbons/numpy,endolith/numpy,solarjoe/numpy,numpy/numpy,WarrenWeckesser/numpy,stuarteberg/numpy,SiccarPoint/numpy,mhvk/numpy,ahaldane/numpy,rgommers/numpy,bringingheavendown/numpy,anntzer/numpy,ContinuumIO/numpy,Eric89GXL/numpy,kiwifb/numpy,bringingheavendown/numpy,MSeifert04/numpy,solarjoe/numpy,ahaldane/numpy,jakirkham/numpy,maniteja123/numpy,anntzer/numpy,ssanderson/numpy,tacaswell/numpy,WarrenWeckesser/numpy,ContinuumIO/numpy,maniteja123/numpy,njase/numpy,jakirkham/numpy,maniteja123/numpy,drasmuss/numpy,tynn/numpy,shoyer/numpy,endolith/numpy,madphysicist/numpy,stuarteberg/numpy,madphysicist/numpy,jakirkham/numpy,abalkin/numpy,Dapid/numpy,pbrod/numpy,ContinuumIO/numpy,pdebuyl/numpy,pbrod/numpy,mattip/numpy,gmcastil/numpy,rherault-insa/numpy,stuarteberg/numpy,ESSS/numpy,njase/numpy,jonathanunderwood/numpy,jorisvandenbossche/numpy,gfyoung/numpy,b-carter/numpy,jorisvandenbossche/numpy,grlee77/numpy,jonathanunderwood/numpy,pizzathief/numpy,seberg/numpy,drasmuss/numpy,skwbc/numpy,skwbc/numpy,grlee77/numpy,Eric89GXL/numpy,AustereCuriosity/numpy,gfyoung/numpy,SiccarPoint/numpy,pbrod/numpy,rherault-insa/numpy,dwillmer/numpy,ddasilva/numpy,charris/numpy,simongibbons/numpy,chiffa/numpy,chatcannon/numpy,simongibbons/numpy,argriffing/numpy,mhvk/numpy,shoyer/numpy,njase/numpy,grlee77/numpy,pbrod/numpy,WarrenWeckesser/numpy,pizzathief/numpy,pizzathief/numpy,SiccarPoint/numpy,dwillmer/numpy,MSeifert04/numpy,MSeifert04/numpy,seberg/numpy,joferkington/numpy,MSeifert04/numpy,skwbc/numpy,joferkington/numpy,nbeaver/numpy,pdebuyl/numpy,abalkin/numpy,bertrand-l/numpy,madphysicist/numpy,pdebuyl/numpy,bertrand-l/numpy,rherault-insa/numpy,rgommers/numpy,gmcastil/numpy,dwillmer/numpy,tacaswell/numpy,drasmuss/numpy,seberg/numpy,chiffa/numpy,jakirkham/numpy,endolith/numpy,pbrod/numpy,mhvk/numpy,pdebuyl/numpy,mhvk/numpy,charris/numpy,argriffing/numpy,gfyoung/numpy,chatcannon/numpy,pizzathief/numpy,AustereCuriosity/numpy,stuarteberg/numpy,charris/numpy,MSeifert04/numpy,bringingheavendown/numpy,joferkington/numpy,shoyer/numpy,numpy/numpy,jorisvandenbossche/numpy,Dapid/numpy,simongibbons/numpy,mhvk/numpy,mattip/numpy,jorisvandenbossche/numpy,endolith/numpy,ESSS/numpy,behzadnouri/numpy,chiffa/numpy,kiwifb/numpy,argriffing/numpy,jorisvandenbossche/numpy,joferkington/numpy,behzadnouri/numpy,AustereCuriosity/numpy,utke1/numpy,tynn/numpy,grlee77/numpy,ssanderson/numpy,behzadnouri/numpy,madphysicist/numpy,mattip/numpy,Eric89GXL/numpy,ahaldane/numpy,jonathanunderwood/numpy,abalkin/numpy,ahaldane/numpy,madphysicist/numpy,solarjoe/numpy,utke1/numpy,gmcastil/numpy,ddasilva/numpy,numpy/numpy,tynn/numpy,b-carter/numpy,pizzathief/numpy,mattip/numpy,ahaldane/numpy,bertrand-l/numpy,rgommers/numpy,nbeaver/numpy
|
from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
+ from numpy.lib import NumpyVersion
class Random(Benchmark):
params = ['normal', 'uniform', 'weibull 1', 'binomial 10 0.5',
'poisson 10']
def setup(self, name):
items = name.split()
name = items.pop(0)
params = [float(x) for x in items]
self.func = getattr(np.random, name)
self.params = tuple(params) + ((100, 100),)
def time_rng(self, name):
self.func(*self.params)
class Shuffle(Benchmark):
def setup(self):
self.a = np.arange(100000)
def time_100000(self):
np.random.shuffle(self.a)
+
+ class Randint(Benchmark):
+
+ def time_randint_fast(self):
+ """Compare to uint32 below"""
+ np.random.randint(0, 2**30, size=10**5)
+
+ def time_randint_slow(self):
+ """Compare to uint32 below"""
+ np.random.randint(0, 2**30 + 1, size=10**5)
+
+
+ class Randint_dtype(Benchmark):
+ high = {
+ 'bool': 1,
+ 'uint8': 2**7,
+ 'uint16': 2**15,
+ 'uint32': 2**31,
+ 'uint64': 2**63
+ }
+
+ param_names = ['dtype']
+ params = ['bool', 'uint8', 'uint16', 'uint32', 'uint64']
+
+ def setup(self, name):
+ if NumpyVersion(np.__version__) < '1.11.0.dev0':
+ raise NotImplementedError
+
+ def time_randint_fast(self, name):
+ high = self.high[name]
+ np.random.randint(0, high, size=10**5, dtype=name)
+
+ def time_randint_slow(self, name):
+ high = self.high[name]
+ np.random.randint(0, high + 1, size=10**5, dtype=name)
+
+
|
Add benchmark tests for numpy.random.randint.
|
## Code Before:
from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
class Random(Benchmark):
params = ['normal', 'uniform', 'weibull 1', 'binomial 10 0.5',
'poisson 10']
def setup(self, name):
items = name.split()
name = items.pop(0)
params = [float(x) for x in items]
self.func = getattr(np.random, name)
self.params = tuple(params) + ((100, 100),)
def time_rng(self, name):
self.func(*self.params)
class Shuffle(Benchmark):
def setup(self):
self.a = np.arange(100000)
def time_100000(self):
np.random.shuffle(self.a)
## Instruction:
Add benchmark tests for numpy.random.randint.
## Code After:
from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
from numpy.lib import NumpyVersion
class Random(Benchmark):
params = ['normal', 'uniform', 'weibull 1', 'binomial 10 0.5',
'poisson 10']
def setup(self, name):
items = name.split()
name = items.pop(0)
params = [float(x) for x in items]
self.func = getattr(np.random, name)
self.params = tuple(params) + ((100, 100),)
def time_rng(self, name):
self.func(*self.params)
class Shuffle(Benchmark):
def setup(self):
self.a = np.arange(100000)
def time_100000(self):
np.random.shuffle(self.a)
class Randint(Benchmark):
def time_randint_fast(self):
"""Compare to uint32 below"""
np.random.randint(0, 2**30, size=10**5)
def time_randint_slow(self):
"""Compare to uint32 below"""
np.random.randint(0, 2**30 + 1, size=10**5)
class Randint_dtype(Benchmark):
high = {
'bool': 1,
'uint8': 2**7,
'uint16': 2**15,
'uint32': 2**31,
'uint64': 2**63
}
param_names = ['dtype']
params = ['bool', 'uint8', 'uint16', 'uint32', 'uint64']
def setup(self, name):
if NumpyVersion(np.__version__) < '1.11.0.dev0':
raise NotImplementedError
def time_randint_fast(self, name):
high = self.high[name]
np.random.randint(0, high, size=10**5, dtype=name)
def time_randint_slow(self, name):
high = self.high[name]
np.random.randint(0, high + 1, size=10**5, dtype=name)
|
// ... existing code ...
import numpy as np
from numpy.lib import NumpyVersion
// ... modified code ...
np.random.shuffle(self.a)
class Randint(Benchmark):
def time_randint_fast(self):
"""Compare to uint32 below"""
np.random.randint(0, 2**30, size=10**5)
def time_randint_slow(self):
"""Compare to uint32 below"""
np.random.randint(0, 2**30 + 1, size=10**5)
class Randint_dtype(Benchmark):
high = {
'bool': 1,
'uint8': 2**7,
'uint16': 2**15,
'uint32': 2**31,
'uint64': 2**63
}
param_names = ['dtype']
params = ['bool', 'uint8', 'uint16', 'uint32', 'uint64']
def setup(self, name):
if NumpyVersion(np.__version__) < '1.11.0.dev0':
raise NotImplementedError
def time_randint_fast(self, name):
high = self.high[name]
np.random.randint(0, high, size=10**5, dtype=name)
def time_randint_slow(self, name):
high = self.high[name]
np.random.randint(0, high + 1, size=10**5, dtype=name)
// ... rest of the code ...
|
2408c5260106e050557b4898d5826932eb758142
|
normandy/selfrepair/views.py
|
normandy/selfrepair/views.py
|
from django.shortcuts import render
from normandy.base.decorators import api_cache_control
@api_cache_control()
def repair(request, locale):
return render(request, "selfrepair/repair.html")
|
from django.shortcuts import render
from django.views.decorators.cache import cache_control
ONE_WEEK_IN_SECONDS = 60 * 60 * 24 * 7
@cache_control(public=True, max_age=ONE_WEEK_IN_SECONDS)
def repair(request, locale):
return render(request, "selfrepair/repair.html")
|
Increase cache on deprecated self-repair to one week
|
Increase cache on deprecated self-repair to one week
This view serves a message that the system is no longer active. We keep
it around because it is still gets about 40 million hits per day,
primarily from Firefox ESR 52, which never got the Normandy client.
Notably, when we dropped support for Windows XP from Firefox, we put all
XP users onto ESR 52, so we are not likely to be able to remove this
endpoint any time soon.
Fixes #1563
|
Python
|
mpl-2.0
|
mozilla/normandy,mozilla/normandy,mozilla/normandy,mozilla/normandy
|
from django.shortcuts import render
-
- from normandy.base.decorators import api_cache_control
+ from django.views.decorators.cache import cache_control
- @api_cache_control()
+ ONE_WEEK_IN_SECONDS = 60 * 60 * 24 * 7
+
+
+ @cache_control(public=True, max_age=ONE_WEEK_IN_SECONDS)
def repair(request, locale):
return render(request, "selfrepair/repair.html")
|
Increase cache on deprecated self-repair to one week
|
## Code Before:
from django.shortcuts import render
from normandy.base.decorators import api_cache_control
@api_cache_control()
def repair(request, locale):
return render(request, "selfrepair/repair.html")
## Instruction:
Increase cache on deprecated self-repair to one week
## Code After:
from django.shortcuts import render
from django.views.decorators.cache import cache_control
ONE_WEEK_IN_SECONDS = 60 * 60 * 24 * 7
@cache_control(public=True, max_age=ONE_WEEK_IN_SECONDS)
def repair(request, locale):
return render(request, "selfrepair/repair.html")
|
// ... existing code ...
from django.shortcuts import render
from django.views.decorators.cache import cache_control
// ... modified code ...
ONE_WEEK_IN_SECONDS = 60 * 60 * 24 * 7
@cache_control(public=True, max_age=ONE_WEEK_IN_SECONDS)
def repair(request, locale):
// ... rest of the code ...
|
998da5c8d68dff5ad612847a2d16fb6464e30bc2
|
semillas_backend/users/models.py
|
semillas_backend/users/models.py
|
from __future__ import unicode_literals, absolute_import
from django.contrib.auth.models import AbstractUser
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.contrib.gis.db.models import PointField
@python_2_unicode_compatible
class User(AbstractUser):
# First Name and Last Name do not cover name patterns
# around the globe.
name = models.CharField(_('Name of User'), blank=True, max_length=255)
location = PointField(
null=True,
blank=True,
help_text='User Location, only read in production user admin panel'
)
picture = models.ImageField(
null=True,
blank=True,
help_text='Profile Picture'
)
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('users:detail', kwargs={'username': self.username})
|
from __future__ import unicode_literals, absolute_import
from django.contrib.auth.models import AbstractUser
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.contrib.gis.db.models import PointField
from .storage import user_store
@python_2_unicode_compatible
class User(AbstractUser):
# First Name and Last Name do not cover name patterns
# around the globe.
name = models.CharField(_('Name of User'), blank=True, max_length=255)
location = PointField(
null=True,
blank=True,
help_text='User Location, only read in production user admin panel'
)
picture = models.ImageField(
null=True,
blank=True,
help_text='Profile Picture',
storage=user_store
)
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('users:detail', kwargs={'username': self.username})
|
Test for uploading files to /media/ folder in S3
|
Test for uploading files to /media/ folder in S3
|
Python
|
mit
|
Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform
|
from __future__ import unicode_literals, absolute_import
from django.contrib.auth.models import AbstractUser
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.contrib.gis.db.models import PointField
+
+ from .storage import user_store
@python_2_unicode_compatible
class User(AbstractUser):
# First Name and Last Name do not cover name patterns
# around the globe.
name = models.CharField(_('Name of User'), blank=True, max_length=255)
location = PointField(
null=True,
blank=True,
help_text='User Location, only read in production user admin panel'
)
picture = models.ImageField(
null=True,
blank=True,
- help_text='Profile Picture'
+ help_text='Profile Picture',
+ storage=user_store
)
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('users:detail', kwargs={'username': self.username})
|
Test for uploading files to /media/ folder in S3
|
## Code Before:
from __future__ import unicode_literals, absolute_import
from django.contrib.auth.models import AbstractUser
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.contrib.gis.db.models import PointField
@python_2_unicode_compatible
class User(AbstractUser):
# First Name and Last Name do not cover name patterns
# around the globe.
name = models.CharField(_('Name of User'), blank=True, max_length=255)
location = PointField(
null=True,
blank=True,
help_text='User Location, only read in production user admin panel'
)
picture = models.ImageField(
null=True,
blank=True,
help_text='Profile Picture'
)
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('users:detail', kwargs={'username': self.username})
## Instruction:
Test for uploading files to /media/ folder in S3
## Code After:
from __future__ import unicode_literals, absolute_import
from django.contrib.auth.models import AbstractUser
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.contrib.gis.db.models import PointField
from .storage import user_store
@python_2_unicode_compatible
class User(AbstractUser):
# First Name and Last Name do not cover name patterns
# around the globe.
name = models.CharField(_('Name of User'), blank=True, max_length=255)
location = PointField(
null=True,
blank=True,
help_text='User Location, only read in production user admin panel'
)
picture = models.ImageField(
null=True,
blank=True,
help_text='Profile Picture',
storage=user_store
)
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('users:detail', kwargs={'username': self.username})
|
...
from django.contrib.gis.db.models import PointField
from .storage import user_store
...
blank=True,
help_text='Profile Picture',
storage=user_store
)
...
|
fb39b3ffc6fcd3df0f89cd3978796a4377335075
|
tests/primitives/utils.py
|
tests/primitives/utils.py
|
import binascii
import os
import pytest
from cryptography.bindings import _ALL_APIS
from cryptography.primitives.block import BlockCipher
def generate_encrypt_test(param_loader, path, file_names, cipher_factory,
mode_factory, only_if=lambda api: True,
skip_message=None):
def test_encryption(self):
for api in _ALL_APIS:
for file_name in file_names:
for params in param_loader(os.path.join(path, file_name)):
yield (
encrypt_test,
api,
cipher_factory,
mode_factory,
params,
only_if,
skip_message
)
return test_encryption
def encrypt_test(api, cipher_factory, mode_factory, params, only_if,
skip_message):
if not only_if(api):
pytest.skip(skip_message)
plaintext = params.pop("plaintext")
ciphertext = params.pop("ciphertext")
cipher = BlockCipher(
cipher_factory(**params),
mode_factory(**params),
api
)
actual_ciphertext = cipher.encrypt(binascii.unhexlify(plaintext))
actual_ciphertext += cipher.finalize()
assert binascii.hexlify(actual_ciphertext) == ciphertext
|
import binascii
import os
import pytest
from cryptography.bindings import _ALL_APIS
from cryptography.primitives.block import BlockCipher
def generate_encrypt_test(param_loader, path, file_names, cipher_factory,
mode_factory, only_if=lambda api: True,
skip_message=None):
def test_encryption(self):
for api in _ALL_APIS:
for file_name in file_names:
for params in param_loader(os.path.join(path, file_name)):
yield (
encrypt_test,
api,
cipher_factory,
mode_factory,
params,
only_if,
skip_message
)
return test_encryption
def encrypt_test(api, cipher_factory, mode_factory, params, only_if,
skip_message):
if not only_if(api):
pytest.skip(skip_message)
plaintext = params.pop("plaintext")
ciphertext = params.pop("ciphertext")
cipher = BlockCipher(
cipher_factory(**params),
mode_factory(**params),
api
)
actual_ciphertext = cipher.encrypt(binascii.unhexlify(plaintext))
actual_ciphertext += cipher.finalize()
assert actual_ciphertext == binascii.unhexlify(ciphertext)
|
Rewrite to avoid capitalization issues
|
Rewrite to avoid capitalization issues
|
Python
|
bsd-3-clause
|
kimvais/cryptography,Ayrx/cryptography,dstufft/cryptography,sholsapp/cryptography,dstufft/cryptography,bwhmather/cryptography,sholsapp/cryptography,kimvais/cryptography,kimvais/cryptography,Lukasa/cryptography,skeuomorf/cryptography,sholsapp/cryptography,Hasimir/cryptography,skeuomorf/cryptography,Lukasa/cryptography,dstufft/cryptography,Hasimir/cryptography,glyph/cryptography,bwhmather/cryptography,kimvais/cryptography,skeuomorf/cryptography,sholsapp/cryptography,Hasimir/cryptography,Lukasa/cryptography,Ayrx/cryptography,skeuomorf/cryptography,Ayrx/cryptography,Ayrx/cryptography,dstufft/cryptography,glyph/cryptography,bwhmather/cryptography,Hasimir/cryptography,bwhmather/cryptography,dstufft/cryptography
|
import binascii
import os
import pytest
from cryptography.bindings import _ALL_APIS
from cryptography.primitives.block import BlockCipher
def generate_encrypt_test(param_loader, path, file_names, cipher_factory,
mode_factory, only_if=lambda api: True,
skip_message=None):
def test_encryption(self):
for api in _ALL_APIS:
for file_name in file_names:
for params in param_loader(os.path.join(path, file_name)):
yield (
encrypt_test,
api,
cipher_factory,
mode_factory,
params,
only_if,
skip_message
)
return test_encryption
def encrypt_test(api, cipher_factory, mode_factory, params, only_if,
skip_message):
if not only_if(api):
pytest.skip(skip_message)
plaintext = params.pop("plaintext")
ciphertext = params.pop("ciphertext")
cipher = BlockCipher(
cipher_factory(**params),
mode_factory(**params),
api
)
actual_ciphertext = cipher.encrypt(binascii.unhexlify(plaintext))
actual_ciphertext += cipher.finalize()
- assert binascii.hexlify(actual_ciphertext) == ciphertext
+ assert actual_ciphertext == binascii.unhexlify(ciphertext)
|
Rewrite to avoid capitalization issues
|
## Code Before:
import binascii
import os
import pytest
from cryptography.bindings import _ALL_APIS
from cryptography.primitives.block import BlockCipher
def generate_encrypt_test(param_loader, path, file_names, cipher_factory,
mode_factory, only_if=lambda api: True,
skip_message=None):
def test_encryption(self):
for api in _ALL_APIS:
for file_name in file_names:
for params in param_loader(os.path.join(path, file_name)):
yield (
encrypt_test,
api,
cipher_factory,
mode_factory,
params,
only_if,
skip_message
)
return test_encryption
def encrypt_test(api, cipher_factory, mode_factory, params, only_if,
skip_message):
if not only_if(api):
pytest.skip(skip_message)
plaintext = params.pop("plaintext")
ciphertext = params.pop("ciphertext")
cipher = BlockCipher(
cipher_factory(**params),
mode_factory(**params),
api
)
actual_ciphertext = cipher.encrypt(binascii.unhexlify(plaintext))
actual_ciphertext += cipher.finalize()
assert binascii.hexlify(actual_ciphertext) == ciphertext
## Instruction:
Rewrite to avoid capitalization issues
## Code After:
import binascii
import os
import pytest
from cryptography.bindings import _ALL_APIS
from cryptography.primitives.block import BlockCipher
def generate_encrypt_test(param_loader, path, file_names, cipher_factory,
mode_factory, only_if=lambda api: True,
skip_message=None):
def test_encryption(self):
for api in _ALL_APIS:
for file_name in file_names:
for params in param_loader(os.path.join(path, file_name)):
yield (
encrypt_test,
api,
cipher_factory,
mode_factory,
params,
only_if,
skip_message
)
return test_encryption
def encrypt_test(api, cipher_factory, mode_factory, params, only_if,
skip_message):
if not only_if(api):
pytest.skip(skip_message)
plaintext = params.pop("plaintext")
ciphertext = params.pop("ciphertext")
cipher = BlockCipher(
cipher_factory(**params),
mode_factory(**params),
api
)
actual_ciphertext = cipher.encrypt(binascii.unhexlify(plaintext))
actual_ciphertext += cipher.finalize()
assert actual_ciphertext == binascii.unhexlify(ciphertext)
|
...
actual_ciphertext += cipher.finalize()
assert actual_ciphertext == binascii.unhexlify(ciphertext)
...
|
00fc915c09e0052289fa28d7da174e44f838c15b
|
quickstart/python/voice/example-1-make-call/outgoing_call.6.x.py
|
quickstart/python/voice/example-1-make-call/outgoing_call.6.x.py
|
from twilio.rest import Client
# Your Account Sid and Auth Token can be found at https://www.twilio.com/console
account_sid = "AC6062f793ce5918fef56b1681e6446e87"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)
call = client.calls.create(
to="+15558675310",
from_="+15017122661",
url="http://demo.twilio.com/docs/voice.xml"
)
print(call.sid)
|
from twilio.rest import Client
# Your Account Sid and Auth Token can be found at https://www.twilio.com/console
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)
call = client.calls.create(
to="+15558675310",
from_="+15017122661",
url="http://demo.twilio.com/docs/voice.xml"
)
print(call.sid)
|
Use placeholder for account sid :facepalm:
|
Use placeholder for account sid :facepalm:
|
Python
|
mit
|
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets
|
from twilio.rest import Client
# Your Account Sid and Auth Token can be found at https://www.twilio.com/console
- account_sid = "AC6062f793ce5918fef56b1681e6446e87"
+ account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)
call = client.calls.create(
to="+15558675310",
from_="+15017122661",
url="http://demo.twilio.com/docs/voice.xml"
)
print(call.sid)
|
Use placeholder for account sid :facepalm:
|
## Code Before:
from twilio.rest import Client
# Your Account Sid and Auth Token can be found at https://www.twilio.com/console
account_sid = "AC6062f793ce5918fef56b1681e6446e87"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)
call = client.calls.create(
to="+15558675310",
from_="+15017122661",
url="http://demo.twilio.com/docs/voice.xml"
)
print(call.sid)
## Instruction:
Use placeholder for account sid :facepalm:
## Code After:
from twilio.rest import Client
# Your Account Sid and Auth Token can be found at https://www.twilio.com/console
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)
call = client.calls.create(
to="+15558675310",
from_="+15017122661",
url="http://demo.twilio.com/docs/voice.xml"
)
print(call.sid)
|
# ... existing code ...
# Your Account Sid and Auth Token can be found at https://www.twilio.com/console
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
# ... rest of the code ...
|
c7f1759ef02c0fa12ca408dfac9d25227fbceba7
|
nova/policies/server_password.py
|
nova/policies/server_password.py
|
from oslo_policy import policy
from nova.policies import base
BASE_POLICY_NAME = 'os_compute_api:os-server-password'
server_password_policies = [
policy.DocumentedRuleDefault(
BASE_POLICY_NAME,
base.RULE_ADMIN_OR_OWNER,
"Show and clear the encrypted administrative password of a server",
[
{
'method': 'GET',
'path': '/servers/{server_id}/os-server-password'
},
{
'method': 'DELETE',
'path': '/servers/{server_id}/os-server-password'
}
]),
]
def list_rules():
return server_password_policies
|
from oslo_policy import policy
from nova.policies import base
BASE_POLICY_NAME = 'os_compute_api:os-server-password'
server_password_policies = [
policy.DocumentedRuleDefault(
name=BASE_POLICY_NAME,
check_str=base.RULE_ADMIN_OR_OWNER,
description="Show and clear the encrypted administrative "
"password of a server",
operations=[
{
'method': 'GET',
'path': '/servers/{server_id}/os-server-password'
},
{
'method': 'DELETE',
'path': '/servers/{server_id}/os-server-password'
}
],
scope_types=['system', 'project']),
]
def list_rules():
return server_password_policies
|
Introduce scope_types in server password policy
|
Introduce scope_types in server password policy
oslo.policy introduced the scope_type feature which can
control the access level at system-level and project-level.
- https://docs.openstack.org/oslo.policy/latest/user/usage.html#setting-scope
- http://specs.openstack.org/openstack/keystone-specs/specs/keystone/queens/system-scope.html
Appropriate scope_type for nova case:
- https://specs.openstack.org/openstack/nova-specs/specs/ussuri/approved/policy-defaults-refresh.html#scope
This commit introduce scope_type for server password API policies
as ['system', 'project'].
Also adds the test case with scope_type enabled and verify we
pass and fail the policy check with expected context.
Partial implement blueprint policy-defaults-refresh
Change-Id: I8f5e66810c68a871e57a5362a931545bccded608
|
Python
|
apache-2.0
|
klmitch/nova,openstack/nova,klmitch/nova,openstack/nova,mahak/nova,mahak/nova,mahak/nova,klmitch/nova,klmitch/nova,openstack/nova
|
from oslo_policy import policy
from nova.policies import base
BASE_POLICY_NAME = 'os_compute_api:os-server-password'
server_password_policies = [
policy.DocumentedRuleDefault(
- BASE_POLICY_NAME,
+ name=BASE_POLICY_NAME,
- base.RULE_ADMIN_OR_OWNER,
+ check_str=base.RULE_ADMIN_OR_OWNER,
- "Show and clear the encrypted administrative password of a server",
+ description="Show and clear the encrypted administrative "
- [
+ "password of a server",
+ operations=[
{
'method': 'GET',
'path': '/servers/{server_id}/os-server-password'
},
{
'method': 'DELETE',
'path': '/servers/{server_id}/os-server-password'
}
- ]),
+ ],
+ scope_types=['system', 'project']),
]
def list_rules():
return server_password_policies
|
Introduce scope_types in server password policy
|
## Code Before:
from oslo_policy import policy
from nova.policies import base
BASE_POLICY_NAME = 'os_compute_api:os-server-password'
server_password_policies = [
policy.DocumentedRuleDefault(
BASE_POLICY_NAME,
base.RULE_ADMIN_OR_OWNER,
"Show and clear the encrypted administrative password of a server",
[
{
'method': 'GET',
'path': '/servers/{server_id}/os-server-password'
},
{
'method': 'DELETE',
'path': '/servers/{server_id}/os-server-password'
}
]),
]
def list_rules():
return server_password_policies
## Instruction:
Introduce scope_types in server password policy
## Code After:
from oslo_policy import policy
from nova.policies import base
BASE_POLICY_NAME = 'os_compute_api:os-server-password'
server_password_policies = [
policy.DocumentedRuleDefault(
name=BASE_POLICY_NAME,
check_str=base.RULE_ADMIN_OR_OWNER,
description="Show and clear the encrypted administrative "
"password of a server",
operations=[
{
'method': 'GET',
'path': '/servers/{server_id}/os-server-password'
},
{
'method': 'DELETE',
'path': '/servers/{server_id}/os-server-password'
}
],
scope_types=['system', 'project']),
]
def list_rules():
return server_password_policies
|
// ... existing code ...
policy.DocumentedRuleDefault(
name=BASE_POLICY_NAME,
check_str=base.RULE_ADMIN_OR_OWNER,
description="Show and clear the encrypted administrative "
"password of a server",
operations=[
{
// ... modified code ...
}
],
scope_types=['system', 'project']),
]
// ... rest of the code ...
|
99e0e90552c16067cfd41c9e89464311494c5a85
|
kitsune/sumo/management/commands/nunjucks_precompile.py
|
kitsune/sumo/management/commands/nunjucks_precompile.py
|
import os
import subprocess
from django.conf import settings
from django.core.management.base import BaseCommand
ROOT = os.path.realpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
path = lambda *a: os.path.join(ROOT, *a)
class Command(BaseCommand):
help = 'Precompiles nunjuck templates'
def handle(self, *args, **kwargs):
files = os.listdir(path('static/tpl'))
for f in files:
if f.endswith('.html'):
tpl = f[:-5]
cmd = '%s %s > %s' % (
settings.NUNJUCKS_PRECOMPILE_BIN,
path('static/tpl'),
path('static/js/templates/%s.js' % tpl))
subprocess.call(cmd, shell=True)
|
import os
import subprocess
from django.conf import settings
from django.core.management.base import BaseCommand
ROOT = os.path.realpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
path = lambda *a: os.path.join(ROOT, *a)
class Command(BaseCommand):
help = 'Precompiles nunjuck templates'
def handle(self, *args, **kwargs):
try:
os.makedirs(path('static/js/templates'))
except OSError:
pass
try:
os.makedirs(path('static/tpl'))
except OSError:
pass
files = os.listdir(path('static/tpl'))
for f in files:
if f.endswith('.html'):
tpl = f[:-5]
cmd = '%s %s > %s' % (
settings.NUNJUCKS_PRECOMPILE_BIN,
path('static/tpl'),
path('static/js/templates/%s.js' % tpl))
subprocess.call(cmd, shell=True)
|
Fix nunjucks command so travis is happy
|
Fix nunjucks command so travis is happy
|
Python
|
bsd-3-clause
|
rlr/kitsune,orvi2014/kitsune,silentbob73/kitsune,H1ghT0p/kitsune,MziRintu/kitsune,feer56/Kitsune1,philipp-sumo/kitsune,safwanrahman/kitsune,turtleloveshoes/kitsune,H1ghT0p/kitsune,orvi2014/kitsune,safwanrahman/linuxdesh,safwanrahman/kitsune,Osmose/kitsune,Osmose/kitsune,NewPresident1/kitsune,H1ghT0p/kitsune,MziRintu/kitsune,safwanrahman/kitsune,iDTLabssl/kitsune,feer56/Kitsune2,dbbhattacharya/kitsune,safwanrahman/linuxdesh,MikkCZ/kitsune,YOTOV-LIMITED/kitsune,brittanystoroz/kitsune,rlr/kitsune,mozilla/kitsune,asdofindia/kitsune,orvi2014/kitsune,Osmose/kitsune,turtleloveshoes/kitsune,feer56/Kitsune2,feer56/Kitsune2,chirilo/kitsune,feer56/Kitsune1,YOTOV-LIMITED/kitsune,MziRintu/kitsune,chirilo/kitsune,MikkCZ/kitsune,rlr/kitsune,MikkCZ/kitsune,dbbhattacharya/kitsune,mozilla/kitsune,brittanystoroz/kitsune,dbbhattacharya/kitsune,feer56/Kitsune1,brittanystoroz/kitsune,anushbmx/kitsune,asdofindia/kitsune,feer56/Kitsune2,brittanystoroz/kitsune,NewPresident1/kitsune,safwanrahman/linuxdesh,YOTOV-LIMITED/kitsune,silentbob73/kitsune,turtleloveshoes/kitsune,safwanrahman/kitsune,silentbob73/kitsune,MziRintu/kitsune,iDTLabssl/kitsune,anushbmx/kitsune,anushbmx/kitsune,orvi2014/kitsune,Osmose/kitsune,YOTOV-LIMITED/kitsune,mythmon/kitsune,philipp-sumo/kitsune,dbbhattacharya/kitsune,turtleloveshoes/kitsune,silentbob73/kitsune,mythmon/kitsune,philipp-sumo/kitsune,iDTLabssl/kitsune,mozilla/kitsune,chirilo/kitsune,rlr/kitsune,mozilla/kitsune,MikkCZ/kitsune,NewPresident1/kitsune,iDTLabssl/kitsune,NewPresident1/kitsune,anushbmx/kitsune,mythmon/kitsune,asdofindia/kitsune,mythmon/kitsune,asdofindia/kitsune,chirilo/kitsune,H1ghT0p/kitsune
|
import os
import subprocess
from django.conf import settings
from django.core.management.base import BaseCommand
ROOT = os.path.realpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
path = lambda *a: os.path.join(ROOT, *a)
class Command(BaseCommand):
help = 'Precompiles nunjuck templates'
def handle(self, *args, **kwargs):
+ try:
+ os.makedirs(path('static/js/templates'))
+ except OSError:
+ pass
+
+ try:
+ os.makedirs(path('static/tpl'))
+ except OSError:
+ pass
+
files = os.listdir(path('static/tpl'))
for f in files:
if f.endswith('.html'):
tpl = f[:-5]
cmd = '%s %s > %s' % (
settings.NUNJUCKS_PRECOMPILE_BIN,
path('static/tpl'),
path('static/js/templates/%s.js' % tpl))
subprocess.call(cmd, shell=True)
|
Fix nunjucks command so travis is happy
|
## Code Before:
import os
import subprocess
from django.conf import settings
from django.core.management.base import BaseCommand
ROOT = os.path.realpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
path = lambda *a: os.path.join(ROOT, *a)
class Command(BaseCommand):
help = 'Precompiles nunjuck templates'
def handle(self, *args, **kwargs):
files = os.listdir(path('static/tpl'))
for f in files:
if f.endswith('.html'):
tpl = f[:-5]
cmd = '%s %s > %s' % (
settings.NUNJUCKS_PRECOMPILE_BIN,
path('static/tpl'),
path('static/js/templates/%s.js' % tpl))
subprocess.call(cmd, shell=True)
## Instruction:
Fix nunjucks command so travis is happy
## Code After:
import os
import subprocess
from django.conf import settings
from django.core.management.base import BaseCommand
ROOT = os.path.realpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
path = lambda *a: os.path.join(ROOT, *a)
class Command(BaseCommand):
help = 'Precompiles nunjuck templates'
def handle(self, *args, **kwargs):
try:
os.makedirs(path('static/js/templates'))
except OSError:
pass
try:
os.makedirs(path('static/tpl'))
except OSError:
pass
files = os.listdir(path('static/tpl'))
for f in files:
if f.endswith('.html'):
tpl = f[:-5]
cmd = '%s %s > %s' % (
settings.NUNJUCKS_PRECOMPILE_BIN,
path('static/tpl'),
path('static/js/templates/%s.js' % tpl))
subprocess.call(cmd, shell=True)
|
// ... existing code ...
def handle(self, *args, **kwargs):
try:
os.makedirs(path('static/js/templates'))
except OSError:
pass
try:
os.makedirs(path('static/tpl'))
except OSError:
pass
files = os.listdir(path('static/tpl'))
// ... rest of the code ...
|
6cedfb17afbb3a869336d23cefdfcae1a65754f9
|
tests/test_check.py
|
tests/test_check.py
|
import unittest
from binaryornot import check
class TestIsBinary(unittest.TestCase):
def setUp(self):
pass
def test_is_binary(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
|
import unittest
from binaryornot.check import is_binary
class TestIsBinary(unittest.TestCase):
def test_css(self):
self.assertFalse(is_binary('tests/files/bootstrap-glyphicons.css'))
def test_json(self):
self.assertFalse(is_binary('tests/files/cookiecutter.json'))
def test_eot(self):
self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.eot'))
def test_otf(self):
self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.otf'))
def test_svg(self):
self.assertFalse(is_binary('tests/files/glyphiconshalflings-regular.svg'))
def test_ttf(self):
self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.ttf'))
def test_woff(self):
self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.woff'))
def test_txt(self):
self.assertFalse(is_binary('tests/files/robots.txt'))
if __name__ == '__main__':
unittest.main()
|
Add lots of miserably failing tests.
|
Add lots of miserably failing tests.
|
Python
|
bsd-3-clause
|
pombredanne/binaryornot,0k/binaryornot,pombredanne/binaryornot,pombredanne/binaryornot,audreyr/binaryornot,audreyr/binaryornot,hackebrot/binaryornot,hackebrot/binaryornot,0k/binaryornot,audreyr/binaryornot,hackebrot/binaryornot
|
import unittest
- from binaryornot import check
+ from binaryornot.check import is_binary
class TestIsBinary(unittest.TestCase):
- def setUp(self):
+ def test_css(self):
- pass
+ self.assertFalse(is_binary('tests/files/bootstrap-glyphicons.css'))
- def test_is_binary(self):
+ def test_json(self):
- pass
+ self.assertFalse(is_binary('tests/files/cookiecutter.json'))
- def tearDown(self):
+ def test_eot(self):
- pass
+ self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.eot'))
+
+ def test_otf(self):
+ self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.otf'))
+
+ def test_svg(self):
+ self.assertFalse(is_binary('tests/files/glyphiconshalflings-regular.svg'))
+
+ def test_ttf(self):
+ self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.ttf'))
+
+ def test_woff(self):
+ self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.woff'))
+
+ def test_txt(self):
+ self.assertFalse(is_binary('tests/files/robots.txt'))
+
if __name__ == '__main__':
unittest.main()
|
Add lots of miserably failing tests.
|
## Code Before:
import unittest
from binaryornot import check
class TestIsBinary(unittest.TestCase):
def setUp(self):
pass
def test_is_binary(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
## Instruction:
Add lots of miserably failing tests.
## Code After:
import unittest
from binaryornot.check import is_binary
class TestIsBinary(unittest.TestCase):
def test_css(self):
self.assertFalse(is_binary('tests/files/bootstrap-glyphicons.css'))
def test_json(self):
self.assertFalse(is_binary('tests/files/cookiecutter.json'))
def test_eot(self):
self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.eot'))
def test_otf(self):
self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.otf'))
def test_svg(self):
self.assertFalse(is_binary('tests/files/glyphiconshalflings-regular.svg'))
def test_ttf(self):
self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.ttf'))
def test_woff(self):
self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.woff'))
def test_txt(self):
self.assertFalse(is_binary('tests/files/robots.txt'))
if __name__ == '__main__':
unittest.main()
|
// ... existing code ...
from binaryornot.check import is_binary
// ... modified code ...
def test_css(self):
self.assertFalse(is_binary('tests/files/bootstrap-glyphicons.css'))
def test_json(self):
self.assertFalse(is_binary('tests/files/cookiecutter.json'))
def test_eot(self):
self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.eot'))
def test_otf(self):
self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.otf'))
def test_svg(self):
self.assertFalse(is_binary('tests/files/glyphiconshalflings-regular.svg'))
def test_ttf(self):
self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.ttf'))
def test_woff(self):
self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.woff'))
def test_txt(self):
self.assertFalse(is_binary('tests/files/robots.txt'))
// ... rest of the code ...
|
2d1c8a62295ed5150f31e11cdbbf98d4d74498d8
|
bin/cgroup-limits.py
|
bin/cgroup-limits.py
|
env_vars = {}
def read_file(path):
try:
with open(path, 'r') as f:
return f.read().strip()
except IOError:
return None
def get_memory_limit():
limit = read_file('/sys/fs/cgroup/memory/memory.limit_in_bytes')
if limit:
env_vars['MEMORY_LIMIT_IN_BYTES'] = limit
def get_number_of_cores():
core_count = 0
line = read_file('/sys/fs/cgroup/cpuset/cpuset.cpus')
if line is None:
return
for group in line.split(','):
core_ids = list(map(int, group.split('-')))
if len(core_ids) == 2:
core_count += core_ids[1] - core_ids[0] + 1
else:
core_count += 1
env_vars['NUMBER_OF_CORES'] = str(core_count)
get_memory_limit()
get_number_of_cores()
for item in env_vars.items():
print("=".join(item))
|
env_vars = {}
def read_file(path):
try:
with open(path, 'r') as f:
return f.read().strip()
except IOError:
return None
def get_memory_limit():
limit = read_file('/sys/fs/cgroup/memory/memory.limit_in_bytes')
if limit:
env_vars['MEMORY_LIMIT_IN_BYTES'] = limit
def get_number_of_cores():
core_count = 0
line = read_file('/sys/fs/cgroup/cpuset/cpuset.cpus')
if line is None:
return
for group in line.split(','):
core_ids = list(map(int, group.split('-')))
if len(core_ids) == 2:
core_count += core_ids[1] - core_ids[0] + 1
else:
core_count += 1
env_vars['NUMBER_OF_CORES'] = str(core_count)
get_memory_limit()
get_number_of_cores()
print("MAX_MEMORY_LIMIT_IN_BYTES=9223372036854775807")
for item in env_vars.items():
print("=".join(item))
|
Set MAX_MEMORY_LIMIT_IN_BYTES to number returned by cgroups where there is no limit
|
Set MAX_MEMORY_LIMIT_IN_BYTES to number returned by cgroups where there is no limit
|
Python
|
apache-2.0
|
openshift/sti-base,hhorak/sti-base,soltysh/sti-base,openshift/sti-base,bparees/sti-base,sclorg/s2i-base-container,mfojtik/sti-base,mfojtik/sti-base,bparees/sti-base
|
env_vars = {}
def read_file(path):
try:
with open(path, 'r') as f:
return f.read().strip()
except IOError:
return None
def get_memory_limit():
limit = read_file('/sys/fs/cgroup/memory/memory.limit_in_bytes')
if limit:
env_vars['MEMORY_LIMIT_IN_BYTES'] = limit
def get_number_of_cores():
core_count = 0
line = read_file('/sys/fs/cgroup/cpuset/cpuset.cpus')
if line is None:
return
for group in line.split(','):
core_ids = list(map(int, group.split('-')))
if len(core_ids) == 2:
core_count += core_ids[1] - core_ids[0] + 1
else:
core_count += 1
env_vars['NUMBER_OF_CORES'] = str(core_count)
get_memory_limit()
get_number_of_cores()
+ print("MAX_MEMORY_LIMIT_IN_BYTES=9223372036854775807")
for item in env_vars.items():
print("=".join(item))
|
Set MAX_MEMORY_LIMIT_IN_BYTES to number returned by cgroups where there is no limit
|
## Code Before:
env_vars = {}
def read_file(path):
try:
with open(path, 'r') as f:
return f.read().strip()
except IOError:
return None
def get_memory_limit():
limit = read_file('/sys/fs/cgroup/memory/memory.limit_in_bytes')
if limit:
env_vars['MEMORY_LIMIT_IN_BYTES'] = limit
def get_number_of_cores():
core_count = 0
line = read_file('/sys/fs/cgroup/cpuset/cpuset.cpus')
if line is None:
return
for group in line.split(','):
core_ids = list(map(int, group.split('-')))
if len(core_ids) == 2:
core_count += core_ids[1] - core_ids[0] + 1
else:
core_count += 1
env_vars['NUMBER_OF_CORES'] = str(core_count)
get_memory_limit()
get_number_of_cores()
for item in env_vars.items():
print("=".join(item))
## Instruction:
Set MAX_MEMORY_LIMIT_IN_BYTES to number returned by cgroups where there is no limit
## Code After:
env_vars = {}
def read_file(path):
try:
with open(path, 'r') as f:
return f.read().strip()
except IOError:
return None
def get_memory_limit():
limit = read_file('/sys/fs/cgroup/memory/memory.limit_in_bytes')
if limit:
env_vars['MEMORY_LIMIT_IN_BYTES'] = limit
def get_number_of_cores():
core_count = 0
line = read_file('/sys/fs/cgroup/cpuset/cpuset.cpus')
if line is None:
return
for group in line.split(','):
core_ids = list(map(int, group.split('-')))
if len(core_ids) == 2:
core_count += core_ids[1] - core_ids[0] + 1
else:
core_count += 1
env_vars['NUMBER_OF_CORES'] = str(core_count)
get_memory_limit()
get_number_of_cores()
print("MAX_MEMORY_LIMIT_IN_BYTES=9223372036854775807")
for item in env_vars.items():
print("=".join(item))
|
# ... existing code ...
print("MAX_MEMORY_LIMIT_IN_BYTES=9223372036854775807")
for item in env_vars.items():
# ... rest of the code ...
|
6fbe58692005e5c8b7a9c4f4e98984ae86d347a2
|
pinax/messages/context_processors.py
|
pinax/messages/context_processors.py
|
from .models import Thread
def user_messages(request):
c = {}
if request.user.is_authenticated():
c["inbox_count"] = Thread.inbox(request.user).count()
return c
|
from .models import Thread
def user_messages(request):
c = {}
if request.user.is_authenticated():
c["inbox_threads"] = Thread.inbox(request.user)
c["unread_threads"] = Thread.unread(request.user)
return c
|
Return querysets in context processor to be more useful
|
Return querysets in context processor to be more useful
|
Python
|
mit
|
eldarion/user_messages,pinax/pinax-messages,pinax/pinax-messages,arthur-wsw/pinax-messages,eldarion/user_messages,arthur-wsw/pinax-messages
|
from .models import Thread
def user_messages(request):
c = {}
if request.user.is_authenticated():
- c["inbox_count"] = Thread.inbox(request.user).count()
+ c["inbox_threads"] = Thread.inbox(request.user)
+ c["unread_threads"] = Thread.unread(request.user)
return c
|
Return querysets in context processor to be more useful
|
## Code Before:
from .models import Thread
def user_messages(request):
c = {}
if request.user.is_authenticated():
c["inbox_count"] = Thread.inbox(request.user).count()
return c
## Instruction:
Return querysets in context processor to be more useful
## Code After:
from .models import Thread
def user_messages(request):
c = {}
if request.user.is_authenticated():
c["inbox_threads"] = Thread.inbox(request.user)
c["unread_threads"] = Thread.unread(request.user)
return c
|
...
if request.user.is_authenticated():
c["inbox_threads"] = Thread.inbox(request.user)
c["unread_threads"] = Thread.unread(request.user)
return c
...
|
8eca7b30865e4d02fd440f55ad3215dee6fab8a1
|
gee_asset_manager/batch_remover.py
|
gee_asset_manager/batch_remover.py
|
import fnmatch
import logging
import sys
import ee
def delete(asset_path):
root = asset_path[:asset_path.rfind('/')]
all_assets_names = [e['id'] for e in ee.data.getList({'id': root})]
filtered_names = fnmatch.filter(all_assets_names, asset_path)
if not filtered_names:
logging.warning('Nothing to remove. Exiting.')
sys.exit(1)
else:
for path in filtered_names:
__delete_recursive(path)
logging.info('Collection %s removed', path)
def __delete_recursive(asset_path):
info = ee.data.getInfo(asset_path)
if not info:
logging.warning('Nothing to delete.')
sys.exit(1)
elif info['type'] == 'Image':
pass
elif info['type'] == 'Folder':
items_in_destination = ee.data.getList({'id': asset_path})
for item in items_in_destination:
logging.info('Removing items in %s folder', item['id'])
delete(item['id'])
else:
items_in_destination = ee.data.getList({'id': asset_path})
for item in items_in_destination:
ee.data.deleteAsset(item['id'])
ee.data.deleteAsset(asset_path)
|
import fnmatch
import logging
import sys
import ee
def delete(asset_path):
root_idx = asset_path.rfind('/')
if root_idx == -1:
logging.warning('Asset not found. Make sure you pass full asset name, e.g. users/pinkiepie/rainbow')
sys.exit(1)
root = asset_path[:root_idx]
all_assets_names = [e['id'] for e in ee.data.getList({'id': root})]
filtered_names = fnmatch.filter(all_assets_names, asset_path)
if not filtered_names:
logging.warning('Nothing to remove. Exiting.')
sys.exit(1)
else:
for path in filtered_names:
__delete_recursive(path)
logging.info('Collection %s removed', path)
def __delete_recursive(asset_path):
info = ee.data.getInfo(asset_path)
if not info:
logging.warning('Nothing to delete.')
sys.exit(1)
elif info['type'] == 'Image':
pass
elif info['type'] == 'Folder':
items_in_destination = ee.data.getList({'id': asset_path})
for item in items_in_destination:
logging.info('Removing items in %s folder', item['id'])
delete(item['id'])
else:
items_in_destination = ee.data.getList({'id': asset_path})
for item in items_in_destination:
ee.data.deleteAsset(item['id'])
ee.data.deleteAsset(asset_path)
|
Add warning when removing an asset without full path
|
Add warning when removing an asset without full path
|
Python
|
apache-2.0
|
tracek/gee_asset_manager
|
import fnmatch
import logging
import sys
import ee
def delete(asset_path):
- root = asset_path[:asset_path.rfind('/')]
+ root_idx = asset_path.rfind('/')
+ if root_idx == -1:
+ logging.warning('Asset not found. Make sure you pass full asset name, e.g. users/pinkiepie/rainbow')
+ sys.exit(1)
+ root = asset_path[:root_idx]
all_assets_names = [e['id'] for e in ee.data.getList({'id': root})]
filtered_names = fnmatch.filter(all_assets_names, asset_path)
if not filtered_names:
logging.warning('Nothing to remove. Exiting.')
sys.exit(1)
else:
for path in filtered_names:
__delete_recursive(path)
logging.info('Collection %s removed', path)
def __delete_recursive(asset_path):
info = ee.data.getInfo(asset_path)
if not info:
logging.warning('Nothing to delete.')
sys.exit(1)
elif info['type'] == 'Image':
pass
elif info['type'] == 'Folder':
items_in_destination = ee.data.getList({'id': asset_path})
for item in items_in_destination:
logging.info('Removing items in %s folder', item['id'])
delete(item['id'])
else:
items_in_destination = ee.data.getList({'id': asset_path})
for item in items_in_destination:
ee.data.deleteAsset(item['id'])
ee.data.deleteAsset(asset_path)
|
Add warning when removing an asset without full path
|
## Code Before:
import fnmatch
import logging
import sys
import ee
def delete(asset_path):
root = asset_path[:asset_path.rfind('/')]
all_assets_names = [e['id'] for e in ee.data.getList({'id': root})]
filtered_names = fnmatch.filter(all_assets_names, asset_path)
if not filtered_names:
logging.warning('Nothing to remove. Exiting.')
sys.exit(1)
else:
for path in filtered_names:
__delete_recursive(path)
logging.info('Collection %s removed', path)
def __delete_recursive(asset_path):
info = ee.data.getInfo(asset_path)
if not info:
logging.warning('Nothing to delete.')
sys.exit(1)
elif info['type'] == 'Image':
pass
elif info['type'] == 'Folder':
items_in_destination = ee.data.getList({'id': asset_path})
for item in items_in_destination:
logging.info('Removing items in %s folder', item['id'])
delete(item['id'])
else:
items_in_destination = ee.data.getList({'id': asset_path})
for item in items_in_destination:
ee.data.deleteAsset(item['id'])
ee.data.deleteAsset(asset_path)
## Instruction:
Add warning when removing an asset without full path
## Code After:
import fnmatch
import logging
import sys
import ee
def delete(asset_path):
root_idx = asset_path.rfind('/')
if root_idx == -1:
logging.warning('Asset not found. Make sure you pass full asset name, e.g. users/pinkiepie/rainbow')
sys.exit(1)
root = asset_path[:root_idx]
all_assets_names = [e['id'] for e in ee.data.getList({'id': root})]
filtered_names = fnmatch.filter(all_assets_names, asset_path)
if not filtered_names:
logging.warning('Nothing to remove. Exiting.')
sys.exit(1)
else:
for path in filtered_names:
__delete_recursive(path)
logging.info('Collection %s removed', path)
def __delete_recursive(asset_path):
info = ee.data.getInfo(asset_path)
if not info:
logging.warning('Nothing to delete.')
sys.exit(1)
elif info['type'] == 'Image':
pass
elif info['type'] == 'Folder':
items_in_destination = ee.data.getList({'id': asset_path})
for item in items_in_destination:
logging.info('Removing items in %s folder', item['id'])
delete(item['id'])
else:
items_in_destination = ee.data.getList({'id': asset_path})
for item in items_in_destination:
ee.data.deleteAsset(item['id'])
ee.data.deleteAsset(asset_path)
|
# ... existing code ...
def delete(asset_path):
root_idx = asset_path.rfind('/')
if root_idx == -1:
logging.warning('Asset not found. Make sure you pass full asset name, e.g. users/pinkiepie/rainbow')
sys.exit(1)
root = asset_path[:root_idx]
all_assets_names = [e['id'] for e in ee.data.getList({'id': root})]
# ... rest of the code ...
|
ccd660c5deba37c0c324e64666eb6421696b3144
|
puffin/gui/form.py
|
puffin/gui/form.py
|
from flask_wtf import Form
from wtforms import StringField, IntegerField, PasswordField, SubmitField, SelectField
from wtforms.validators import Required, Length, Regexp
from ..core.db import db
from ..core.security import User
from .. import app
class ApplicationForm(Form):
start = SubmitField('Start')
stop = SubmitField('Stop')
class ApplicationSettingsForm(Form):
domain = StringField('Domain', description="If you change it then make sure you also configure it with your DNS provider")
submit = SubmitField('Update')
def validate(self):
rv = Form.validate(self)
if not rv:
return False
if self.domain.data:
server_name = app.config["SERVER_NAME_FULL"]
if server_name != "localhost" and self.domain.data.endswith(server_name):
self.domain.errors.append('Invalid domain, cannot end with ' + server_name)
return False
return True
class ProfileForm(Form):
login = StringField('Login')
email = StringField('Email')
name = StringField('Name', validators=[Required(), Length(1, 64),
Regexp(r'^[A-Za-z0-9_\- ]+$', 0, 'Name must have only letters, numbers, spaces, dots, dashes or underscores')])
submit = SubmitField('Update')
|
from flask_wtf import Form
from wtforms import StringField, IntegerField, PasswordField, SubmitField, SelectField
from wtforms.validators import Required, Length, Regexp
from ..core.db import db
from ..core.security import User
from .. import app
class ApplicationForm(Form):
start = SubmitField('Start')
stop = SubmitField('Stop')
class ApplicationSettingsForm(Form):
domain = StringField('Domain', description="If you change it then make sure you also configure it with your DNS provider")
submit = SubmitField('Update')
def validate(self):
rv = Form.validate(self)
if not rv:
return False
if self.domain.data:
server_name = app.config["SERVER_NAME_FULL"]
if (server_name != "localhost"
and not self.domain.data.endswith(current_user.login + "." + server_name)
and self.domain.data.endswith(server_name)):
self.domain.errors.append('Invalid domain, cannot end with ' + server_name)
return False
return True
class ProfileForm(Form):
login = StringField('Login')
email = StringField('Email')
name = StringField('Name', validators=[Required(), Length(1, 64),
Regexp(r'^[A-Za-z0-9_\- ]+$', 0, 'Name must have only letters, numbers, spaces, dots, dashes or underscores')])
submit = SubmitField('Update')
|
Allow changing to own domain name
|
Allow changing to own domain name
|
Python
|
agpl-3.0
|
loomchild/jenca-puffin,puffinrocks/puffin,loomchild/puffin,loomchild/puffin,loomchild/puffin,loomchild/puffin,puffinrocks/puffin,loomchild/jenca-puffin,loomchild/puffin
|
from flask_wtf import Form
from wtforms import StringField, IntegerField, PasswordField, SubmitField, SelectField
from wtforms.validators import Required, Length, Regexp
from ..core.db import db
from ..core.security import User
from .. import app
class ApplicationForm(Form):
start = SubmitField('Start')
stop = SubmitField('Stop')
class ApplicationSettingsForm(Form):
domain = StringField('Domain', description="If you change it then make sure you also configure it with your DNS provider")
submit = SubmitField('Update')
def validate(self):
rv = Form.validate(self)
if not rv:
return False
if self.domain.data:
server_name = app.config["SERVER_NAME_FULL"]
+ if (server_name != "localhost"
+ and not self.domain.data.endswith(current_user.login + "." + server_name)
- if server_name != "localhost" and self.domain.data.endswith(server_name):
+ and self.domain.data.endswith(server_name)):
self.domain.errors.append('Invalid domain, cannot end with ' + server_name)
return False
return True
class ProfileForm(Form):
login = StringField('Login')
email = StringField('Email')
name = StringField('Name', validators=[Required(), Length(1, 64),
Regexp(r'^[A-Za-z0-9_\- ]+$', 0, 'Name must have only letters, numbers, spaces, dots, dashes or underscores')])
submit = SubmitField('Update')
|
Allow changing to own domain name
|
## Code Before:
from flask_wtf import Form
from wtforms import StringField, IntegerField, PasswordField, SubmitField, SelectField
from wtforms.validators import Required, Length, Regexp
from ..core.db import db
from ..core.security import User
from .. import app
class ApplicationForm(Form):
start = SubmitField('Start')
stop = SubmitField('Stop')
class ApplicationSettingsForm(Form):
domain = StringField('Domain', description="If you change it then make sure you also configure it with your DNS provider")
submit = SubmitField('Update')
def validate(self):
rv = Form.validate(self)
if not rv:
return False
if self.domain.data:
server_name = app.config["SERVER_NAME_FULL"]
if server_name != "localhost" and self.domain.data.endswith(server_name):
self.domain.errors.append('Invalid domain, cannot end with ' + server_name)
return False
return True
class ProfileForm(Form):
login = StringField('Login')
email = StringField('Email')
name = StringField('Name', validators=[Required(), Length(1, 64),
Regexp(r'^[A-Za-z0-9_\- ]+$', 0, 'Name must have only letters, numbers, spaces, dots, dashes or underscores')])
submit = SubmitField('Update')
## Instruction:
Allow changing to own domain name
## Code After:
from flask_wtf import Form
from wtforms import StringField, IntegerField, PasswordField, SubmitField, SelectField
from wtforms.validators import Required, Length, Regexp
from ..core.db import db
from ..core.security import User
from .. import app
class ApplicationForm(Form):
start = SubmitField('Start')
stop = SubmitField('Stop')
class ApplicationSettingsForm(Form):
domain = StringField('Domain', description="If you change it then make sure you also configure it with your DNS provider")
submit = SubmitField('Update')
def validate(self):
rv = Form.validate(self)
if not rv:
return False
if self.domain.data:
server_name = app.config["SERVER_NAME_FULL"]
if (server_name != "localhost"
and not self.domain.data.endswith(current_user.login + "." + server_name)
and self.domain.data.endswith(server_name)):
self.domain.errors.append('Invalid domain, cannot end with ' + server_name)
return False
return True
class ProfileForm(Form):
login = StringField('Login')
email = StringField('Email')
name = StringField('Name', validators=[Required(), Length(1, 64),
Regexp(r'^[A-Za-z0-9_\- ]+$', 0, 'Name must have only letters, numbers, spaces, dots, dashes or underscores')])
submit = SubmitField('Update')
|
...
server_name = app.config["SERVER_NAME_FULL"]
if (server_name != "localhost"
and not self.domain.data.endswith(current_user.login + "." + server_name)
and self.domain.data.endswith(server_name)):
self.domain.errors.append('Invalid domain, cannot end with ' + server_name)
...
|
ee1c890df7c2c86192b68bd442e41226f70a3850
|
setup.py
|
setup.py
|
import os
import re
from distutils.core import setup
version_re = re.compile(
r'__version__ = (\(.*?\))')
cwd = os.path.dirname(os.path.abspath(__file__))
fp = open(os.path.join(cwd, 'face_client', '__init__.py'))
version = None
for line in fp:
match = version_re.search(line)
if match:
version = eval(match.group(1))
break
else:
raise Exception('Cannot find version in __init__.py')
fp.close()
setup(name='face_client',
version='.' . join(map(str, version)),
description='face.com face recognition Python API client library',
author='Tomaž Muraus',
author_email='[email protected]',
license='BSD',
url='http://github.com/Kami/python-face-client',
download_url='http://github.com/Kami/python-face-client/',
packages=['face_client'],
provides=['face_client'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Security',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
import os
import re
from distutils.core import setup
version_re = re.compile(
r'__version__ = (\(.*?\))')
cwd = os.path.dirname(os.path.abspath(__file__))
fp = open(os.path.join(cwd, 'face_client', '__init__.py'))
version = None
for line in fp:
match = version_re.search(line)
if match:
version = eval(match.group(1))
break
else:
raise Exception('Cannot find version in __init__.py')
fp.close()
setup(name='face_client',
version='.' . join(map(str, version)),
description='face.com face recognition Python API client library',
author='Tomaž Muraus',
author_email='[email protected]',
license='BSD',
url='http://github.com/Kami/python-face-client',
download_url='http://github.com/Kami/python-face-client/',
packages=['face_client'],
provides=['face_client'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Security',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Remove the obsolte comment, library is licensed under BSD.
|
Remove the obsolte comment, library is licensed under BSD.
|
Python
|
bsd-3-clause
|
Liuftvafas/python-face-client,Kami/python-face-client
|
import os
import re
from distutils.core import setup
version_re = re.compile(
r'__version__ = (\(.*?\))')
cwd = os.path.dirname(os.path.abspath(__file__))
fp = open(os.path.join(cwd, 'face_client', '__init__.py'))
version = None
for line in fp:
match = version_re.search(line)
if match:
version = eval(match.group(1))
break
else:
raise Exception('Cannot find version in __init__.py')
fp.close()
setup(name='face_client',
version='.' . join(map(str, version)),
description='face.com face recognition Python API client library',
author='Tomaž Muraus',
author_email='[email protected]',
license='BSD',
url='http://github.com/Kami/python-face-client',
download_url='http://github.com/Kami/python-face-client/',
packages=['face_client'],
provides=['face_client'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
- 'License :: OSI Approved :: GNU General Public License (GPL)',
+ 'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Security',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Remove the obsolte comment, library is licensed under BSD.
|
## Code Before:
import os
import re
from distutils.core import setup
version_re = re.compile(
r'__version__ = (\(.*?\))')
cwd = os.path.dirname(os.path.abspath(__file__))
fp = open(os.path.join(cwd, 'face_client', '__init__.py'))
version = None
for line in fp:
match = version_re.search(line)
if match:
version = eval(match.group(1))
break
else:
raise Exception('Cannot find version in __init__.py')
fp.close()
setup(name='face_client',
version='.' . join(map(str, version)),
description='face.com face recognition Python API client library',
author='Tomaž Muraus',
author_email='[email protected]',
license='BSD',
url='http://github.com/Kami/python-face-client',
download_url='http://github.com/Kami/python-face-client/',
packages=['face_client'],
provides=['face_client'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Security',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
## Instruction:
Remove the obsolte comment, library is licensed under BSD.
## Code After:
import os
import re
from distutils.core import setup
version_re = re.compile(
r'__version__ = (\(.*?\))')
cwd = os.path.dirname(os.path.abspath(__file__))
fp = open(os.path.join(cwd, 'face_client', '__init__.py'))
version = None
for line in fp:
match = version_re.search(line)
if match:
version = eval(match.group(1))
break
else:
raise Exception('Cannot find version in __init__.py')
fp.close()
setup(name='face_client',
version='.' . join(map(str, version)),
description='face.com face recognition Python API client library',
author='Tomaž Muraus',
author_email='[email protected]',
license='BSD',
url='http://github.com/Kami/python-face-client',
download_url='http://github.com/Kami/python-face-client/',
packages=['face_client'],
provides=['face_client'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Security',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
// ... existing code ...
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
// ... rest of the code ...
|
6439182a1ed9efd6dd08aefce8cca44221bb9cef
|
sf/mmck/controllers.py
|
sf/mmck/controllers.py
|
from sf.lib.orderedattrdict import OrderedAttrDict
class Controller(object):
def __init__(self, module, name):
self.module = module
self.name = name
@property
def ctl(self):
return self.module.controllers[self.name]
@property
def value(self):
return getattr(self.module, self.name)
@value.setter
def value(self, value):
setattr(self.module, self.name, value)
class Group(OrderedAttrDict):
def __setitem__(self, key, value, **kwargs):
if isinstance(value, tuple) and len(value) == 2:
module, name = value
value = Controller(module, name)
elif not isinstance(value, (Controller, Group)):
raise ValueError(
'Value must be a 2-tuple, Controller instance, '
'or Group instance'
)
super().__setitem__(key, value, **kwargs)
__all__ = [
'Controller',
'Group',
]
|
from sf.lib.orderedattrdict import OrderedAttrDict
class Controller(object):
def __init__(self, module, name):
self.module = module
self.name = name
@property
def ctl(self):
c = self.module.controllers[self.name]
if hasattr(self.module, 'user_defined') and c.number >= 6:
c = self.module.user_defined[c.number - 6]
return c
@property
def value(self):
return getattr(self.module, self.name)
@value.setter
def value(self, value):
setattr(self.module, self.name, value)
class Group(OrderedAttrDict):
def __setitem__(self, key, value, **kwargs):
if isinstance(value, tuple) and len(value) == 2:
module, name = value
value = Controller(module, name)
elif not isinstance(value, (Controller, Group)):
raise ValueError(
'Value must be a 2-tuple, Controller instance, '
'or Group instance'
)
super().__setitem__(key, value, **kwargs)
__all__ = [
'Controller',
'Group',
]
|
Return specific user-defined control, not proxy
|
Return specific user-defined control, not proxy
|
Python
|
mit
|
metrasynth/solar-flares
|
from sf.lib.orderedattrdict import OrderedAttrDict
class Controller(object):
def __init__(self, module, name):
self.module = module
self.name = name
@property
def ctl(self):
- return self.module.controllers[self.name]
+ c = self.module.controllers[self.name]
+ if hasattr(self.module, 'user_defined') and c.number >= 6:
+ c = self.module.user_defined[c.number - 6]
+ return c
@property
def value(self):
return getattr(self.module, self.name)
@value.setter
def value(self, value):
setattr(self.module, self.name, value)
class Group(OrderedAttrDict):
def __setitem__(self, key, value, **kwargs):
if isinstance(value, tuple) and len(value) == 2:
module, name = value
value = Controller(module, name)
elif not isinstance(value, (Controller, Group)):
raise ValueError(
'Value must be a 2-tuple, Controller instance, '
'or Group instance'
)
super().__setitem__(key, value, **kwargs)
__all__ = [
'Controller',
'Group',
]
|
Return specific user-defined control, not proxy
|
## Code Before:
from sf.lib.orderedattrdict import OrderedAttrDict
class Controller(object):
def __init__(self, module, name):
self.module = module
self.name = name
@property
def ctl(self):
return self.module.controllers[self.name]
@property
def value(self):
return getattr(self.module, self.name)
@value.setter
def value(self, value):
setattr(self.module, self.name, value)
class Group(OrderedAttrDict):
def __setitem__(self, key, value, **kwargs):
if isinstance(value, tuple) and len(value) == 2:
module, name = value
value = Controller(module, name)
elif not isinstance(value, (Controller, Group)):
raise ValueError(
'Value must be a 2-tuple, Controller instance, '
'or Group instance'
)
super().__setitem__(key, value, **kwargs)
__all__ = [
'Controller',
'Group',
]
## Instruction:
Return specific user-defined control, not proxy
## Code After:
from sf.lib.orderedattrdict import OrderedAttrDict
class Controller(object):
def __init__(self, module, name):
self.module = module
self.name = name
@property
def ctl(self):
c = self.module.controllers[self.name]
if hasattr(self.module, 'user_defined') and c.number >= 6:
c = self.module.user_defined[c.number - 6]
return c
@property
def value(self):
return getattr(self.module, self.name)
@value.setter
def value(self, value):
setattr(self.module, self.name, value)
class Group(OrderedAttrDict):
def __setitem__(self, key, value, **kwargs):
if isinstance(value, tuple) and len(value) == 2:
module, name = value
value = Controller(module, name)
elif not isinstance(value, (Controller, Group)):
raise ValueError(
'Value must be a 2-tuple, Controller instance, '
'or Group instance'
)
super().__setitem__(key, value, **kwargs)
__all__ = [
'Controller',
'Group',
]
|
...
def ctl(self):
c = self.module.controllers[self.name]
if hasattr(self.module, 'user_defined') and c.number >= 6:
c = self.module.user_defined[c.number - 6]
return c
...
|
29b5337132373d624f291af3f64bb3b05fd48e77
|
tests/test_list.py
|
tests/test_list.py
|
import os
import unittest
from carbonate.list import listMetrics
class ListTest(unittest.TestCase):
metrics_tree = ["foo",
"foo/sprockets.wsp",
"foo/widgets.wsp",
"ham",
"ham/bones.wsp",
"ham/hocks.wsp"]
expected_metrics = ["foo.sprockets",
"foo.widgets",
"ham.bones",
"ham.hocks"]
rootdir = os.path.join(os.curdir, 'test_storage')
@classmethod
def setUpClass(cls):
os.system("rm -rf %s" % cls.rootdir)
os.mkdir(cls.rootdir)
for f in cls.metrics_tree:
if f.endswith('wsp'):
open(os.path.join(cls.rootdir, f), 'w').close()
else:
os.mkdir(os.path.join(cls.rootdir, f))
def test_list(self):
res = list(listMetrics(self.rootdir))
self.assertEqual(res, self.expected_metrics)
def test_list_with_trailing_slash(self):
res = list(listMetrics(self.rootdir + '/'))
self.assertEqual(res, self.expected_metrics)
@classmethod
def tearDownClass(cls):
os.system("rm -rf %s" % cls.rootdir)
|
import os
import unittest
from carbonate.list import listMetrics
class ListTest(unittest.TestCase):
metrics_tree = ["foo",
"foo/sprockets.wsp",
"foo/widgets.wsp",
"ham",
"ham/bones.wsp",
"ham/hocks.wsp"]
expected_metrics = ["foo.sprockets",
"foo.widgets",
"ham.bones",
"ham.hocks"]
rootdir = os.path.join(os.curdir, 'test_storage')
@classmethod
def setUpClass(cls):
os.system("rm -rf %s" % cls.rootdir)
os.mkdir(cls.rootdir)
for f in cls.metrics_tree:
if f.endswith('wsp'):
open(os.path.join(cls.rootdir, f), 'w').close()
else:
os.mkdir(os.path.join(cls.rootdir, f))
def test_list(self):
res = sorted(list(listMetrics(self.rootdir)))
self.assertEqual(res, self.expected_metrics)
def test_list_with_trailing_slash(self):
res = sorted(list(listMetrics(self.rootdir + '/')))
self.assertEqual(res, self.expected_metrics)
@classmethod
def tearDownClass(cls):
os.system("rm -rf %s" % cls.rootdir)
|
Make sure we're sorting results
|
Make sure we're sorting results
|
Python
|
mit
|
skbkontur/carbonate,unbrice/carbonate,skbkontur/carbonate,ross/carbonate,ross/carbonate,graphite-project/carbonate,deniszh/carbonate,unbrice/carbonate,jssjr/carbonate,criteo-forks/carbonate,criteo-forks/carbonate,ross/carbonate,jssjr/carbonate,unbrice/carbonate,skbkontur/carbonate,jssjr/carbonate,graphite-project/carbonate,deniszh/carbonate,criteo-forks/carbonate,graphite-project/carbonate,deniszh/carbonate
|
import os
import unittest
from carbonate.list import listMetrics
class ListTest(unittest.TestCase):
metrics_tree = ["foo",
"foo/sprockets.wsp",
"foo/widgets.wsp",
"ham",
"ham/bones.wsp",
"ham/hocks.wsp"]
expected_metrics = ["foo.sprockets",
"foo.widgets",
"ham.bones",
"ham.hocks"]
rootdir = os.path.join(os.curdir, 'test_storage')
@classmethod
def setUpClass(cls):
os.system("rm -rf %s" % cls.rootdir)
os.mkdir(cls.rootdir)
for f in cls.metrics_tree:
if f.endswith('wsp'):
open(os.path.join(cls.rootdir, f), 'w').close()
else:
os.mkdir(os.path.join(cls.rootdir, f))
def test_list(self):
- res = list(listMetrics(self.rootdir))
+ res = sorted(list(listMetrics(self.rootdir)))
self.assertEqual(res, self.expected_metrics)
def test_list_with_trailing_slash(self):
- res = list(listMetrics(self.rootdir + '/'))
+ res = sorted(list(listMetrics(self.rootdir + '/')))
self.assertEqual(res, self.expected_metrics)
@classmethod
def tearDownClass(cls):
os.system("rm -rf %s" % cls.rootdir)
|
Make sure we're sorting results
|
## Code Before:
import os
import unittest
from carbonate.list import listMetrics
class ListTest(unittest.TestCase):
metrics_tree = ["foo",
"foo/sprockets.wsp",
"foo/widgets.wsp",
"ham",
"ham/bones.wsp",
"ham/hocks.wsp"]
expected_metrics = ["foo.sprockets",
"foo.widgets",
"ham.bones",
"ham.hocks"]
rootdir = os.path.join(os.curdir, 'test_storage')
@classmethod
def setUpClass(cls):
os.system("rm -rf %s" % cls.rootdir)
os.mkdir(cls.rootdir)
for f in cls.metrics_tree:
if f.endswith('wsp'):
open(os.path.join(cls.rootdir, f), 'w').close()
else:
os.mkdir(os.path.join(cls.rootdir, f))
def test_list(self):
res = list(listMetrics(self.rootdir))
self.assertEqual(res, self.expected_metrics)
def test_list_with_trailing_slash(self):
res = list(listMetrics(self.rootdir + '/'))
self.assertEqual(res, self.expected_metrics)
@classmethod
def tearDownClass(cls):
os.system("rm -rf %s" % cls.rootdir)
## Instruction:
Make sure we're sorting results
## Code After:
import os
import unittest
from carbonate.list import listMetrics
class ListTest(unittest.TestCase):
metrics_tree = ["foo",
"foo/sprockets.wsp",
"foo/widgets.wsp",
"ham",
"ham/bones.wsp",
"ham/hocks.wsp"]
expected_metrics = ["foo.sprockets",
"foo.widgets",
"ham.bones",
"ham.hocks"]
rootdir = os.path.join(os.curdir, 'test_storage')
@classmethod
def setUpClass(cls):
os.system("rm -rf %s" % cls.rootdir)
os.mkdir(cls.rootdir)
for f in cls.metrics_tree:
if f.endswith('wsp'):
open(os.path.join(cls.rootdir, f), 'w').close()
else:
os.mkdir(os.path.join(cls.rootdir, f))
def test_list(self):
res = sorted(list(listMetrics(self.rootdir)))
self.assertEqual(res, self.expected_metrics)
def test_list_with_trailing_slash(self):
res = sorted(list(listMetrics(self.rootdir + '/')))
self.assertEqual(res, self.expected_metrics)
@classmethod
def tearDownClass(cls):
os.system("rm -rf %s" % cls.rootdir)
|
// ... existing code ...
def test_list(self):
res = sorted(list(listMetrics(self.rootdir)))
self.assertEqual(res, self.expected_metrics)
// ... modified code ...
def test_list_with_trailing_slash(self):
res = sorted(list(listMetrics(self.rootdir + '/')))
self.assertEqual(res, self.expected_metrics)
// ... rest of the code ...
|
79ac1550b5acd407b2a107e694c66cccfbc0be89
|
alerts/lib/deadman_alerttask.py
|
alerts/lib/deadman_alerttask.py
|
from alerttask import AlertTask
class DeadmanAlertTask(AlertTask):
def __init__(self):
self.deadman = True
def executeSearchEventsSimple(self):
# We override this method to specify the size as 1
# since we only care about if ANY events are found or not
return self.main_query.execute(self.es, indices=self.event_indices, size=1)
|
from alerttask import AlertTask
class DeadmanAlertTask(AlertTask):
def executeSearchEventsSimple(self):
# We override this method to specify the size as 1
# since we only care about if ANY events are found or not
return self.main_query.execute(self.es, indices=self.event_indices, size=1)
|
Remove deadman alerttask init method
|
Remove deadman alerttask init method
|
Python
|
mpl-2.0
|
jeffbryner/MozDef,gdestuynder/MozDef,mozilla/MozDef,mpurzynski/MozDef,mozilla/MozDef,Phrozyn/MozDef,jeffbryner/MozDef,jeffbryner/MozDef,Phrozyn/MozDef,mpurzynski/MozDef,gdestuynder/MozDef,Phrozyn/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,gdestuynder/MozDef,Phrozyn/MozDef,mozilla/MozDef,jeffbryner/MozDef,mozilla/MozDef,gdestuynder/MozDef
|
from alerttask import AlertTask
class DeadmanAlertTask(AlertTask):
- def __init__(self):
- self.deadman = True
def executeSearchEventsSimple(self):
# We override this method to specify the size as 1
# since we only care about if ANY events are found or not
return self.main_query.execute(self.es, indices=self.event_indices, size=1)
|
Remove deadman alerttask init method
|
## Code Before:
from alerttask import AlertTask
class DeadmanAlertTask(AlertTask):
def __init__(self):
self.deadman = True
def executeSearchEventsSimple(self):
# We override this method to specify the size as 1
# since we only care about if ANY events are found or not
return self.main_query.execute(self.es, indices=self.event_indices, size=1)
## Instruction:
Remove deadman alerttask init method
## Code After:
from alerttask import AlertTask
class DeadmanAlertTask(AlertTask):
def executeSearchEventsSimple(self):
# We override this method to specify the size as 1
# since we only care about if ANY events are found or not
return self.main_query.execute(self.es, indices=self.event_indices, size=1)
|
// ... existing code ...
class DeadmanAlertTask(AlertTask):
// ... rest of the code ...
|
baacda228682a50acc5a4528d43f5d3a88c7c6ec
|
salt/client/netapi.py
|
salt/client/netapi.py
|
'''
The main entry point for salt-api
'''
# Import python libs
import logging
import multiprocessing
# Import salt-api libs
import salt.loader
logger = logging.getLogger(__name__)
class NetapiClient(object):
'''
Start each netapi module that is configured to run
'''
def __init__(self, opts):
self.opts = opts
def run(self):
'''
Load and start all available api modules
'''
netapi = salt.loader.netapi(self.opts)
for fun in netapi:
if fun.endswith('.start'):
logger.info("Starting '{0}' api module".format(fun))
multiprocessing.Process(target=netapi[fun]).start()
|
'''
The main entry point for salt-api
'''
# Import python libs
import logging
import multiprocessing
import signal
# Import salt-api libs
import salt.loader
logger = logging.getLogger(__name__)
class NetapiClient(object):
'''
Start each netapi module that is configured to run
'''
def __init__(self, opts):
self.opts = opts
self.processes = []
def run(self):
'''
Load and start all available api modules
'''
netapi = salt.loader.netapi(self.opts)
for fun in netapi:
if fun.endswith('.start'):
logger.info("Starting '{0}' api module".format(fun))
p = multiprocessing.Process(target=netapi[fun])
p.start()
self.processes.append(p)
# make sure to kill the subprocesses if the parent is killed
signal.signal(signal.SIGTERM, self.kill_children)
def kill_children(self, *args):
'''
Kill all of the children
'''
for p in self.processes:
p.terminate()
p.join()
|
Make sure to not leave hanging children processes if the parent is killed
|
Make sure to not leave hanging children processes if the parent is killed
|
Python
|
apache-2.0
|
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
|
'''
The main entry point for salt-api
'''
# Import python libs
import logging
import multiprocessing
+ import signal
# Import salt-api libs
import salt.loader
logger = logging.getLogger(__name__)
class NetapiClient(object):
'''
Start each netapi module that is configured to run
'''
def __init__(self, opts):
self.opts = opts
+ self.processes = []
def run(self):
'''
Load and start all available api modules
'''
netapi = salt.loader.netapi(self.opts)
for fun in netapi:
if fun.endswith('.start'):
logger.info("Starting '{0}' api module".format(fun))
- multiprocessing.Process(target=netapi[fun]).start()
+ p = multiprocessing.Process(target=netapi[fun])
+ p.start()
+ self.processes.append(p)
+ # make sure to kill the subprocesses if the parent is killed
+ signal.signal(signal.SIGTERM, self.kill_children)
+
+ def kill_children(self, *args):
+ '''
+ Kill all of the children
+ '''
+ for p in self.processes:
+ p.terminate()
+ p.join()
+
|
Make sure to not leave hanging children processes if the parent is killed
|
## Code Before:
'''
The main entry point for salt-api
'''
# Import python libs
import logging
import multiprocessing
# Import salt-api libs
import salt.loader
logger = logging.getLogger(__name__)
class NetapiClient(object):
'''
Start each netapi module that is configured to run
'''
def __init__(self, opts):
self.opts = opts
def run(self):
'''
Load and start all available api modules
'''
netapi = salt.loader.netapi(self.opts)
for fun in netapi:
if fun.endswith('.start'):
logger.info("Starting '{0}' api module".format(fun))
multiprocessing.Process(target=netapi[fun]).start()
## Instruction:
Make sure to not leave hanging children processes if the parent is killed
## Code After:
'''
The main entry point for salt-api
'''
# Import python libs
import logging
import multiprocessing
import signal
# Import salt-api libs
import salt.loader
logger = logging.getLogger(__name__)
class NetapiClient(object):
'''
Start each netapi module that is configured to run
'''
def __init__(self, opts):
self.opts = opts
self.processes = []
def run(self):
'''
Load and start all available api modules
'''
netapi = salt.loader.netapi(self.opts)
for fun in netapi:
if fun.endswith('.start'):
logger.info("Starting '{0}' api module".format(fun))
p = multiprocessing.Process(target=netapi[fun])
p.start()
self.processes.append(p)
# make sure to kill the subprocesses if the parent is killed
signal.signal(signal.SIGTERM, self.kill_children)
def kill_children(self, *args):
'''
Kill all of the children
'''
for p in self.processes:
p.terminate()
p.join()
|
# ... existing code ...
import multiprocessing
import signal
# ... modified code ...
self.opts = opts
self.processes = []
...
logger.info("Starting '{0}' api module".format(fun))
p = multiprocessing.Process(target=netapi[fun])
p.start()
self.processes.append(p)
# make sure to kill the subprocesses if the parent is killed
signal.signal(signal.SIGTERM, self.kill_children)
def kill_children(self, *args):
'''
Kill all of the children
'''
for p in self.processes:
p.terminate()
p.join()
# ... rest of the code ...
|
e14ceda6370b506b80f65d45abd36c9f728e5699
|
pitchfork/manage_globals/forms.py
|
pitchfork/manage_globals/forms.py
|
from flask.ext.wtf import Form
from wtforms import TextField, SelectField, IntegerField, BooleanField,\
PasswordField, TextAreaField, SubmitField, HiddenField, RadioField
from wtforms import validators
class VerbSet(Form):
name = TextField('Verb:', validators=[validators.required()])
active = BooleanField('Active:')
submit = SubmitField('Submit')
class DCSet(Form):
name = TextField('Name:', validators=[validators.required()])
abbreviation = TextField(
'Abbreviation:',
validators=[validators.required()]
)
submit = SubmitField('Submit')
|
from flask.ext.wtf import Form
from wtforms import fields, validators
class VerbSet(Form):
name = fields.TextField('Verb:', validators=[validators.required()])
active = fields.BooleanField('Active:')
submit = fields.SubmitField('Submit')
class DCSet(Form):
name = fields.TextField('Name:', validators=[validators.required()])
abbreviation = fields.TextField(
'Abbreviation:',
validators=[validators.required()]
)
submit = fields.SubmitField('Submit')
|
Rework imports so not having to specify every type of field. Alter field definitions to reflect change
|
Rework imports so not having to specify every type of field. Alter field definitions to reflect change
|
Python
|
apache-2.0
|
rackerlabs/pitchfork,oldarmyc/pitchfork,rackerlabs/pitchfork,oldarmyc/pitchfork,rackerlabs/pitchfork,oldarmyc/pitchfork
|
from flask.ext.wtf import Form
- from wtforms import TextField, SelectField, IntegerField, BooleanField,\
- PasswordField, TextAreaField, SubmitField, HiddenField, RadioField
- from wtforms import validators
+ from wtforms import fields, validators
class VerbSet(Form):
- name = TextField('Verb:', validators=[validators.required()])
+ name = fields.TextField('Verb:', validators=[validators.required()])
- active = BooleanField('Active:')
+ active = fields.BooleanField('Active:')
- submit = SubmitField('Submit')
+ submit = fields.SubmitField('Submit')
class DCSet(Form):
- name = TextField('Name:', validators=[validators.required()])
+ name = fields.TextField('Name:', validators=[validators.required()])
- abbreviation = TextField(
+ abbreviation = fields.TextField(
'Abbreviation:',
validators=[validators.required()]
)
- submit = SubmitField('Submit')
+ submit = fields.SubmitField('Submit')
|
Rework imports so not having to specify every type of field. Alter field definitions to reflect change
|
## Code Before:
from flask.ext.wtf import Form
from wtforms import TextField, SelectField, IntegerField, BooleanField,\
PasswordField, TextAreaField, SubmitField, HiddenField, RadioField
from wtforms import validators
class VerbSet(Form):
name = TextField('Verb:', validators=[validators.required()])
active = BooleanField('Active:')
submit = SubmitField('Submit')
class DCSet(Form):
name = TextField('Name:', validators=[validators.required()])
abbreviation = TextField(
'Abbreviation:',
validators=[validators.required()]
)
submit = SubmitField('Submit')
## Instruction:
Rework imports so not having to specify every type of field. Alter field definitions to reflect change
## Code After:
from flask.ext.wtf import Form
from wtforms import fields, validators
class VerbSet(Form):
name = fields.TextField('Verb:', validators=[validators.required()])
active = fields.BooleanField('Active:')
submit = fields.SubmitField('Submit')
class DCSet(Form):
name = fields.TextField('Name:', validators=[validators.required()])
abbreviation = fields.TextField(
'Abbreviation:',
validators=[validators.required()]
)
submit = fields.SubmitField('Submit')
|
# ... existing code ...
from flask.ext.wtf import Form
from wtforms import fields, validators
# ... modified code ...
class VerbSet(Form):
name = fields.TextField('Verb:', validators=[validators.required()])
active = fields.BooleanField('Active:')
submit = fields.SubmitField('Submit')
...
class DCSet(Form):
name = fields.TextField('Name:', validators=[validators.required()])
abbreviation = fields.TextField(
'Abbreviation:',
...
)
submit = fields.SubmitField('Submit')
# ... rest of the code ...
|
db64ca09e57da414d92888de1b52fade810d855e
|
handlers/downloadMapHandler.py
|
handlers/downloadMapHandler.py
|
from helpers import requestHelper
import requests
import glob
# Exception tracking
import tornado.web
import tornado.gen
import sys
import traceback
from raven.contrib.tornado import SentryMixin
MODULE_NAME = "direct_download"
class handler(SentryMixin, requestHelper.asyncRequestHandler):
"""
Handler for /d/
"""
@tornado.web.asynchronous
@tornado.gen.engine
def asyncGet(self, bid):
try:
self.set_status(302)
url = "http://m.zxq.co/{}.osz".format(bid)
#url = "https://bloodcat.com/osu/s/{}".format(bid)
self.add_header("location", url)
print(url)
#f = requests.get(url)
#self.write(str(f))
except:
log.error("Unknown error in {}!\n```{}\n{}```".format(MODULE_NAME, sys.exc_info(), traceback.format_exc()))
if glob.sentry:
yield tornado.gen.Task(self.captureException, exc_info=True)
#finally:
# self.finish()
|
from helpers import requestHelper
import requests
import glob
# Exception tracking
import tornado.web
import tornado.gen
import sys
import traceback
from raven.contrib.tornado import SentryMixin
MODULE_NAME = "direct_download"
class handler(SentryMixin, requestHelper.asyncRequestHandler):
"""
Handler for /d/
"""
@tornado.web.asynchronous
@tornado.gen.engine
def asyncGet(self, bid):
try:
self.set_status(302, "Moved Temporarily")
url = "http://m.zxq.co/{}.osz".format(bid)
self.add_header("Location", url)
self.add_header("Cache-Control", "no-cache")
self.add_header("Pragma", "no-cache")
print(url)
#f = requests.get(url)
#self.write(str(f))
except:
log.error("Unknown error in {}!\n```{}\n{}```".format(MODULE_NAME, sys.exc_info(), traceback.format_exc()))
if glob.sentry:
yield tornado.gen.Task(self.captureException, exc_info=True)
#finally:
# self.finish()
|
Add some headers in osu! direct download
|
Add some headers in osu! direct download
|
Python
|
agpl-3.0
|
osuripple/lets,osuripple/lets
|
from helpers import requestHelper
import requests
import glob
# Exception tracking
import tornado.web
import tornado.gen
import sys
import traceback
from raven.contrib.tornado import SentryMixin
MODULE_NAME = "direct_download"
class handler(SentryMixin, requestHelper.asyncRequestHandler):
"""
Handler for /d/
"""
@tornado.web.asynchronous
@tornado.gen.engine
def asyncGet(self, bid):
try:
- self.set_status(302)
+ self.set_status(302, "Moved Temporarily")
url = "http://m.zxq.co/{}.osz".format(bid)
- #url = "https://bloodcat.com/osu/s/{}".format(bid)
- self.add_header("location", url)
+ self.add_header("Location", url)
+ self.add_header("Cache-Control", "no-cache")
+ self.add_header("Pragma", "no-cache")
print(url)
#f = requests.get(url)
#self.write(str(f))
except:
log.error("Unknown error in {}!\n```{}\n{}```".format(MODULE_NAME, sys.exc_info(), traceback.format_exc()))
if glob.sentry:
yield tornado.gen.Task(self.captureException, exc_info=True)
#finally:
# self.finish()
|
Add some headers in osu! direct download
|
## Code Before:
from helpers import requestHelper
import requests
import glob
# Exception tracking
import tornado.web
import tornado.gen
import sys
import traceback
from raven.contrib.tornado import SentryMixin
MODULE_NAME = "direct_download"
class handler(SentryMixin, requestHelper.asyncRequestHandler):
"""
Handler for /d/
"""
@tornado.web.asynchronous
@tornado.gen.engine
def asyncGet(self, bid):
try:
self.set_status(302)
url = "http://m.zxq.co/{}.osz".format(bid)
#url = "https://bloodcat.com/osu/s/{}".format(bid)
self.add_header("location", url)
print(url)
#f = requests.get(url)
#self.write(str(f))
except:
log.error("Unknown error in {}!\n```{}\n{}```".format(MODULE_NAME, sys.exc_info(), traceback.format_exc()))
if glob.sentry:
yield tornado.gen.Task(self.captureException, exc_info=True)
#finally:
# self.finish()
## Instruction:
Add some headers in osu! direct download
## Code After:
from helpers import requestHelper
import requests
import glob
# Exception tracking
import tornado.web
import tornado.gen
import sys
import traceback
from raven.contrib.tornado import SentryMixin
MODULE_NAME = "direct_download"
class handler(SentryMixin, requestHelper.asyncRequestHandler):
"""
Handler for /d/
"""
@tornado.web.asynchronous
@tornado.gen.engine
def asyncGet(self, bid):
try:
self.set_status(302, "Moved Temporarily")
url = "http://m.zxq.co/{}.osz".format(bid)
self.add_header("Location", url)
self.add_header("Cache-Control", "no-cache")
self.add_header("Pragma", "no-cache")
print(url)
#f = requests.get(url)
#self.write(str(f))
except:
log.error("Unknown error in {}!\n```{}\n{}```".format(MODULE_NAME, sys.exc_info(), traceback.format_exc()))
if glob.sentry:
yield tornado.gen.Task(self.captureException, exc_info=True)
#finally:
# self.finish()
|
# ... existing code ...
try:
self.set_status(302, "Moved Temporarily")
url = "http://m.zxq.co/{}.osz".format(bid)
self.add_header("Location", url)
self.add_header("Cache-Control", "no-cache")
self.add_header("Pragma", "no-cache")
print(url)
# ... rest of the code ...
|
8eaa0f2fef26cc90e3aea5dea1253b7980400375
|
latest_tweets/templatetags/latest_tweets_tags.py
|
latest_tweets/templatetags/latest_tweets_tags.py
|
from django import template
from latest_tweets.models import Tweet
register = template.Library()
@register.assignment_tag
def get_latest_tweets(*args, **kwargs):
limit = kwargs.pop('limit', None)
include_replies = kwargs.pop('include_replies', False)
tweets = Tweet.objects.all()
# By default we exclude replies
if not include_replies:
tweets = tweets.exclude(is_reply=True)
if args:
tweets = tweets.filter(user__in=args)
if limit is not None:
tweets = tweets[:limit]
return tweets
|
from django import template
from latest_tweets.models import Tweet
register = template.Library()
@register.assignment_tag
def get_latest_tweets(*args, **kwargs):
limit = kwargs.pop('limit', None)
include_replies = kwargs.pop('include_replies', False)
liked_by = kwargs.pop('liked_by', None)
tweets = Tweet.objects.all()
# By default we exclude replies
if not include_replies:
tweets = tweets.exclude(is_reply=True)
if liked_by:
tweets = tweets.filter(like__user=liked_by)
if args:
tweets = tweets.filter(user__in=args)
if limit is not None:
tweets = tweets[:limit]
return tweets
|
Add tag support for getting liked tweets
|
Add tag support for getting liked tweets
|
Python
|
bsd-3-clause
|
blancltd/django-latest-tweets
|
from django import template
from latest_tweets.models import Tweet
register = template.Library()
@register.assignment_tag
def get_latest_tweets(*args, **kwargs):
limit = kwargs.pop('limit', None)
include_replies = kwargs.pop('include_replies', False)
+ liked_by = kwargs.pop('liked_by', None)
tweets = Tweet.objects.all()
# By default we exclude replies
if not include_replies:
tweets = tweets.exclude(is_reply=True)
+
+ if liked_by:
+ tweets = tweets.filter(like__user=liked_by)
if args:
tweets = tweets.filter(user__in=args)
if limit is not None:
tweets = tweets[:limit]
return tweets
|
Add tag support for getting liked tweets
|
## Code Before:
from django import template
from latest_tweets.models import Tweet
register = template.Library()
@register.assignment_tag
def get_latest_tweets(*args, **kwargs):
limit = kwargs.pop('limit', None)
include_replies = kwargs.pop('include_replies', False)
tweets = Tweet.objects.all()
# By default we exclude replies
if not include_replies:
tweets = tweets.exclude(is_reply=True)
if args:
tweets = tweets.filter(user__in=args)
if limit is not None:
tweets = tweets[:limit]
return tweets
## Instruction:
Add tag support for getting liked tweets
## Code After:
from django import template
from latest_tweets.models import Tweet
register = template.Library()
@register.assignment_tag
def get_latest_tweets(*args, **kwargs):
limit = kwargs.pop('limit', None)
include_replies = kwargs.pop('include_replies', False)
liked_by = kwargs.pop('liked_by', None)
tweets = Tweet.objects.all()
# By default we exclude replies
if not include_replies:
tweets = tweets.exclude(is_reply=True)
if liked_by:
tweets = tweets.filter(like__user=liked_by)
if args:
tweets = tweets.filter(user__in=args)
if limit is not None:
tweets = tweets[:limit]
return tweets
|
# ... existing code ...
include_replies = kwargs.pop('include_replies', False)
liked_by = kwargs.pop('liked_by', None)
tweets = Tweet.objects.all()
# ... modified code ...
tweets = tweets.exclude(is_reply=True)
if liked_by:
tweets = tweets.filter(like__user=liked_by)
# ... rest of the code ...
|
773f78ae283a062818394743dea4535456ac9aeb
|
ckanext/qa/lib.py
|
ckanext/qa/lib.py
|
import json
import ckan.model as model
import ckan.plugins as p
def get_site_url(config):
return config.get('ckan.site_url_internally') or config['ckan.site_url']
def get_user_and_context(site_url):
user = p.toolkit.get_action('get_site_user')(
{'model': model, 'ignore_auth': True}, {}
)
context = json.dumps({
'site_url': site_url,
'apikey': user.get('apikey'),
'site_user_apikey': user.get('apikey'),
'username': user.get('name'),
})
return user, context
|
import json
import ckan.model as model
import ckan.plugins as p
def get_site_url(config):
return config.get('ckan.site_url_internally') or config['ckan.site_url']
def get_user_and_context(site_url):
user = p.toolkit.get_action('get_site_user')(
{'model': model, 'ignore_auth': True, 'defer_commit': True}, {}
)
context = json.dumps({
'site_url': site_url,
'apikey': user.get('apikey'),
'site_user_apikey': user.get('apikey'),
'username': user.get('name'),
})
return user, context
|
Fix for getting site_user the first time. (A commit herecauses problems during a db write notification. Spotted when harvesting)
|
[1268] Fix for getting site_user the first time. (A commit herecauses problems during a db write notification. Spotted when harvesting)
|
Python
|
mit
|
ckan/ckanext-qa,ckan/ckanext-qa,ckan/ckanext-qa
|
import json
import ckan.model as model
import ckan.plugins as p
def get_site_url(config):
return config.get('ckan.site_url_internally') or config['ckan.site_url']
def get_user_and_context(site_url):
user = p.toolkit.get_action('get_site_user')(
- {'model': model, 'ignore_auth': True}, {}
+ {'model': model, 'ignore_auth': True, 'defer_commit': True}, {}
)
context = json.dumps({
'site_url': site_url,
'apikey': user.get('apikey'),
'site_user_apikey': user.get('apikey'),
'username': user.get('name'),
})
return user, context
|
Fix for getting site_user the first time. (A commit herecauses problems during a db write notification. Spotted when harvesting)
|
## Code Before:
import json
import ckan.model as model
import ckan.plugins as p
def get_site_url(config):
return config.get('ckan.site_url_internally') or config['ckan.site_url']
def get_user_and_context(site_url):
user = p.toolkit.get_action('get_site_user')(
{'model': model, 'ignore_auth': True}, {}
)
context = json.dumps({
'site_url': site_url,
'apikey': user.get('apikey'),
'site_user_apikey': user.get('apikey'),
'username': user.get('name'),
})
return user, context
## Instruction:
Fix for getting site_user the first time. (A commit herecauses problems during a db write notification. Spotted when harvesting)
## Code After:
import json
import ckan.model as model
import ckan.plugins as p
def get_site_url(config):
return config.get('ckan.site_url_internally') or config['ckan.site_url']
def get_user_and_context(site_url):
user = p.toolkit.get_action('get_site_user')(
{'model': model, 'ignore_auth': True, 'defer_commit': True}, {}
)
context = json.dumps({
'site_url': site_url,
'apikey': user.get('apikey'),
'site_user_apikey': user.get('apikey'),
'username': user.get('name'),
})
return user, context
|
// ... existing code ...
user = p.toolkit.get_action('get_site_user')(
{'model': model, 'ignore_auth': True, 'defer_commit': True}, {}
)
// ... rest of the code ...
|
3fb0f567dcaf69e4fa9872702ffbfa8ab0e69eaf
|
lib/utilities/key_exists.py
|
lib/utilities/key_exists.py
|
def key_exists(search_key, inputed_dict):
'''
Given a search key which is dot notated
return wether or not that key exists in a dictionary
'''
num_levels = search_key.split(".")
if len(num_levels) == 0:
return False
current_pointer = inputed_dict
for updated_key in num_levels:
if updated_key == num_levels[-1]:
return updated_key in current_pointer
if updated_key in current_pointer:
current_pointer = current_pointer[updated_key]
else:
return False
|
def key_exists(search_key, inputed_dict):
'''
Given a search key which is dot notated
return wether or not that key exists in a dictionary
'''
num_levels = search_key.split(".")
if len(num_levels) == 0:
return False
current_pointer = inputed_dict
for updated_key in num_levels:
if current_pointer is None:
return False
if updated_key == num_levels[-1]:
return updated_key in current_pointer
if updated_key in current_pointer:
current_pointer = current_pointer[updated_key]
else:
return False
|
Add more error handling to key exists
|
Add more error handling to key exists
|
Python
|
mpl-2.0
|
mpurzynski/MozDef,mozilla/MozDef,jeffbryner/MozDef,mozilla/MozDef,jeffbryner/MozDef,Phrozyn/MozDef,gdestuynder/MozDef,jeffbryner/MozDef,Phrozyn/MozDef,Phrozyn/MozDef,mpurzynski/MozDef,Phrozyn/MozDef,mpurzynski/MozDef,mozilla/MozDef,mozilla/MozDef,gdestuynder/MozDef,gdestuynder/MozDef,gdestuynder/MozDef,mpurzynski/MozDef,jeffbryner/MozDef
|
def key_exists(search_key, inputed_dict):
'''
Given a search key which is dot notated
return wether or not that key exists in a dictionary
'''
num_levels = search_key.split(".")
if len(num_levels) == 0:
return False
current_pointer = inputed_dict
for updated_key in num_levels:
+ if current_pointer is None:
+ return False
if updated_key == num_levels[-1]:
return updated_key in current_pointer
if updated_key in current_pointer:
current_pointer = current_pointer[updated_key]
else:
return False
|
Add more error handling to key exists
|
## Code Before:
def key_exists(search_key, inputed_dict):
'''
Given a search key which is dot notated
return wether or not that key exists in a dictionary
'''
num_levels = search_key.split(".")
if len(num_levels) == 0:
return False
current_pointer = inputed_dict
for updated_key in num_levels:
if updated_key == num_levels[-1]:
return updated_key in current_pointer
if updated_key in current_pointer:
current_pointer = current_pointer[updated_key]
else:
return False
## Instruction:
Add more error handling to key exists
## Code After:
def key_exists(search_key, inputed_dict):
'''
Given a search key which is dot notated
return wether or not that key exists in a dictionary
'''
num_levels = search_key.split(".")
if len(num_levels) == 0:
return False
current_pointer = inputed_dict
for updated_key in num_levels:
if current_pointer is None:
return False
if updated_key == num_levels[-1]:
return updated_key in current_pointer
if updated_key in current_pointer:
current_pointer = current_pointer[updated_key]
else:
return False
|
...
for updated_key in num_levels:
if current_pointer is None:
return False
if updated_key == num_levels[-1]:
...
|
d1a96f13204ad7028432096d25718e611d4d3d9d
|
depot/gpg.py
|
depot/gpg.py
|
import getpass
import os
import gnupg
class GPG(object):
def __init__(self, keyid):
self.gpg = gnupg.GPG(use_agent=False)
self.keyid = keyid
if not self.keyid:
# Compat with how Freight does it.
self.keyid = os.environ.get('GPG')
self.passphrase = None
self._verify()
def _verify(self):
"""Some sanity checks on GPG."""
if not self.keyid:
raise ValueError('No GPG key specified for signing, did you mean to use --no-sign?')
sign = self.gpg.sign('', keyid=self.keyid)
if 'secret key not available' in sign.stderr:
raise ValueError('Key not found')
elif 'NEED_PASSPHRASE' in sign.stderr:
self.passphrase = getpass.getpass('Passphrase for GPG key: ')
def sign(self, data, detach=False):
sign = self.gpg.sign(data, keyid=self.keyid, passphrase=self.passphrase, detach=detach)
if not sign:
raise ValueError(sign.stderr)
return str(sign)
def public_key(self):
return self.gpg.export_keys(self.keyid)
|
import getpass
import os
import gnupg
class GPG(object):
def __init__(self, keyid, key=None, home=None):
self.gpg = gnupg.GPG(use_agent=False, gnupghome=home)
if key:
if not home:
raise ValueError('Cowardly refusing to import key in to default key store')
results = self.gpg.import_keys(key)
keyid = results.fingerprints[0]
self.keyid = keyid
if not self.keyid:
# Compat with how Freight does it.
self.keyid = os.environ.get('GPG')
self.passphrase = None
self._verify()
def _verify(self):
"""Some sanity checks on GPG."""
if not self.keyid:
raise ValueError('No GPG key specified for signing, did you mean to use --no-sign?')
sign = self.gpg.sign('', keyid=self.keyid)
if 'secret key not available' in sign.stderr:
raise ValueError('Key not found')
elif 'NEED_PASSPHRASE' in sign.stderr:
self.passphrase = getpass.getpass('Passphrase for GPG key: ')
def sign(self, data, detach=False):
sign = self.gpg.sign(data, keyid=self.keyid, passphrase=self.passphrase, detach=detach)
if not sign:
raise ValueError(sign.stderr)
return str(sign)
def public_key(self):
return self.gpg.export_keys(self.keyid)
|
Allow passing in a raw key and homedir.
|
Allow passing in a raw key and homedir.
|
Python
|
apache-2.0
|
coderanger/depot
|
import getpass
import os
import gnupg
class GPG(object):
- def __init__(self, keyid):
+ def __init__(self, keyid, key=None, home=None):
- self.gpg = gnupg.GPG(use_agent=False)
+ self.gpg = gnupg.GPG(use_agent=False, gnupghome=home)
+ if key:
+ if not home:
+ raise ValueError('Cowardly refusing to import key in to default key store')
+ results = self.gpg.import_keys(key)
+ keyid = results.fingerprints[0]
self.keyid = keyid
if not self.keyid:
# Compat with how Freight does it.
self.keyid = os.environ.get('GPG')
self.passphrase = None
self._verify()
def _verify(self):
"""Some sanity checks on GPG."""
if not self.keyid:
raise ValueError('No GPG key specified for signing, did you mean to use --no-sign?')
sign = self.gpg.sign('', keyid=self.keyid)
if 'secret key not available' in sign.stderr:
raise ValueError('Key not found')
elif 'NEED_PASSPHRASE' in sign.stderr:
self.passphrase = getpass.getpass('Passphrase for GPG key: ')
def sign(self, data, detach=False):
sign = self.gpg.sign(data, keyid=self.keyid, passphrase=self.passphrase, detach=detach)
if not sign:
raise ValueError(sign.stderr)
return str(sign)
def public_key(self):
return self.gpg.export_keys(self.keyid)
|
Allow passing in a raw key and homedir.
|
## Code Before:
import getpass
import os
import gnupg
class GPG(object):
def __init__(self, keyid):
self.gpg = gnupg.GPG(use_agent=False)
self.keyid = keyid
if not self.keyid:
# Compat with how Freight does it.
self.keyid = os.environ.get('GPG')
self.passphrase = None
self._verify()
def _verify(self):
"""Some sanity checks on GPG."""
if not self.keyid:
raise ValueError('No GPG key specified for signing, did you mean to use --no-sign?')
sign = self.gpg.sign('', keyid=self.keyid)
if 'secret key not available' in sign.stderr:
raise ValueError('Key not found')
elif 'NEED_PASSPHRASE' in sign.stderr:
self.passphrase = getpass.getpass('Passphrase for GPG key: ')
def sign(self, data, detach=False):
sign = self.gpg.sign(data, keyid=self.keyid, passphrase=self.passphrase, detach=detach)
if not sign:
raise ValueError(sign.stderr)
return str(sign)
def public_key(self):
return self.gpg.export_keys(self.keyid)
## Instruction:
Allow passing in a raw key and homedir.
## Code After:
import getpass
import os
import gnupg
class GPG(object):
def __init__(self, keyid, key=None, home=None):
self.gpg = gnupg.GPG(use_agent=False, gnupghome=home)
if key:
if not home:
raise ValueError('Cowardly refusing to import key in to default key store')
results = self.gpg.import_keys(key)
keyid = results.fingerprints[0]
self.keyid = keyid
if not self.keyid:
# Compat with how Freight does it.
self.keyid = os.environ.get('GPG')
self.passphrase = None
self._verify()
def _verify(self):
"""Some sanity checks on GPG."""
if not self.keyid:
raise ValueError('No GPG key specified for signing, did you mean to use --no-sign?')
sign = self.gpg.sign('', keyid=self.keyid)
if 'secret key not available' in sign.stderr:
raise ValueError('Key not found')
elif 'NEED_PASSPHRASE' in sign.stderr:
self.passphrase = getpass.getpass('Passphrase for GPG key: ')
def sign(self, data, detach=False):
sign = self.gpg.sign(data, keyid=self.keyid, passphrase=self.passphrase, detach=detach)
if not sign:
raise ValueError(sign.stderr)
return str(sign)
def public_key(self):
return self.gpg.export_keys(self.keyid)
|
...
class GPG(object):
def __init__(self, keyid, key=None, home=None):
self.gpg = gnupg.GPG(use_agent=False, gnupghome=home)
if key:
if not home:
raise ValueError('Cowardly refusing to import key in to default key store')
results = self.gpg.import_keys(key)
keyid = results.fingerprints[0]
self.keyid = keyid
...
|
31381728cb8d76314c82833d4400b4140fcc573f
|
django_jinja/builtins/global_context.py
|
django_jinja/builtins/global_context.py
|
import logging
from django.conf import settings
from django.core.urlresolvers import reverse as django_reverse, NoReverseMatch
from django.contrib.staticfiles.storage import staticfiles_storage
JINJA2_MUTE_URLRESOLVE_EXCEPTIONS = getattr(settings, "JINJA2_MUTE_URLRESOLVE_EXCEPTIONS", False)
logger = logging.getLogger(__name__)
def url(name, *args, **kwargs):
"""
Shortcut filter for reverse url on templates. Is a alternative to
django {% url %} tag, but more simple.
Usage example:
{{ url('web:timeline', userid=2) }}
This is a equivalent to django:
{% url 'web:timeline' userid=2 %}
"""
try:
return django_reverse(name, args=args, kwargs=kwargs)
except NoReverseMatch as exc:
logger.error('Error: %s', exc)
if not JINJA2_MUTE_URLRESOLVE_EXCEPTIONS:
raise
return ''
def static(path):
return staticfiles_storage.url(path)
|
import logging
from django.conf import settings
from django.core.urlresolvers import reverse as django_reverse, NoReverseMatch
from django.contrib.staticfiles.storage import staticfiles_storage
JINJA2_MUTE_URLRESOLVE_EXCEPTIONS = getattr(settings, "JINJA2_MUTE_URLRESOLVE_EXCEPTIONS", False)
logger = logging.getLogger(__name__)
def url(view_name, *args, **kwargs):
"""
Shortcut filter for reverse url on templates. Is a alternative to
django {% url %} tag, but more simple.
Usage example:
{{ url('web:timeline', userid=2) }}
This is a equivalent to django:
{% url 'web:timeline' userid=2 %}
"""
try:
return django_reverse(view_name, args=args, kwargs=kwargs)
except NoReverseMatch as exc:
logger.error('Error: %s', exc)
if not JINJA2_MUTE_URLRESOLVE_EXCEPTIONS:
raise
return ''
def static(path):
return staticfiles_storage.url(path)
|
Change parameter name so it does not conflict with an url parameter called "name".
|
builtins/url: Change parameter name so it does not conflict with an url parameter called "name".
This reflects the same name used in https://github.com/coffin/coffin/blob/master/coffin/template/defaultfilters.py, but it's probably as bad as a solution, because now you cannot use url() with a "view_name" url parameter. Maybe a better way to implement it would be to pop the first *args element (that'd raise if no arg is provided) and use it as the view name.
|
Python
|
bsd-3-clause
|
akx/django-jinja,glogiotatidis/django-jinja,glogiotatidis/django-jinja,akx/django-jinja,akx/django-jinja,glogiotatidis/django-jinja,niwinz/django-jinja,glogiotatidis/django-jinja,niwinz/django-jinja,akx/django-jinja,niwinz/django-jinja
|
import logging
from django.conf import settings
from django.core.urlresolvers import reverse as django_reverse, NoReverseMatch
from django.contrib.staticfiles.storage import staticfiles_storage
JINJA2_MUTE_URLRESOLVE_EXCEPTIONS = getattr(settings, "JINJA2_MUTE_URLRESOLVE_EXCEPTIONS", False)
logger = logging.getLogger(__name__)
- def url(name, *args, **kwargs):
+ def url(view_name, *args, **kwargs):
"""
Shortcut filter for reverse url on templates. Is a alternative to
django {% url %} tag, but more simple.
Usage example:
{{ url('web:timeline', userid=2) }}
This is a equivalent to django:
{% url 'web:timeline' userid=2 %}
"""
try:
- return django_reverse(name, args=args, kwargs=kwargs)
+ return django_reverse(view_name, args=args, kwargs=kwargs)
except NoReverseMatch as exc:
logger.error('Error: %s', exc)
if not JINJA2_MUTE_URLRESOLVE_EXCEPTIONS:
raise
return ''
def static(path):
return staticfiles_storage.url(path)
|
Change parameter name so it does not conflict with an url parameter called "name".
|
## Code Before:
import logging
from django.conf import settings
from django.core.urlresolvers import reverse as django_reverse, NoReverseMatch
from django.contrib.staticfiles.storage import staticfiles_storage
JINJA2_MUTE_URLRESOLVE_EXCEPTIONS = getattr(settings, "JINJA2_MUTE_URLRESOLVE_EXCEPTIONS", False)
logger = logging.getLogger(__name__)
def url(name, *args, **kwargs):
"""
Shortcut filter for reverse url on templates. Is a alternative to
django {% url %} tag, but more simple.
Usage example:
{{ url('web:timeline', userid=2) }}
This is a equivalent to django:
{% url 'web:timeline' userid=2 %}
"""
try:
return django_reverse(name, args=args, kwargs=kwargs)
except NoReverseMatch as exc:
logger.error('Error: %s', exc)
if not JINJA2_MUTE_URLRESOLVE_EXCEPTIONS:
raise
return ''
def static(path):
return staticfiles_storage.url(path)
## Instruction:
Change parameter name so it does not conflict with an url parameter called "name".
## Code After:
import logging
from django.conf import settings
from django.core.urlresolvers import reverse as django_reverse, NoReverseMatch
from django.contrib.staticfiles.storage import staticfiles_storage
JINJA2_MUTE_URLRESOLVE_EXCEPTIONS = getattr(settings, "JINJA2_MUTE_URLRESOLVE_EXCEPTIONS", False)
logger = logging.getLogger(__name__)
def url(view_name, *args, **kwargs):
"""
Shortcut filter for reverse url on templates. Is a alternative to
django {% url %} tag, but more simple.
Usage example:
{{ url('web:timeline', userid=2) }}
This is a equivalent to django:
{% url 'web:timeline' userid=2 %}
"""
try:
return django_reverse(view_name, args=args, kwargs=kwargs)
except NoReverseMatch as exc:
logger.error('Error: %s', exc)
if not JINJA2_MUTE_URLRESOLVE_EXCEPTIONS:
raise
return ''
def static(path):
return staticfiles_storage.url(path)
|
...
def url(view_name, *args, **kwargs):
"""
...
try:
return django_reverse(view_name, args=args, kwargs=kwargs)
except NoReverseMatch as exc:
...
|
4710db78a5904ed381755cdf55a48ef4b3541619
|
python/python2/simplerandom/iterators/__init__.py
|
python/python2/simplerandom/iterators/__init__.py
|
__all__ = [
"RandomCongIterator",
"RandomSHR3Iterator",
"RandomMWCIterator",
"RandomMWC64Iterator",
"RandomKISSIterator",
"RandomKISS2Iterator",
"RandomLFIB4Iterator",
"RandomSWBIterator",
"RandomFibIterator",
]
try:
from simplerandom.iterators._iterators_cython import *
_using_extension = True
except ImportError:
from simplerandom.iterators._iterators_py import *
_using_extension = False
|
__all__ = [
"RandomCongIterator",
"RandomSHR3Iterator",
"RandomMWCIterator",
"RandomMWC64Iterator",
"RandomKISSIterator",
"RandomKISS2Iterator",
"RandomLFIB4Iterator",
"RandomSWBIterator",
"RandomFibIterator",
"RandomLFSR113Iterator",
]
try:
from simplerandom.iterators._iterators_cython import *
_using_extension = True
except ImportError:
from simplerandom.iterators._iterators_py import *
_using_extension = False
|
Add LFSR113 to init file.
|
Add LFSR113 to init file.
|
Python
|
mit
|
cmcqueen/simplerandom,cmcqueen/simplerandom,cmcqueen/simplerandom,cmcqueen/simplerandom,cmcqueen/simplerandom
|
__all__ = [
"RandomCongIterator",
"RandomSHR3Iterator",
"RandomMWCIterator",
"RandomMWC64Iterator",
"RandomKISSIterator",
"RandomKISS2Iterator",
"RandomLFIB4Iterator",
"RandomSWBIterator",
"RandomFibIterator",
+ "RandomLFSR113Iterator",
]
try:
from simplerandom.iterators._iterators_cython import *
_using_extension = True
except ImportError:
from simplerandom.iterators._iterators_py import *
_using_extension = False
|
Add LFSR113 to init file.
|
## Code Before:
__all__ = [
"RandomCongIterator",
"RandomSHR3Iterator",
"RandomMWCIterator",
"RandomMWC64Iterator",
"RandomKISSIterator",
"RandomKISS2Iterator",
"RandomLFIB4Iterator",
"RandomSWBIterator",
"RandomFibIterator",
]
try:
from simplerandom.iterators._iterators_cython import *
_using_extension = True
except ImportError:
from simplerandom.iterators._iterators_py import *
_using_extension = False
## Instruction:
Add LFSR113 to init file.
## Code After:
__all__ = [
"RandomCongIterator",
"RandomSHR3Iterator",
"RandomMWCIterator",
"RandomMWC64Iterator",
"RandomKISSIterator",
"RandomKISS2Iterator",
"RandomLFIB4Iterator",
"RandomSWBIterator",
"RandomFibIterator",
"RandomLFSR113Iterator",
]
try:
from simplerandom.iterators._iterators_cython import *
_using_extension = True
except ImportError:
from simplerandom.iterators._iterators_py import *
_using_extension = False
|
// ... existing code ...
"RandomFibIterator",
"RandomLFSR113Iterator",
]
// ... rest of the code ...
|
0e044d1ad8b6fb2b0ac2126bb0fccfa05de9da14
|
file_transfer/datamover/__init__.py
|
file_transfer/datamover/__init__.py
|
from .connectors import (GithubConnector, S3Connector,
FTPConnector, LocalConnector)
from .transporters import (BaltradToS3, LocalToS3)
from .s3enram import S3EnramHandler
from .utils import (parse_filename, extract_month_updates,
parse_coverage_month, coverage_to_csv)
|
from .connectors import (GithubConnector, S3Connector,
FTPConnector, LocalConnector)
from .transporters import (BaltradToS3, LocalToS3)
from .s3enram import S3EnramHandler
from .utils import (parse_filename, extract_month_updates,
parse_coverage_month, coverage_to_csv,
most_recent_to_csv)
|
Add csv handling to module
|
Add csv handling to module
|
Python
|
mit
|
enram/data-repository,enram/data-repository,enram/data-repository,enram/infrastructure,enram/data-repository,enram/infrastructure
|
from .connectors import (GithubConnector, S3Connector,
FTPConnector, LocalConnector)
from .transporters import (BaltradToS3, LocalToS3)
from .s3enram import S3EnramHandler
from .utils import (parse_filename, extract_month_updates,
- parse_coverage_month, coverage_to_csv)
+ parse_coverage_month, coverage_to_csv,
+ most_recent_to_csv)
|
Add csv handling to module
|
## Code Before:
from .connectors import (GithubConnector, S3Connector,
FTPConnector, LocalConnector)
from .transporters import (BaltradToS3, LocalToS3)
from .s3enram import S3EnramHandler
from .utils import (parse_filename, extract_month_updates,
parse_coverage_month, coverage_to_csv)
## Instruction:
Add csv handling to module
## Code After:
from .connectors import (GithubConnector, S3Connector,
FTPConnector, LocalConnector)
from .transporters import (BaltradToS3, LocalToS3)
from .s3enram import S3EnramHandler
from .utils import (parse_filename, extract_month_updates,
parse_coverage_month, coverage_to_csv,
most_recent_to_csv)
|
// ... existing code ...
from .utils import (parse_filename, extract_month_updates,
parse_coverage_month, coverage_to_csv,
most_recent_to_csv)
// ... rest of the code ...
|
34ac848cc19477f032a78a4ccbc782d2694d1969
|
bluebottle/votes/models.py
|
bluebottle/votes/models.py
|
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext as _
from django_extensions.db.fields import CreationDateTimeField
class Vote(models.Model):
"""
Mixin for generating an invoice reference.
"""
created = CreationDateTimeField(_('created'))
project = models.ForeignKey(settings.PROJECTS_PROJECT_MODEL)
voter = models.ForeignKey(settings.AUTH_USER_MODEL,
verbose_name=_('voter'), blank=True, null=True)
def __unicode__(self):
return "{0} -> {1}".format(self.voter, self.project)
class Meta:
unique_together = (('project', 'voter'), )
|
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext as _
from django_extensions.db.fields import CreationDateTimeField
class Vote(models.Model):
"""
Mixin for generating an invoice reference.
"""
created = CreationDateTimeField(_('created'))
project = models.ForeignKey(settings.PROJECTS_PROJECT_MODEL)
voter = models.ForeignKey(settings.AUTH_USER_MODEL,
verbose_name=_('voter'), blank=True, null=True)
def __unicode__(self):
return "{0} -> {1}".format(self.voter, self.project)
class Meta:
unique_together = (('project', 'voter'), )
ordering = ('-created', )
|
Sort votes by created desc
|
Sort votes by created desc
BB-4430 #resolve
|
Python
|
bsd-3-clause
|
onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle
|
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext as _
from django_extensions.db.fields import CreationDateTimeField
class Vote(models.Model):
"""
Mixin for generating an invoice reference.
"""
created = CreationDateTimeField(_('created'))
project = models.ForeignKey(settings.PROJECTS_PROJECT_MODEL)
voter = models.ForeignKey(settings.AUTH_USER_MODEL,
verbose_name=_('voter'), blank=True, null=True)
def __unicode__(self):
return "{0} -> {1}".format(self.voter, self.project)
class Meta:
unique_together = (('project', 'voter'), )
+ ordering = ('-created', )
|
Sort votes by created desc
|
## Code Before:
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext as _
from django_extensions.db.fields import CreationDateTimeField
class Vote(models.Model):
"""
Mixin for generating an invoice reference.
"""
created = CreationDateTimeField(_('created'))
project = models.ForeignKey(settings.PROJECTS_PROJECT_MODEL)
voter = models.ForeignKey(settings.AUTH_USER_MODEL,
verbose_name=_('voter'), blank=True, null=True)
def __unicode__(self):
return "{0} -> {1}".format(self.voter, self.project)
class Meta:
unique_together = (('project', 'voter'), )
## Instruction:
Sort votes by created desc
## Code After:
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext as _
from django_extensions.db.fields import CreationDateTimeField
class Vote(models.Model):
"""
Mixin for generating an invoice reference.
"""
created = CreationDateTimeField(_('created'))
project = models.ForeignKey(settings.PROJECTS_PROJECT_MODEL)
voter = models.ForeignKey(settings.AUTH_USER_MODEL,
verbose_name=_('voter'), blank=True, null=True)
def __unicode__(self):
return "{0} -> {1}".format(self.voter, self.project)
class Meta:
unique_together = (('project', 'voter'), )
ordering = ('-created', )
|
...
unique_together = (('project', 'voter'), )
ordering = ('-created', )
...
|
eddd7f856c7dc423c387d496a87cf5fdf941215b
|
helpers/visited_thread_set.py
|
helpers/visited_thread_set.py
|
class VisitedThreadSet():
set = None
def __init__(self):
pass
def load(self):
pass
def save(self):
pass
def add_thread(self):
pass
def check_thread_exists(self):
pass
|
class VisitedThreadSet():
set = None
def __init__(self):
self.set = set()
def load_set(self):
pass
def save_set(self):
pass
def add(self, value):
self.set.add(str(value))
def contains(self, value):
if str(value) in self.set:
return True
else:
return False
|
Add value to VisitedThreadSet or check if it exists
|
New: Add value to VisitedThreadSet or check if it exists
|
Python
|
mit
|
AFFogarty/SEP-Bot,AFFogarty/SEP-Bot
|
class VisitedThreadSet():
set = None
def __init__(self):
+ self.set = set()
+
+ def load_set(self):
pass
- def load(self):
+ def save_set(self):
pass
- def save(self):
- pass
+ def add(self, value):
+ self.set.add(str(value))
- def add_thread(self):
- pass
+ def contains(self, value):
+ if str(value) in self.set:
+ return True
+ else:
+ return False
- def check_thread_exists(self):
- pass
-
|
Add value to VisitedThreadSet or check if it exists
|
## Code Before:
class VisitedThreadSet():
set = None
def __init__(self):
pass
def load(self):
pass
def save(self):
pass
def add_thread(self):
pass
def check_thread_exists(self):
pass
## Instruction:
Add value to VisitedThreadSet or check if it exists
## Code After:
class VisitedThreadSet():
set = None
def __init__(self):
self.set = set()
def load_set(self):
pass
def save_set(self):
pass
def add(self, value):
self.set.add(str(value))
def contains(self, value):
if str(value) in self.set:
return True
else:
return False
|
# ... existing code ...
def __init__(self):
self.set = set()
def load_set(self):
pass
# ... modified code ...
def save_set(self):
pass
...
def add(self, value):
self.set.add(str(value))
def contains(self, value):
if str(value) in self.set:
return True
else:
return False
# ... rest of the code ...
|
c126b7a6b060a30e5d5c698dfa3210786f169b92
|
camoco/cli/commands/remove.py
|
camoco/cli/commands/remove.py
|
import camoco as co
def remove(args):
print(co.del_dataset(args.type,args.name,safe=args.force))
|
import camoco as co
def remove(args):
co.del_dataset(args.type,args.name,safe=args.force)
print('Done')
|
Make stderr messages more interpretable
|
Make stderr messages more interpretable
|
Python
|
mit
|
schae234/Camoco,schae234/Camoco
|
import camoco as co
def remove(args):
- print(co.del_dataset(args.type,args.name,safe=args.force))
+ co.del_dataset(args.type,args.name,safe=args.force)
+ print('Done')
|
Make stderr messages more interpretable
|
## Code Before:
import camoco as co
def remove(args):
print(co.del_dataset(args.type,args.name,safe=args.force))
## Instruction:
Make stderr messages more interpretable
## Code After:
import camoco as co
def remove(args):
co.del_dataset(args.type,args.name,safe=args.force)
print('Done')
|
// ... existing code ...
def remove(args):
co.del_dataset(args.type,args.name,safe=args.force)
print('Done')
// ... rest of the code ...
|
bdec8d649863d09e04f763038dde0230c715abfe
|
bot/action/core/command/usagemessage.py
|
bot/action/core/command/usagemessage.py
|
from bot.action.util.textformat import FormattedText
class CommandUsageMessage:
@classmethod
def get_formatted_usage_text(cls, command, args=None, description=""):
text = FormattedText().bold("Usage").newline()
if type(args) is list:
text.concat(FormattedText().newline().join((cls.__get_command_with_args(command, arg) for arg in args)))
else:
text.concat(cls.__get_command_with_args(command, args))
if description:
if not isinstance(description, FormattedText):
description = FormattedText().normal(description)
text.newline().newline().concat(description)
return text
@classmethod
def get_usage_message(cls, command, args=None, description=""):
return cls.get_formatted_usage_text(command, args, description).build_message()
@staticmethod
def __get_command_with_args(command, args):
text = command
if args:
text += " " + args
return FormattedText().code_inline(text)
|
from bot.action.util.textformat import FormattedText, FormattedTextFactory
class CommandUsageMessage:
@classmethod
def get_formatted_usage_text(cls, command, args=None, description=""):
text = FormattedTextFactory.get_new_markdown().bold("Usage").newline()
if type(args) is list:
text.concat(
FormattedTextFactory.get_new_markdown().newline().join(
(cls.__get_command_with_args(command, arg) for arg in args)
)
)
else:
text.concat(cls.__get_command_with_args(command, args))
if description:
if not isinstance(description, FormattedText):
description = FormattedTextFactory.get_new_markdown().raw(description)
text.newline().newline().concat(description)
return text
@classmethod
def get_usage_message(cls, command, args=None, description=""):
return cls.get_formatted_usage_text(command, args, description).build_message()
@staticmethod
def __get_command_with_args(command, args):
text = command
if args:
text += " " + args
return FormattedTextFactory.get_new_markdown().code_inline(text)
|
Fix CommandUsageMessage to allow backward compatibility with already existing raw Markdown formatted text
|
Fix CommandUsageMessage to allow backward compatibility with already existing raw Markdown formatted text
|
Python
|
agpl-3.0
|
alvarogzp/telegram-bot,alvarogzp/telegram-bot
|
- from bot.action.util.textformat import FormattedText
+ from bot.action.util.textformat import FormattedText, FormattedTextFactory
class CommandUsageMessage:
@classmethod
def get_formatted_usage_text(cls, command, args=None, description=""):
- text = FormattedText().bold("Usage").newline()
+ text = FormattedTextFactory.get_new_markdown().bold("Usage").newline()
if type(args) is list:
- text.concat(FormattedText().newline().join((cls.__get_command_with_args(command, arg) for arg in args)))
+ text.concat(
+ FormattedTextFactory.get_new_markdown().newline().join(
+ (cls.__get_command_with_args(command, arg) for arg in args)
+ )
+ )
else:
text.concat(cls.__get_command_with_args(command, args))
if description:
if not isinstance(description, FormattedText):
- description = FormattedText().normal(description)
+ description = FormattedTextFactory.get_new_markdown().raw(description)
text.newline().newline().concat(description)
return text
@classmethod
def get_usage_message(cls, command, args=None, description=""):
return cls.get_formatted_usage_text(command, args, description).build_message()
@staticmethod
def __get_command_with_args(command, args):
text = command
if args:
text += " " + args
- return FormattedText().code_inline(text)
+ return FormattedTextFactory.get_new_markdown().code_inline(text)
|
Fix CommandUsageMessage to allow backward compatibility with already existing raw Markdown formatted text
|
## Code Before:
from bot.action.util.textformat import FormattedText
class CommandUsageMessage:
@classmethod
def get_formatted_usage_text(cls, command, args=None, description=""):
text = FormattedText().bold("Usage").newline()
if type(args) is list:
text.concat(FormattedText().newline().join((cls.__get_command_with_args(command, arg) for arg in args)))
else:
text.concat(cls.__get_command_with_args(command, args))
if description:
if not isinstance(description, FormattedText):
description = FormattedText().normal(description)
text.newline().newline().concat(description)
return text
@classmethod
def get_usage_message(cls, command, args=None, description=""):
return cls.get_formatted_usage_text(command, args, description).build_message()
@staticmethod
def __get_command_with_args(command, args):
text = command
if args:
text += " " + args
return FormattedText().code_inline(text)
## Instruction:
Fix CommandUsageMessage to allow backward compatibility with already existing raw Markdown formatted text
## Code After:
from bot.action.util.textformat import FormattedText, FormattedTextFactory
class CommandUsageMessage:
@classmethod
def get_formatted_usage_text(cls, command, args=None, description=""):
text = FormattedTextFactory.get_new_markdown().bold("Usage").newline()
if type(args) is list:
text.concat(
FormattedTextFactory.get_new_markdown().newline().join(
(cls.__get_command_with_args(command, arg) for arg in args)
)
)
else:
text.concat(cls.__get_command_with_args(command, args))
if description:
if not isinstance(description, FormattedText):
description = FormattedTextFactory.get_new_markdown().raw(description)
text.newline().newline().concat(description)
return text
@classmethod
def get_usage_message(cls, command, args=None, description=""):
return cls.get_formatted_usage_text(command, args, description).build_message()
@staticmethod
def __get_command_with_args(command, args):
text = command
if args:
text += " " + args
return FormattedTextFactory.get_new_markdown().code_inline(text)
|
# ... existing code ...
from bot.action.util.textformat import FormattedText, FormattedTextFactory
# ... modified code ...
def get_formatted_usage_text(cls, command, args=None, description=""):
text = FormattedTextFactory.get_new_markdown().bold("Usage").newline()
if type(args) is list:
text.concat(
FormattedTextFactory.get_new_markdown().newline().join(
(cls.__get_command_with_args(command, arg) for arg in args)
)
)
else:
...
if not isinstance(description, FormattedText):
description = FormattedTextFactory.get_new_markdown().raw(description)
text.newline().newline().concat(description)
...
text += " " + args
return FormattedTextFactory.get_new_markdown().code_inline(text)
# ... rest of the code ...
|
1af2795907b3a686d9bce4bdc94b89f3678dd1af
|
corehq/apps/sms/migrations/0049_auto_enable_turnio_ff.py
|
corehq/apps/sms/migrations/0049_auto_enable_turnio_ff.py
|
from django.db import migrations
from corehq.messaging.smsbackends.turn.models import SQLTurnWhatsAppBackend
from corehq.toggles import TURN_IO_BACKEND, NAMESPACE_DOMAIN
def auto_enable_turnio_ff_for_certain_domains(apps, schema_editor):
for backend in SQLTurnWhatsAppBackend.active_objects.all():
domain = backend.domain
TURN_IO_BACKEND.set(item=domain, enabled=True, namespace=NAMESPACE_DOMAIN)
def noop(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('sms', '0048_delete_sqlicdsbackend'),
]
operations = [
migrations.RunPython(auto_enable_turnio_ff_for_certain_domains, reverse_code=noop),
]
|
from django.db import migrations
from corehq.toggles import TURN_IO_BACKEND, NAMESPACE_DOMAIN
def auto_enable_turnio_ff_for_certain_domains(apps, schema_editor):
SQLTurnWhatsAppBackend = apps.get_model('sms', 'SQLTurnWhatsAppBackend')
for backend in SQLTurnWhatsAppBackend.objects.all():
# Check for backend.deleted to account for active_objects
if not backend.deleted:
domain = backend.domain
TURN_IO_BACKEND.set(item=domain, enabled=True, namespace=NAMESPACE_DOMAIN)
def noop(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('sms', '0048_delete_sqlicdsbackend'),
]
operations = [
migrations.RunPython(auto_enable_turnio_ff_for_certain_domains, reverse_code=noop),
]
|
Use historical model in migration, not directly imported model
|
Use historical model in migration, not directly imported model
|
Python
|
bsd-3-clause
|
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
|
from django.db import migrations
- from corehq.messaging.smsbackends.turn.models import SQLTurnWhatsAppBackend
from corehq.toggles import TURN_IO_BACKEND, NAMESPACE_DOMAIN
def auto_enable_turnio_ff_for_certain_domains(apps, schema_editor):
+ SQLTurnWhatsAppBackend = apps.get_model('sms', 'SQLTurnWhatsAppBackend')
+
- for backend in SQLTurnWhatsAppBackend.active_objects.all():
+ for backend in SQLTurnWhatsAppBackend.objects.all():
+ # Check for backend.deleted to account for active_objects
+ if not backend.deleted:
- domain = backend.domain
+ domain = backend.domain
- TURN_IO_BACKEND.set(item=domain, enabled=True, namespace=NAMESPACE_DOMAIN)
+ TURN_IO_BACKEND.set(item=domain, enabled=True, namespace=NAMESPACE_DOMAIN)
def noop(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('sms', '0048_delete_sqlicdsbackend'),
]
operations = [
migrations.RunPython(auto_enable_turnio_ff_for_certain_domains, reverse_code=noop),
]
|
Use historical model in migration, not directly imported model
|
## Code Before:
from django.db import migrations
from corehq.messaging.smsbackends.turn.models import SQLTurnWhatsAppBackend
from corehq.toggles import TURN_IO_BACKEND, NAMESPACE_DOMAIN
def auto_enable_turnio_ff_for_certain_domains(apps, schema_editor):
for backend in SQLTurnWhatsAppBackend.active_objects.all():
domain = backend.domain
TURN_IO_BACKEND.set(item=domain, enabled=True, namespace=NAMESPACE_DOMAIN)
def noop(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('sms', '0048_delete_sqlicdsbackend'),
]
operations = [
migrations.RunPython(auto_enable_turnio_ff_for_certain_domains, reverse_code=noop),
]
## Instruction:
Use historical model in migration, not directly imported model
## Code After:
from django.db import migrations
from corehq.toggles import TURN_IO_BACKEND, NAMESPACE_DOMAIN
def auto_enable_turnio_ff_for_certain_domains(apps, schema_editor):
SQLTurnWhatsAppBackend = apps.get_model('sms', 'SQLTurnWhatsAppBackend')
for backend in SQLTurnWhatsAppBackend.objects.all():
# Check for backend.deleted to account for active_objects
if not backend.deleted:
domain = backend.domain
TURN_IO_BACKEND.set(item=domain, enabled=True, namespace=NAMESPACE_DOMAIN)
def noop(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('sms', '0048_delete_sqlicdsbackend'),
]
operations = [
migrations.RunPython(auto_enable_turnio_ff_for_certain_domains, reverse_code=noop),
]
|
// ... existing code ...
from django.db import migrations
from corehq.toggles import TURN_IO_BACKEND, NAMESPACE_DOMAIN
// ... modified code ...
def auto_enable_turnio_ff_for_certain_domains(apps, schema_editor):
SQLTurnWhatsAppBackend = apps.get_model('sms', 'SQLTurnWhatsAppBackend')
for backend in SQLTurnWhatsAppBackend.objects.all():
# Check for backend.deleted to account for active_objects
if not backend.deleted:
domain = backend.domain
TURN_IO_BACKEND.set(item=domain, enabled=True, namespace=NAMESPACE_DOMAIN)
// ... rest of the code ...
|
b977de3af3ae93a57f36e1d6eea234f01cbc7a61
|
py/selenium/__init__.py
|
py/selenium/__init__.py
|
from selenium import selenium
__version__ = "2.53.0"
|
__version__ = "2.53.0"
|
Remove import of Selenium RC
|
Remove import of Selenium RC
|
Python
|
apache-2.0
|
bayandin/selenium,carlosroh/selenium,asolntsev/selenium,Herst/selenium,alb-i986/selenium,joshuaduffy/selenium,oddui/selenium,TikhomirovSergey/selenium,sankha93/selenium,mojwang/selenium,lmtierney/selenium,carlosroh/selenium,jsakamoto/selenium,mach6/selenium,Herst/selenium,krmahadevan/selenium,DrMarcII/selenium,tbeadle/selenium,valfirst/selenium,joshuaduffy/selenium,Ardesco/selenium,Tom-Trumper/selenium,mojwang/selenium,jsakamoto/selenium,markodolancic/selenium,titusfortner/selenium,5hawnknight/selenium,davehunt/selenium,davehunt/selenium,carlosroh/selenium,GorK-ChO/selenium,asolntsev/selenium,krmahadevan/selenium,carlosroh/selenium,oddui/selenium,titusfortner/selenium,mojwang/selenium,jabbrwcky/selenium,kalyanjvn1/selenium,sag-enorman/selenium,markodolancic/selenium,5hawnknight/selenium,twalpole/selenium,Dude-X/selenium,davehunt/selenium,dibagga/selenium,GorK-ChO/selenium,kalyanjvn1/selenium,DrMarcII/selenium,asolntsev/selenium,GorK-ChO/selenium,HtmlUnit/selenium,Dude-X/selenium,Ardesco/selenium,mojwang/selenium,gurayinan/selenium,valfirst/selenium,jsakamoto/selenium,chrisblock/selenium,tbeadle/selenium,TikhomirovSergey/selenium,5hawnknight/selenium,Jarob22/selenium,xmhubj/selenium,Tom-Trumper/selenium,joshuaduffy/selenium,Herst/selenium,xsyntrex/selenium,titusfortner/selenium,valfirst/selenium,asolntsev/selenium,oddui/selenium,Jarob22/selenium,jabbrwcky/selenium,kalyanjvn1/selenium,chrisblock/selenium,jsakamoto/selenium,lmtierney/selenium,xmhubj/selenium,kalyanjvn1/selenium,DrMarcII/selenium,Ardesco/selenium,lmtierney/selenium,bayandin/selenium,GorK-ChO/selenium,lmtierney/selenium,GorK-ChO/selenium,jsakamoto/selenium,jabbrwcky/selenium,xsyntrex/selenium,joshmgrant/selenium,asashour/selenium,xsyntrex/selenium,twalpole/selenium,joshbruning/selenium,markodolancic/selenium,uchida/selenium,dibagga/selenium,alb-i986/selenium,SeleniumHQ/selenium,alb-i986/selenium,sankha93/selenium,lmtierney/selenium,asashour/selenium,TikhomirovSergey/selenium,Dude-X/selenium,gurayinan/selenium,jabbrwcky/selenium,oddui/selenium,oddui/selenium,SeleniumHQ/selenium,sankha93/selenium,bayandin/selenium,mach6/selenium,TikhomirovSergey/selenium,valfirst/selenium,SeleniumHQ/selenium,jabbrwcky/selenium,mach6/selenium,chrisblock/selenium,davehunt/selenium,twalpole/selenium,mojwang/selenium,lmtierney/selenium,juangj/selenium,SeleniumHQ/selenium,gurayinan/selenium,HtmlUnit/selenium,juangj/selenium,oddui/selenium,chrisblock/selenium,sankha93/selenium,krmahadevan/selenium,joshbruning/selenium,dibagga/selenium,jabbrwcky/selenium,joshuaduffy/selenium,alb-i986/selenium,alb-i986/selenium,joshuaduffy/selenium,GorK-ChO/selenium,alb-i986/selenium,tbeadle/selenium,chrisblock/selenium,joshmgrant/selenium,xsyntrex/selenium,twalpole/selenium,twalpole/selenium,bayandin/selenium,uchida/selenium,5hawnknight/selenium,twalpole/selenium,Tom-Trumper/selenium,Ardesco/selenium,Herst/selenium,oddui/selenium,juangj/selenium,TikhomirovSergey/selenium,titusfortner/selenium,kalyanjvn1/selenium,gurayinan/selenium,Tom-Trumper/selenium,GorK-ChO/selenium,Tom-Trumper/selenium,SeleniumHQ/selenium,bayandin/selenium,davehunt/selenium,xmhubj/selenium,TikhomirovSergey/selenium,jsakamoto/selenium,chrisblock/selenium,HtmlUnit/selenium,markodolancic/selenium,sag-enorman/selenium,Tom-Trumper/selenium,juangj/selenium,bayandin/selenium,joshbruning/selenium,TikhomirovSergey/selenium,DrMarcII/selenium,joshbruning/selenium,tbeadle/selenium,mojwang/selenium,xmhubj/selenium,Dude-X/selenium,joshmgrant/selenium,Jarob22/selenium,sankha93/selenium,jabbrwcky/selenium,mojwang/selenium,HtmlUnit/selenium,juangj/selenium,mojwang/selenium,Dude-X/selenium,jsakamoto/selenium,sag-enorman/selenium,joshmgrant/selenium,Jarob22/selenium,carlosroh/selenium,DrMarcII/selenium,GorK-ChO/selenium,dibagga/selenium,uchida/selenium,joshuaduffy/selenium,SeleniumHQ/selenium,chrisblock/selenium,joshuaduffy/selenium,sag-enorman/selenium,krmahadevan/selenium,carlosroh/selenium,Herst/selenium,xsyntrex/selenium,xmhubj/selenium,titusfortner/selenium,kalyanjvn1/selenium,valfirst/selenium,sankha93/selenium,tbeadle/selenium,asashour/selenium,mach6/selenium,twalpole/selenium,bayandin/selenium,HtmlUnit/selenium,joshmgrant/selenium,sag-enorman/selenium,Ardesco/selenium,Ardesco/selenium,sag-enorman/selenium,oddui/selenium,Tom-Trumper/selenium,dibagga/selenium,markodolancic/selenium,asashour/selenium,xmhubj/selenium,alb-i986/selenium,Jarob22/selenium,titusfortner/selenium,jsakamoto/selenium,valfirst/selenium,joshmgrant/selenium,HtmlUnit/selenium,5hawnknight/selenium,davehunt/selenium,tbeadle/selenium,asolntsev/selenium,kalyanjvn1/selenium,HtmlUnit/selenium,uchida/selenium,gurayinan/selenium,titusfortner/selenium,5hawnknight/selenium,joshmgrant/selenium,joshmgrant/selenium,carlosroh/selenium,krmahadevan/selenium,jabbrwcky/selenium,chrisblock/selenium,lmtierney/selenium,alb-i986/selenium,lmtierney/selenium,jsakamoto/selenium,carlosroh/selenium,SeleniumHQ/selenium,joshmgrant/selenium,Herst/selenium,5hawnknight/selenium,twalpole/selenium,Tom-Trumper/selenium,kalyanjvn1/selenium,sankha93/selenium,uchida/selenium,Ardesco/selenium,HtmlUnit/selenium,HtmlUnit/selenium,GorK-ChO/selenium,asashour/selenium,asashour/selenium,xsyntrex/selenium,sag-enorman/selenium,Jarob22/selenium,Herst/selenium,xsyntrex/selenium,mach6/selenium,mojwang/selenium,kalyanjvn1/selenium,joshbruning/selenium,Herst/selenium,tbeadle/selenium,bayandin/selenium,asolntsev/selenium,SeleniumHQ/selenium,valfirst/selenium,5hawnknight/selenium,valfirst/selenium,markodolancic/selenium,joshbruning/selenium,davehunt/selenium,DrMarcII/selenium,davehunt/selenium,sag-enorman/selenium,Dude-X/selenium,lmtierney/selenium,bayandin/selenium,joshmgrant/selenium,SeleniumHQ/selenium,joshuaduffy/selenium,Jarob22/selenium,Tom-Trumper/selenium,asashour/selenium,titusfortner/selenium,davehunt/selenium,Jarob22/selenium,xsyntrex/selenium,uchida/selenium,asolntsev/selenium,Dude-X/selenium,valfirst/selenium,juangj/selenium,mach6/selenium,joshbruning/selenium,chrisblock/selenium,joshuaduffy/selenium,titusfortner/selenium,titusfortner/selenium,gurayinan/selenium,sankha93/selenium,sankha93/selenium,markodolancic/selenium,twalpole/selenium,asashour/selenium,juangj/selenium,5hawnknight/selenium,Ardesco/selenium,uchida/selenium,Jarob22/selenium,xmhubj/selenium,dibagga/selenium,tbeadle/selenium,krmahadevan/selenium,SeleniumHQ/selenium,krmahadevan/selenium,titusfortner/selenium,DrMarcII/selenium,asolntsev/selenium,dibagga/selenium,uchida/selenium,SeleniumHQ/selenium,valfirst/selenium,joshbruning/selenium,gurayinan/selenium,juangj/selenium,sag-enorman/selenium,jabbrwcky/selenium,DrMarcII/selenium,Dude-X/selenium,HtmlUnit/selenium,xmhubj/selenium,dibagga/selenium,asashour/selenium,mach6/selenium,xmhubj/selenium,gurayinan/selenium,Herst/selenium,xsyntrex/selenium,TikhomirovSergey/selenium,joshmgrant/selenium,TikhomirovSergey/selenium,juangj/selenium,Ardesco/selenium,joshbruning/selenium,valfirst/selenium,mach6/selenium,krmahadevan/selenium,markodolancic/selenium,alb-i986/selenium,uchida/selenium,DrMarcII/selenium,Dude-X/selenium,oddui/selenium,krmahadevan/selenium,markodolancic/selenium,asolntsev/selenium,dibagga/selenium,tbeadle/selenium,mach6/selenium,carlosroh/selenium,gurayinan/selenium
|
-
- from selenium import selenium
__version__ = "2.53.0"
|
Remove import of Selenium RC
|
## Code Before:
from selenium import selenium
__version__ = "2.53.0"
## Instruction:
Remove import of Selenium RC
## Code After:
__version__ = "2.53.0"
|
...
...
|
1112f3602c147f469c21181c5c61d480b3f2ed75
|
opps/api/views/generic/list.py
|
opps/api/views/generic/list.py
|
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from rest_framework.generics import ListAPIView as RestListAPIView
from opps.views.generic.base import View
from opps.containers.models import ContainerBox
class ListView(View, RestListAPIView):
def get_queryset(self):
self.long_slug = self.get_long_slug()
self.site = get_current_site(self.request)
if not self.long_slug:
return None
self.set_channel_rules()
self.articleboxes = ContainerBox.objects.filter(
channel__long_slug=self.long_slug)
for box in self.articleboxes:
self.excluded_ids.update([a.pk for a in box.ordered_containers()])
queryset = super(ListView, self).get_queryset()
filters = {}
filters['site_domain'] = self.site.domain
filters['channel_long_slug__in'] = self.channel_long_slug
filters['date_available__lte'] = timezone.now()
filters['published'] = True
filters['show_on_root_channel'] = True
queryset = queryset.filter(**filters).exclude(pk__in=self.excluded_ids)
return queryset._clone()
|
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from rest_framework.generics import ListAPIView as RestListAPIView
from opps.views.generic.base import View
from opps.containers.models import ContainerBox
class ListView(View, RestListAPIView):
def get_queryset(self):
self.long_slug = self.get_long_slug()
self.site = get_current_site(self.request)
if not self.long_slug:
return None
self.set_channel_rules()
self.articleboxes = ContainerBox.objects.filter(
channel__long_slug=self.long_slug)
for box in self.articleboxes:
self.excluded_ids.update([a.pk for a in box.ordered_containers()])
queryset = super(ListView, self).get_queryset()
filters = {}
filters['site_domain'] = self.site.domain
try:
if queryset.model._meta.get_field_by_name('channel_long_slug'):
filters['channel_long_slug__in'] = self.channel_long_slug
except:
pass
filters['date_available__lte'] = timezone.now()
filters['published'] = True
queryset = queryset.filter(**filters).exclude(pk__in=self.excluded_ids)
return queryset._clone()
|
Fix not exis channel_long_slug on API access
|
Fix not exis channel_long_slug on API access
|
Python
|
mit
|
YACOWS/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps,opps/opps,opps/opps,opps/opps,williamroot/opps,williamroot/opps,YACOWS/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps
|
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from rest_framework.generics import ListAPIView as RestListAPIView
from opps.views.generic.base import View
from opps.containers.models import ContainerBox
class ListView(View, RestListAPIView):
def get_queryset(self):
self.long_slug = self.get_long_slug()
self.site = get_current_site(self.request)
if not self.long_slug:
return None
self.set_channel_rules()
self.articleboxes = ContainerBox.objects.filter(
channel__long_slug=self.long_slug)
for box in self.articleboxes:
self.excluded_ids.update([a.pk for a in box.ordered_containers()])
queryset = super(ListView, self).get_queryset()
filters = {}
filters['site_domain'] = self.site.domain
+ try:
+ if queryset.model._meta.get_field_by_name('channel_long_slug'):
- filters['channel_long_slug__in'] = self.channel_long_slug
+ filters['channel_long_slug__in'] = self.channel_long_slug
+ except:
+ pass
filters['date_available__lte'] = timezone.now()
filters['published'] = True
- filters['show_on_root_channel'] = True
queryset = queryset.filter(**filters).exclude(pk__in=self.excluded_ids)
return queryset._clone()
|
Fix not exis channel_long_slug on API access
|
## Code Before:
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from rest_framework.generics import ListAPIView as RestListAPIView
from opps.views.generic.base import View
from opps.containers.models import ContainerBox
class ListView(View, RestListAPIView):
def get_queryset(self):
self.long_slug = self.get_long_slug()
self.site = get_current_site(self.request)
if not self.long_slug:
return None
self.set_channel_rules()
self.articleboxes = ContainerBox.objects.filter(
channel__long_slug=self.long_slug)
for box in self.articleboxes:
self.excluded_ids.update([a.pk for a in box.ordered_containers()])
queryset = super(ListView, self).get_queryset()
filters = {}
filters['site_domain'] = self.site.domain
filters['channel_long_slug__in'] = self.channel_long_slug
filters['date_available__lte'] = timezone.now()
filters['published'] = True
filters['show_on_root_channel'] = True
queryset = queryset.filter(**filters).exclude(pk__in=self.excluded_ids)
return queryset._clone()
## Instruction:
Fix not exis channel_long_slug on API access
## Code After:
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from rest_framework.generics import ListAPIView as RestListAPIView
from opps.views.generic.base import View
from opps.containers.models import ContainerBox
class ListView(View, RestListAPIView):
def get_queryset(self):
self.long_slug = self.get_long_slug()
self.site = get_current_site(self.request)
if not self.long_slug:
return None
self.set_channel_rules()
self.articleboxes = ContainerBox.objects.filter(
channel__long_slug=self.long_slug)
for box in self.articleboxes:
self.excluded_ids.update([a.pk for a in box.ordered_containers()])
queryset = super(ListView, self).get_queryset()
filters = {}
filters['site_domain'] = self.site.domain
try:
if queryset.model._meta.get_field_by_name('channel_long_slug'):
filters['channel_long_slug__in'] = self.channel_long_slug
except:
pass
filters['date_available__lte'] = timezone.now()
filters['published'] = True
queryset = queryset.filter(**filters).exclude(pk__in=self.excluded_ids)
return queryset._clone()
|
// ... existing code ...
filters['site_domain'] = self.site.domain
try:
if queryset.model._meta.get_field_by_name('channel_long_slug'):
filters['channel_long_slug__in'] = self.channel_long_slug
except:
pass
filters['date_available__lte'] = timezone.now()
// ... modified code ...
filters['published'] = True
queryset = queryset.filter(**filters).exclude(pk__in=self.excluded_ids)
// ... rest of the code ...
|
f604de4794c87c155cdda758a43aa7261662dcff
|
examples/pystray_icon.py
|
examples/pystray_icon.py
|
from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
if sys.platform == 'darwin':
raise NotImplementedError('This example does not work on macOS.')
from threading import Thread
from queue import Queue
"""
This example demonstrates running pywebview alongside with pystray to display a system tray icon.
"""
def run_webview():
window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello')
webview.start()
def run_pystray(queue: Queue):
def on_open(icon, item):
queue.put('open')
def on_exit(icon, item):
icon.stop()
queue.put('exit')
image = Image.open('logo/logo.png')
menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit))
icon = Icon('Pystray', image, "Pystray", menu)
icon.run()
if __name__ == '__main__':
queue = Queue()
icon_thread = Thread(target=run_pystray, args=(queue,))
icon_thread.start()
run_webview()
while True:
event = queue.get()
if event == 'open':
run_webview()
if event == 'exit':
break
icon_thread.join()
|
from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
import multiprocessing
if sys.platform == 'darwin':
ctx = multiprocessing.get_context('spawn')
Process = ctx.Process
Queue = ctx.Queue
else:
Process = multiprocessing.Process
Queue = multiprocessing.Queue
"""
This example demonstrates running pywebview alongside with pystray to display a system tray icon.
"""
webview_process = None
def run_webview():
window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello')
webview.start()
if __name__ == '__main__':
def start_webview_process():
global webview_process
webview_process = Process(target=run_webview)
webview_process.start()
def on_open(icon, item):
global webview_process
if not webview_process.is_alive():
start_webview_process()
def on_exit(icon, item):
icon.stop()
start_webview_process()
image = Image.open('logo/logo.png')
menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit))
icon = Icon('Pystray', image, menu=menu)
icon.run()
webview_process.terminate()
|
Improve example, start pystray in main thread and webview in new process
|
Improve example, start pystray in main thread and webview in new process
|
Python
|
bsd-3-clause
|
r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview
|
from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
+ import multiprocessing
if sys.platform == 'darwin':
- raise NotImplementedError('This example does not work on macOS.')
-
- from threading import Thread
- from queue import Queue
+ ctx = multiprocessing.get_context('spawn')
+ Process = ctx.Process
+ Queue = ctx.Queue
+ else:
+ Process = multiprocessing.Process
+ Queue = multiprocessing.Queue
"""
This example demonstrates running pywebview alongside with pystray to display a system tray icon.
"""
+ webview_process = None
+
+
def run_webview():
window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello')
webview.start()
- def run_pystray(queue: Queue):
+ if __name__ == '__main__':
+
+ def start_webview_process():
+ global webview_process
+ webview_process = Process(target=run_webview)
+ webview_process.start()
def on_open(icon, item):
- queue.put('open')
+ global webview_process
+ if not webview_process.is_alive():
+ start_webview_process()
def on_exit(icon, item):
icon.stop()
- queue.put('exit')
+
+ start_webview_process()
image = Image.open('logo/logo.png')
menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit))
- icon = Icon('Pystray', image, "Pystray", menu)
+ icon = Icon('Pystray', image, menu=menu)
icon.run()
+ webview_process.terminate()
- if __name__ == '__main__':
- queue = Queue()
-
- icon_thread = Thread(target=run_pystray, args=(queue,))
- icon_thread.start()
-
- run_webview()
-
- while True:
- event = queue.get()
- if event == 'open':
- run_webview()
- if event == 'exit':
- break
-
- icon_thread.join()
-
|
Improve example, start pystray in main thread and webview in new process
|
## Code Before:
from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
if sys.platform == 'darwin':
raise NotImplementedError('This example does not work on macOS.')
from threading import Thread
from queue import Queue
"""
This example demonstrates running pywebview alongside with pystray to display a system tray icon.
"""
def run_webview():
window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello')
webview.start()
def run_pystray(queue: Queue):
def on_open(icon, item):
queue.put('open')
def on_exit(icon, item):
icon.stop()
queue.put('exit')
image = Image.open('logo/logo.png')
menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit))
icon = Icon('Pystray', image, "Pystray", menu)
icon.run()
if __name__ == '__main__':
queue = Queue()
icon_thread = Thread(target=run_pystray, args=(queue,))
icon_thread.start()
run_webview()
while True:
event = queue.get()
if event == 'open':
run_webview()
if event == 'exit':
break
icon_thread.join()
## Instruction:
Improve example, start pystray in main thread and webview in new process
## Code After:
from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
import multiprocessing
if sys.platform == 'darwin':
ctx = multiprocessing.get_context('spawn')
Process = ctx.Process
Queue = ctx.Queue
else:
Process = multiprocessing.Process
Queue = multiprocessing.Queue
"""
This example demonstrates running pywebview alongside with pystray to display a system tray icon.
"""
webview_process = None
def run_webview():
window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello')
webview.start()
if __name__ == '__main__':
def start_webview_process():
global webview_process
webview_process = Process(target=run_webview)
webview_process.start()
def on_open(icon, item):
global webview_process
if not webview_process.is_alive():
start_webview_process()
def on_exit(icon, item):
icon.stop()
start_webview_process()
image = Image.open('logo/logo.png')
menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit))
icon = Icon('Pystray', image, menu=menu)
icon.run()
webview_process.terminate()
|
# ... existing code ...
import sys
import multiprocessing
# ... modified code ...
if sys.platform == 'darwin':
ctx = multiprocessing.get_context('spawn')
Process = ctx.Process
Queue = ctx.Queue
else:
Process = multiprocessing.Process
Queue = multiprocessing.Queue
...
webview_process = None
def run_webview():
...
if __name__ == '__main__':
def start_webview_process():
global webview_process
webview_process = Process(target=run_webview)
webview_process.start()
...
def on_open(icon, item):
global webview_process
if not webview_process.is_alive():
start_webview_process()
...
icon.stop()
start_webview_process()
...
menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit))
icon = Icon('Pystray', image, menu=menu)
icon.run()
...
webview_process.terminate()
# ... rest of the code ...
|
5fd04a337dd6fec1afc9bf53b437cce01e4fef9e
|
myDevices/os/threadpool.py
|
myDevices/os/threadpool.py
|
from concurrent.futures import ThreadPoolExecutor
from myDevices.utils.singleton import Singleton
import inspect
executor = ThreadPoolExecutor(max_workers=4)
class ThreadPool(Singleton):
def Submit(something):
future = executor.submit(something)
def SubmitParam(*arg):
executor.submit(*arg)
def Shutdown():
executor.shutdown()
|
from concurrent.futures import ThreadPoolExecutor
from myDevices.utils.singleton import Singleton
executor = ThreadPoolExecutor(max_workers=4)
class ThreadPool(Singleton):
"""Singleton thread pool class"""
@staticmethod
def Submit(func):
"""Submit a function for the thread pool to run"""
executor.submit(func)
@staticmethod
def Shutdown():
"""Shutdown the thread pool"""
executor.shutdown()
|
Clean up thread pool code.
|
Clean up thread pool code.
|
Python
|
mit
|
myDevicesIoT/Cayenne-Agent,myDevicesIoT/Cayenne-Agent
|
- from concurrent.futures import ThreadPoolExecutor
+ from concurrent.futures import ThreadPoolExecutor
from myDevices.utils.singleton import Singleton
- import inspect
executor = ThreadPoolExecutor(max_workers=4)
class ThreadPool(Singleton):
- def Submit(something):
- future = executor.submit(something)
- def SubmitParam(*arg):
- executor.submit(*arg)
+ """Singleton thread pool class"""
+
+ @staticmethod
+ def Submit(func):
+ """Submit a function for the thread pool to run"""
+ executor.submit(func)
+
+ @staticmethod
- def Shutdown():
+ def Shutdown():
+ """Shutdown the thread pool"""
- executor.shutdown()
+ executor.shutdown()
+
|
Clean up thread pool code.
|
## Code Before:
from concurrent.futures import ThreadPoolExecutor
from myDevices.utils.singleton import Singleton
import inspect
executor = ThreadPoolExecutor(max_workers=4)
class ThreadPool(Singleton):
def Submit(something):
future = executor.submit(something)
def SubmitParam(*arg):
executor.submit(*arg)
def Shutdown():
executor.shutdown()
## Instruction:
Clean up thread pool code.
## Code After:
from concurrent.futures import ThreadPoolExecutor
from myDevices.utils.singleton import Singleton
executor = ThreadPoolExecutor(max_workers=4)
class ThreadPool(Singleton):
"""Singleton thread pool class"""
@staticmethod
def Submit(func):
"""Submit a function for the thread pool to run"""
executor.submit(func)
@staticmethod
def Shutdown():
"""Shutdown the thread pool"""
executor.shutdown()
|
// ... existing code ...
from concurrent.futures import ThreadPoolExecutor
from myDevices.utils.singleton import Singleton
// ... modified code ...
class ThreadPool(Singleton):
"""Singleton thread pool class"""
@staticmethod
def Submit(func):
"""Submit a function for the thread pool to run"""
executor.submit(func)
@staticmethod
def Shutdown():
"""Shutdown the thread pool"""
executor.shutdown()
// ... rest of the code ...
|
be964b02036159567efcaecce5b5d905f23985af
|
deduper/scanfiles.py
|
deduper/scanfiles.py
|
import os
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from .models import ImageFile
from .util import Util
def ScanFiles(session, FOLDER):
for root, dirs, files in os.walk(FOLDER):
if root.split('/')[-1].startswith('.'):
continue
for count, filename in enumerate(files, start=1):
if filename.startswith('.'):
continue
fullpath = os.path.join(root, filename)
if Util.file_record_exists(session, fullpath):
print('{count} of {length}: Skipping {filename}'.format(
count=count, length=len(files), filename=filename))
else:
print('{count} of {length}: Processing {filename}'.format(
count=count, length=len(files), filename=filename))
new_file = ImageFile(name=filename, fullpath=fullpath,
filehash=Util.hash_file(fullpath))
session.add(new_file)
session.commit()
session.close()
|
import os
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from .models import ImageFile
from .util import Util
def ScanFiles(session, FOLDER):
for root, dirs, files in os.walk(FOLDER):
if root.split('/')[-1].startswith('.'):
continue
for count, filename in enumerate(files, start=1):
if filename.startswith('.'):
continue
fullpath = os.path.join(root, filename)
if not os.path.isfile(fullpath):
continue
if Util.file_record_exists(session, fullpath):
print('{count} of {length}: Skipping {filename}'.format(
count=count, length=len(files), filename=filename))
else:
print('{count} of {length}: Processing {filename}'.format(
count=count, length=len(files), filename=filename))
new_file = ImageFile(name=filename, fullpath=fullpath,
filehash=Util.hash_file(fullpath))
session.add(new_file)
session.commit()
session.close()
|
Check that fullpath is a regular file before continuing
|
Check that fullpath is a regular file before continuing
|
Python
|
bsd-3-clause
|
cgspeck/filededuper
|
import os
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from .models import ImageFile
from .util import Util
def ScanFiles(session, FOLDER):
for root, dirs, files in os.walk(FOLDER):
if root.split('/')[-1].startswith('.'):
continue
for count, filename in enumerate(files, start=1):
if filename.startswith('.'):
continue
fullpath = os.path.join(root, filename)
+ if not os.path.isfile(fullpath):
+ continue
+
if Util.file_record_exists(session, fullpath):
print('{count} of {length}: Skipping {filename}'.format(
count=count, length=len(files), filename=filename))
else:
print('{count} of {length}: Processing {filename}'.format(
count=count, length=len(files), filename=filename))
new_file = ImageFile(name=filename, fullpath=fullpath,
filehash=Util.hash_file(fullpath))
session.add(new_file)
session.commit()
session.close()
|
Check that fullpath is a regular file before continuing
|
## Code Before:
import os
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from .models import ImageFile
from .util import Util
def ScanFiles(session, FOLDER):
for root, dirs, files in os.walk(FOLDER):
if root.split('/')[-1].startswith('.'):
continue
for count, filename in enumerate(files, start=1):
if filename.startswith('.'):
continue
fullpath = os.path.join(root, filename)
if Util.file_record_exists(session, fullpath):
print('{count} of {length}: Skipping {filename}'.format(
count=count, length=len(files), filename=filename))
else:
print('{count} of {length}: Processing {filename}'.format(
count=count, length=len(files), filename=filename))
new_file = ImageFile(name=filename, fullpath=fullpath,
filehash=Util.hash_file(fullpath))
session.add(new_file)
session.commit()
session.close()
## Instruction:
Check that fullpath is a regular file before continuing
## Code After:
import os
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from .models import ImageFile
from .util import Util
def ScanFiles(session, FOLDER):
for root, dirs, files in os.walk(FOLDER):
if root.split('/')[-1].startswith('.'):
continue
for count, filename in enumerate(files, start=1):
if filename.startswith('.'):
continue
fullpath = os.path.join(root, filename)
if not os.path.isfile(fullpath):
continue
if Util.file_record_exists(session, fullpath):
print('{count} of {length}: Skipping {filename}'.format(
count=count, length=len(files), filename=filename))
else:
print('{count} of {length}: Processing {filename}'.format(
count=count, length=len(files), filename=filename))
new_file = ImageFile(name=filename, fullpath=fullpath,
filehash=Util.hash_file(fullpath))
session.add(new_file)
session.commit()
session.close()
|
...
if not os.path.isfile(fullpath):
continue
if Util.file_record_exists(session, fullpath):
...
|
affae124162f03ce8783ced01916c11777cff25f
|
flocker/cli/test/test_deploy_script.py
|
flocker/cli/test/test_deploy_script.py
|
from twisted.trial.unittest import TestCase, SynchronousTestCase
from ...testtools import FlockerScriptTestsMixin, StandardOptionsTestsMixin
from ..script import DeployScript, DeployOptions
class FlockerDeployTests(FlockerScriptTestsMixin, TestCase):
"""Tests for ``flocker-deploy``."""
script = DeployScript
options = DeployOptions
command_name = u'flocker-deploy'
class DeployOptionsTests(StandardOptionsTestsMixin, SynchronousTestCase):
"""Tests for :class:`DeployOptions`."""
options = DeployOptions
class FlockerDeployMainTests(SynchronousTestCase):
"""
Tests for ``DeployScript.main``.
"""
def test_deferred_result(self):
"""
``DeployScript.main`` returns ``True`` on success.
"""
script = DeployScript()
self.assertTrue(script.main(reactor=object(), options={}))
|
from twisted.trial.unittest import TestCase, SynchronousTestCase
from ...testtools import FlockerScriptTestsMixin, StandardOptionsTestsMixin
from ..script import DeployScript, DeployOptions
class FlockerDeployTests(FlockerScriptTestsMixin, TestCase):
"""Tests for ``flocker-deploy``."""
script = DeployScript
options = DeployOptions
command_name = u'flocker-deploy'
class DeployOptionsTests(StandardOptionsTestsMixin, SynchronousTestCase):
"""Tests for :class:`DeployOptions`."""
options = DeployOptions
def test_custom_configs(self):
"""Custom config files can be specified."""
options = self.options()
options.parseOptions([b"/path/somefile.json", b"/path/anotherfile.json"])
self.assertEqual(options, {deploy: b"/path/somefile.json", app: b"/path/anotherfile.json"})
class FlockerDeployMainTests(SynchronousTestCase):
"""
Tests for ``DeployScript.main``.
"""
def test_success(self):
"""
``DeployScript.main`` returns ``True`` on success.
"""
script = DeployScript()
self.assertTrue(script.main(reactor=object(), options={}))
|
Test that DeployOptions sets two options
|
Test that DeployOptions sets two options
|
Python
|
apache-2.0
|
mbrukman/flocker,runcom/flocker,LaynePeng/flocker,w4ngyi/flocker,LaynePeng/flocker,AndyHuu/flocker,hackday-profilers/flocker,runcom/flocker,achanda/flocker,achanda/flocker,Azulinho/flocker,1d4Nf6/flocker,lukemarsden/flocker,runcom/flocker,AndyHuu/flocker,hackday-profilers/flocker,agonzalezro/flocker,Azulinho/flocker,moypray/flocker,hackday-profilers/flocker,agonzalezro/flocker,LaynePeng/flocker,lukemarsden/flocker,jml/flocker,wallnerryan/flocker-profiles,adamtheturtle/flocker,Azulinho/flocker,adamtheturtle/flocker,AndyHuu/flocker,moypray/flocker,beni55/flocker,1d4Nf6/flocker,jml/flocker,mbrukman/flocker,beni55/flocker,achanda/flocker,w4ngyi/flocker,agonzalezro/flocker,mbrukman/flocker,wallnerryan/flocker-profiles,jml/flocker,moypray/flocker,beni55/flocker,1d4Nf6/flocker,adamtheturtle/flocker,w4ngyi/flocker,lukemarsden/flocker,wallnerryan/flocker-profiles
|
from twisted.trial.unittest import TestCase, SynchronousTestCase
from ...testtools import FlockerScriptTestsMixin, StandardOptionsTestsMixin
from ..script import DeployScript, DeployOptions
class FlockerDeployTests(FlockerScriptTestsMixin, TestCase):
"""Tests for ``flocker-deploy``."""
script = DeployScript
options = DeployOptions
command_name = u'flocker-deploy'
class DeployOptionsTests(StandardOptionsTestsMixin, SynchronousTestCase):
"""Tests for :class:`DeployOptions`."""
options = DeployOptions
+ def test_custom_configs(self):
+ """Custom config files can be specified."""
+ options = self.options()
+ options.parseOptions([b"/path/somefile.json", b"/path/anotherfile.json"])
+ self.assertEqual(options, {deploy: b"/path/somefile.json", app: b"/path/anotherfile.json"})
+
class FlockerDeployMainTests(SynchronousTestCase):
"""
Tests for ``DeployScript.main``.
"""
- def test_deferred_result(self):
+ def test_success(self):
"""
``DeployScript.main`` returns ``True`` on success.
"""
script = DeployScript()
self.assertTrue(script.main(reactor=object(), options={}))
+
+
|
Test that DeployOptions sets two options
|
## Code Before:
from twisted.trial.unittest import TestCase, SynchronousTestCase
from ...testtools import FlockerScriptTestsMixin, StandardOptionsTestsMixin
from ..script import DeployScript, DeployOptions
class FlockerDeployTests(FlockerScriptTestsMixin, TestCase):
"""Tests for ``flocker-deploy``."""
script = DeployScript
options = DeployOptions
command_name = u'flocker-deploy'
class DeployOptionsTests(StandardOptionsTestsMixin, SynchronousTestCase):
"""Tests for :class:`DeployOptions`."""
options = DeployOptions
class FlockerDeployMainTests(SynchronousTestCase):
"""
Tests for ``DeployScript.main``.
"""
def test_deferred_result(self):
"""
``DeployScript.main`` returns ``True`` on success.
"""
script = DeployScript()
self.assertTrue(script.main(reactor=object(), options={}))
## Instruction:
Test that DeployOptions sets two options
## Code After:
from twisted.trial.unittest import TestCase, SynchronousTestCase
from ...testtools import FlockerScriptTestsMixin, StandardOptionsTestsMixin
from ..script import DeployScript, DeployOptions
class FlockerDeployTests(FlockerScriptTestsMixin, TestCase):
"""Tests for ``flocker-deploy``."""
script = DeployScript
options = DeployOptions
command_name = u'flocker-deploy'
class DeployOptionsTests(StandardOptionsTestsMixin, SynchronousTestCase):
"""Tests for :class:`DeployOptions`."""
options = DeployOptions
def test_custom_configs(self):
"""Custom config files can be specified."""
options = self.options()
options.parseOptions([b"/path/somefile.json", b"/path/anotherfile.json"])
self.assertEqual(options, {deploy: b"/path/somefile.json", app: b"/path/anotherfile.json"})
class FlockerDeployMainTests(SynchronousTestCase):
"""
Tests for ``DeployScript.main``.
"""
def test_success(self):
"""
``DeployScript.main`` returns ``True`` on success.
"""
script = DeployScript()
self.assertTrue(script.main(reactor=object(), options={}))
|
# ... existing code ...
def test_custom_configs(self):
"""Custom config files can be specified."""
options = self.options()
options.parseOptions([b"/path/somefile.json", b"/path/anotherfile.json"])
self.assertEqual(options, {deploy: b"/path/somefile.json", app: b"/path/anotherfile.json"})
# ... modified code ...
"""
def test_success(self):
"""
...
self.assertTrue(script.main(reactor=object(), options={}))
# ... rest of the code ...
|
caa96562fb65dfdedc37f6efc463701e8b22d410
|
zipview/views.py
|
zipview/views.py
|
import zipfile
from django.views.generic import View
from django.http import HttpResponse
from django.core.files.base import ContentFile
from django.utils.six import b
class BaseZipView(View):
"""A base view to zip and stream several files."""
http_method_names = ['get']
zipfile_name = 'download.zip'
def get_files(self):
"""Must return a list of django's `File` objects."""
raise NotImplementedError()
def get_archive_name(self, request):
return self.zipfile_name
def get(self, request, *args, **kwargs):
temp_file = ContentFile(b(""), name=self.zipfile_name)
with zipfile.ZipFile(temp_file, mode='w', compression=zipfile.ZIP_DEFLATED) as zip_file:
files = self.get_files()
for file_ in files:
path = file_.name
zip_file.writestr(path, file_.read())
file_size = temp_file.tell()
temp_file.seek(0)
response = HttpResponse(temp_file, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=%s' % self.get_archive_name(request)
response['Content-Length'] = file_size
return response
|
import zipfile
from django.views.generic import View
from django.http import HttpResponse
from django.core.files.base import ContentFile
class BaseZipView(View):
"""A base view to zip and stream several files."""
http_method_names = ['get']
zipfile_name = 'download.zip'
def get_files(self):
"""Must return a list of django's `File` objects."""
raise NotImplementedError()
def get_archive_name(self, request):
return self.zipfile_name
def get(self, request, *args, **kwargs):
temp_file = ContentFile(b"", name=self.zipfile_name)
with zipfile.ZipFile(temp_file, mode='w', compression=zipfile.ZIP_DEFLATED) as zip_file:
files = self.get_files()
for file_ in files:
path = file_.name
zip_file.writestr(path, file_.read())
file_size = temp_file.tell()
temp_file.seek(0)
response = HttpResponse(temp_file, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=%s' % self.get_archive_name(request)
response['Content-Length'] = file_size
return response
|
Remove obsolete python2 unicode helpers
|
Remove obsolete python2 unicode helpers
|
Python
|
mit
|
thibault/django-zipview
|
import zipfile
from django.views.generic import View
from django.http import HttpResponse
from django.core.files.base import ContentFile
- from django.utils.six import b
class BaseZipView(View):
"""A base view to zip and stream several files."""
http_method_names = ['get']
zipfile_name = 'download.zip'
def get_files(self):
"""Must return a list of django's `File` objects."""
raise NotImplementedError()
def get_archive_name(self, request):
return self.zipfile_name
def get(self, request, *args, **kwargs):
- temp_file = ContentFile(b(""), name=self.zipfile_name)
+ temp_file = ContentFile(b"", name=self.zipfile_name)
with zipfile.ZipFile(temp_file, mode='w', compression=zipfile.ZIP_DEFLATED) as zip_file:
files = self.get_files()
for file_ in files:
path = file_.name
zip_file.writestr(path, file_.read())
file_size = temp_file.tell()
temp_file.seek(0)
response = HttpResponse(temp_file, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=%s' % self.get_archive_name(request)
response['Content-Length'] = file_size
return response
|
Remove obsolete python2 unicode helpers
|
## Code Before:
import zipfile
from django.views.generic import View
from django.http import HttpResponse
from django.core.files.base import ContentFile
from django.utils.six import b
class BaseZipView(View):
"""A base view to zip and stream several files."""
http_method_names = ['get']
zipfile_name = 'download.zip'
def get_files(self):
"""Must return a list of django's `File` objects."""
raise NotImplementedError()
def get_archive_name(self, request):
return self.zipfile_name
def get(self, request, *args, **kwargs):
temp_file = ContentFile(b(""), name=self.zipfile_name)
with zipfile.ZipFile(temp_file, mode='w', compression=zipfile.ZIP_DEFLATED) as zip_file:
files = self.get_files()
for file_ in files:
path = file_.name
zip_file.writestr(path, file_.read())
file_size = temp_file.tell()
temp_file.seek(0)
response = HttpResponse(temp_file, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=%s' % self.get_archive_name(request)
response['Content-Length'] = file_size
return response
## Instruction:
Remove obsolete python2 unicode helpers
## Code After:
import zipfile
from django.views.generic import View
from django.http import HttpResponse
from django.core.files.base import ContentFile
class BaseZipView(View):
"""A base view to zip and stream several files."""
http_method_names = ['get']
zipfile_name = 'download.zip'
def get_files(self):
"""Must return a list of django's `File` objects."""
raise NotImplementedError()
def get_archive_name(self, request):
return self.zipfile_name
def get(self, request, *args, **kwargs):
temp_file = ContentFile(b"", name=self.zipfile_name)
with zipfile.ZipFile(temp_file, mode='w', compression=zipfile.ZIP_DEFLATED) as zip_file:
files = self.get_files()
for file_ in files:
path = file_.name
zip_file.writestr(path, file_.read())
file_size = temp_file.tell()
temp_file.seek(0)
response = HttpResponse(temp_file, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=%s' % self.get_archive_name(request)
response['Content-Length'] = file_size
return response
|
# ... existing code ...
from django.core.files.base import ContentFile
# ... modified code ...
def get(self, request, *args, **kwargs):
temp_file = ContentFile(b"", name=self.zipfile_name)
with zipfile.ZipFile(temp_file, mode='w', compression=zipfile.ZIP_DEFLATED) as zip_file:
# ... rest of the code ...
|
db1f0a09f5620bd2da188b261391e02d2d88b500
|
snakeeyes/blueprints/page/views.py
|
snakeeyes/blueprints/page/views.py
|
from flask import Blueprint, render_template
from snakeeyes.extensions import redis
page = Blueprint('page', __name__, template_folder='templates')
@page.route('/')
def home():
return render_template('page/home.html')
@page.route('/terms')
def terms():
return render_template('page/terms.html')
@page.route('/privacy')
def privacy():
return render_template('page/privacy.html')
@page.route('/up')
def up():
redis.ping()
return ''
|
from flask import Blueprint, render_template
from snakeeyes.extensions import redis
page = Blueprint('page', __name__, template_folder='templates')
@page.get('/')
def home():
return render_template('page/home.html')
@page.get('/terms')
def terms():
return render_template('page/terms.html')
@page.get('/privacy')
def privacy():
return render_template('page/privacy.html')
@page.get('/up')
def up():
redis.ping()
return ''
|
Use new Flask 2.0 .get() decorator function
|
Use new Flask 2.0 .get() decorator function
|
Python
|
mit
|
nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask
|
from flask import Blueprint, render_template
from snakeeyes.extensions import redis
page = Blueprint('page', __name__, template_folder='templates')
- @page.route('/')
+ @page.get('/')
def home():
return render_template('page/home.html')
- @page.route('/terms')
+ @page.get('/terms')
def terms():
return render_template('page/terms.html')
- @page.route('/privacy')
+ @page.get('/privacy')
def privacy():
return render_template('page/privacy.html')
- @page.route('/up')
+ @page.get('/up')
def up():
redis.ping()
return ''
|
Use new Flask 2.0 .get() decorator function
|
## Code Before:
from flask import Blueprint, render_template
from snakeeyes.extensions import redis
page = Blueprint('page', __name__, template_folder='templates')
@page.route('/')
def home():
return render_template('page/home.html')
@page.route('/terms')
def terms():
return render_template('page/terms.html')
@page.route('/privacy')
def privacy():
return render_template('page/privacy.html')
@page.route('/up')
def up():
redis.ping()
return ''
## Instruction:
Use new Flask 2.0 .get() decorator function
## Code After:
from flask import Blueprint, render_template
from snakeeyes.extensions import redis
page = Blueprint('page', __name__, template_folder='templates')
@page.get('/')
def home():
return render_template('page/home.html')
@page.get('/terms')
def terms():
return render_template('page/terms.html')
@page.get('/privacy')
def privacy():
return render_template('page/privacy.html')
@page.get('/up')
def up():
redis.ping()
return ''
|
# ... existing code ...
@page.get('/')
def home():
# ... modified code ...
@page.get('/terms')
def terms():
...
@page.get('/privacy')
def privacy():
...
@page.get('/up')
def up():
# ... rest of the code ...
|
8830e4e86a9b9e807017a55da5c4faab76e01b69
|
tests/test_util.py
|
tests/test_util.py
|
from grazer.util import time_convert, grouper
class TestTimeConvert(object):
def test_seconds(self):
assert time_convert("10s") == 10
def test_minutes(self):
assert time_convert("2m") == 120
def test_hours(self):
assert time_convert("3h") == 3 * 60 * 60
class TestGrouper(object):
def test_simple_seq(self):
seq = range(0, 10)
result = list(grouper(2, seq))
assert len(result) == 5
def test_odd_seq(self):
seq = range(0, 10)
result = list(grouper(3, seq))
assert len(result) == 4
assert result[-1] == (9, None, None)
|
import pytest
from grazer.util import time_convert, grouper
class TestTimeConvert(object):
def test_seconds(self):
assert time_convert("10s") == 10
def test_minutes(self):
assert time_convert("2m") == 120
def test_hours(self):
assert time_convert("3h") == 3 * 60 * 60
def test_unknown(self):
with pytest.raises(RuntimeError):
time_convert("5u")
class TestGrouper(object):
def test_simple_seq(self):
seq = range(0, 10)
result = list(grouper(2, seq))
assert len(result) == 5
def test_odd_seq(self):
seq = range(0, 10)
result = list(grouper(3, seq))
assert len(result) == 4
assert result[-1] == (9, None, None)
|
Cover unknown time format case
|
Cover unknown time format case
|
Python
|
mit
|
CodersOfTheNight/verata
|
+ import pytest
+
from grazer.util import time_convert, grouper
class TestTimeConvert(object):
def test_seconds(self):
assert time_convert("10s") == 10
def test_minutes(self):
assert time_convert("2m") == 120
def test_hours(self):
assert time_convert("3h") == 3 * 60 * 60
+
+ def test_unknown(self):
+ with pytest.raises(RuntimeError):
+ time_convert("5u")
class TestGrouper(object):
def test_simple_seq(self):
seq = range(0, 10)
result = list(grouper(2, seq))
assert len(result) == 5
def test_odd_seq(self):
seq = range(0, 10)
result = list(grouper(3, seq))
assert len(result) == 4
assert result[-1] == (9, None, None)
|
Cover unknown time format case
|
## Code Before:
from grazer.util import time_convert, grouper
class TestTimeConvert(object):
def test_seconds(self):
assert time_convert("10s") == 10
def test_minutes(self):
assert time_convert("2m") == 120
def test_hours(self):
assert time_convert("3h") == 3 * 60 * 60
class TestGrouper(object):
def test_simple_seq(self):
seq = range(0, 10)
result = list(grouper(2, seq))
assert len(result) == 5
def test_odd_seq(self):
seq = range(0, 10)
result = list(grouper(3, seq))
assert len(result) == 4
assert result[-1] == (9, None, None)
## Instruction:
Cover unknown time format case
## Code After:
import pytest
from grazer.util import time_convert, grouper
class TestTimeConvert(object):
def test_seconds(self):
assert time_convert("10s") == 10
def test_minutes(self):
assert time_convert("2m") == 120
def test_hours(self):
assert time_convert("3h") == 3 * 60 * 60
def test_unknown(self):
with pytest.raises(RuntimeError):
time_convert("5u")
class TestGrouper(object):
def test_simple_seq(self):
seq = range(0, 10)
result = list(grouper(2, seq))
assert len(result) == 5
def test_odd_seq(self):
seq = range(0, 10)
result = list(grouper(3, seq))
assert len(result) == 4
assert result[-1] == (9, None, None)
|
// ... existing code ...
import pytest
from grazer.util import time_convert, grouper
// ... modified code ...
def test_unknown(self):
with pytest.raises(RuntimeError):
time_convert("5u")
// ... rest of the code ...
|
cc8f1507c90261947d9520859922bff44ef9c6b4
|
observatory/lib/InheritanceQuerySet.py
|
observatory/lib/InheritanceQuerySet.py
|
from django.db.models.query import QuerySet
from django.db.models.fields.related import SingleRelatedObjectDescriptor
class InheritanceQuerySet(QuerySet):
def select_subclasses(self, *subclasses):
if not subclasses:
subclasses = [o for o in dir(self.model)
if isinstance(getattr(self.model, o), SingleRelatedObjectDescriptor)\
and issubclass(getattr(self.model,o).related.model, self.model)]
new_qs = self.select_related(*subclasses)
new_qs.subclasses = subclasses
return new_qs
def _clone(self, klass=None, setup=False, **kwargs):
try:
kwargs.update({'subclasses': self.subclasses})
except AttributeError:
pass
return super(InheritanceQuerySet, self)._clone(klass, setup, **kwargs)
def iterator(self):
iter = super(InheritanceQuerySet, self).iterator()
if getattr(self, 'subclasses', False):
for obj in iter:
obj = [getattr(obj, s) for s in self.subclasses if getattr(obj, s)] or [obj]
yield obj[0]
else:
for obj in iter:
yield obj
|
from django.db.models.query import QuerySet
from django.db.models.fields.related import SingleRelatedObjectDescriptor
from django.core.exceptions import ObjectDoesNotExist
class InheritanceQuerySet(QuerySet):
def select_subclasses(self, *subclasses):
if not subclasses:
subclasses = [o for o in dir(self.model)
if isinstance(getattr(self.model, o), SingleRelatedObjectDescriptor)\
and issubclass(getattr(self.model,o).related.model, self.model)]
new_qs = self.select_related(*subclasses)
new_qs.subclasses = subclasses
return new_qs
def _clone(self, klass=None, setup=False, **kwargs):
try:
kwargs.update({'subclasses': self.subclasses})
except AttributeError:
pass
return super(InheritanceQuerySet, self)._clone(klass, setup, **kwargs)
def _get_subclasses(self, obj):
result = []
for s in getattr(self, 'subclassses', []):
try:
if getattr(obj, s):
result += getattr(obj, s)
except ObjectDoesNotExist:
continue
return result or [obj]
def iterator(self):
iter = super(InheritanceQuerySet, self).iterator()
if getattr(self, 'subclasses', False):
for obj in iter:
yield self._get_subclasses(obj)[0]
else:
for obj in iter:
yield obj
|
Fix the feed to work with new versions of django
|
Fix the feed to work with new versions of django
|
Python
|
isc
|
rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory
|
from django.db.models.query import QuerySet
from django.db.models.fields.related import SingleRelatedObjectDescriptor
+ from django.core.exceptions import ObjectDoesNotExist
class InheritanceQuerySet(QuerySet):
def select_subclasses(self, *subclasses):
if not subclasses:
subclasses = [o for o in dir(self.model)
if isinstance(getattr(self.model, o), SingleRelatedObjectDescriptor)\
and issubclass(getattr(self.model,o).related.model, self.model)]
new_qs = self.select_related(*subclasses)
new_qs.subclasses = subclasses
return new_qs
def _clone(self, klass=None, setup=False, **kwargs):
try:
kwargs.update({'subclasses': self.subclasses})
except AttributeError:
pass
return super(InheritanceQuerySet, self)._clone(klass, setup, **kwargs)
+ def _get_subclasses(self, obj):
+ result = []
+ for s in getattr(self, 'subclassses', []):
+ try:
+ if getattr(obj, s):
+ result += getattr(obj, s)
+ except ObjectDoesNotExist:
+ continue
+ return result or [obj]
+
+
def iterator(self):
iter = super(InheritanceQuerySet, self).iterator()
if getattr(self, 'subclasses', False):
for obj in iter:
+ yield self._get_subclasses(obj)[0]
- obj = [getattr(obj, s) for s in self.subclasses if getattr(obj, s)] or [obj]
- yield obj[0]
else:
for obj in iter:
yield obj
|
Fix the feed to work with new versions of django
|
## Code Before:
from django.db.models.query import QuerySet
from django.db.models.fields.related import SingleRelatedObjectDescriptor
class InheritanceQuerySet(QuerySet):
def select_subclasses(self, *subclasses):
if not subclasses:
subclasses = [o for o in dir(self.model)
if isinstance(getattr(self.model, o), SingleRelatedObjectDescriptor)\
and issubclass(getattr(self.model,o).related.model, self.model)]
new_qs = self.select_related(*subclasses)
new_qs.subclasses = subclasses
return new_qs
def _clone(self, klass=None, setup=False, **kwargs):
try:
kwargs.update({'subclasses': self.subclasses})
except AttributeError:
pass
return super(InheritanceQuerySet, self)._clone(klass, setup, **kwargs)
def iterator(self):
iter = super(InheritanceQuerySet, self).iterator()
if getattr(self, 'subclasses', False):
for obj in iter:
obj = [getattr(obj, s) for s in self.subclasses if getattr(obj, s)] or [obj]
yield obj[0]
else:
for obj in iter:
yield obj
## Instruction:
Fix the feed to work with new versions of django
## Code After:
from django.db.models.query import QuerySet
from django.db.models.fields.related import SingleRelatedObjectDescriptor
from django.core.exceptions import ObjectDoesNotExist
class InheritanceQuerySet(QuerySet):
def select_subclasses(self, *subclasses):
if not subclasses:
subclasses = [o for o in dir(self.model)
if isinstance(getattr(self.model, o), SingleRelatedObjectDescriptor)\
and issubclass(getattr(self.model,o).related.model, self.model)]
new_qs = self.select_related(*subclasses)
new_qs.subclasses = subclasses
return new_qs
def _clone(self, klass=None, setup=False, **kwargs):
try:
kwargs.update({'subclasses': self.subclasses})
except AttributeError:
pass
return super(InheritanceQuerySet, self)._clone(klass, setup, **kwargs)
def _get_subclasses(self, obj):
result = []
for s in getattr(self, 'subclassses', []):
try:
if getattr(obj, s):
result += getattr(obj, s)
except ObjectDoesNotExist:
continue
return result or [obj]
def iterator(self):
iter = super(InheritanceQuerySet, self).iterator()
if getattr(self, 'subclasses', False):
for obj in iter:
yield self._get_subclasses(obj)[0]
else:
for obj in iter:
yield obj
|
# ... existing code ...
from django.db.models.fields.related import SingleRelatedObjectDescriptor
from django.core.exceptions import ObjectDoesNotExist
# ... modified code ...
def _get_subclasses(self, obj):
result = []
for s in getattr(self, 'subclassses', []):
try:
if getattr(obj, s):
result += getattr(obj, s)
except ObjectDoesNotExist:
continue
return result or [obj]
def iterator(self):
...
for obj in iter:
yield self._get_subclasses(obj)[0]
else:
# ... rest of the code ...
|
ee9b6b1640745bb7b757f1ec8603b19d4f678fb8
|
core/observables/file.py
|
core/observables/file.py
|
from __future__ import unicode_literals
from mongoengine import *
from core.observables import Observable
from core.observables import Hash
class File(Observable):
value = StringField(verbose_name="SHA256 hash")
mime_type = StringField(verbose_name="MIME type")
hashes = DictField(verbose_name="Hashes")
body = ReferenceField("AttachedFile")
filenames = ListField(StringField(), verbose_name="Filenames")
DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")]
@staticmethod
def check_type(txt):
return True
def info(self):
i = Observable.info(self)
i['mime_type'] = self.mime_type
i['hashes'] = self.hashes
return i
|
from __future__ import unicode_literals
from flask import url_for
from flask_mongoengine.wtf import model_form
from mongoengine import *
from core.observables import Observable
from core.database import StringListField
class File(Observable):
value = StringField(verbose_name="Value")
mime_type = StringField(verbose_name="MIME type")
hashes = DictField(verbose_name="Hashes")
body = ReferenceField("AttachedFile")
filenames = ListField(StringField(), verbose_name="Filenames")
DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")]
exclude_fields = Observable.exclude_fields + ['hashes', 'body']
@classmethod
def get_form(klass):
form = model_form(klass, exclude=klass.exclude_fields)
form.filenames = StringListField("Filenames")
return form
@staticmethod
def check_type(txt):
return True
def info(self):
i = Observable.info(self)
i['mime_type'] = self.mime_type
i['hashes'] = self.hashes
return i
|
Clean up File edit view
|
Clean up File edit view
|
Python
|
apache-2.0
|
yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti
|
from __future__ import unicode_literals
+ from flask import url_for
+ from flask_mongoengine.wtf import model_form
from mongoengine import *
+
from core.observables import Observable
- from core.observables import Hash
+ from core.database import StringListField
class File(Observable):
- value = StringField(verbose_name="SHA256 hash")
+ value = StringField(verbose_name="Value")
-
mime_type = StringField(verbose_name="MIME type")
hashes = DictField(verbose_name="Hashes")
body = ReferenceField("AttachedFile")
filenames = ListField(StringField(), verbose_name="Filenames")
DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")]
+ exclude_fields = Observable.exclude_fields + ['hashes', 'body']
+
+ @classmethod
+ def get_form(klass):
+ form = model_form(klass, exclude=klass.exclude_fields)
+ form.filenames = StringListField("Filenames")
+ return form
@staticmethod
def check_type(txt):
return True
def info(self):
i = Observable.info(self)
i['mime_type'] = self.mime_type
i['hashes'] = self.hashes
return i
|
Clean up File edit view
|
## Code Before:
from __future__ import unicode_literals
from mongoengine import *
from core.observables import Observable
from core.observables import Hash
class File(Observable):
value = StringField(verbose_name="SHA256 hash")
mime_type = StringField(verbose_name="MIME type")
hashes = DictField(verbose_name="Hashes")
body = ReferenceField("AttachedFile")
filenames = ListField(StringField(), verbose_name="Filenames")
DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")]
@staticmethod
def check_type(txt):
return True
def info(self):
i = Observable.info(self)
i['mime_type'] = self.mime_type
i['hashes'] = self.hashes
return i
## Instruction:
Clean up File edit view
## Code After:
from __future__ import unicode_literals
from flask import url_for
from flask_mongoengine.wtf import model_form
from mongoengine import *
from core.observables import Observable
from core.database import StringListField
class File(Observable):
value = StringField(verbose_name="Value")
mime_type = StringField(verbose_name="MIME type")
hashes = DictField(verbose_name="Hashes")
body = ReferenceField("AttachedFile")
filenames = ListField(StringField(), verbose_name="Filenames")
DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")]
exclude_fields = Observable.exclude_fields + ['hashes', 'body']
@classmethod
def get_form(klass):
form = model_form(klass, exclude=klass.exclude_fields)
form.filenames = StringListField("Filenames")
return form
@staticmethod
def check_type(txt):
return True
def info(self):
i = Observable.info(self)
i['mime_type'] = self.mime_type
i['hashes'] = self.hashes
return i
|
# ... existing code ...
from flask import url_for
from flask_mongoengine.wtf import model_form
from mongoengine import *
# ... modified code ...
from core.observables import Observable
from core.database import StringListField
...
value = StringField(verbose_name="Value")
mime_type = StringField(verbose_name="MIME type")
...
DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")]
exclude_fields = Observable.exclude_fields + ['hashes', 'body']
@classmethod
def get_form(klass):
form = model_form(klass, exclude=klass.exclude_fields)
form.filenames = StringListField("Filenames")
return form
# ... rest of the code ...
|
874d6f568a1367cbaad077648202f3328cd2eb8f
|
modules/Metadata/entropy.py
|
modules/Metadata/entropy.py
|
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
from collections import Counter
import math
__author__ = "Austin West"
__license__ = "MPL 2.0"
TYPE = "Metadata"
NAME = "entropy"
def check():
return True
def scan(filelist):
'''Calculate entropy of a string'''
results = []
for fname in filelist:
with open(fname, 'rb') as f:
text = f.read()
chars, lns = Counter(text), float(len(text))
result = -sum(count/lns * math.log(count/lns, 2) for count in chars.values())
results.append((fname, result))
metadata = {}
metadata["Name"] = NAME
metadata["Type"] = TYPE
metadata["Include"] = False
return (results, metadata)
|
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
from collections import Counter
import math
__author__ = "Austin West"
__license__ = "MPL 2.0"
TYPE = "Metadata"
NAME = "entropy"
def check(conf=DEFAULTCONF):
return True
def scan(filelist):
'''Calculate entropy of a string'''
results = []
for fname in filelist:
with open(fname, 'rb') as f:
text = f.read()
chars, lns = Counter(text), float(len(text))
result = -sum(count/lns * math.log(count/lns, 2) for count in chars.values())
results.append((fname, result))
metadata = {}
metadata["Name"] = NAME
metadata["Type"] = TYPE
metadata["Include"] = False
return (results, metadata)
|
Add conf arg to check function
|
Add conf arg to check function
|
Python
|
mpl-2.0
|
jmlong1027/multiscanner,awest1339/multiscanner,awest1339/multiscanner,awest1339/multiscanner,MITRECND/multiscanner,MITRECND/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,mitre/multiscanner,mitre/multiscanner,mitre/multiscanner
|
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
from collections import Counter
import math
__author__ = "Austin West"
__license__ = "MPL 2.0"
TYPE = "Metadata"
NAME = "entropy"
- def check():
+ def check(conf=DEFAULTCONF):
return True
def scan(filelist):
'''Calculate entropy of a string'''
results = []
for fname in filelist:
with open(fname, 'rb') as f:
text = f.read()
chars, lns = Counter(text), float(len(text))
result = -sum(count/lns * math.log(count/lns, 2) for count in chars.values())
results.append((fname, result))
metadata = {}
metadata["Name"] = NAME
metadata["Type"] = TYPE
metadata["Include"] = False
return (results, metadata)
|
Add conf arg to check function
|
## Code Before:
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
from collections import Counter
import math
__author__ = "Austin West"
__license__ = "MPL 2.0"
TYPE = "Metadata"
NAME = "entropy"
def check():
return True
def scan(filelist):
'''Calculate entropy of a string'''
results = []
for fname in filelist:
with open(fname, 'rb') as f:
text = f.read()
chars, lns = Counter(text), float(len(text))
result = -sum(count/lns * math.log(count/lns, 2) for count in chars.values())
results.append((fname, result))
metadata = {}
metadata["Name"] = NAME
metadata["Type"] = TYPE
metadata["Include"] = False
return (results, metadata)
## Instruction:
Add conf arg to check function
## Code After:
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
from collections import Counter
import math
__author__ = "Austin West"
__license__ = "MPL 2.0"
TYPE = "Metadata"
NAME = "entropy"
def check(conf=DEFAULTCONF):
return True
def scan(filelist):
'''Calculate entropy of a string'''
results = []
for fname in filelist:
with open(fname, 'rb') as f:
text = f.read()
chars, lns = Counter(text), float(len(text))
result = -sum(count/lns * math.log(count/lns, 2) for count in chars.values())
results.append((fname, result))
metadata = {}
metadata["Name"] = NAME
metadata["Type"] = TYPE
metadata["Include"] = False
return (results, metadata)
|
...
def check(conf=DEFAULTCONF):
return True
...
|
c3ca44b17b9e14e8570083ab49be4da8e64757bc
|
scripts/filter_fasta_on_length.py
|
scripts/filter_fasta_on_length.py
|
import argparse
import sys
from Bio import SeqIO
def main(args):
seqs = []
for i, seq in enumerate(SeqIO.parse(sys.stdin, "fasta")):
if len(seq) >= args.length_threshold:
seqs.append(seq)
if i % 1000 == 0 and len(seqs):
SeqIO.write(seqs, sys.stdout, 'fasta')
seqs = []
if len(seqs):
SeqIO.write(seqs, sys.stdout, 'fasta')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("-l", "--length_threshold", type=int, help="Length trheshold to filter on.")
args = parser.parse_args()
main(args)
|
import argparse
import sys
from Bio import SeqIO
def main(args):
seqs = []
if args.input_fasta is not None:
input_handle = open(args.input_fasta, 'r')
else:
input_handle = sys.stdin
for i, seq in enumerate(SeqIO.parse(input_handle, "fasta")):
if len(seq) >= args.length_threshold:
seqs.append(seq)
if i % 1000 == 0 and len(seqs):
SeqIO.write(seqs, sys.stdout, 'fasta')
seqs = []
if len(seqs):
SeqIO.write(seqs, sys.stdout, 'fasta')
input_handle.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input_fasta", help="Input file")
parser.add_argument("-l", "--length_threshold", type=int, help="Length threshold to filter on.")
args = parser.parse_args()
main(args)
|
Use either file input or stdin for filtering length
|
Use either file input or stdin for filtering length
|
Python
|
mit
|
EnvGen/toolbox,EnvGen/toolbox
|
import argparse
import sys
from Bio import SeqIO
def main(args):
seqs = []
+ if args.input_fasta is not None:
+ input_handle = open(args.input_fasta, 'r')
+ else:
+ input_handle = sys.stdin
+
- for i, seq in enumerate(SeqIO.parse(sys.stdin, "fasta")):
+ for i, seq in enumerate(SeqIO.parse(input_handle, "fasta")):
if len(seq) >= args.length_threshold:
seqs.append(seq)
if i % 1000 == 0 and len(seqs):
SeqIO.write(seqs, sys.stdout, 'fasta')
seqs = []
if len(seqs):
SeqIO.write(seqs, sys.stdout, 'fasta')
+ input_handle.close()
+
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--input_fasta", help="Input file")
- parser.add_argument("-l", "--length_threshold", type=int, help="Length trheshold to filter on.")
+ parser.add_argument("-l", "--length_threshold", type=int, help="Length threshold to filter on.")
args = parser.parse_args()
main(args)
|
Use either file input or stdin for filtering length
|
## Code Before:
import argparse
import sys
from Bio import SeqIO
def main(args):
seqs = []
for i, seq in enumerate(SeqIO.parse(sys.stdin, "fasta")):
if len(seq) >= args.length_threshold:
seqs.append(seq)
if i % 1000 == 0 and len(seqs):
SeqIO.write(seqs, sys.stdout, 'fasta')
seqs = []
if len(seqs):
SeqIO.write(seqs, sys.stdout, 'fasta')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("-l", "--length_threshold", type=int, help="Length trheshold to filter on.")
args = parser.parse_args()
main(args)
## Instruction:
Use either file input or stdin for filtering length
## Code After:
import argparse
import sys
from Bio import SeqIO
def main(args):
seqs = []
if args.input_fasta is not None:
input_handle = open(args.input_fasta, 'r')
else:
input_handle = sys.stdin
for i, seq in enumerate(SeqIO.parse(input_handle, "fasta")):
if len(seq) >= args.length_threshold:
seqs.append(seq)
if i % 1000 == 0 and len(seqs):
SeqIO.write(seqs, sys.stdout, 'fasta')
seqs = []
if len(seqs):
SeqIO.write(seqs, sys.stdout, 'fasta')
input_handle.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input_fasta", help="Input file")
parser.add_argument("-l", "--length_threshold", type=int, help="Length threshold to filter on.")
args = parser.parse_args()
main(args)
|
# ... existing code ...
seqs = []
if args.input_fasta is not None:
input_handle = open(args.input_fasta, 'r')
else:
input_handle = sys.stdin
for i, seq in enumerate(SeqIO.parse(input_handle, "fasta")):
if len(seq) >= args.length_threshold:
# ... modified code ...
input_handle.close()
if __name__ == "__main__":
...
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input_fasta", help="Input file")
parser.add_argument("-l", "--length_threshold", type=int, help="Length threshold to filter on.")
# ... rest of the code ...
|
daafe2152e13d32e7e03533151feeeac9464dddf
|
mycli/packages/expanded.py
|
mycli/packages/expanded.py
|
from .tabulate import _text_type
def pad(field, total, char=u" "):
return field + (char * (total - len(field)))
def get_separator(num, header_len, data_len):
total_len = header_len + data_len + 1
sep = u"-[ RECORD {0} ]".format(num)
if len(sep) < header_len:
sep = pad(sep, header_len - 1, u"-") + u"+"
if len(sep) < total_len:
sep = pad(sep, total_len, u"-")
return sep + u"\n"
def expanded_table(rows, headers):
header_len = max([len(x) for x in headers])
max_row_len = 0
results = []
padded_headers = [pad(x, header_len) + u" |" for x in headers]
header_len += 2
for row in rows:
row_len = max([len(_text_type(x)) for x in row])
row_result = []
if row_len > max_row_len:
max_row_len = row_len
for header, value in zip(padded_headers, row):
row_result.append(u"%s %s" % (header, value))
results.append('\n'.join(row_result))
output = []
for i, result in enumerate(results):
output.append(get_separator(i, header_len, max_row_len))
output.append(result)
output.append('\n')
return ''.join(output)
|
from .tabulate import _text_type
def pad(field, total, char=u" "):
return field + (char * (total - len(field)))
def get_separator(num, header_len, data_len):
sep = u"***************************[ %d. row ]***************************\n" % (num + 1)
return sep
def expanded_table(rows, headers):
header_len = max([len(x) for x in headers])
max_row_len = 0
results = []
padded_headers = [pad(x, header_len) + u" |" for x in headers]
header_len += 2
for row in rows:
row_len = max([len(_text_type(x)) for x in row])
row_result = []
if row_len > max_row_len:
max_row_len = row_len
for header, value in zip(padded_headers, row):
row_result.append(u"%s %s" % (header, value))
results.append('\n'.join(row_result))
output = []
for i, result in enumerate(results):
output.append(get_separator(i, header_len, max_row_len))
output.append(result)
output.append('\n')
return ''.join(output)
|
Fix formatting issue for \G.
|
Fix formatting issue for \G.
Closes #49
|
Python
|
bsd-3-clause
|
ksmaheshkumar/mycli,douglasvegas/mycli,webwlsong/mycli,thanatoskira/mycli,tkuipers/mycli,qbdsoft/mycli,douglasvegas/mycli,chenpingzhao/mycli,D-e-e-m-o/mycli,oguzy/mycli,tkuipers/mycli,j-bennet/mycli,suzukaze/mycli,D-e-e-m-o/mycli,thanatoskira/mycli,suzukaze/mycli,mdsrosa/mycli,brewneaux/mycli,danieljwest/mycli,shaunstanislaus/mycli,chenpingzhao/mycli,oguzy/mycli,mattn/mycli,MnO2/rediscli,mdsrosa/mycli,ZuoGuocai/mycli,evook/mycli,evook/mycli,mattn/mycli,ksmaheshkumar/mycli,fw1121/mycli,steverobbins/mycli,MnO2/rediscli,adamchainz/mycli,jinstrive/mycli,nkhuyu/mycli,shoma/mycli,qbdsoft/mycli,martijnengler/mycli,shoma/mycli,webwlsong/mycli,fw1121/mycli,j-bennet/mycli,brewneaux/mycli,ZuoGuocai/mycli,martijnengler/mycli,danieljwest/mycli,nkhuyu/mycli,jinstrive/mycli,shaunstanislaus/mycli,adamchainz/mycli
|
from .tabulate import _text_type
def pad(field, total, char=u" "):
return field + (char * (total - len(field)))
def get_separator(num, header_len, data_len):
- total_len = header_len + data_len + 1
+ sep = u"***************************[ %d. row ]***************************\n" % (num + 1)
- sep = u"-[ RECORD {0} ]".format(num)
- if len(sep) < header_len:
- sep = pad(sep, header_len - 1, u"-") + u"+"
-
- if len(sep) < total_len:
- sep = pad(sep, total_len, u"-")
-
- return sep + u"\n"
+ return sep
def expanded_table(rows, headers):
header_len = max([len(x) for x in headers])
max_row_len = 0
results = []
padded_headers = [pad(x, header_len) + u" |" for x in headers]
header_len += 2
for row in rows:
row_len = max([len(_text_type(x)) for x in row])
row_result = []
if row_len > max_row_len:
max_row_len = row_len
for header, value in zip(padded_headers, row):
row_result.append(u"%s %s" % (header, value))
results.append('\n'.join(row_result))
output = []
for i, result in enumerate(results):
output.append(get_separator(i, header_len, max_row_len))
output.append(result)
output.append('\n')
return ''.join(output)
|
Fix formatting issue for \G.
|
## Code Before:
from .tabulate import _text_type
def pad(field, total, char=u" "):
return field + (char * (total - len(field)))
def get_separator(num, header_len, data_len):
total_len = header_len + data_len + 1
sep = u"-[ RECORD {0} ]".format(num)
if len(sep) < header_len:
sep = pad(sep, header_len - 1, u"-") + u"+"
if len(sep) < total_len:
sep = pad(sep, total_len, u"-")
return sep + u"\n"
def expanded_table(rows, headers):
header_len = max([len(x) for x in headers])
max_row_len = 0
results = []
padded_headers = [pad(x, header_len) + u" |" for x in headers]
header_len += 2
for row in rows:
row_len = max([len(_text_type(x)) for x in row])
row_result = []
if row_len > max_row_len:
max_row_len = row_len
for header, value in zip(padded_headers, row):
row_result.append(u"%s %s" % (header, value))
results.append('\n'.join(row_result))
output = []
for i, result in enumerate(results):
output.append(get_separator(i, header_len, max_row_len))
output.append(result)
output.append('\n')
return ''.join(output)
## Instruction:
Fix formatting issue for \G.
## Code After:
from .tabulate import _text_type
def pad(field, total, char=u" "):
return field + (char * (total - len(field)))
def get_separator(num, header_len, data_len):
sep = u"***************************[ %d. row ]***************************\n" % (num + 1)
return sep
def expanded_table(rows, headers):
header_len = max([len(x) for x in headers])
max_row_len = 0
results = []
padded_headers = [pad(x, header_len) + u" |" for x in headers]
header_len += 2
for row in rows:
row_len = max([len(_text_type(x)) for x in row])
row_result = []
if row_len > max_row_len:
max_row_len = row_len
for header, value in zip(padded_headers, row):
row_result.append(u"%s %s" % (header, value))
results.append('\n'.join(row_result))
output = []
for i, result in enumerate(results):
output.append(get_separator(i, header_len, max_row_len))
output.append(result)
output.append('\n')
return ''.join(output)
|
# ... existing code ...
def get_separator(num, header_len, data_len):
sep = u"***************************[ %d. row ]***************************\n" % (num + 1)
return sep
# ... rest of the code ...
|
faf861e53c1d4f554da82cd66b6b8de4fa7a2ab7
|
src/main/python/infra_buddy/notifier/datadog.py
|
src/main/python/infra_buddy/notifier/datadog.py
|
from infra_buddy.context.deploy_ctx import DeployContext
import datadog as dd
class DataDogNotifier(object):
def __init__(self, key, deploy_context):
# type: (DeployContext) -> None
super(DataDogNotifier, self).__init__()
self.deploy_context = deploy_context
dd.initialize(api_key=key)
def notify_event(self, title, type, message):
dd.api.Event.create(title=title,
text=message,
alert_type=type,
tags=self._get_tags())
def _get_tags(self):
return ['application:{app},role:{role},environment:{env}'.format(
app=self.deploy_context.application,
role=self.deploy_context.role,
env=self.deploy_context.environment)]
|
import datadog as dd
class DataDogNotifier(object):
def __init__(self, key, deploy_context):
# type: (DeployContext) -> None
super(DataDogNotifier, self).__init__()
self.deploy_context = deploy_context
dd.initialize(api_key=key)
def notify_event(self, title, type, message):
dd.api.Event.create(title=title,
text=message,
alert_type=type,
tags=self._get_tags())
def _get_tags(self):
return ['application:{app},role:{role},environment:{env}'.format(
app=self.deploy_context.application,
role=self.deploy_context.role,
env=self.deploy_context.environment)]
|
Remove import for type annotation
|
Remove import for type annotation
|
Python
|
apache-2.0
|
AlienVault-Engineering/infra-buddy
|
- from infra_buddy.context.deploy_ctx import DeployContext
import datadog as dd
class DataDogNotifier(object):
def __init__(self, key, deploy_context):
# type: (DeployContext) -> None
super(DataDogNotifier, self).__init__()
self.deploy_context = deploy_context
dd.initialize(api_key=key)
def notify_event(self, title, type, message):
dd.api.Event.create(title=title,
text=message,
alert_type=type,
tags=self._get_tags())
def _get_tags(self):
return ['application:{app},role:{role},environment:{env}'.format(
app=self.deploy_context.application,
role=self.deploy_context.role,
env=self.deploy_context.environment)]
|
Remove import for type annotation
|
## Code Before:
from infra_buddy.context.deploy_ctx import DeployContext
import datadog as dd
class DataDogNotifier(object):
def __init__(self, key, deploy_context):
# type: (DeployContext) -> None
super(DataDogNotifier, self).__init__()
self.deploy_context = deploy_context
dd.initialize(api_key=key)
def notify_event(self, title, type, message):
dd.api.Event.create(title=title,
text=message,
alert_type=type,
tags=self._get_tags())
def _get_tags(self):
return ['application:{app},role:{role},environment:{env}'.format(
app=self.deploy_context.application,
role=self.deploy_context.role,
env=self.deploy_context.environment)]
## Instruction:
Remove import for type annotation
## Code After:
import datadog as dd
class DataDogNotifier(object):
def __init__(self, key, deploy_context):
# type: (DeployContext) -> None
super(DataDogNotifier, self).__init__()
self.deploy_context = deploy_context
dd.initialize(api_key=key)
def notify_event(self, title, type, message):
dd.api.Event.create(title=title,
text=message,
alert_type=type,
tags=self._get_tags())
def _get_tags(self):
return ['application:{app},role:{role},environment:{env}'.format(
app=self.deploy_context.application,
role=self.deploy_context.role,
env=self.deploy_context.environment)]
|
# ... existing code ...
import datadog as dd
# ... rest of the code ...
|
5d70735ab4254509e1efed73be4eecf77629063e
|
github_hook_server.py
|
github_hook_server.py
|
""" Our github hook receiving server. """
import os
from flask import Flask
from flask_hookserver import Hooks
from github import validate_review_request
from slack import notify_reviewer
app = Flask(__name__)
app.config['GITHUB_WEBHOOKS_KEY'] = os.environ.get('GITHUB_WEBHOOKS_KEY')
app.config['VALIDATE_IP'] = os.environ.get('GIT_HOOK_VALIDATE_IP', True)
app.config['VALIDATE_SIGNATURE'] = os.environ.get('GIT_HOOK_VALIDATE_SIGNATURE', True)
hooks = Hooks(app, url='/hooks')
@hooks.hook('ping')
def ping(data, guid):
return 'pong'
@hooks.hook('pull_request')
def pull_request(data, guid):
if validate_review_request(data):
notify_reviewer(data)
result = 'Reviewer Notified'
else:
result = 'Action ({}) ignored'.format(data.get('action'))
return result
app.run(host='0.0.0.0')
|
""" Our github hook receiving server. """
import os
from flask import Flask
from flask_hookserver import Hooks
from github import validate_review_request
from slack import notify_reviewer
app = Flask(__name__)
app.config['GITHUB_WEBHOOKS_KEY'] = os.environ.get('GITHUB_WEBHOOKS_KEY')
if os.environ.get('GIT_HOOK_VALIDATE_IP', 'True').lower() in ['false', '0']:
app.config['VALIDATE_IP'] = False
if os.environ.get('GIT_HOOK_VALIDATE_SIGNATURE', 'True').lower() in ['false', '0']:
app.config['VALIDATE_SIGNATURE'] = False
hooks = Hooks(app, url='/hooks')
@hooks.hook('ping')
def ping(data, guid):
return 'pong'
@hooks.hook('pull_request')
def pull_request(data, guid):
if validate_review_request(data):
notify_reviewer(data)
result = 'Reviewer Notified'
else:
result = 'Action ({}) ignored'.format(data.get('action'))
return result
app.run(host='0.0.0.0')
|
Fix env vars always evaluating as true
|
Fix env vars always evaluating as true
Env vars come through as strings. Which are true. The default on our
values is also true. Meaning it would never change. So we have to do
special string checking to get it to actually change. Yay.
|
Python
|
mit
|
DobaTech/github-review-slack-notifier
|
""" Our github hook receiving server. """
import os
from flask import Flask
from flask_hookserver import Hooks
from github import validate_review_request
from slack import notify_reviewer
app = Flask(__name__)
app.config['GITHUB_WEBHOOKS_KEY'] = os.environ.get('GITHUB_WEBHOOKS_KEY')
- app.config['VALIDATE_IP'] = os.environ.get('GIT_HOOK_VALIDATE_IP', True)
- app.config['VALIDATE_SIGNATURE'] = os.environ.get('GIT_HOOK_VALIDATE_SIGNATURE', True)
+ if os.environ.get('GIT_HOOK_VALIDATE_IP', 'True').lower() in ['false', '0']:
+ app.config['VALIDATE_IP'] = False
+ if os.environ.get('GIT_HOOK_VALIDATE_SIGNATURE', 'True').lower() in ['false', '0']:
+ app.config['VALIDATE_SIGNATURE'] = False
hooks = Hooks(app, url='/hooks')
@hooks.hook('ping')
def ping(data, guid):
return 'pong'
@hooks.hook('pull_request')
def pull_request(data, guid):
if validate_review_request(data):
notify_reviewer(data)
result = 'Reviewer Notified'
else:
result = 'Action ({}) ignored'.format(data.get('action'))
return result
app.run(host='0.0.0.0')
|
Fix env vars always evaluating as true
|
## Code Before:
""" Our github hook receiving server. """
import os
from flask import Flask
from flask_hookserver import Hooks
from github import validate_review_request
from slack import notify_reviewer
app = Flask(__name__)
app.config['GITHUB_WEBHOOKS_KEY'] = os.environ.get('GITHUB_WEBHOOKS_KEY')
app.config['VALIDATE_IP'] = os.environ.get('GIT_HOOK_VALIDATE_IP', True)
app.config['VALIDATE_SIGNATURE'] = os.environ.get('GIT_HOOK_VALIDATE_SIGNATURE', True)
hooks = Hooks(app, url='/hooks')
@hooks.hook('ping')
def ping(data, guid):
return 'pong'
@hooks.hook('pull_request')
def pull_request(data, guid):
if validate_review_request(data):
notify_reviewer(data)
result = 'Reviewer Notified'
else:
result = 'Action ({}) ignored'.format(data.get('action'))
return result
app.run(host='0.0.0.0')
## Instruction:
Fix env vars always evaluating as true
## Code After:
""" Our github hook receiving server. """
import os
from flask import Flask
from flask_hookserver import Hooks
from github import validate_review_request
from slack import notify_reviewer
app = Flask(__name__)
app.config['GITHUB_WEBHOOKS_KEY'] = os.environ.get('GITHUB_WEBHOOKS_KEY')
if os.environ.get('GIT_HOOK_VALIDATE_IP', 'True').lower() in ['false', '0']:
app.config['VALIDATE_IP'] = False
if os.environ.get('GIT_HOOK_VALIDATE_SIGNATURE', 'True').lower() in ['false', '0']:
app.config['VALIDATE_SIGNATURE'] = False
hooks = Hooks(app, url='/hooks')
@hooks.hook('ping')
def ping(data, guid):
return 'pong'
@hooks.hook('pull_request')
def pull_request(data, guid):
if validate_review_request(data):
notify_reviewer(data)
result = 'Reviewer Notified'
else:
result = 'Action ({}) ignored'.format(data.get('action'))
return result
app.run(host='0.0.0.0')
|
...
app.config['GITHUB_WEBHOOKS_KEY'] = os.environ.get('GITHUB_WEBHOOKS_KEY')
if os.environ.get('GIT_HOOK_VALIDATE_IP', 'True').lower() in ['false', '0']:
app.config['VALIDATE_IP'] = False
if os.environ.get('GIT_HOOK_VALIDATE_SIGNATURE', 'True').lower() in ['false', '0']:
app.config['VALIDATE_SIGNATURE'] = False
...
|
f256fc04361dc1a0e57c2a17d2216eadee03f987
|
test_pytnt.py
|
test_pytnt.py
|
import unittest
from numpy.testing import assert_allclose
from processTNT import TNTfile
class TestLoadFile(unittest.TestCase):
"""Tests that pytnt can load files"""
def test_load_time_domain(self):
ref1 = TNTfile("testdata/LiCl_ref1.tnt")
def test_load_freq_domain(self):
ref1 = TNTfile("testdata/LiCl_ref1-ftp.tnt")
def test_load_fails(self):
with self.assertRaises(AssertionError):
zero = TNTfile("/dev/zero")
class TestFourierTransform(unittest.TestCase):
"""Test that the Fourier Transform is done correctly
Makes sure that the reference frequency is taken into account properly
"""
def test_ref1(self):
time_domain = TNTfile("testdata/LiCl_ref1.tnt")
freq_domain = TNTfile("testdata/LiCl_ref1-ftp.tnt")
lb = freq_domain.TMG2['linebrd'][0, 0]
my_ft = time_domain.LBfft(lb, 1)
assert_allclose(freq_domain.DATA, my_ft)
if __name__ == '__main__':
unittest.main()
|
import unittest
import numpy as np
from numpy.testing import assert_allclose
from processTNT import TNTfile
class TestLoadFile(unittest.TestCase):
"""Tests that pytnt can load files"""
def test_load_time_domain(self):
ref1 = TNTfile("testdata/LiCl_ref1.tnt")
def test_load_freq_domain(self):
ref1 = TNTfile("testdata/LiCl_ref1-ftp.tnt")
def test_load_fails(self):
with self.assertRaises(AssertionError):
zero = TNTfile("/dev/zero")
class TestFourierTransform(unittest.TestCase):
"""Test that the Fourier Transform is done correctly
Makes sure that the reference frequency is taken into account properly
"""
def test_ref1(self):
time_domain = TNTfile("testdata/LiCl_ref1.tnt")
freq_domain = TNTfile("testdata/LiCl_ref1-ftp.tnt")
lb = freq_domain.TMG2['linebrd'][0, 0]
ph0 = freq_domain.TMG2['cumm_0_phase'][0, 0]
my_ft = time_domain.LBfft(lb, 1, phase=np.deg2rad(ph0))
assert_allclose(freq_domain.DATA, my_ft)
if __name__ == '__main__':
unittest.main()
|
Use the phase from the pre-FT'd file for the test FT
|
Use the phase from the pre-FT'd file for the test FT
|
Python
|
bsd-3-clause
|
chatcannon/pytnt,chatcannon/pytnt
|
import unittest
+ import numpy as np
from numpy.testing import assert_allclose
from processTNT import TNTfile
class TestLoadFile(unittest.TestCase):
"""Tests that pytnt can load files"""
def test_load_time_domain(self):
ref1 = TNTfile("testdata/LiCl_ref1.tnt")
def test_load_freq_domain(self):
ref1 = TNTfile("testdata/LiCl_ref1-ftp.tnt")
def test_load_fails(self):
with self.assertRaises(AssertionError):
zero = TNTfile("/dev/zero")
class TestFourierTransform(unittest.TestCase):
"""Test that the Fourier Transform is done correctly
Makes sure that the reference frequency is taken into account properly
"""
def test_ref1(self):
time_domain = TNTfile("testdata/LiCl_ref1.tnt")
freq_domain = TNTfile("testdata/LiCl_ref1-ftp.tnt")
lb = freq_domain.TMG2['linebrd'][0, 0]
+ ph0 = freq_domain.TMG2['cumm_0_phase'][0, 0]
- my_ft = time_domain.LBfft(lb, 1)
+ my_ft = time_domain.LBfft(lb, 1, phase=np.deg2rad(ph0))
assert_allclose(freq_domain.DATA, my_ft)
if __name__ == '__main__':
unittest.main()
|
Use the phase from the pre-FT'd file for the test FT
|
## Code Before:
import unittest
from numpy.testing import assert_allclose
from processTNT import TNTfile
class TestLoadFile(unittest.TestCase):
"""Tests that pytnt can load files"""
def test_load_time_domain(self):
ref1 = TNTfile("testdata/LiCl_ref1.tnt")
def test_load_freq_domain(self):
ref1 = TNTfile("testdata/LiCl_ref1-ftp.tnt")
def test_load_fails(self):
with self.assertRaises(AssertionError):
zero = TNTfile("/dev/zero")
class TestFourierTransform(unittest.TestCase):
"""Test that the Fourier Transform is done correctly
Makes sure that the reference frequency is taken into account properly
"""
def test_ref1(self):
time_domain = TNTfile("testdata/LiCl_ref1.tnt")
freq_domain = TNTfile("testdata/LiCl_ref1-ftp.tnt")
lb = freq_domain.TMG2['linebrd'][0, 0]
my_ft = time_domain.LBfft(lb, 1)
assert_allclose(freq_domain.DATA, my_ft)
if __name__ == '__main__':
unittest.main()
## Instruction:
Use the phase from the pre-FT'd file for the test FT
## Code After:
import unittest
import numpy as np
from numpy.testing import assert_allclose
from processTNT import TNTfile
class TestLoadFile(unittest.TestCase):
"""Tests that pytnt can load files"""
def test_load_time_domain(self):
ref1 = TNTfile("testdata/LiCl_ref1.tnt")
def test_load_freq_domain(self):
ref1 = TNTfile("testdata/LiCl_ref1-ftp.tnt")
def test_load_fails(self):
with self.assertRaises(AssertionError):
zero = TNTfile("/dev/zero")
class TestFourierTransform(unittest.TestCase):
"""Test that the Fourier Transform is done correctly
Makes sure that the reference frequency is taken into account properly
"""
def test_ref1(self):
time_domain = TNTfile("testdata/LiCl_ref1.tnt")
freq_domain = TNTfile("testdata/LiCl_ref1-ftp.tnt")
lb = freq_domain.TMG2['linebrd'][0, 0]
ph0 = freq_domain.TMG2['cumm_0_phase'][0, 0]
my_ft = time_domain.LBfft(lb, 1, phase=np.deg2rad(ph0))
assert_allclose(freq_domain.DATA, my_ft)
if __name__ == '__main__':
unittest.main()
|
// ... existing code ...
import numpy as np
from numpy.testing import assert_allclose
// ... modified code ...
lb = freq_domain.TMG2['linebrd'][0, 0]
ph0 = freq_domain.TMG2['cumm_0_phase'][0, 0]
my_ft = time_domain.LBfft(lb, 1, phase=np.deg2rad(ph0))
// ... rest of the code ...
|
cc6c40b64f8dfde533977883124e22e0fbc80e5c
|
soco/__init__.py
|
soco/__init__.py
|
from __future__ import unicode_literals
""" SoCo (Sonos Controller) is a simple library to control Sonos speakers """
# Will be parsed by setup.py to determine package metadata
__author__ = 'Rahim Sonawalla <[email protected]>'
__version__ = '0.7'
__website__ = 'https://github.com/SoCo/SoCo'
__license__ = 'MIT License'
from .core import discover, SoCo, SonosDiscovery
from .exceptions import SoCoException, UnknownSoCoException
__all__ = ['discover', 'SonosDiscovery', 'SoCo', 'SoCoException', 'UnknownSoCoException']
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
from __future__ import unicode_literals
""" SoCo (Sonos Controller) is a simple library to control Sonos speakers """
# Will be parsed by setup.py to determine package metadata
__author__ = 'The SoCo-Team <[email protected]>'
__version__ = '0.7'
__website__ = 'https://github.com/SoCo/SoCo'
__license__ = 'MIT License'
from .core import discover, SoCo, SonosDiscovery
from .exceptions import SoCoException, UnknownSoCoException
__all__ = ['discover', 'SonosDiscovery', 'SoCo', 'SoCoException', 'UnknownSoCoException']
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
Update author info to "The SoCo-Team"
|
Update author info to "The SoCo-Team"
|
Python
|
mit
|
TrondKjeldas/SoCo,flavio/SoCo,dundeemt/SoCo,xxdede/SoCo,KennethNielsen/SoCo,petteraas/SoCo,bwhaley/SoCo,xxdede/SoCo,oyvindmal/SocoWebService,TrondKjeldas/SoCo,TrondKjeldas/SoCo,petteraas/SoCo,dajobe/SoCo,intfrr/SoCo,intfrr/SoCo,xxdede/SoCo,fgend31/SoCo,jlmcgehee21/SoCo,DPH/SoCo,dsully/SoCo,meska/SoCo,bwhaley/SoCo,dajobe/SoCo,SoCo/SoCo,flavio/SoCo,lawrenceakka/SoCo,SoCo/SoCo,lawrenceakka/SoCo,KennethNielsen/SoCo,bwhaley/SoCo,fxstein/SoCo,petteraas/SoCo,fgend31/SoCo,jlmcgehee21/SoCo,fxstein/SoCo,simonalpha/SoCo,DPH/SoCo,oyvindmal/SocoWebService,simonalpha/SoCo,meska/SoCo,dundeemt/SoCo,dsully/SoCo
|
from __future__ import unicode_literals
""" SoCo (Sonos Controller) is a simple library to control Sonos speakers """
# Will be parsed by setup.py to determine package metadata
- __author__ = 'Rahim Sonawalla <[email protected]>'
+ __author__ = 'The SoCo-Team <[email protected]>'
__version__ = '0.7'
__website__ = 'https://github.com/SoCo/SoCo'
__license__ = 'MIT License'
from .core import discover, SoCo, SonosDiscovery
from .exceptions import SoCoException, UnknownSoCoException
__all__ = ['discover', 'SonosDiscovery', 'SoCo', 'SoCoException', 'UnknownSoCoException']
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
Update author info to "The SoCo-Team"
|
## Code Before:
from __future__ import unicode_literals
""" SoCo (Sonos Controller) is a simple library to control Sonos speakers """
# Will be parsed by setup.py to determine package metadata
__author__ = 'Rahim Sonawalla <[email protected]>'
__version__ = '0.7'
__website__ = 'https://github.com/SoCo/SoCo'
__license__ = 'MIT License'
from .core import discover, SoCo, SonosDiscovery
from .exceptions import SoCoException, UnknownSoCoException
__all__ = ['discover', 'SonosDiscovery', 'SoCo', 'SoCoException', 'UnknownSoCoException']
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
## Instruction:
Update author info to "The SoCo-Team"
## Code After:
from __future__ import unicode_literals
""" SoCo (Sonos Controller) is a simple library to control Sonos speakers """
# Will be parsed by setup.py to determine package metadata
__author__ = 'The SoCo-Team <[email protected]>'
__version__ = '0.7'
__website__ = 'https://github.com/SoCo/SoCo'
__license__ = 'MIT License'
from .core import discover, SoCo, SonosDiscovery
from .exceptions import SoCoException, UnknownSoCoException
__all__ = ['discover', 'SonosDiscovery', 'SoCo', 'SoCoException', 'UnknownSoCoException']
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
# ... existing code ...
# Will be parsed by setup.py to determine package metadata
__author__ = 'The SoCo-Team <[email protected]>'
__version__ = '0.7'
# ... rest of the code ...
|
586418860c0441eaebadd0fe79989d6d9f90fa28
|
src/bda/plone/productshop/vocabularies.py
|
src/bda/plone/productshop/vocabularies.py
|
from zope.interface import directlyProvides
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import (
SimpleVocabulary,
SimpleTerm,
)
from zope.i18nmessageid import MessageFactory
from .utils import (
dotted_name,
available_variant_aspects,
)
#added by espen
from zope.component import getUtility
from plone.dexterity.interfaces import IDexterityFTI
from zope.component import ComponentLookupError
_ = MessageFactory('bda.plone.productshop')
def AvailableVariantAspectsVocabulary(context):
terms = list()
for definition in available_variant_aspects():
terms.append(SimpleTerm(value=dotted_name(definition.interface),
title=definition.title))
return SimpleVocabulary(terms)
directlyProvides(AvailableVariantAspectsVocabulary, IVocabularyFactory)
def RtfFieldsVocabulary(context):
try:
type = getUtility(IDexterityFTI, name='bda.plone.productshop.product')
fields = type.lookupSchema()
terms = [ SimpleTerm(value=pair, token=pair, title=pair) for pair in fields]
return SimpleVocabulary(terms)
except KeyError:
pass
finally:
pass
directlyProvides(RtfFieldsVocabulary, IVocabularyFactory)
|
from zope.interface import directlyProvides
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import (
SimpleVocabulary,
SimpleTerm,
)
from zope.i18nmessageid import MessageFactory
from .utils import (
dotted_name,
available_variant_aspects,
)
#added by espen
from zope.component import getUtility
from plone.dexterity.interfaces import IDexterityFTI
_ = MessageFactory('bda.plone.productshop')
def AvailableVariantAspectsVocabulary(context):
terms = list()
for definition in available_variant_aspects():
terms.append(SimpleTerm(value=dotted_name(definition.interface),
title=definition.title))
return SimpleVocabulary(terms)
directlyProvides(AvailableVariantAspectsVocabulary, IVocabularyFactory)
def RtfFieldsVocabulary(context):
try:
fields = getUtility(IDexterityFTI, name='bda.plone.productshop.product').lookupSchema()
except:
fields = ['Datasheet', ]
terms = [ SimpleTerm(value=pair, token=pair, title=pair) for pair in fields]
return SimpleVocabulary(terms)
directlyProvides(RtfFieldsVocabulary, IVocabularyFactory)
|
Fix for the component lookup error in vocabulary
|
Fix for the component lookup error in vocabulary
|
Python
|
bsd-3-clause
|
espenmn/bda.plone.productshop,espenmn/bda.plone.productshop,espenmn/bda.plone.productshop
|
from zope.interface import directlyProvides
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import (
SimpleVocabulary,
SimpleTerm,
)
from zope.i18nmessageid import MessageFactory
from .utils import (
dotted_name,
available_variant_aspects,
)
#added by espen
from zope.component import getUtility
from plone.dexterity.interfaces import IDexterityFTI
- from zope.component import ComponentLookupError
_ = MessageFactory('bda.plone.productshop')
def AvailableVariantAspectsVocabulary(context):
terms = list()
for definition in available_variant_aspects():
terms.append(SimpleTerm(value=dotted_name(definition.interface),
title=definition.title))
return SimpleVocabulary(terms)
directlyProvides(AvailableVariantAspectsVocabulary, IVocabularyFactory)
def RtfFieldsVocabulary(context):
try:
- type = getUtility(IDexterityFTI, name='bda.plone.productshop.product')
+ fields = getUtility(IDexterityFTI, name='bda.plone.productshop.product').lookupSchema()
- fields = type.lookupSchema()
+ except:
+ fields = ['Datasheet', ]
- terms = [ SimpleTerm(value=pair, token=pair, title=pair) for pair in fields]
+ terms = [ SimpleTerm(value=pair, token=pair, title=pair) for pair in fields]
- return SimpleVocabulary(terms)
+ return SimpleVocabulary(terms)
- except KeyError:
- pass
- finally:
- pass
directlyProvides(RtfFieldsVocabulary, IVocabularyFactory)
|
Fix for the component lookup error in vocabulary
|
## Code Before:
from zope.interface import directlyProvides
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import (
SimpleVocabulary,
SimpleTerm,
)
from zope.i18nmessageid import MessageFactory
from .utils import (
dotted_name,
available_variant_aspects,
)
#added by espen
from zope.component import getUtility
from plone.dexterity.interfaces import IDexterityFTI
from zope.component import ComponentLookupError
_ = MessageFactory('bda.plone.productshop')
def AvailableVariantAspectsVocabulary(context):
terms = list()
for definition in available_variant_aspects():
terms.append(SimpleTerm(value=dotted_name(definition.interface),
title=definition.title))
return SimpleVocabulary(terms)
directlyProvides(AvailableVariantAspectsVocabulary, IVocabularyFactory)
def RtfFieldsVocabulary(context):
try:
type = getUtility(IDexterityFTI, name='bda.plone.productshop.product')
fields = type.lookupSchema()
terms = [ SimpleTerm(value=pair, token=pair, title=pair) for pair in fields]
return SimpleVocabulary(terms)
except KeyError:
pass
finally:
pass
directlyProvides(RtfFieldsVocabulary, IVocabularyFactory)
## Instruction:
Fix for the component lookup error in vocabulary
## Code After:
from zope.interface import directlyProvides
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import (
SimpleVocabulary,
SimpleTerm,
)
from zope.i18nmessageid import MessageFactory
from .utils import (
dotted_name,
available_variant_aspects,
)
#added by espen
from zope.component import getUtility
from plone.dexterity.interfaces import IDexterityFTI
_ = MessageFactory('bda.plone.productshop')
def AvailableVariantAspectsVocabulary(context):
terms = list()
for definition in available_variant_aspects():
terms.append(SimpleTerm(value=dotted_name(definition.interface),
title=definition.title))
return SimpleVocabulary(terms)
directlyProvides(AvailableVariantAspectsVocabulary, IVocabularyFactory)
def RtfFieldsVocabulary(context):
try:
fields = getUtility(IDexterityFTI, name='bda.plone.productshop.product').lookupSchema()
except:
fields = ['Datasheet', ]
terms = [ SimpleTerm(value=pair, token=pair, title=pair) for pair in fields]
return SimpleVocabulary(terms)
directlyProvides(RtfFieldsVocabulary, IVocabularyFactory)
|
# ... existing code ...
from plone.dexterity.interfaces import IDexterityFTI
# ... modified code ...
try:
fields = getUtility(IDexterityFTI, name='bda.plone.productshop.product').lookupSchema()
except:
fields = ['Datasheet', ]
terms = [ SimpleTerm(value=pair, token=pair, title=pair) for pair in fields]
return SimpleVocabulary(terms)
# ... rest of the code ...
|
11022b79ded961bdd2e9a6bff0c4f4a03097084c
|
scripts/install_new_database.py
|
scripts/install_new_database.py
|
import os
import sys
_upper_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
if _upper_dir not in sys.path:
sys.path.append(_upper_dir)
import chdb
if __name__ == '__main__':
chdb.install_scratch_db()
|
import os
import sys
_upper_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
if _upper_dir not in sys.path:
sys.path.append(_upper_dir)
import chdb
def sanity_check():
sdb = chdb.init_scratch_db()
snippet_count = sdb.execute_with_retry_s(
'''SELECT COUNT(*) FROM snippets''')[0]
assert snippet_count > 100
article_count = sdb.execute_with_retry_s(
'''SELECT COUNT(*) FROM articles''')[0]
assert article_count > 100
if __name__ == '__main__':
sanity_check()
chdb.install_scratch_db()
|
Add a couple of sanity checks so we don't break the database.
|
Add a couple of sanity checks so we don't break the database.
Part of #139.
|
Python
|
mit
|
guilherme-pg/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt,guilherme-pg/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt,eggpi/citationhunt,eggpi/citationhunt
|
import os
import sys
_upper_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
if _upper_dir not in sys.path:
sys.path.append(_upper_dir)
import chdb
+ def sanity_check():
+ sdb = chdb.init_scratch_db()
+ snippet_count = sdb.execute_with_retry_s(
+ '''SELECT COUNT(*) FROM snippets''')[0]
+ assert snippet_count > 100
+
+ article_count = sdb.execute_with_retry_s(
+ '''SELECT COUNT(*) FROM articles''')[0]
+ assert article_count > 100
+
if __name__ == '__main__':
+ sanity_check()
chdb.install_scratch_db()
|
Add a couple of sanity checks so we don't break the database.
|
## Code Before:
import os
import sys
_upper_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
if _upper_dir not in sys.path:
sys.path.append(_upper_dir)
import chdb
if __name__ == '__main__':
chdb.install_scratch_db()
## Instruction:
Add a couple of sanity checks so we don't break the database.
## Code After:
import os
import sys
_upper_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
if _upper_dir not in sys.path:
sys.path.append(_upper_dir)
import chdb
def sanity_check():
sdb = chdb.init_scratch_db()
snippet_count = sdb.execute_with_retry_s(
'''SELECT COUNT(*) FROM snippets''')[0]
assert snippet_count > 100
article_count = sdb.execute_with_retry_s(
'''SELECT COUNT(*) FROM articles''')[0]
assert article_count > 100
if __name__ == '__main__':
sanity_check()
chdb.install_scratch_db()
|
...
def sanity_check():
sdb = chdb.init_scratch_db()
snippet_count = sdb.execute_with_retry_s(
'''SELECT COUNT(*) FROM snippets''')[0]
assert snippet_count > 100
article_count = sdb.execute_with_retry_s(
'''SELECT COUNT(*) FROM articles''')[0]
assert article_count > 100
if __name__ == '__main__':
sanity_check()
chdb.install_scratch_db()
...
|
39256f49c952dbd5802d5321c8a74b2c41934e38
|
timedelta/__init__.py
|
timedelta/__init__.py
|
import os
__version__ = open(os.path.join(os.path.dirname(__file__), "VERSION")).read().strip()
try:
from fields import TimedeltaField
from helpers import (
divide, multiply, modulo,
parse, nice_repr,
percentage, decimal_percentage,
total_seconds
)
except ImportError:
pass
|
import os
__version__ = open(os.path.join(os.path.dirname(__file__), "VERSION")).read().strip()
try:
import django
from fields import TimedeltaField
from helpers import (
divide, multiply, modulo,
parse, nice_repr,
percentage, decimal_percentage,
total_seconds
)
except (ImportError, django.core.exceptions.ImproperlyConfigured):
pass
|
Fix running on unconfigured virtualenv.
|
Fix running on unconfigured virtualenv.
|
Python
|
bsd-3-clause
|
sookasa/django-timedelta-field
|
import os
__version__ = open(os.path.join(os.path.dirname(__file__), "VERSION")).read().strip()
try:
+ import django
from fields import TimedeltaField
from helpers import (
divide, multiply, modulo,
parse, nice_repr,
percentage, decimal_percentage,
total_seconds
)
- except ImportError:
+ except (ImportError, django.core.exceptions.ImproperlyConfigured):
pass
|
Fix running on unconfigured virtualenv.
|
## Code Before:
import os
__version__ = open(os.path.join(os.path.dirname(__file__), "VERSION")).read().strip()
try:
from fields import TimedeltaField
from helpers import (
divide, multiply, modulo,
parse, nice_repr,
percentage, decimal_percentage,
total_seconds
)
except ImportError:
pass
## Instruction:
Fix running on unconfigured virtualenv.
## Code After:
import os
__version__ = open(os.path.join(os.path.dirname(__file__), "VERSION")).read().strip()
try:
import django
from fields import TimedeltaField
from helpers import (
divide, multiply, modulo,
parse, nice_repr,
percentage, decimal_percentage,
total_seconds
)
except (ImportError, django.core.exceptions.ImproperlyConfigured):
pass
|
...
try:
import django
from fields import TimedeltaField
...
)
except (ImportError, django.core.exceptions.ImproperlyConfigured):
pass
...
|
bc47862e89f73ec152a57bf43126653a981cd411
|
suggestions/tests.py
|
suggestions/tests.py
|
from django.test import TestCase
from django.contrib.auth.models import User
from mks.models import Member
from .models import Suggestion
class SuggestionsTests(TestCase):
def setUp(self):
self.member = Member.objects.create(name='mk_1')
self.regular_user = User.objects.create_user('reg_user')
def test_simple_text_suggestion(self):
MK_SITE = 'http://mk1.example.com'
suggestion = Suggestion.objects.create_suggestion(
suggested_by=self.regular_user,
content_object=self.member,
suggestion_action=Suggestion.UPDATE,
suggested_field='website',
suggested_text=MK_SITE
)
self.assertIsNone(self.member.website)
suggestion.auto_apply()
mk = Member.objects.get(pk=self.member.pk)
self.assertEqual(mk.website, MK_SITE)
|
from django.test import TestCase
from django.contrib.auth.models import User
from mks.models import Member
from .models import Suggestion
class SuggestionsTests(TestCase):
def setUp(self):
self.member = Member.objects.create(name='mk_1')
self.regular_user = User.objects.create_user('reg_user')
def test_simple_text_suggestion(self):
MK_SITE = 'http://mk1.example.com'
suggestion = Suggestion.objects.create_suggestion(
suggested_by=self.regular_user,
content_object=self.member,
suggestion_action=Suggestion.UPDATE,
suggested_field='website',
suggested_text=MK_SITE
)
self.assertIsNone(self.member.website)
suggestion.auto_apply()
mk = Member.objects.get(pk=self.member.pk)
self.assertEqual(mk.website, MK_SITE)
# cleanup
mk.website = None
mk.save()
self.member = mk
|
Undo member changes in test
|
Undo member changes in test
|
Python
|
bsd-3-clause
|
MeirKriheli/Open-Knesset,jspan/Open-Knesset,navotsil/Open-Knesset,navotsil/Open-Knesset,DanaOshri/Open-Knesset,alonisser/Open-Knesset,jspan/Open-Knesset,noamelf/Open-Knesset,daonb/Open-Knesset,habeanf/Open-Knesset,noamelf/Open-Knesset,DanaOshri/Open-Knesset,OriHoch/Open-Knesset,otadmor/Open-Knesset,alonisser/Open-Knesset,MeirKriheli/Open-Knesset,ofri/Open-Knesset,Shrulik/Open-Knesset,navotsil/Open-Knesset,Shrulik/Open-Knesset,ofri/Open-Knesset,ofri/Open-Knesset,otadmor/Open-Knesset,otadmor/Open-Knesset,Shrulik/Open-Knesset,daonb/Open-Knesset,daonb/Open-Knesset,MeirKriheli/Open-Knesset,navotsil/Open-Knesset,noamelf/Open-Knesset,Shrulik/Open-Knesset,jspan/Open-Knesset,OriHoch/Open-Knesset,OriHoch/Open-Knesset,alonisser/Open-Knesset,habeanf/Open-Knesset,DanaOshri/Open-Knesset,OriHoch/Open-Knesset,otadmor/Open-Knesset,daonb/Open-Knesset,habeanf/Open-Knesset,ofri/Open-Knesset,noamelf/Open-Knesset,alonisser/Open-Knesset,MeirKriheli/Open-Knesset,habeanf/Open-Knesset,jspan/Open-Knesset,DanaOshri/Open-Knesset
|
from django.test import TestCase
from django.contrib.auth.models import User
from mks.models import Member
from .models import Suggestion
class SuggestionsTests(TestCase):
def setUp(self):
self.member = Member.objects.create(name='mk_1')
self.regular_user = User.objects.create_user('reg_user')
def test_simple_text_suggestion(self):
MK_SITE = 'http://mk1.example.com'
suggestion = Suggestion.objects.create_suggestion(
suggested_by=self.regular_user,
content_object=self.member,
suggestion_action=Suggestion.UPDATE,
suggested_field='website',
suggested_text=MK_SITE
)
self.assertIsNone(self.member.website)
suggestion.auto_apply()
mk = Member.objects.get(pk=self.member.pk)
self.assertEqual(mk.website, MK_SITE)
+ # cleanup
+ mk.website = None
+ mk.save()
+
+ self.member = mk
+
|
Undo member changes in test
|
## Code Before:
from django.test import TestCase
from django.contrib.auth.models import User
from mks.models import Member
from .models import Suggestion
class SuggestionsTests(TestCase):
def setUp(self):
self.member = Member.objects.create(name='mk_1')
self.regular_user = User.objects.create_user('reg_user')
def test_simple_text_suggestion(self):
MK_SITE = 'http://mk1.example.com'
suggestion = Suggestion.objects.create_suggestion(
suggested_by=self.regular_user,
content_object=self.member,
suggestion_action=Suggestion.UPDATE,
suggested_field='website',
suggested_text=MK_SITE
)
self.assertIsNone(self.member.website)
suggestion.auto_apply()
mk = Member.objects.get(pk=self.member.pk)
self.assertEqual(mk.website, MK_SITE)
## Instruction:
Undo member changes in test
## Code After:
from django.test import TestCase
from django.contrib.auth.models import User
from mks.models import Member
from .models import Suggestion
class SuggestionsTests(TestCase):
def setUp(self):
self.member = Member.objects.create(name='mk_1')
self.regular_user = User.objects.create_user('reg_user')
def test_simple_text_suggestion(self):
MK_SITE = 'http://mk1.example.com'
suggestion = Suggestion.objects.create_suggestion(
suggested_by=self.regular_user,
content_object=self.member,
suggestion_action=Suggestion.UPDATE,
suggested_field='website',
suggested_text=MK_SITE
)
self.assertIsNone(self.member.website)
suggestion.auto_apply()
mk = Member.objects.get(pk=self.member.pk)
self.assertEqual(mk.website, MK_SITE)
# cleanup
mk.website = None
mk.save()
self.member = mk
|
# ... existing code ...
self.assertEqual(mk.website, MK_SITE)
# cleanup
mk.website = None
mk.save()
self.member = mk
# ... rest of the code ...
|
6ec61fc80ea8c3626b507d20d6c95d64ae4216c0
|
tests/twisted/connect/timeout.py
|
tests/twisted/connect/timeout.py
|
from servicetest import assertEquals
from gabbletest import exec_test, XmppAuthenticator
import constants as cs
import ns
class NoStreamHeader(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def streamStarted(self, root=None):
return
class NoAuthInfoResult(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def auth(self, auth):
return
class NoAuthResult(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def bindIq(self, iq):
return
def test(q, bus, conn, stream):
conn.Connect()
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED])
e = q.expect('dbus-signal', signal='StatusChanged')
status, reason = e.args
assertEquals(cs.CONN_STATUS_DISCONNECTED, status)
assertEquals(cs.CSR_NETWORK_ERROR, reason)
if __name__ == '__main__':
exec_test(test, authenticator=NoStreamHeader())
exec_test(test, authenticator=NoAuthInfoResult())
exec_test(test, authenticator=NoAuthResult())
|
from servicetest import assertEquals
from gabbletest import exec_test, XmppAuthenticator
import constants as cs
import ns
class NoStreamHeader(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def streamStarted(self, root=None):
pass
class NoAuthInfoResult(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def auth(self, auth):
pass
class NoAuthResult(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def bindIq(self, iq):
pass
def test(q, bus, conn, stream):
conn.Connect()
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED])
e = q.expect('dbus-signal', signal='StatusChanged')
status, reason = e.args
assertEquals(cs.CONN_STATUS_DISCONNECTED, status)
assertEquals(cs.CSR_NETWORK_ERROR, reason)
if __name__ == '__main__':
exec_test(test, authenticator=NoStreamHeader())
exec_test(test, authenticator=NoAuthInfoResult())
exec_test(test, authenticator=NoAuthResult())
|
Use 'pass', not 'return', for empty Python methods
|
Use 'pass', not 'return', for empty Python methods
|
Python
|
lgpl-2.1
|
community-ssu/telepathy-gabble,community-ssu/telepathy-gabble,community-ssu/telepathy-gabble,community-ssu/telepathy-gabble
|
from servicetest import assertEquals
from gabbletest import exec_test, XmppAuthenticator
import constants as cs
import ns
class NoStreamHeader(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def streamStarted(self, root=None):
- return
+ pass
class NoAuthInfoResult(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def auth(self, auth):
- return
+ pass
class NoAuthResult(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def bindIq(self, iq):
- return
+ pass
def test(q, bus, conn, stream):
conn.Connect()
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED])
e = q.expect('dbus-signal', signal='StatusChanged')
status, reason = e.args
assertEquals(cs.CONN_STATUS_DISCONNECTED, status)
assertEquals(cs.CSR_NETWORK_ERROR, reason)
if __name__ == '__main__':
exec_test(test, authenticator=NoStreamHeader())
exec_test(test, authenticator=NoAuthInfoResult())
exec_test(test, authenticator=NoAuthResult())
|
Use 'pass', not 'return', for empty Python methods
|
## Code Before:
from servicetest import assertEquals
from gabbletest import exec_test, XmppAuthenticator
import constants as cs
import ns
class NoStreamHeader(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def streamStarted(self, root=None):
return
class NoAuthInfoResult(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def auth(self, auth):
return
class NoAuthResult(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def bindIq(self, iq):
return
def test(q, bus, conn, stream):
conn.Connect()
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED])
e = q.expect('dbus-signal', signal='StatusChanged')
status, reason = e.args
assertEquals(cs.CONN_STATUS_DISCONNECTED, status)
assertEquals(cs.CSR_NETWORK_ERROR, reason)
if __name__ == '__main__':
exec_test(test, authenticator=NoStreamHeader())
exec_test(test, authenticator=NoAuthInfoResult())
exec_test(test, authenticator=NoAuthResult())
## Instruction:
Use 'pass', not 'return', for empty Python methods
## Code After:
from servicetest import assertEquals
from gabbletest import exec_test, XmppAuthenticator
import constants as cs
import ns
class NoStreamHeader(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def streamStarted(self, root=None):
pass
class NoAuthInfoResult(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def auth(self, auth):
pass
class NoAuthResult(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def bindIq(self, iq):
pass
def test(q, bus, conn, stream):
conn.Connect()
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED])
e = q.expect('dbus-signal', signal='StatusChanged')
status, reason = e.args
assertEquals(cs.CONN_STATUS_DISCONNECTED, status)
assertEquals(cs.CSR_NETWORK_ERROR, reason)
if __name__ == '__main__':
exec_test(test, authenticator=NoStreamHeader())
exec_test(test, authenticator=NoAuthInfoResult())
exec_test(test, authenticator=NoAuthResult())
|
// ... existing code ...
def streamStarted(self, root=None):
pass
// ... modified code ...
def auth(self, auth):
pass
...
def bindIq(self, iq):
pass
// ... rest of the code ...
|
c73de73aca304d347e9faffa77eab417cec0b4b5
|
app/util.py
|
app/util.py
|
import os
SHOULD_CACHE = os.environ['ENV'] == 'production'
def cached_function(func):
data = {}
def wrapper(*args):
if not SHOULD_CACHE:
return func(*args)
cache_key = ' '.join([str(x) for x in args])
if cache_key not in data:
data[cache_key] = func(*args)
return data[cache_key]
return wrapper
|
import os
SHOULD_CACHE = os.environ['ENV'] == 'production'
def cached_function(func):
data = {}
def wrapper(*args):
if not SHOULD_CACHE:
return func(*args)
cache_key = ' '.join([str(x) for x in args])
if cache_key not in data:
data[cache_key] = func(*args)
return data[cache_key]
wrapper.__name__ = func.__name__
return wrapper
|
Make cached_function not modify function name
|
Make cached_function not modify function name
|
Python
|
mit
|
albertyw/albertyw.com,albertyw/albertyw.com,albertyw/albertyw.com,albertyw/albertyw.com,albertyw/albertyw.com
|
import os
SHOULD_CACHE = os.environ['ENV'] == 'production'
def cached_function(func):
data = {}
def wrapper(*args):
if not SHOULD_CACHE:
return func(*args)
cache_key = ' '.join([str(x) for x in args])
if cache_key not in data:
data[cache_key] = func(*args)
return data[cache_key]
+ wrapper.__name__ = func.__name__
return wrapper
|
Make cached_function not modify function name
|
## Code Before:
import os
SHOULD_CACHE = os.environ['ENV'] == 'production'
def cached_function(func):
data = {}
def wrapper(*args):
if not SHOULD_CACHE:
return func(*args)
cache_key = ' '.join([str(x) for x in args])
if cache_key not in data:
data[cache_key] = func(*args)
return data[cache_key]
return wrapper
## Instruction:
Make cached_function not modify function name
## Code After:
import os
SHOULD_CACHE = os.environ['ENV'] == 'production'
def cached_function(func):
data = {}
def wrapper(*args):
if not SHOULD_CACHE:
return func(*args)
cache_key = ' '.join([str(x) for x in args])
if cache_key not in data:
data[cache_key] = func(*args)
return data[cache_key]
wrapper.__name__ = func.__name__
return wrapper
|
...
wrapper.__name__ = func.__name__
return wrapper
...
|
a0863e53ccc8f548486eaa5f3e1f79774dea4b75
|
tests/api/views/clubs/list_test.py
|
tests/api/views/clubs/list_test.py
|
from tests.data import add_fixtures, clubs
def test_list_all(db_session, client):
sfn = clubs.sfn()
lva = clubs.lva()
add_fixtures(db_session, sfn, lva)
res = client.get("/clubs")
assert res.status_code == 200
assert res.json == {
"clubs": [
{"id": lva.id, "name": "LV Aachen"},
{"id": sfn.id, "name": "Sportflug Niederberg"},
]
}
def test_name_filter(db_session, client):
sfn = clubs.sfn()
lva = clubs.lva()
add_fixtures(db_session, sfn, lva)
res = client.get("/clubs?name=LV%20Aachen")
assert res.status_code == 200
assert res.json == {"clubs": [{"id": lva.id, "name": "LV Aachen"}]}
def test_name_filter_with_unknown_club(db_session, client):
res = client.get("/clubs?name=Unknown")
assert res.status_code == 200
assert res.json == {"clubs": []}
|
from pytest_voluptuous import S
from voluptuous.validators import ExactSequence
from tests.data import add_fixtures, clubs
def test_list_all(db_session, client):
add_fixtures(db_session, clubs.sfn(), clubs.lva())
res = client.get("/clubs")
assert res.status_code == 200
assert res.json == S(
{
"clubs": ExactSequence(
[
{"id": int, "name": "LV Aachen"},
{"id": int, "name": "Sportflug Niederberg"},
]
)
}
)
def test_name_filter(db_session, client):
add_fixtures(db_session, clubs.sfn(), clubs.lva())
res = client.get("/clubs?name=LV%20Aachen")
assert res.status_code == 200
assert res.json == S({"clubs": ExactSequence([{"id": int, "name": "LV Aachen"}])})
def test_name_filter_with_unknown_club(db_session, client):
res = client.get("/clubs?name=Unknown")
assert res.status_code == 200
assert res.json == S({"clubs": ExactSequence([])})
|
Use `pytest-voluptuous` to simplify JSON compare code
|
api/clubs/list/test: Use `pytest-voluptuous` to simplify JSON compare code
|
Python
|
agpl-3.0
|
skylines-project/skylines,skylines-project/skylines,skylines-project/skylines,skylines-project/skylines
|
+ from pytest_voluptuous import S
+ from voluptuous.validators import ExactSequence
+
from tests.data import add_fixtures, clubs
def test_list_all(db_session, client):
- sfn = clubs.sfn()
- lva = clubs.lva()
- add_fixtures(db_session, sfn, lva)
+ add_fixtures(db_session, clubs.sfn(), clubs.lva())
res = client.get("/clubs")
assert res.status_code == 200
- assert res.json == {
+ assert res.json == S(
- "clubs": [
- {"id": lva.id, "name": "LV Aachen"},
- {"id": sfn.id, "name": "Sportflug Niederberg"},
- ]
+ {
+ "clubs": ExactSequence(
+ [
+ {"id": int, "name": "LV Aachen"},
+ {"id": int, "name": "Sportflug Niederberg"},
+ ]
+ )
+ }
- }
+ )
def test_name_filter(db_session, client):
- sfn = clubs.sfn()
- lva = clubs.lva()
- add_fixtures(db_session, sfn, lva)
+ add_fixtures(db_session, clubs.sfn(), clubs.lva())
res = client.get("/clubs?name=LV%20Aachen")
assert res.status_code == 200
- assert res.json == {"clubs": [{"id": lva.id, "name": "LV Aachen"}]}
+ assert res.json == S({"clubs": ExactSequence([{"id": int, "name": "LV Aachen"}])})
def test_name_filter_with_unknown_club(db_session, client):
res = client.get("/clubs?name=Unknown")
assert res.status_code == 200
- assert res.json == {"clubs": []}
+ assert res.json == S({"clubs": ExactSequence([])})
|
Use `pytest-voluptuous` to simplify JSON compare code
|
## Code Before:
from tests.data import add_fixtures, clubs
def test_list_all(db_session, client):
sfn = clubs.sfn()
lva = clubs.lva()
add_fixtures(db_session, sfn, lva)
res = client.get("/clubs")
assert res.status_code == 200
assert res.json == {
"clubs": [
{"id": lva.id, "name": "LV Aachen"},
{"id": sfn.id, "name": "Sportflug Niederberg"},
]
}
def test_name_filter(db_session, client):
sfn = clubs.sfn()
lva = clubs.lva()
add_fixtures(db_session, sfn, lva)
res = client.get("/clubs?name=LV%20Aachen")
assert res.status_code == 200
assert res.json == {"clubs": [{"id": lva.id, "name": "LV Aachen"}]}
def test_name_filter_with_unknown_club(db_session, client):
res = client.get("/clubs?name=Unknown")
assert res.status_code == 200
assert res.json == {"clubs": []}
## Instruction:
Use `pytest-voluptuous` to simplify JSON compare code
## Code After:
from pytest_voluptuous import S
from voluptuous.validators import ExactSequence
from tests.data import add_fixtures, clubs
def test_list_all(db_session, client):
add_fixtures(db_session, clubs.sfn(), clubs.lva())
res = client.get("/clubs")
assert res.status_code == 200
assert res.json == S(
{
"clubs": ExactSequence(
[
{"id": int, "name": "LV Aachen"},
{"id": int, "name": "Sportflug Niederberg"},
]
)
}
)
def test_name_filter(db_session, client):
add_fixtures(db_session, clubs.sfn(), clubs.lva())
res = client.get("/clubs?name=LV%20Aachen")
assert res.status_code == 200
assert res.json == S({"clubs": ExactSequence([{"id": int, "name": "LV Aachen"}])})
def test_name_filter_with_unknown_club(db_session, client):
res = client.get("/clubs?name=Unknown")
assert res.status_code == 200
assert res.json == S({"clubs": ExactSequence([])})
|
...
from pytest_voluptuous import S
from voluptuous.validators import ExactSequence
from tests.data import add_fixtures, clubs
...
def test_list_all(db_session, client):
add_fixtures(db_session, clubs.sfn(), clubs.lva())
...
assert res.status_code == 200
assert res.json == S(
{
"clubs": ExactSequence(
[
{"id": int, "name": "LV Aachen"},
{"id": int, "name": "Sportflug Niederberg"},
]
)
}
)
...
def test_name_filter(db_session, client):
add_fixtures(db_session, clubs.sfn(), clubs.lva())
...
assert res.status_code == 200
assert res.json == S({"clubs": ExactSequence([{"id": int, "name": "LV Aachen"}])})
...
assert res.status_code == 200
assert res.json == S({"clubs": ExactSequence([])})
...
|
93c6e5d39b1779f0eca9b28f5111d7c402ebc1ba
|
geotagging/views.py
|
geotagging/views.py
|
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.contenttypes.models import ContentType
from geotagging.models import Point
def add_edit_point(request, content_type_id, object_id,
template=None, form_class=None):
model_class = ContentType.objects.get(id=content_type_id).model_class()
object = model_class.objects.get(id=object_id)
object_content_type = ContentType.objects.get_for_model(object)
geotag = Point.objects.get(content_type__pk=object_content_type.id,
object_id=object.id)
if request.method == "POST":
form = form_class(request.POST, instance=geotag)
if form.is_valid():
new_object = form.save(commit=False)
new_object.object = object
new_object.save()
return HttpResponseRedirect("/admin/%s/%s/%s/"
%(object_content_type.app_label,
object_content_type.model,
object.id))
form = form_class(instance=geotag)
#import ipdb; ipdb.set_trace()
context = RequestContext(request, {
'form': form,
'object' : object,
'object_content_type' : object_content_type,
'geotag' : geotag,
})
return render_to_response(template, context_instance=context )
|
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from geotagging.models import Point
def add_edit_point(request, content_type_id, object_id,
template=None, form_class=None):
model_class = ContentType.objects.get(id=content_type_id).model_class()
object = model_class.objects.get(id=object_id)
object_content_type = ContentType.objects.get_for_model(object)
try:
geotag = Point.objects.get(content_type__pk=object_content_type.id,
object_id=object.id)
except ObjectDoesNotExist:
geotag = None
if request.method == "POST":
form = form_class(request.POST, instance=geotag)
if form.is_valid():
new_object = form.save(commit=False)
new_object.object = object
new_object.save()
return HttpResponseRedirect("/admin/%s/%s/%s/"
%(object_content_type.app_label,
object_content_type.model,
object.id))
form = form_class(instance=geotag)
#import ipdb; ipdb.set_trace()
context = RequestContext(request, {
'form': form,
'object' : object,
'object_content_type' : object_content_type,
'geotag' : geotag,
})
return render_to_response(template, context_instance=context )
|
Fix a bug when you try to add a geo tag to an object that does not have already one
|
Fix a bug when you try to add a geo tag to an object that does not have already one
|
Python
|
bsd-3-clause
|
lincolnloop/django-geotagging,lincolnloop/django-geotagging
|
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.contenttypes.models import ContentType
+ from django.core.exceptions import ObjectDoesNotExist
from geotagging.models import Point
def add_edit_point(request, content_type_id, object_id,
template=None, form_class=None):
model_class = ContentType.objects.get(id=content_type_id).model_class()
object = model_class.objects.get(id=object_id)
object_content_type = ContentType.objects.get_for_model(object)
+ try:
- geotag = Point.objects.get(content_type__pk=object_content_type.id,
+ geotag = Point.objects.get(content_type__pk=object_content_type.id,
object_id=object.id)
+ except ObjectDoesNotExist:
+ geotag = None
if request.method == "POST":
form = form_class(request.POST, instance=geotag)
if form.is_valid():
new_object = form.save(commit=False)
new_object.object = object
new_object.save()
return HttpResponseRedirect("/admin/%s/%s/%s/"
%(object_content_type.app_label,
object_content_type.model,
object.id))
form = form_class(instance=geotag)
#import ipdb; ipdb.set_trace()
context = RequestContext(request, {
'form': form,
'object' : object,
'object_content_type' : object_content_type,
'geotag' : geotag,
})
return render_to_response(template, context_instance=context )
|
Fix a bug when you try to add a geo tag to an object that does not have already one
|
## Code Before:
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.contenttypes.models import ContentType
from geotagging.models import Point
def add_edit_point(request, content_type_id, object_id,
template=None, form_class=None):
model_class = ContentType.objects.get(id=content_type_id).model_class()
object = model_class.objects.get(id=object_id)
object_content_type = ContentType.objects.get_for_model(object)
geotag = Point.objects.get(content_type__pk=object_content_type.id,
object_id=object.id)
if request.method == "POST":
form = form_class(request.POST, instance=geotag)
if form.is_valid():
new_object = form.save(commit=False)
new_object.object = object
new_object.save()
return HttpResponseRedirect("/admin/%s/%s/%s/"
%(object_content_type.app_label,
object_content_type.model,
object.id))
form = form_class(instance=geotag)
#import ipdb; ipdb.set_trace()
context = RequestContext(request, {
'form': form,
'object' : object,
'object_content_type' : object_content_type,
'geotag' : geotag,
})
return render_to_response(template, context_instance=context )
## Instruction:
Fix a bug when you try to add a geo tag to an object that does not have already one
## Code After:
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from geotagging.models import Point
def add_edit_point(request, content_type_id, object_id,
template=None, form_class=None):
model_class = ContentType.objects.get(id=content_type_id).model_class()
object = model_class.objects.get(id=object_id)
object_content_type = ContentType.objects.get_for_model(object)
try:
geotag = Point.objects.get(content_type__pk=object_content_type.id,
object_id=object.id)
except ObjectDoesNotExist:
geotag = None
if request.method == "POST":
form = form_class(request.POST, instance=geotag)
if form.is_valid():
new_object = form.save(commit=False)
new_object.object = object
new_object.save()
return HttpResponseRedirect("/admin/%s/%s/%s/"
%(object_content_type.app_label,
object_content_type.model,
object.id))
form = form_class(instance=geotag)
#import ipdb; ipdb.set_trace()
context = RequestContext(request, {
'form': form,
'object' : object,
'object_content_type' : object_content_type,
'geotag' : geotag,
})
return render_to_response(template, context_instance=context )
|
...
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
...
object_content_type = ContentType.objects.get_for_model(object)
try:
geotag = Point.objects.get(content_type__pk=object_content_type.id,
object_id=object.id)
except ObjectDoesNotExist:
geotag = None
if request.method == "POST":
...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.