commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 10
3.52k
| 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 7
43k
| ndiff
stringlengths 52
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
| fuzzy_diff
stringlengths 17
3.24k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
75d6920503b166efd778a6becf0939fe1d2cbe1f | openprescribing/pipeline/management/commands/fetch_prescribing_data.py | openprescribing/pipeline/management/commands/fetch_prescribing_data.py | import os
import requests
from bs4 import BeautifulSoup
from django.conf import settings
from django.core.management import BaseCommand
from openprescribing.utils import mkdir_p
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("year", type=int)
parser.add_argument("month", type=int)
def handle(self, year, month, **kwargs):
year_and_month = "{year}_{month:02d}".format(year=year, month=month)
dir_path = os.path.join(
settings.PIPELINE_DATA_BASEDIR, "prescribing_v2", year_and_month
)
mkdir_p(dir_path)
rsp = requests.get(
"https://opendata.nhsbsa.net/dataset/english-prescribing-data-epd"
)
doc = BeautifulSoup(rsp.text, "html.parser")
filename = "epd_{year}{month:02d}.csv".format(year=year, month=month)
urls = [a["href"] for a in doc.find_all("a") if filename in a["href"]]
assert len(urls) == 1, urls
rsp = requests.get(urls[0], stream=True)
assert rsp.ok
with open(os.path.join(dir_path, filename), "wb") as f:
for block in rsp.iter_content(32 * 1024):
f.write(block)
| import os
import requests
from django.conf import settings
from django.core.management import BaseCommand
from openprescribing.utils import mkdir_p
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("year", type=int)
parser.add_argument("month", type=int)
def handle(self, year, month, **kwargs):
rsp = requests.get(
"https://opendata.nhsbsa.net/api/3/action/package_show?id=english-prescribing-data-epd"
)
resources = rsp.json()["result"]["resources"]
urls = [
r["url"]
for r in resources
if r["name"] == "EPD_{year}{month:02d}".format(year=year, month=month)
]
assert len(urls) == 1, urls
rsp = requests.get(urls[0], stream=True)
assert rsp.ok
dir_path = os.path.join(
settings.PIPELINE_DATA_BASEDIR,
"prescribing_v2",
"{year}{month:02d}".format(year=year, month=month),
)
mkdir_p(dir_path)
filename = "epd_{year}{month:02d}.csv".format(year=year, month=month)
with open(os.path.join(dir_path, filename), "wb") as f:
for block in rsp.iter_content(32 * 1024):
f.write(block)
| Use BSA's API to get URL of latest prescribing data | Use BSA's API to get URL of latest prescribing data
| Python | mit | ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing,ebmdatalab/openprescribing | import os
import requests
- from bs4 import BeautifulSoup
from django.conf import settings
from django.core.management import BaseCommand
from openprescribing.utils import mkdir_p
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("year", type=int)
parser.add_argument("month", type=int)
def handle(self, year, month, **kwargs):
+ rsp = requests.get(
+ "https://opendata.nhsbsa.net/api/3/action/package_show?id=english-prescribing-data-epd"
- year_and_month = "{year}_{month:02d}".format(year=year, month=month)
- dir_path = os.path.join(
- settings.PIPELINE_DATA_BASEDIR, "prescribing_v2", year_and_month
)
- mkdir_p(dir_path)
-
- rsp = requests.get(
- "https://opendata.nhsbsa.net/dataset/english-prescribing-data-epd"
+ resources = rsp.json()["result"]["resources"]
+ urls = [
+ r["url"]
+ for r in resources
+ if r["name"] == "EPD_{year}{month:02d}".format(year=year, month=month)
- )
+ ]
- doc = BeautifulSoup(rsp.text, "html.parser")
- filename = "epd_{year}{month:02d}.csv".format(year=year, month=month)
- urls = [a["href"] for a in doc.find_all("a") if filename in a["href"]]
assert len(urls) == 1, urls
rsp = requests.get(urls[0], stream=True)
assert rsp.ok
+
+ dir_path = os.path.join(
+ settings.PIPELINE_DATA_BASEDIR,
+ "prescribing_v2",
+ "{year}{month:02d}".format(year=year, month=month),
+ )
+ mkdir_p(dir_path)
+ filename = "epd_{year}{month:02d}.csv".format(year=year, month=month)
with open(os.path.join(dir_path, filename), "wb") as f:
for block in rsp.iter_content(32 * 1024):
f.write(block)
| Use BSA's API to get URL of latest prescribing data | ## Code Before:
import os
import requests
from bs4 import BeautifulSoup
from django.conf import settings
from django.core.management import BaseCommand
from openprescribing.utils import mkdir_p
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("year", type=int)
parser.add_argument("month", type=int)
def handle(self, year, month, **kwargs):
year_and_month = "{year}_{month:02d}".format(year=year, month=month)
dir_path = os.path.join(
settings.PIPELINE_DATA_BASEDIR, "prescribing_v2", year_and_month
)
mkdir_p(dir_path)
rsp = requests.get(
"https://opendata.nhsbsa.net/dataset/english-prescribing-data-epd"
)
doc = BeautifulSoup(rsp.text, "html.parser")
filename = "epd_{year}{month:02d}.csv".format(year=year, month=month)
urls = [a["href"] for a in doc.find_all("a") if filename in a["href"]]
assert len(urls) == 1, urls
rsp = requests.get(urls[0], stream=True)
assert rsp.ok
with open(os.path.join(dir_path, filename), "wb") as f:
for block in rsp.iter_content(32 * 1024):
f.write(block)
## Instruction:
Use BSA's API to get URL of latest prescribing data
## Code After:
import os
import requests
from django.conf import settings
from django.core.management import BaseCommand
from openprescribing.utils import mkdir_p
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("year", type=int)
parser.add_argument("month", type=int)
def handle(self, year, month, **kwargs):
rsp = requests.get(
"https://opendata.nhsbsa.net/api/3/action/package_show?id=english-prescribing-data-epd"
)
resources = rsp.json()["result"]["resources"]
urls = [
r["url"]
for r in resources
if r["name"] == "EPD_{year}{month:02d}".format(year=year, month=month)
]
assert len(urls) == 1, urls
rsp = requests.get(urls[0], stream=True)
assert rsp.ok
dir_path = os.path.join(
settings.PIPELINE_DATA_BASEDIR,
"prescribing_v2",
"{year}{month:02d}".format(year=year, month=month),
)
mkdir_p(dir_path)
filename = "epd_{year}{month:02d}.csv".format(year=year, month=month)
with open(os.path.join(dir_path, filename), "wb") as f:
for block in rsp.iter_content(32 * 1024):
f.write(block)
| # ... existing code ...
import requests
from django.conf import settings
# ... modified code ...
def handle(self, year, month, **kwargs):
rsp = requests.get(
"https://opendata.nhsbsa.net/api/3/action/package_show?id=english-prescribing-data-epd"
)
resources = rsp.json()["result"]["resources"]
urls = [
r["url"]
for r in resources
if r["name"] == "EPD_{year}{month:02d}".format(year=year, month=month)
]
assert len(urls) == 1, urls
rsp = requests.get(urls[0], stream=True)
...
assert rsp.ok
dir_path = os.path.join(
settings.PIPELINE_DATA_BASEDIR,
"prescribing_v2",
"{year}{month:02d}".format(year=year, month=month),
)
mkdir_p(dir_path)
filename = "epd_{year}{month:02d}.csv".format(year=year, month=month)
with open(os.path.join(dir_path, filename), "wb") as f:
for block in rsp.iter_content(32 * 1024):
# ... rest of the code ... |
1cb201c57c592ebd014910fe225fa594cd87c745 | opendebates/middleware.py | opendebates/middleware.py | from opendebates.utils import get_site_mode
class SiteModeMiddleware(object):
"""
Gets or creates a SiteMode for the request, based on the hostname.
"""
def process_view(self, request, view_func, view_args, view_kwargs):
request.site_mode = get_site_mode(request)
| from opendebates.utils import get_site_mode
class SiteModeMiddleware(object):
"""
Gets or creates a SiteMode for the request, based on the hostname.
"""
def process_request(self, request):
request.site_mode = get_site_mode(request)
| Make sure that the site mode is populated on the request | Make sure that the site mode is populated on the request
even if the request winds up getting dispatched to a flatpage.
| Python | apache-2.0 | caktus/django-opendebates,caktus/django-opendebates,caktus/django-opendebates,caktus/django-opendebates | from opendebates.utils import get_site_mode
class SiteModeMiddleware(object):
"""
Gets or creates a SiteMode for the request, based on the hostname.
"""
- def process_view(self, request, view_func, view_args, view_kwargs):
+ def process_request(self, request):
request.site_mode = get_site_mode(request)
| Make sure that the site mode is populated on the request | ## Code Before:
from opendebates.utils import get_site_mode
class SiteModeMiddleware(object):
"""
Gets or creates a SiteMode for the request, based on the hostname.
"""
def process_view(self, request, view_func, view_args, view_kwargs):
request.site_mode = get_site_mode(request)
## Instruction:
Make sure that the site mode is populated on the request
## Code After:
from opendebates.utils import get_site_mode
class SiteModeMiddleware(object):
"""
Gets or creates a SiteMode for the request, based on the hostname.
"""
def process_request(self, request):
request.site_mode = get_site_mode(request)
| # ... existing code ...
"""
def process_request(self, request):
request.site_mode = get_site_mode(request)
# ... rest of the code ... |
9a97b9df87f06268ab1075726835da95f4852052 | romanesco/format/tree/nested_to_vtktree.py | romanesco/format/tree/nested_to_vtktree.py | from romanesco.format import dict_to_vtkarrays, dict_to_vtkrow
import vtk
vtk_builder = vtk.vtkMutableDirectedGraph()
node_fields = input["node_fields"]
edge_fields = input["edge_fields"]
dict_to_vtkarrays(input["node_data"], node_fields, vtk_builder.GetVertexData())
if "children" in input and len(input["children"]) > 0:
dict_to_vtkarrays(input["children"][0]["edge_data"], edge_fields,
vtk_builder.GetEdgeData())
def process_node(vtknode, node):
if "children" in node:
for n in node["children"]:
vtkchild = vtk_builder.AddVertex()
vtkparentedge = vtk_builder.AddGraphEdge(vtknode, vtkchild).GetId()
dict_to_vtkrow(n["node_data"], vtk_builder.GetVertexData())
if "edge_data" in n:
dict_to_vtkrow(n["edge_data"], vtk_builder.GetEdgeData())
process_node(vtkchild, n)
vtk_builder.AddVertex()
dict_to_vtkrow(input["node_data"], vtk_builder.GetVertexData())
process_node(0, input)
output = vtk.vtkTree()
output.ShallowCopy(vtk_builder)
| from romanesco.format import dict_to_vtkarrays, dict_to_vtkrow
import vtk
vtk_builder = vtk.vtkMutableDirectedGraph()
node_fields = input["node_fields"]
edge_fields = input["edge_fields"]
dict_to_vtkarrays(input["node_data"], node_fields, vtk_builder.GetVertexData())
if "children" in input and len(input["children"]) > 0:
dict_to_vtkarrays(input["children"][0]["edge_data"], edge_fields,
vtk_builder.GetEdgeData())
def process_node(vtknode, node):
if "children" in node:
for n in node["children"]:
vtkchild = vtk_builder.AddVertex()
vtkparentedge = vtk_builder.AddGraphEdge(vtknode, vtkchild).GetId()
dict_to_vtkrow(n["node_data"], vtk_builder.GetVertexData())
dict_to_vtkrow(n["edge_data"], vtk_builder.GetEdgeData())
process_node(vtkchild, n)
vtk_builder.AddVertex()
dict_to_vtkrow(input["node_data"], vtk_builder.GetVertexData())
process_node(0, input)
output = vtk.vtkTree()
output.ShallowCopy(vtk_builder)
| Revert "tolerate missing edge data" | Revert "tolerate missing edge data"
This reverts commit 93f1f6b24b7e8e61dbbfebe500048db752bc9fed.
| Python | apache-2.0 | Kitware/romanesco,Kitware/romanesco,Kitware/romanesco,Kitware/romanesco,girder/girder_worker,girder/girder_worker,girder/girder_worker | from romanesco.format import dict_to_vtkarrays, dict_to_vtkrow
import vtk
vtk_builder = vtk.vtkMutableDirectedGraph()
node_fields = input["node_fields"]
edge_fields = input["edge_fields"]
dict_to_vtkarrays(input["node_data"], node_fields, vtk_builder.GetVertexData())
if "children" in input and len(input["children"]) > 0:
dict_to_vtkarrays(input["children"][0]["edge_data"], edge_fields,
vtk_builder.GetEdgeData())
def process_node(vtknode, node):
if "children" in node:
for n in node["children"]:
vtkchild = vtk_builder.AddVertex()
vtkparentedge = vtk_builder.AddGraphEdge(vtknode, vtkchild).GetId()
dict_to_vtkrow(n["node_data"], vtk_builder.GetVertexData())
- if "edge_data" in n:
- dict_to_vtkrow(n["edge_data"], vtk_builder.GetEdgeData())
+ dict_to_vtkrow(n["edge_data"], vtk_builder.GetEdgeData())
process_node(vtkchild, n)
vtk_builder.AddVertex()
dict_to_vtkrow(input["node_data"], vtk_builder.GetVertexData())
process_node(0, input)
output = vtk.vtkTree()
output.ShallowCopy(vtk_builder)
| Revert "tolerate missing edge data" | ## Code Before:
from romanesco.format import dict_to_vtkarrays, dict_to_vtkrow
import vtk
vtk_builder = vtk.vtkMutableDirectedGraph()
node_fields = input["node_fields"]
edge_fields = input["edge_fields"]
dict_to_vtkarrays(input["node_data"], node_fields, vtk_builder.GetVertexData())
if "children" in input and len(input["children"]) > 0:
dict_to_vtkarrays(input["children"][0]["edge_data"], edge_fields,
vtk_builder.GetEdgeData())
def process_node(vtknode, node):
if "children" in node:
for n in node["children"]:
vtkchild = vtk_builder.AddVertex()
vtkparentedge = vtk_builder.AddGraphEdge(vtknode, vtkchild).GetId()
dict_to_vtkrow(n["node_data"], vtk_builder.GetVertexData())
if "edge_data" in n:
dict_to_vtkrow(n["edge_data"], vtk_builder.GetEdgeData())
process_node(vtkchild, n)
vtk_builder.AddVertex()
dict_to_vtkrow(input["node_data"], vtk_builder.GetVertexData())
process_node(0, input)
output = vtk.vtkTree()
output.ShallowCopy(vtk_builder)
## Instruction:
Revert "tolerate missing edge data"
## Code After:
from romanesco.format import dict_to_vtkarrays, dict_to_vtkrow
import vtk
vtk_builder = vtk.vtkMutableDirectedGraph()
node_fields = input["node_fields"]
edge_fields = input["edge_fields"]
dict_to_vtkarrays(input["node_data"], node_fields, vtk_builder.GetVertexData())
if "children" in input and len(input["children"]) > 0:
dict_to_vtkarrays(input["children"][0]["edge_data"], edge_fields,
vtk_builder.GetEdgeData())
def process_node(vtknode, node):
if "children" in node:
for n in node["children"]:
vtkchild = vtk_builder.AddVertex()
vtkparentedge = vtk_builder.AddGraphEdge(vtknode, vtkchild).GetId()
dict_to_vtkrow(n["node_data"], vtk_builder.GetVertexData())
dict_to_vtkrow(n["edge_data"], vtk_builder.GetEdgeData())
process_node(vtkchild, n)
vtk_builder.AddVertex()
dict_to_vtkrow(input["node_data"], vtk_builder.GetVertexData())
process_node(0, input)
output = vtk.vtkTree()
output.ShallowCopy(vtk_builder)
| // ... existing code ...
vtkparentedge = vtk_builder.AddGraphEdge(vtknode, vtkchild).GetId()
dict_to_vtkrow(n["node_data"], vtk_builder.GetVertexData())
dict_to_vtkrow(n["edge_data"], vtk_builder.GetEdgeData())
process_node(vtkchild, n)
vtk_builder.AddVertex()
// ... rest of the code ... |
84f913d928d28bc193d21eb223e7815f69c53a22 | plugins/jira.py | plugins/jira.py | from neb.engine import Plugin, Command
import requests
class JiraPlugin(Plugin):
def get_commands(self):
"""Return human readable commands with descriptions.
Returns:
list[Command]
"""
return [
Command("jira", self.jira, "Perform commands on Matrix JIRA.", [
"server-info - Retrieve server information."
]),
]
def jira(self, event, args):
action = args[1]
actions = {
"server-info": self._server_info
}
return actions[action](event, args)
def _server_info(self, event, args):
return self._body("Boo")
def sync(self, matrix, initial_sync):
pass
| from neb.engine import Plugin, Command, KeyValueStore
import json
import requests
class JiraPlugin(Plugin):
def __init__(self, config="jira.json"):
self.store = KeyValueStore(config)
if not self.store.has("url"):
url = raw_input("JIRA URL: ").strip()
self.store.set("url", url)
def get_commands(self):
"""Return human readable commands with descriptions.
Returns:
list[Command]
"""
return [
Command("jira", self.jira, "Perform commands on a JIRA platform.", [
"server-info - Retrieve server information."
]),
]
def jira(self, event, args):
if len(args) == 1:
return self._body("Perform commands on a JIRA platform.")
action = args[1]
actions = {
"server-info": self._server_info
}
return actions[action](event, args)
def _server_info(self, event, args):
url = self._url("/rest/api/2/serverInfo")
response = json.loads(requests.get(url).text)
info = "%s : version %s : build %s" % (response["serverTitle"],
response["version"], response["buildNumber"])
return self._body(info)
def sync(self, matrix, initial_sync):
pass
def _url(self, path):
return self.store.get("url") + path
| Make the plugin request server info from JIRA. | Make the plugin request server info from JIRA.
| Python | apache-2.0 | Kegsay/Matrix-NEB,matrix-org/Matrix-NEB,illicitonion/Matrix-NEB | - from neb.engine import Plugin, Command
+ from neb.engine import Plugin, Command, KeyValueStore
+ import json
import requests
+
class JiraPlugin(Plugin):
+ def __init__(self, config="jira.json"):
+ self.store = KeyValueStore(config)
+
+ if not self.store.has("url"):
+ url = raw_input("JIRA URL: ").strip()
+ self.store.set("url", url)
+
def get_commands(self):
"""Return human readable commands with descriptions.
-
+
Returns:
list[Command]
"""
return [
- Command("jira", self.jira, "Perform commands on Matrix JIRA.", [
+ Command("jira", self.jira, "Perform commands on a JIRA platform.", [
"server-info - Retrieve server information."
]),
]
-
+
def jira(self, event, args):
+ if len(args) == 1:
+ return self._body("Perform commands on a JIRA platform.")
+
action = args[1]
actions = {
"server-info": self._server_info
}
return actions[action](event, args)
-
+
def _server_info(self, event, args):
+ url = self._url("/rest/api/2/serverInfo")
+ response = json.loads(requests.get(url).text)
+
+ info = "%s : version %s : build %s" % (response["serverTitle"],
+ response["version"], response["buildNumber"])
+
- return self._body("Boo")
+ return self._body(info)
-
+
def sync(self, matrix, initial_sync):
pass
-
-
+ def _url(self, path):
+ return self.store.get("url") + path
+
+
+ | Make the plugin request server info from JIRA. | ## Code Before:
from neb.engine import Plugin, Command
import requests
class JiraPlugin(Plugin):
def get_commands(self):
"""Return human readable commands with descriptions.
Returns:
list[Command]
"""
return [
Command("jira", self.jira, "Perform commands on Matrix JIRA.", [
"server-info - Retrieve server information."
]),
]
def jira(self, event, args):
action = args[1]
actions = {
"server-info": self._server_info
}
return actions[action](event, args)
def _server_info(self, event, args):
return self._body("Boo")
def sync(self, matrix, initial_sync):
pass
## Instruction:
Make the plugin request server info from JIRA.
## Code After:
from neb.engine import Plugin, Command, KeyValueStore
import json
import requests
class JiraPlugin(Plugin):
def __init__(self, config="jira.json"):
self.store = KeyValueStore(config)
if not self.store.has("url"):
url = raw_input("JIRA URL: ").strip()
self.store.set("url", url)
def get_commands(self):
"""Return human readable commands with descriptions.
Returns:
list[Command]
"""
return [
Command("jira", self.jira, "Perform commands on a JIRA platform.", [
"server-info - Retrieve server information."
]),
]
def jira(self, event, args):
if len(args) == 1:
return self._body("Perform commands on a JIRA platform.")
action = args[1]
actions = {
"server-info": self._server_info
}
return actions[action](event, args)
def _server_info(self, event, args):
url = self._url("/rest/api/2/serverInfo")
response = json.loads(requests.get(url).text)
info = "%s : version %s : build %s" % (response["serverTitle"],
response["version"], response["buildNumber"])
return self._body(info)
def sync(self, matrix, initial_sync):
pass
def _url(self, path):
return self.store.get("url") + path
| ...
from neb.engine import Plugin, Command, KeyValueStore
import json
import requests
class JiraPlugin(Plugin):
def __init__(self, config="jira.json"):
self.store = KeyValueStore(config)
if not self.store.has("url"):
url = raw_input("JIRA URL: ").strip()
self.store.set("url", url)
def get_commands(self):
"""Return human readable commands with descriptions.
Returns:
list[Command]
...
"""
return [
Command("jira", self.jira, "Perform commands on a JIRA platform.", [
"server-info - Retrieve server information."
]),
]
def jira(self, event, args):
if len(args) == 1:
return self._body("Perform commands on a JIRA platform.")
action = args[1]
actions = {
...
return actions[action](event, args)
def _server_info(self, event, args):
url = self._url("/rest/api/2/serverInfo")
response = json.loads(requests.get(url).text)
info = "%s : version %s : build %s" % (response["serverTitle"],
response["version"], response["buildNumber"])
return self._body(info)
def sync(self, matrix, initial_sync):
pass
def _url(self, path):
return self.store.get("url") + path
... |
d3837972d5aff2812ea534e053695373497192d5 | cheroot/__init__.py | cheroot/__init__.py | try:
import pkg_resources
__version__ = pkg_resources.get_distribution('cheroot').version
except ImportError:
__version__ = 'unknown'
| try:
import pkg_resources
__version__ = pkg_resources.get_distribution('cheroot').version
except (ImportError, pkg_resources.DistributionNotFound):
__version__ = 'unknown'
| Handle DistributionNotFound when getting version | Handle DistributionNotFound when getting version
When frozen with e.g. cx_Freeze, cheroot will be importable, but not discoverable by pkg_resources. | Python | bsd-3-clause | cherrypy/cheroot | try:
import pkg_resources
__version__ = pkg_resources.get_distribution('cheroot').version
- except ImportError:
+ except (ImportError, pkg_resources.DistributionNotFound):
__version__ = 'unknown'
| Handle DistributionNotFound when getting version | ## Code Before:
try:
import pkg_resources
__version__ = pkg_resources.get_distribution('cheroot').version
except ImportError:
__version__ = 'unknown'
## Instruction:
Handle DistributionNotFound when getting version
## Code After:
try:
import pkg_resources
__version__ = pkg_resources.get_distribution('cheroot').version
except (ImportError, pkg_resources.DistributionNotFound):
__version__ = 'unknown'
| // ... existing code ...
import pkg_resources
__version__ = pkg_resources.get_distribution('cheroot').version
except (ImportError, pkg_resources.DistributionNotFound):
__version__ = 'unknown'
// ... rest of the code ... |
46e9db6167a9c4f7f778381da888537c00d35bfd | emailsupport/admin.py | emailsupport/admin.py | from __future__ import unicode_literals
from django.contrib import admin
from models import Email, Resolution
class ResolutionInline(admin.StackedInline):
model = Resolution
max_num = 1
class EmailAdmin(admin.ModelAdmin):
list_display = ('subject', 'submitter', 'get_state_display')
inlines = [ResolutionInline]
ordering = ('-state', '-created')
change_form_template = 'admin/email_change_form.html'
readonly_fields = ('submitter', 'subject', 'body', 'body_html')
fieldsets = (
('Question', {
'fields': ('submitter', 'subject', 'body', 'body_html', 'state')
}),
)
class Media:
css = {
"all": ("admin/css/admin.css",)
}
def render_change_form(self, *args, **kwargs):
response = super(EmailAdmin, self).render_change_form(*args, **kwargs)
email = response.context_data['original']
response.context_data['previous_email'] = self.get_previous_email(email)
response.context_data['next_email'] = self.get_next_email(email)
return response
def get_previous_email(self, email):
return Email.objects.get_previous_email(email)
def get_next_email(self, email):
return Email.objects.get_next_email(email)
admin.site.register(Email, EmailAdmin)
| from __future__ import unicode_literals
from django.contrib import admin
from models import Email, Resolution
class ResolutionInline(admin.StackedInline):
model = Resolution
max_num = 1
class EmailAdmin(admin.ModelAdmin):
list_display = ('subject', 'submitter', 'get_state_display')
inlines = [ResolutionInline]
ordering = ('-state', '-created')
change_form_template = 'admin/email_change_form.html'
readonly_fields = ('submitter', 'subject', 'body', 'body_html')
fieldsets = (
('Question', {
'fields': ('submitter', 'subject', 'body', 'body_html', 'state')
}),
)
class Media:
css = {
"all": ("admin/css/admin.css",)
}
def render_change_form(self, *args, **kwargs):
response = super(EmailAdmin, self).render_change_form(*args, **kwargs)
email = response.context_data['original']
if email:
response.context_data['previous_email'] = self.get_previous_email(email)
response.context_data['next_email'] = self.get_next_email(email)
return response
def get_previous_email(self, email):
return Email.objects.get_previous_email(email)
def get_next_email(self, email):
return Email.objects.get_next_email(email)
admin.site.register(Email, EmailAdmin)
| Add prev. and next email to context only if exist original (current) | Add prev. and next email to context only if exist original (current)
| Python | mit | rosti-cz/django-emailsupport | from __future__ import unicode_literals
from django.contrib import admin
from models import Email, Resolution
class ResolutionInline(admin.StackedInline):
model = Resolution
max_num = 1
class EmailAdmin(admin.ModelAdmin):
list_display = ('subject', 'submitter', 'get_state_display')
inlines = [ResolutionInline]
ordering = ('-state', '-created')
change_form_template = 'admin/email_change_form.html'
readonly_fields = ('submitter', 'subject', 'body', 'body_html')
fieldsets = (
('Question', {
'fields': ('submitter', 'subject', 'body', 'body_html', 'state')
}),
)
class Media:
css = {
"all": ("admin/css/admin.css",)
}
def render_change_form(self, *args, **kwargs):
response = super(EmailAdmin, self).render_change_form(*args, **kwargs)
email = response.context_data['original']
+ if email:
- response.context_data['previous_email'] = self.get_previous_email(email)
+ response.context_data['previous_email'] = self.get_previous_email(email)
- response.context_data['next_email'] = self.get_next_email(email)
+ response.context_data['next_email'] = self.get_next_email(email)
return response
def get_previous_email(self, email):
return Email.objects.get_previous_email(email)
def get_next_email(self, email):
return Email.objects.get_next_email(email)
admin.site.register(Email, EmailAdmin)
| Add prev. and next email to context only if exist original (current) | ## Code Before:
from __future__ import unicode_literals
from django.contrib import admin
from models import Email, Resolution
class ResolutionInline(admin.StackedInline):
model = Resolution
max_num = 1
class EmailAdmin(admin.ModelAdmin):
list_display = ('subject', 'submitter', 'get_state_display')
inlines = [ResolutionInline]
ordering = ('-state', '-created')
change_form_template = 'admin/email_change_form.html'
readonly_fields = ('submitter', 'subject', 'body', 'body_html')
fieldsets = (
('Question', {
'fields': ('submitter', 'subject', 'body', 'body_html', 'state')
}),
)
class Media:
css = {
"all": ("admin/css/admin.css",)
}
def render_change_form(self, *args, **kwargs):
response = super(EmailAdmin, self).render_change_form(*args, **kwargs)
email = response.context_data['original']
response.context_data['previous_email'] = self.get_previous_email(email)
response.context_data['next_email'] = self.get_next_email(email)
return response
def get_previous_email(self, email):
return Email.objects.get_previous_email(email)
def get_next_email(self, email):
return Email.objects.get_next_email(email)
admin.site.register(Email, EmailAdmin)
## Instruction:
Add prev. and next email to context only if exist original (current)
## Code After:
from __future__ import unicode_literals
from django.contrib import admin
from models import Email, Resolution
class ResolutionInline(admin.StackedInline):
model = Resolution
max_num = 1
class EmailAdmin(admin.ModelAdmin):
list_display = ('subject', 'submitter', 'get_state_display')
inlines = [ResolutionInline]
ordering = ('-state', '-created')
change_form_template = 'admin/email_change_form.html'
readonly_fields = ('submitter', 'subject', 'body', 'body_html')
fieldsets = (
('Question', {
'fields': ('submitter', 'subject', 'body', 'body_html', 'state')
}),
)
class Media:
css = {
"all": ("admin/css/admin.css",)
}
def render_change_form(self, *args, **kwargs):
response = super(EmailAdmin, self).render_change_form(*args, **kwargs)
email = response.context_data['original']
if email:
response.context_data['previous_email'] = self.get_previous_email(email)
response.context_data['next_email'] = self.get_next_email(email)
return response
def get_previous_email(self, email):
return Email.objects.get_previous_email(email)
def get_next_email(self, email):
return Email.objects.get_next_email(email)
admin.site.register(Email, EmailAdmin)
| ...
response = super(EmailAdmin, self).render_change_form(*args, **kwargs)
email = response.context_data['original']
if email:
response.context_data['previous_email'] = self.get_previous_email(email)
response.context_data['next_email'] = self.get_next_email(email)
return response
... |
6891981cd32a9dbf71346f95256f8447726672df | packages/pixman.py | packages/pixman.py | CairoGraphicsPackage ('pixman', '0.30.0')
| class PixmanPackage (CairoGraphicsPackage):
def __init__ (self):
CairoGraphicsPackage.__init__ (self, 'pixman', '0.30.0')
#This package would like to be built with fat binaries
if Package.profile.m64 == True:
self.fat_build = True
def arch_build (self, arch):
if arch == 'darwin-fat': #multi-arch build pass
self.local_ld_flags = ['-arch i386' , '-arch x86_64']
self.local_gcc_flags = ['-arch i386' , '-arch x86_64', '-Os']
self.local_configure_flags = ['--disable-dependency-tracking']
Package.arch_build (self, arch)
PixmanPackage ()
| Enable fat binaries on pitman package | Enable fat binaries on pitman package
| Python | mit | mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,mono/bockbuild | + class PixmanPackage (CairoGraphicsPackage):
+ def __init__ (self):
- CairoGraphicsPackage ('pixman', '0.30.0')
+ CairoGraphicsPackage.__init__ (self, 'pixman', '0.30.0')
+
+ #This package would like to be built with fat binaries
+ if Package.profile.m64 == True:
+ self.fat_build = True
+ def arch_build (self, arch):
+ if arch == 'darwin-fat': #multi-arch build pass
+ self.local_ld_flags = ['-arch i386' , '-arch x86_64']
+ self.local_gcc_flags = ['-arch i386' , '-arch x86_64', '-Os']
+ self.local_configure_flags = ['--disable-dependency-tracking']
+
+ Package.arch_build (self, arch)
+
+ PixmanPackage ()
+ | Enable fat binaries on pitman package | ## Code Before:
CairoGraphicsPackage ('pixman', '0.30.0')
## Instruction:
Enable fat binaries on pitman package
## Code After:
class PixmanPackage (CairoGraphicsPackage):
def __init__ (self):
CairoGraphicsPackage.__init__ (self, 'pixman', '0.30.0')
#This package would like to be built with fat binaries
if Package.profile.m64 == True:
self.fat_build = True
def arch_build (self, arch):
if arch == 'darwin-fat': #multi-arch build pass
self.local_ld_flags = ['-arch i386' , '-arch x86_64']
self.local_gcc_flags = ['-arch i386' , '-arch x86_64', '-Os']
self.local_configure_flags = ['--disable-dependency-tracking']
Package.arch_build (self, arch)
PixmanPackage ()
| # ... existing code ...
class PixmanPackage (CairoGraphicsPackage):
def __init__ (self):
CairoGraphicsPackage.__init__ (self, 'pixman', '0.30.0')
#This package would like to be built with fat binaries
if Package.profile.m64 == True:
self.fat_build = True
def arch_build (self, arch):
if arch == 'darwin-fat': #multi-arch build pass
self.local_ld_flags = ['-arch i386' , '-arch x86_64']
self.local_gcc_flags = ['-arch i386' , '-arch x86_64', '-Os']
self.local_configure_flags = ['--disable-dependency-tracking']
Package.arch_build (self, arch)
PixmanPackage ()
# ... rest of the code ... |
e1721a515520a85fbbfae112eb63f877de33e7c9 | caffe2/python/test_util.py | caffe2/python/test_util.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from caffe2.python import workspace
import unittest
def rand_array(*dims):
# np.random.rand() returns float instead of 0-dim array, that's why need to
# do some tricks
return np.array(np.random.rand(*dims) - 0.5).astype(np.float32)
class TestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
workspace.GlobalInit([
'caffe2',
'--caffe2_log_level=0',
])
def setUp(self):
self.ws = workspace.C.Workspace()
workspace.ResetWorkspace()
def tearDown(self):
workspace.ResetWorkspace()
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from caffe2.python import core, workspace
import unittest
def rand_array(*dims):
# np.random.rand() returns float instead of 0-dim array, that's why need to
# do some tricks
return np.array(np.random.rand(*dims) - 0.5).astype(np.float32)
class TestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
workspace.GlobalInit([
'caffe2',
'--caffe2_log_level=0',
])
# clear the default engines settings to separate out its
# affect from the ops tests
core.SetEnginePref({}, {})
def setUp(self):
self.ws = workspace.C.Workspace()
workspace.ResetWorkspace()
def tearDown(self):
workspace.ResetWorkspace()
| Clear the operator default engines before running operator tests | Clear the operator default engines before running operator tests
Reviewed By: akyrola
Differential Revision: D5729024
fbshipit-source-id: f2850d5cf53537b22298b39a07f64dfcc2753c75
| Python | apache-2.0 | sf-wind/caffe2,xzturn/caffe2,pietern/caffe2,davinwang/caffe2,pietern/caffe2,davinwang/caffe2,sf-wind/caffe2,Yangqing/caffe2,sf-wind/caffe2,Yangqing/caffe2,davinwang/caffe2,xzturn/caffe2,sf-wind/caffe2,sf-wind/caffe2,xzturn/caffe2,pietern/caffe2,pietern/caffe2,xzturn/caffe2,Yangqing/caffe2,Yangqing/caffe2,caffe2/caffe2,pietern/caffe2,Yangqing/caffe2,xzturn/caffe2,davinwang/caffe2,davinwang/caffe2 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
- from caffe2.python import workspace
+ from caffe2.python import core, workspace
import unittest
def rand_array(*dims):
# np.random.rand() returns float instead of 0-dim array, that's why need to
# do some tricks
return np.array(np.random.rand(*dims) - 0.5).astype(np.float32)
class TestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
workspace.GlobalInit([
'caffe2',
'--caffe2_log_level=0',
])
+ # clear the default engines settings to separate out its
+ # affect from the ops tests
+ core.SetEnginePref({}, {})
def setUp(self):
self.ws = workspace.C.Workspace()
workspace.ResetWorkspace()
def tearDown(self):
workspace.ResetWorkspace()
| Clear the operator default engines before running operator tests | ## Code Before:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from caffe2.python import workspace
import unittest
def rand_array(*dims):
# np.random.rand() returns float instead of 0-dim array, that's why need to
# do some tricks
return np.array(np.random.rand(*dims) - 0.5).astype(np.float32)
class TestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
workspace.GlobalInit([
'caffe2',
'--caffe2_log_level=0',
])
def setUp(self):
self.ws = workspace.C.Workspace()
workspace.ResetWorkspace()
def tearDown(self):
workspace.ResetWorkspace()
## Instruction:
Clear the operator default engines before running operator tests
## Code After:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from caffe2.python import core, workspace
import unittest
def rand_array(*dims):
# np.random.rand() returns float instead of 0-dim array, that's why need to
# do some tricks
return np.array(np.random.rand(*dims) - 0.5).astype(np.float32)
class TestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
workspace.GlobalInit([
'caffe2',
'--caffe2_log_level=0',
])
# clear the default engines settings to separate out its
# affect from the ops tests
core.SetEnginePref({}, {})
def setUp(self):
self.ws = workspace.C.Workspace()
workspace.ResetWorkspace()
def tearDown(self):
workspace.ResetWorkspace()
| // ... existing code ...
from __future__ import unicode_literals
import numpy as np
from caffe2.python import core, workspace
import unittest
// ... modified code ...
'--caffe2_log_level=0',
])
# clear the default engines settings to separate out its
# affect from the ops tests
core.SetEnginePref({}, {})
def setUp(self):
// ... rest of the code ... |
de75ec4f92c424b22f1d64dc43b3d8259b96fde0 | coverart_redirect/loggers.py | coverart_redirect/loggers.py | import raven
import raven.transport.threaded_requests
from raven.handlers.logging import SentryHandler
from raven.conf import setup_logging
import logging
class MissingRavenClient(raven.Client):
"""Raven client class that is used as a placeholder.
This is done to make sure that calls to functions in the client don't fail
even if the client is not initialized. Sentry server might be missing, but
we don't want to check if it actually exists in every place exception is
captured.
"""
captureException = lambda self, *args, **kwargs: None
captureMessage = lambda self, *args, **kwargs: None
_sentry = MissingRavenClient() # type: raven.Client
def get_sentry():
return _sentry
def init_raven_client(dsn):
global _sentry
_sentry = raven.Client(
dsn=dsn,
transport=raven.transport.threaded_requests.ThreadedRequestsHTTPTransport,
ignore_exceptions={'KeyboardInterrupt'},
logging=True,
)
sentry_errors_logger = logging.getLogger("sentry.errors")
sentry_errors_logger.addHandler(logging.StreamHandler())
handler = SentryHandler(_sentry)
handler.setLevel(logging.ERROR)
setup_logging(handler)
| import raven
import raven.transport.threaded_requests
from raven.handlers.logging import SentryHandler
from raven.conf import setup_logging
from werkzeug.exceptions import HTTPException
from exceptions import KeyboardInterrupt
import logging
class MissingRavenClient(raven.Client):
"""Raven client class that is used as a placeholder.
This is done to make sure that calls to functions in the client don't fail
even if the client is not initialized. Sentry server might be missing, but
we don't want to check if it actually exists in every place exception is
captured.
"""
captureException = lambda self, *args, **kwargs: None
captureMessage = lambda self, *args, **kwargs: None
_sentry = MissingRavenClient() # type: raven.Client
def get_sentry():
return _sentry
def init_raven_client(dsn):
global _sentry
_sentry = raven.Client(
dsn=dsn,
transport=raven.transport.threaded_requests.ThreadedRequestsHTTPTransport,
ignore_exceptions={KeyboardInterrupt, HTTPException},
logging=True,
)
sentry_errors_logger = logging.getLogger("sentry.errors")
sentry_errors_logger.addHandler(logging.StreamHandler())
handler = SentryHandler(_sentry)
handler.setLevel(logging.ERROR)
setup_logging(handler)
| Exclude HTTP exceptions from logging by Raven | Exclude HTTP exceptions from logging by Raven
| Python | mit | metabrainz/coverart_redirect,metabrainz/coverart_redirect,metabrainz/coverart_redirect | import raven
import raven.transport.threaded_requests
from raven.handlers.logging import SentryHandler
from raven.conf import setup_logging
+ from werkzeug.exceptions import HTTPException
+ from exceptions import KeyboardInterrupt
import logging
class MissingRavenClient(raven.Client):
"""Raven client class that is used as a placeholder.
This is done to make sure that calls to functions in the client don't fail
even if the client is not initialized. Sentry server might be missing, but
we don't want to check if it actually exists in every place exception is
captured.
"""
captureException = lambda self, *args, **kwargs: None
captureMessage = lambda self, *args, **kwargs: None
_sentry = MissingRavenClient() # type: raven.Client
def get_sentry():
return _sentry
def init_raven_client(dsn):
global _sentry
_sentry = raven.Client(
dsn=dsn,
transport=raven.transport.threaded_requests.ThreadedRequestsHTTPTransport,
- ignore_exceptions={'KeyboardInterrupt'},
+ ignore_exceptions={KeyboardInterrupt, HTTPException},
logging=True,
)
sentry_errors_logger = logging.getLogger("sentry.errors")
sentry_errors_logger.addHandler(logging.StreamHandler())
handler = SentryHandler(_sentry)
handler.setLevel(logging.ERROR)
setup_logging(handler)
| Exclude HTTP exceptions from logging by Raven | ## Code Before:
import raven
import raven.transport.threaded_requests
from raven.handlers.logging import SentryHandler
from raven.conf import setup_logging
import logging
class MissingRavenClient(raven.Client):
"""Raven client class that is used as a placeholder.
This is done to make sure that calls to functions in the client don't fail
even if the client is not initialized. Sentry server might be missing, but
we don't want to check if it actually exists in every place exception is
captured.
"""
captureException = lambda self, *args, **kwargs: None
captureMessage = lambda self, *args, **kwargs: None
_sentry = MissingRavenClient() # type: raven.Client
def get_sentry():
return _sentry
def init_raven_client(dsn):
global _sentry
_sentry = raven.Client(
dsn=dsn,
transport=raven.transport.threaded_requests.ThreadedRequestsHTTPTransport,
ignore_exceptions={'KeyboardInterrupt'},
logging=True,
)
sentry_errors_logger = logging.getLogger("sentry.errors")
sentry_errors_logger.addHandler(logging.StreamHandler())
handler = SentryHandler(_sentry)
handler.setLevel(logging.ERROR)
setup_logging(handler)
## Instruction:
Exclude HTTP exceptions from logging by Raven
## Code After:
import raven
import raven.transport.threaded_requests
from raven.handlers.logging import SentryHandler
from raven.conf import setup_logging
from werkzeug.exceptions import HTTPException
from exceptions import KeyboardInterrupt
import logging
class MissingRavenClient(raven.Client):
"""Raven client class that is used as a placeholder.
This is done to make sure that calls to functions in the client don't fail
even if the client is not initialized. Sentry server might be missing, but
we don't want to check if it actually exists in every place exception is
captured.
"""
captureException = lambda self, *args, **kwargs: None
captureMessage = lambda self, *args, **kwargs: None
_sentry = MissingRavenClient() # type: raven.Client
def get_sentry():
return _sentry
def init_raven_client(dsn):
global _sentry
_sentry = raven.Client(
dsn=dsn,
transport=raven.transport.threaded_requests.ThreadedRequestsHTTPTransport,
ignore_exceptions={KeyboardInterrupt, HTTPException},
logging=True,
)
sentry_errors_logger = logging.getLogger("sentry.errors")
sentry_errors_logger.addHandler(logging.StreamHandler())
handler = SentryHandler(_sentry)
handler.setLevel(logging.ERROR)
setup_logging(handler)
| // ... existing code ...
from raven.handlers.logging import SentryHandler
from raven.conf import setup_logging
from werkzeug.exceptions import HTTPException
from exceptions import KeyboardInterrupt
import logging
// ... modified code ...
dsn=dsn,
transport=raven.transport.threaded_requests.ThreadedRequestsHTTPTransport,
ignore_exceptions={KeyboardInterrupt, HTTPException},
logging=True,
)
// ... rest of the code ... |
3394278f379763dae9db34f3b528a229b8f06bc6 | tempora/tests/test_timing.py | tempora/tests/test_timing.py | import datetime
import time
import contextlib
import os
from unittest import mock
import pytest
from tempora import timing
def test_IntervalGovernor():
"""
IntervalGovernor should prevent a function from being called more than
once per interval.
"""
func_under_test = mock.MagicMock()
# to look like a function, it needs a __name__ attribute
func_under_test.__name__ = 'func_under_test'
interval = datetime.timedelta(seconds=1)
governed = timing.IntervalGovernor(interval)(func_under_test)
governed('a')
governed('b')
governed(3, 'sir')
func_under_test.assert_called_once_with('a')
@pytest.mark.skipif("not hasattr(time, 'tzset')")
@pytest.fixture
def alt_tz(monkeypatch):
@contextlib.contextmanager
def change():
val = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
with monkeypatch.context() as ctx:
ctx.setitem(os.environ, 'TZ', val)
time.tzset()
yield
time.tzset()
return change()
def test_Stopwatch_timezone_change(alt_tz):
"""
The stopwatch should provide a consistent duration even
if the timezone changes.
"""
watch = timing.Stopwatch()
with alt_tz:
assert abs(watch.split().total_seconds()) < 0.1
| import datetime
import time
import contextlib
import os
from unittest import mock
import pytest
from tempora import timing
def test_IntervalGovernor():
"""
IntervalGovernor should prevent a function from being called more than
once per interval.
"""
func_under_test = mock.MagicMock()
# to look like a function, it needs a __name__ attribute
func_under_test.__name__ = 'func_under_test'
interval = datetime.timedelta(seconds=1)
governed = timing.IntervalGovernor(interval)(func_under_test)
governed('a')
governed('b')
governed(3, 'sir')
func_under_test.assert_called_once_with('a')
@pytest.fixture
def alt_tz(monkeypatch):
if not hasattr(time, 'tzset'):
pytest.skip("tzset not available")
@contextlib.contextmanager
def change():
val = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
with monkeypatch.context() as ctx:
ctx.setitem(os.environ, 'TZ', val)
time.tzset()
yield
time.tzset()
return change()
def test_Stopwatch_timezone_change(alt_tz):
"""
The stopwatch should provide a consistent duration even
if the timezone changes.
"""
watch = timing.Stopwatch()
with alt_tz:
assert abs(watch.split().total_seconds()) < 0.1
| Revert "Use pytest.mark to selectively skip test." | Revert "Use pytest.mark to selectively skip test."
Markers can not be applied to fixtures (https://docs.pytest.org/en/latest/reference/reference.html#marks). Fixes #16.
This reverts commit 14d532af265e35af33a28d61a68d545993fc5b78.
| Python | mit | jaraco/tempora | import datetime
import time
import contextlib
import os
from unittest import mock
import pytest
from tempora import timing
def test_IntervalGovernor():
"""
IntervalGovernor should prevent a function from being called more than
once per interval.
"""
func_under_test = mock.MagicMock()
# to look like a function, it needs a __name__ attribute
func_under_test.__name__ = 'func_under_test'
interval = datetime.timedelta(seconds=1)
governed = timing.IntervalGovernor(interval)(func_under_test)
governed('a')
governed('b')
governed(3, 'sir')
func_under_test.assert_called_once_with('a')
- @pytest.mark.skipif("not hasattr(time, 'tzset')")
@pytest.fixture
def alt_tz(monkeypatch):
+ if not hasattr(time, 'tzset'):
+ pytest.skip("tzset not available")
+
@contextlib.contextmanager
def change():
val = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
with monkeypatch.context() as ctx:
ctx.setitem(os.environ, 'TZ', val)
time.tzset()
yield
time.tzset()
return change()
def test_Stopwatch_timezone_change(alt_tz):
"""
The stopwatch should provide a consistent duration even
if the timezone changes.
"""
watch = timing.Stopwatch()
with alt_tz:
assert abs(watch.split().total_seconds()) < 0.1
| Revert "Use pytest.mark to selectively skip test." | ## Code Before:
import datetime
import time
import contextlib
import os
from unittest import mock
import pytest
from tempora import timing
def test_IntervalGovernor():
"""
IntervalGovernor should prevent a function from being called more than
once per interval.
"""
func_under_test = mock.MagicMock()
# to look like a function, it needs a __name__ attribute
func_under_test.__name__ = 'func_under_test'
interval = datetime.timedelta(seconds=1)
governed = timing.IntervalGovernor(interval)(func_under_test)
governed('a')
governed('b')
governed(3, 'sir')
func_under_test.assert_called_once_with('a')
@pytest.mark.skipif("not hasattr(time, 'tzset')")
@pytest.fixture
def alt_tz(monkeypatch):
@contextlib.contextmanager
def change():
val = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
with monkeypatch.context() as ctx:
ctx.setitem(os.environ, 'TZ', val)
time.tzset()
yield
time.tzset()
return change()
def test_Stopwatch_timezone_change(alt_tz):
"""
The stopwatch should provide a consistent duration even
if the timezone changes.
"""
watch = timing.Stopwatch()
with alt_tz:
assert abs(watch.split().total_seconds()) < 0.1
## Instruction:
Revert "Use pytest.mark to selectively skip test."
## Code After:
import datetime
import time
import contextlib
import os
from unittest import mock
import pytest
from tempora import timing
def test_IntervalGovernor():
"""
IntervalGovernor should prevent a function from being called more than
once per interval.
"""
func_under_test = mock.MagicMock()
# to look like a function, it needs a __name__ attribute
func_under_test.__name__ = 'func_under_test'
interval = datetime.timedelta(seconds=1)
governed = timing.IntervalGovernor(interval)(func_under_test)
governed('a')
governed('b')
governed(3, 'sir')
func_under_test.assert_called_once_with('a')
@pytest.fixture
def alt_tz(monkeypatch):
if not hasattr(time, 'tzset'):
pytest.skip("tzset not available")
@contextlib.contextmanager
def change():
val = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
with monkeypatch.context() as ctx:
ctx.setitem(os.environ, 'TZ', val)
time.tzset()
yield
time.tzset()
return change()
def test_Stopwatch_timezone_change(alt_tz):
"""
The stopwatch should provide a consistent duration even
if the timezone changes.
"""
watch = timing.Stopwatch()
with alt_tz:
assert abs(watch.split().total_seconds()) < 0.1
| # ... existing code ...
@pytest.fixture
def alt_tz(monkeypatch):
if not hasattr(time, 'tzset'):
pytest.skip("tzset not available")
@contextlib.contextmanager
def change():
# ... rest of the code ... |
24cbbd24e6398aa11956ac48282bd907806284c3 | genderbot.py | genderbot.py | import re
from twitterbot import TwitterBot
import wikipedia
class Genderbot(TwitterBot):
boring_article_regex = (r"municipality|village|town|football|genus|family|"
"administrative|district|community|region|hamlet|"
"school|actor|mountain|basketball|city|species|film|"
"county|located|politician|professional|settlement")
def tweet(self):
article = self.__random_wikipedia_article()
match = re.search(r"\bis [^.?]+", article.content, re.UNICODE)
if match:
status = self.__format_status(match.group(0), article.url)
if self.__is_interesting(status):
self.post_tweet(status)
def __format_status(self, is_phrase, url):
status = 'gender %s' % (is_phrase)
if len(status) > 114: status = status[0:113] + '...'
return status + ' %s' % (url)
def __is_interesting(self, status):
boring_match = re.search(Genderbot.boring_article_regex, status, re.UNICODE)
return boring_match is None
def __random_wikipedia_article(self):
random_title = wikipedia.random(pages=1)
return wikipedia.page(title=random_title)
if __name__ == "__main__":
try:
Genderbot("CustomGender").tweet()
except:
pass
| import re
from twitterbot import TwitterBot
import wikipedia
class Genderbot(TwitterBot):
boring_regex = (r"municipality|village|town|football|genus|family|"
"administrative|district|community|region|hamlet|"
"school|actor|mountain|basketball|city|species|film|"
"county|located|politician|professional|settlement|"
"river|lake|province|replaced|origin|band|park|song"
"approximately|north|south|east|west|business")
def tweet(self):
article = self.__random_wikipedia_article()
match = re.search(r"\bis [^.?]+", article.content, re.UNICODE)
if match:
status = self.__format_status(match.group(0), article.url)
if self.__is_interesting(status):
self.post_tweet(status)
def __format_status(self, is_phrase, url):
status = 'gender %s' % (is_phrase)
if len(status) > 114: status = status[0:113] + '...'
return status + ' %s' % (url)
def __is_interesting(self, status):
flags = re.UNICODE | re.IGNORECASE
boring = re.search(Genderbot.boring_regex, status, flags)
return boring is None
def __random_wikipedia_article(self):
random_title = wikipedia.random(pages=1)
return wikipedia.page(title=random_title)
if __name__ == "__main__":
try:
Genderbot("CustomGender").tweet()
except:
pass
| Tweak boring regex to exclude more terms | Tweak boring regex to exclude more terms
| Python | mit | DanielleSucher/genderbot | import re
from twitterbot import TwitterBot
import wikipedia
class Genderbot(TwitterBot):
- boring_article_regex = (r"municipality|village|town|football|genus|family|"
+ boring_regex = (r"municipality|village|town|football|genus|family|"
- "administrative|district|community|region|hamlet|"
+ "administrative|district|community|region|hamlet|"
- "school|actor|mountain|basketball|city|species|film|"
+ "school|actor|mountain|basketball|city|species|film|"
- "county|located|politician|professional|settlement")
+ "county|located|politician|professional|settlement|"
+ "river|lake|province|replaced|origin|band|park|song"
+ "approximately|north|south|east|west|business")
def tweet(self):
article = self.__random_wikipedia_article()
match = re.search(r"\bis [^.?]+", article.content, re.UNICODE)
if match:
status = self.__format_status(match.group(0), article.url)
if self.__is_interesting(status):
self.post_tweet(status)
def __format_status(self, is_phrase, url):
status = 'gender %s' % (is_phrase)
if len(status) > 114: status = status[0:113] + '...'
return status + ' %s' % (url)
def __is_interesting(self, status):
+ flags = re.UNICODE | re.IGNORECASE
- boring_match = re.search(Genderbot.boring_article_regex, status, re.UNICODE)
+ boring = re.search(Genderbot.boring_regex, status, flags)
- return boring_match is None
+ return boring is None
def __random_wikipedia_article(self):
random_title = wikipedia.random(pages=1)
return wikipedia.page(title=random_title)
if __name__ == "__main__":
try:
Genderbot("CustomGender").tweet()
except:
pass
| Tweak boring regex to exclude more terms | ## Code Before:
import re
from twitterbot import TwitterBot
import wikipedia
class Genderbot(TwitterBot):
boring_article_regex = (r"municipality|village|town|football|genus|family|"
"administrative|district|community|region|hamlet|"
"school|actor|mountain|basketball|city|species|film|"
"county|located|politician|professional|settlement")
def tweet(self):
article = self.__random_wikipedia_article()
match = re.search(r"\bis [^.?]+", article.content, re.UNICODE)
if match:
status = self.__format_status(match.group(0), article.url)
if self.__is_interesting(status):
self.post_tweet(status)
def __format_status(self, is_phrase, url):
status = 'gender %s' % (is_phrase)
if len(status) > 114: status = status[0:113] + '...'
return status + ' %s' % (url)
def __is_interesting(self, status):
boring_match = re.search(Genderbot.boring_article_regex, status, re.UNICODE)
return boring_match is None
def __random_wikipedia_article(self):
random_title = wikipedia.random(pages=1)
return wikipedia.page(title=random_title)
if __name__ == "__main__":
try:
Genderbot("CustomGender").tweet()
except:
pass
## Instruction:
Tweak boring regex to exclude more terms
## Code After:
import re
from twitterbot import TwitterBot
import wikipedia
class Genderbot(TwitterBot):
boring_regex = (r"municipality|village|town|football|genus|family|"
"administrative|district|community|region|hamlet|"
"school|actor|mountain|basketball|city|species|film|"
"county|located|politician|professional|settlement|"
"river|lake|province|replaced|origin|band|park|song"
"approximately|north|south|east|west|business")
def tweet(self):
article = self.__random_wikipedia_article()
match = re.search(r"\bis [^.?]+", article.content, re.UNICODE)
if match:
status = self.__format_status(match.group(0), article.url)
if self.__is_interesting(status):
self.post_tweet(status)
def __format_status(self, is_phrase, url):
status = 'gender %s' % (is_phrase)
if len(status) > 114: status = status[0:113] + '...'
return status + ' %s' % (url)
def __is_interesting(self, status):
flags = re.UNICODE | re.IGNORECASE
boring = re.search(Genderbot.boring_regex, status, flags)
return boring is None
def __random_wikipedia_article(self):
random_title = wikipedia.random(pages=1)
return wikipedia.page(title=random_title)
if __name__ == "__main__":
try:
Genderbot("CustomGender").tweet()
except:
pass
| // ... existing code ...
class Genderbot(TwitterBot):
boring_regex = (r"municipality|village|town|football|genus|family|"
"administrative|district|community|region|hamlet|"
"school|actor|mountain|basketball|city|species|film|"
"county|located|politician|professional|settlement|"
"river|lake|province|replaced|origin|band|park|song"
"approximately|north|south|east|west|business")
def tweet(self):
// ... modified code ...
def __is_interesting(self, status):
flags = re.UNICODE | re.IGNORECASE
boring = re.search(Genderbot.boring_regex, status, flags)
return boring is None
def __random_wikipedia_article(self):
// ... rest of the code ... |
85d684369e72aa2968f9ffbd0632f84558e1b44e | tests/test_vector2_dot.py | tests/test_vector2_dot.py | from ppb_vector import Vector2
from math import isclose, sqrt
import pytest # type: ignore
from hypothesis import assume, given, note
from utils import floats, vectors
@given(x=vectors(), y=vectors())
def test_dot_commutes(x: Vector2, y: Vector2):
assert x * y == y * x
MAGNITUDE=1e10
@given(x=vectors(max_magnitude=MAGNITUDE), z=vectors(max_magnitude=MAGNITUDE),
y=vectors(max_magnitude=sqrt(MAGNITUDE)),
scalar=floats(max_magnitude=sqrt(MAGNITUDE)))
def test_dot_linear(x: Vector2, y: Vector2, z: Vector2, scalar: float):
"""Test that x · (λ y + z) = λ x·y + x·z"""
inner, outer = x * (scalar * y + z), scalar * x * y + x * z
note(f"inner: {inner}")
note(f"outer: {outer}")
assert isclose(inner, outer, abs_tol=1e-5, rel_tol=1e-5)
| from ppb_vector import Vector2
from math import isclose, sqrt
import pytest # type: ignore
from hypothesis import assume, given, note
from utils import floats, vectors
@given(x=vectors(), y=vectors())
def test_dot_commutes(x: Vector2, y: Vector2):
assert x * y == y * x
@given(x=vectors())
def test_dot_length(x: Vector2):
assert isclose(x * x, x.length * x.length)
MAGNITUDE=1e10
@given(x=vectors(max_magnitude=MAGNITUDE), z=vectors(max_magnitude=MAGNITUDE),
y=vectors(max_magnitude=sqrt(MAGNITUDE)),
scalar=floats(max_magnitude=sqrt(MAGNITUDE)))
def test_dot_linear(x: Vector2, y: Vector2, z: Vector2, scalar: float):
"""Test that x · (λ y + z) = λ x·y + x·z"""
inner, outer = x * (scalar * y + z), scalar * x * y + x * z
note(f"inner: {inner}")
note(f"outer: {outer}")
assert isclose(inner, outer, abs_tol=1e-5, rel_tol=1e-5)
| Test that x² == |x|² | tests/dot: Test that x² == |x|²
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector | from ppb_vector import Vector2
from math import isclose, sqrt
import pytest # type: ignore
from hypothesis import assume, given, note
from utils import floats, vectors
@given(x=vectors(), y=vectors())
def test_dot_commutes(x: Vector2, y: Vector2):
assert x * y == y * x
+
+ @given(x=vectors())
+ def test_dot_length(x: Vector2):
+ assert isclose(x * x, x.length * x.length)
MAGNITUDE=1e10
@given(x=vectors(max_magnitude=MAGNITUDE), z=vectors(max_magnitude=MAGNITUDE),
y=vectors(max_magnitude=sqrt(MAGNITUDE)),
scalar=floats(max_magnitude=sqrt(MAGNITUDE)))
def test_dot_linear(x: Vector2, y: Vector2, z: Vector2, scalar: float):
"""Test that x · (λ y + z) = λ x·y + x·z"""
inner, outer = x * (scalar * y + z), scalar * x * y + x * z
note(f"inner: {inner}")
note(f"outer: {outer}")
assert isclose(inner, outer, abs_tol=1e-5, rel_tol=1e-5)
| Test that x² == |x|² | ## Code Before:
from ppb_vector import Vector2
from math import isclose, sqrt
import pytest # type: ignore
from hypothesis import assume, given, note
from utils import floats, vectors
@given(x=vectors(), y=vectors())
def test_dot_commutes(x: Vector2, y: Vector2):
assert x * y == y * x
MAGNITUDE=1e10
@given(x=vectors(max_magnitude=MAGNITUDE), z=vectors(max_magnitude=MAGNITUDE),
y=vectors(max_magnitude=sqrt(MAGNITUDE)),
scalar=floats(max_magnitude=sqrt(MAGNITUDE)))
def test_dot_linear(x: Vector2, y: Vector2, z: Vector2, scalar: float):
"""Test that x · (λ y + z) = λ x·y + x·z"""
inner, outer = x * (scalar * y + z), scalar * x * y + x * z
note(f"inner: {inner}")
note(f"outer: {outer}")
assert isclose(inner, outer, abs_tol=1e-5, rel_tol=1e-5)
## Instruction:
Test that x² == |x|²
## Code After:
from ppb_vector import Vector2
from math import isclose, sqrt
import pytest # type: ignore
from hypothesis import assume, given, note
from utils import floats, vectors
@given(x=vectors(), y=vectors())
def test_dot_commutes(x: Vector2, y: Vector2):
assert x * y == y * x
@given(x=vectors())
def test_dot_length(x: Vector2):
assert isclose(x * x, x.length * x.length)
MAGNITUDE=1e10
@given(x=vectors(max_magnitude=MAGNITUDE), z=vectors(max_magnitude=MAGNITUDE),
y=vectors(max_magnitude=sqrt(MAGNITUDE)),
scalar=floats(max_magnitude=sqrt(MAGNITUDE)))
def test_dot_linear(x: Vector2, y: Vector2, z: Vector2, scalar: float):
"""Test that x · (λ y + z) = λ x·y + x·z"""
inner, outer = x * (scalar * y + z), scalar * x * y + x * z
note(f"inner: {inner}")
note(f"outer: {outer}")
assert isclose(inner, outer, abs_tol=1e-5, rel_tol=1e-5)
| # ... existing code ...
assert x * y == y * x
@given(x=vectors())
def test_dot_length(x: Vector2):
assert isclose(x * x, x.length * x.length)
MAGNITUDE=1e10
# ... rest of the code ... |
492004049da87744cd96a6e6afeb9a6239a8ac44 | ocradmin/lib/nodetree/registry.py | ocradmin/lib/nodetree/registry.py |
class NotRegistered(KeyError):
pass
__all__ = ["NodeRegistry", "nodes"]
class NodeRegistry(dict):
NotRegistered = NotRegistered
def register(self, node):
"""Register a node in the node registry.
The node will be automatically instantiated if not already an
instance.
"""
self[node.name] = inspect.isclass(node) and node() or node
def unregister(self, name):
"""Unregister node by name."""
try:
# Might be a node class
name = name.name
except AttributeError:
pass
self.pop(name)
def filter_types(self, type):
"""Return all nodes of a specific type."""
return dict((name, node) for name, node in self.iteritems()
if node.type == type)
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
raise self.NotRegistered(key)
def pop(self, key, *args):
try:
return dict.pop(self, key, *args)
except KeyError:
raise self.NotRegistered(key)
nodes = NodeRegistry()
|
import inspect
class NotRegistered(KeyError):
pass
class NodeRegistry(dict):
NotRegistered = NotRegistered
def register(self, node):
"""Register a node class in the node registry."""
self[node.name] = inspect.isclass(node) and node or node.__class__
def unregister(self, name):
"""Unregister node by name."""
try:
# Might be a node class
name = name.name
except AttributeError:
pass
self.pop(name)
def get_by_attr(self, attr, value=None):
"""Return all nodes of a specific type that have a matching attr.
If `value` is given, only return nodes where the attr value matches."""
ret = {}
for name, node in self.iteritems():
if hasattr(node, attr) and value is None\
or hasattr(node, name) and getattr(node, name) == value:
ret[name] = node
return ret
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
raise self.NotRegistered(key)
def pop(self, key, *args):
try:
return dict.pop(self, key, *args)
except KeyError:
raise self.NotRegistered(key)
nodes = NodeRegistry()
| Fix missing import. Add method to get all nodes with a particular attribute | Fix missing import. Add method to get all nodes with a particular attribute
| Python | apache-2.0 | vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium | +
+ import inspect
class NotRegistered(KeyError):
pass
-
-
- __all__ = ["NodeRegistry", "nodes"]
class NodeRegistry(dict):
NotRegistered = NotRegistered
def register(self, node):
- """Register a node in the node registry.
+ """Register a node class in the node registry."""
-
- The node will be automatically instantiated if not already an
- instance.
-
- """
- self[node.name] = inspect.isclass(node) and node() or node
+ self[node.name] = inspect.isclass(node) and node or node.__class__
def unregister(self, name):
"""Unregister node by name."""
try:
# Might be a node class
name = name.name
except AttributeError:
pass
self.pop(name)
- def filter_types(self, type):
+ def get_by_attr(self, attr, value=None):
- """Return all nodes of a specific type."""
+ """Return all nodes of a specific type that have a matching attr.
- return dict((name, node) for name, node in self.iteritems()
- if node.type == type)
+ If `value` is given, only return nodes where the attr value matches."""
+ ret = {}
+ for name, node in self.iteritems():
+ if hasattr(node, attr) and value is None\
+ or hasattr(node, name) and getattr(node, name) == value:
+ ret[name] = node
+ return ret
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
raise self.NotRegistered(key)
def pop(self, key, *args):
try:
return dict.pop(self, key, *args)
except KeyError:
raise self.NotRegistered(key)
nodes = NodeRegistry()
| Fix missing import. Add method to get all nodes with a particular attribute | ## Code Before:
class NotRegistered(KeyError):
pass
__all__ = ["NodeRegistry", "nodes"]
class NodeRegistry(dict):
NotRegistered = NotRegistered
def register(self, node):
"""Register a node in the node registry.
The node will be automatically instantiated if not already an
instance.
"""
self[node.name] = inspect.isclass(node) and node() or node
def unregister(self, name):
"""Unregister node by name."""
try:
# Might be a node class
name = name.name
except AttributeError:
pass
self.pop(name)
def filter_types(self, type):
"""Return all nodes of a specific type."""
return dict((name, node) for name, node in self.iteritems()
if node.type == type)
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
raise self.NotRegistered(key)
def pop(self, key, *args):
try:
return dict.pop(self, key, *args)
except KeyError:
raise self.NotRegistered(key)
nodes = NodeRegistry()
## Instruction:
Fix missing import. Add method to get all nodes with a particular attribute
## Code After:
import inspect
class NotRegistered(KeyError):
pass
class NodeRegistry(dict):
NotRegistered = NotRegistered
def register(self, node):
"""Register a node class in the node registry."""
self[node.name] = inspect.isclass(node) and node or node.__class__
def unregister(self, name):
"""Unregister node by name."""
try:
# Might be a node class
name = name.name
except AttributeError:
pass
self.pop(name)
def get_by_attr(self, attr, value=None):
"""Return all nodes of a specific type that have a matching attr.
If `value` is given, only return nodes where the attr value matches."""
ret = {}
for name, node in self.iteritems():
if hasattr(node, attr) and value is None\
or hasattr(node, name) and getattr(node, name) == value:
ret[name] = node
return ret
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
raise self.NotRegistered(key)
def pop(self, key, *args):
try:
return dict.pop(self, key, *args)
except KeyError:
raise self.NotRegistered(key)
nodes = NodeRegistry()
| # ... existing code ...
import inspect
class NotRegistered(KeyError):
pass
# ... modified code ...
def register(self, node):
"""Register a node class in the node registry."""
self[node.name] = inspect.isclass(node) and node or node.__class__
def unregister(self, name):
...
self.pop(name)
def get_by_attr(self, attr, value=None):
"""Return all nodes of a specific type that have a matching attr.
If `value` is given, only return nodes where the attr value matches."""
ret = {}
for name, node in self.iteritems():
if hasattr(node, attr) and value is None\
or hasattr(node, name) and getattr(node, name) == value:
ret[name] = node
return ret
def __getitem__(self, key):
# ... rest of the code ... |
7fd76d87cfda8f02912985cb3cf650ee8ff2e11e | mica/report/tests/test_write_report.py | mica/report/tests/test_write_report.py | import tempfile
import os
import shutil
import pytest
from .. import report
try:
import Ska.DBI
with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db:
assert db.conn._is_connected == 1
HAS_SYBASE_ACCESS = True
except:
HAS_SYBASE_ACCESS = False
HAS_SC_ARCHIVE = os.path.exists(report.starcheck.FILES['data_root'])
@pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access')
@pytest.mark.skipif('not HAS_SC_ARCHIVE', reason='Report test requires mica starcheck archive')
def test_write_reports():
"""
Make a report and database
"""
tempdir = tempfile.mkdtemp()
# Get a temporary file, but then delete it, because report.py will only
# make a new table if the supplied file doesn't exist
fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3')
os.unlink(fn)
report.REPORT_ROOT = tempdir
report.REPORT_SERVER = fn
for obsid in [20001, 15175, 54778]:
report.main(obsid)
os.unlink(fn)
shutil.rmtree(tempdir)
| import tempfile
import os
import shutil
import pytest
from .. import report
try:
import Ska.DBI
with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db:
HAS_SYBASE_ACCESS = True
except:
HAS_SYBASE_ACCESS = False
HAS_SC_ARCHIVE = os.path.exists(report.starcheck.FILES['data_root'])
@pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access')
@pytest.mark.skipif('not HAS_SC_ARCHIVE', reason='Report test requires mica starcheck archive')
def test_write_reports():
"""
Make a report and database
"""
tempdir = tempfile.mkdtemp()
# Get a temporary file, but then delete it, because report.py will only
# make a new table if the supplied file doesn't exist
fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3')
os.unlink(fn)
report.REPORT_ROOT = tempdir
report.REPORT_SERVER = fn
for obsid in [20001, 15175, 54778]:
report.main(obsid)
os.unlink(fn)
shutil.rmtree(tempdir)
| Remove py2 Ska.DBI assert in report test | Remove py2 Ska.DBI assert in report test
| Python | bsd-3-clause | sot/mica,sot/mica | import tempfile
import os
import shutil
import pytest
from .. import report
try:
import Ska.DBI
with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db:
- assert db.conn._is_connected == 1
HAS_SYBASE_ACCESS = True
except:
HAS_SYBASE_ACCESS = False
HAS_SC_ARCHIVE = os.path.exists(report.starcheck.FILES['data_root'])
@pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access')
@pytest.mark.skipif('not HAS_SC_ARCHIVE', reason='Report test requires mica starcheck archive')
def test_write_reports():
"""
Make a report and database
"""
tempdir = tempfile.mkdtemp()
# Get a temporary file, but then delete it, because report.py will only
# make a new table if the supplied file doesn't exist
fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3')
os.unlink(fn)
report.REPORT_ROOT = tempdir
report.REPORT_SERVER = fn
for obsid in [20001, 15175, 54778]:
report.main(obsid)
os.unlink(fn)
shutil.rmtree(tempdir)
| Remove py2 Ska.DBI assert in report test | ## Code Before:
import tempfile
import os
import shutil
import pytest
from .. import report
try:
import Ska.DBI
with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db:
assert db.conn._is_connected == 1
HAS_SYBASE_ACCESS = True
except:
HAS_SYBASE_ACCESS = False
HAS_SC_ARCHIVE = os.path.exists(report.starcheck.FILES['data_root'])
@pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access')
@pytest.mark.skipif('not HAS_SC_ARCHIVE', reason='Report test requires mica starcheck archive')
def test_write_reports():
"""
Make a report and database
"""
tempdir = tempfile.mkdtemp()
# Get a temporary file, but then delete it, because report.py will only
# make a new table if the supplied file doesn't exist
fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3')
os.unlink(fn)
report.REPORT_ROOT = tempdir
report.REPORT_SERVER = fn
for obsid in [20001, 15175, 54778]:
report.main(obsid)
os.unlink(fn)
shutil.rmtree(tempdir)
## Instruction:
Remove py2 Ska.DBI assert in report test
## Code After:
import tempfile
import os
import shutil
import pytest
from .. import report
try:
import Ska.DBI
with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db:
HAS_SYBASE_ACCESS = True
except:
HAS_SYBASE_ACCESS = False
HAS_SC_ARCHIVE = os.path.exists(report.starcheck.FILES['data_root'])
@pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access')
@pytest.mark.skipif('not HAS_SC_ARCHIVE', reason='Report test requires mica starcheck archive')
def test_write_reports():
"""
Make a report and database
"""
tempdir = tempfile.mkdtemp()
# Get a temporary file, but then delete it, because report.py will only
# make a new table if the supplied file doesn't exist
fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3')
os.unlink(fn)
report.REPORT_ROOT = tempdir
report.REPORT_SERVER = fn
for obsid in [20001, 15175, 54778]:
report.main(obsid)
os.unlink(fn)
shutil.rmtree(tempdir)
| // ... existing code ...
import Ska.DBI
with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db:
HAS_SYBASE_ACCESS = True
except:
// ... rest of the code ... |
74d0e710711f1b499ab32784b751adc55e8b7f00 | python/bonetrousle.py | python/bonetrousle.py |
import os
import sys
# n: the integer number of sticks to buy
# k: the integer number of box sizes the store carries
# b: the integer number of boxes to buy
def bonetrousle(n, k, b):
if (minimumValue(k, b) <= n <= maximumValue(k, b)):
return boxesToBuy(n, k, b)
else:
return -1
# The minimum number of sticks that may be purchased
def minimumValue(k, b):
return 0
# The maximum number of sticks that may be purchased
def maximumValue(k, b):
return 100
# One possible solution of boxes that sum to n
def boxesToBuy(n, k, b):
return [0]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
nkb = input().split()
n = int(nkb[0])
k = int(nkb[1])
b = int(nkb[2])
result = bonetrousle(n, k, b)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
|
import os
import sys
# n: the integer number of sticks to buy
# k: the integer number of box sizes the store carries
# b: the integer number of boxes to buy
def bonetrousle(n, k, b):
if (minimumValue(k, b) <= n <= maximumValue(k, b)):
return boxesToBuy(n, k, b)
else:
return -1
# The minimum number of sticks that may be purchased
# Equivalant to: 1 + 2 + 3 ... b
# See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum
def minimumValue(k, b):
return b * (1 + b) / 2
# The maximum number of sticks that may be purchased
# Equivalant to: (k - b + 1) ... (k - 2) + (k -1) + k
# See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum
def maximumValue(k, b):
return b * ((k - b + 1) + k) / 2
# One possible solution of boxes that sum to n
def boxesToBuy(n, k, b):
return [0]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
nkb = input().split()
n = int(nkb[0])
k = int(nkb[1])
b = int(nkb[2])
result = bonetrousle(n, k, b)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
| Implement minimum and maximum values | Implement minimum and maximum values
| Python | mit | rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank |
import os
import sys
# n: the integer number of sticks to buy
# k: the integer number of box sizes the store carries
# b: the integer number of boxes to buy
def bonetrousle(n, k, b):
if (minimumValue(k, b) <= n <= maximumValue(k, b)):
return boxesToBuy(n, k, b)
else:
return -1
# The minimum number of sticks that may be purchased
+ # Equivalant to: 1 + 2 + 3 ... b
+ # See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum
def minimumValue(k, b):
- return 0
+ return b * (1 + b) / 2
# The maximum number of sticks that may be purchased
+ # Equivalant to: (k - b + 1) ... (k - 2) + (k -1) + k
+ # See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum
def maximumValue(k, b):
- return 100
+ return b * ((k - b + 1) + k) / 2
# One possible solution of boxes that sum to n
def boxesToBuy(n, k, b):
return [0]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
nkb = input().split()
n = int(nkb[0])
k = int(nkb[1])
b = int(nkb[2])
result = bonetrousle(n, k, b)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
| Implement minimum and maximum values | ## Code Before:
import os
import sys
# n: the integer number of sticks to buy
# k: the integer number of box sizes the store carries
# b: the integer number of boxes to buy
def bonetrousle(n, k, b):
if (minimumValue(k, b) <= n <= maximumValue(k, b)):
return boxesToBuy(n, k, b)
else:
return -1
# The minimum number of sticks that may be purchased
def minimumValue(k, b):
return 0
# The maximum number of sticks that may be purchased
def maximumValue(k, b):
return 100
# One possible solution of boxes that sum to n
def boxesToBuy(n, k, b):
return [0]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
nkb = input().split()
n = int(nkb[0])
k = int(nkb[1])
b = int(nkb[2])
result = bonetrousle(n, k, b)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
## Instruction:
Implement minimum and maximum values
## Code After:
import os
import sys
# n: the integer number of sticks to buy
# k: the integer number of box sizes the store carries
# b: the integer number of boxes to buy
def bonetrousle(n, k, b):
if (minimumValue(k, b) <= n <= maximumValue(k, b)):
return boxesToBuy(n, k, b)
else:
return -1
# The minimum number of sticks that may be purchased
# Equivalant to: 1 + 2 + 3 ... b
# See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum
def minimumValue(k, b):
return b * (1 + b) / 2
# The maximum number of sticks that may be purchased
# Equivalant to: (k - b + 1) ... (k - 2) + (k -1) + k
# See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum
def maximumValue(k, b):
return b * ((k - b + 1) + k) / 2
# One possible solution of boxes that sum to n
def boxesToBuy(n, k, b):
return [0]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
nkb = input().split()
n = int(nkb[0])
k = int(nkb[1])
b = int(nkb[2])
result = bonetrousle(n, k, b)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
| ...
# The minimum number of sticks that may be purchased
# Equivalant to: 1 + 2 + 3 ... b
# See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum
def minimumValue(k, b):
return b * (1 + b) / 2
# The maximum number of sticks that may be purchased
# Equivalant to: (k - b + 1) ... (k - 2) + (k -1) + k
# See: https://en.wikipedia.org/wiki/Arithmetic_progression#Sum
def maximumValue(k, b):
return b * ((k - b + 1) + k) / 2
# One possible solution of boxes that sum to n
... |
eb0362c489f63d94d082ee4700dfdc871f68f916 | tests/dal/await_syntax.py | tests/dal/await_syntax.py | from umongo import Document
# Await syntax related tests are stored in a separate file in order to
# catch a SyntaxError when Python doesn't support it
async def test_await_syntax(db):
class Doc(Document):
class Meta:
collection = db.doc
async def test_cursor(cursor):
await cursor.count()
await cursor.to_list(length=10)
cursor.rewind()
await cursor.fetch_next
_ = cursor.next_object()
doc = Doc()
await doc.commit()
cursor = Doc.find()
await test_cursor(cursor)
cursor = doc.find()
await test_cursor(cursor)
await Doc.find_one()
await doc.find_one()
await Doc.ensure_indexes()
await doc.ensure_indexes()
await doc.reload()
await doc.remove()
| from umongo import Document
from umongo.dal.motor_asyncio import MotorAsyncIOReference
# Await syntax related tests are stored in a separate file in order to
# catch a SyntaxError when Python doesn't support it
async def test_await_syntax(db):
class Doc(Document):
class Meta:
collection = db.doc
async def test_cursor(cursor):
await cursor.count()
await cursor.to_list(length=10)
cursor.rewind()
await cursor.fetch_next
_ = cursor.next_object()
doc = Doc()
await doc.commit()
assert doc == await MotorAsyncIOReference(Doc, doc.id).fetch()
cursor = Doc.find()
await test_cursor(cursor)
cursor = doc.find()
await test_cursor(cursor)
await Doc.find_one()
await doc.find_one()
await Doc.ensure_indexes()
await doc.ensure_indexes()
await doc.reload()
await doc.remove()
| Add test for MotorAsyncIOReference await support | Add test for MotorAsyncIOReference await support
| Python | mit | Scille/umongo | from umongo import Document
+ from umongo.dal.motor_asyncio import MotorAsyncIOReference
# Await syntax related tests are stored in a separate file in order to
# catch a SyntaxError when Python doesn't support it
async def test_await_syntax(db):
class Doc(Document):
class Meta:
collection = db.doc
async def test_cursor(cursor):
await cursor.count()
await cursor.to_list(length=10)
cursor.rewind()
await cursor.fetch_next
_ = cursor.next_object()
doc = Doc()
await doc.commit()
+ assert doc == await MotorAsyncIOReference(Doc, doc.id).fetch()
+
cursor = Doc.find()
await test_cursor(cursor)
cursor = doc.find()
await test_cursor(cursor)
await Doc.find_one()
await doc.find_one()
await Doc.ensure_indexes()
await doc.ensure_indexes()
await doc.reload()
await doc.remove()
| Add test for MotorAsyncIOReference await support | ## Code Before:
from umongo import Document
# Await syntax related tests are stored in a separate file in order to
# catch a SyntaxError when Python doesn't support it
async def test_await_syntax(db):
class Doc(Document):
class Meta:
collection = db.doc
async def test_cursor(cursor):
await cursor.count()
await cursor.to_list(length=10)
cursor.rewind()
await cursor.fetch_next
_ = cursor.next_object()
doc = Doc()
await doc.commit()
cursor = Doc.find()
await test_cursor(cursor)
cursor = doc.find()
await test_cursor(cursor)
await Doc.find_one()
await doc.find_one()
await Doc.ensure_indexes()
await doc.ensure_indexes()
await doc.reload()
await doc.remove()
## Instruction:
Add test for MotorAsyncIOReference await support
## Code After:
from umongo import Document
from umongo.dal.motor_asyncio import MotorAsyncIOReference
# Await syntax related tests are stored in a separate file in order to
# catch a SyntaxError when Python doesn't support it
async def test_await_syntax(db):
class Doc(Document):
class Meta:
collection = db.doc
async def test_cursor(cursor):
await cursor.count()
await cursor.to_list(length=10)
cursor.rewind()
await cursor.fetch_next
_ = cursor.next_object()
doc = Doc()
await doc.commit()
assert doc == await MotorAsyncIOReference(Doc, doc.id).fetch()
cursor = Doc.find()
await test_cursor(cursor)
cursor = doc.find()
await test_cursor(cursor)
await Doc.find_one()
await doc.find_one()
await Doc.ensure_indexes()
await doc.ensure_indexes()
await doc.reload()
await doc.remove()
| ...
from umongo import Document
from umongo.dal.motor_asyncio import MotorAsyncIOReference
# Await syntax related tests are stored in a separate file in order to
...
await doc.commit()
assert doc == await MotorAsyncIOReference(Doc, doc.id).fetch()
cursor = Doc.find()
await test_cursor(cursor)
... |
71ef5d2994dbbf4aa993ba1110eb5404de1f6ac3 | test_graph.py | test_graph.py | from __future__ import unicode_literals
import pytest
from graph import Graph
@pytest.fixture()
def graph_empty():
g = Graph()
return g
@pytest.fixture()
def graph_filled():
g = Graph()
g.graph = {
5: set([10]),
10: set([5, 20, 15]),
15: set(),
20: set([5]),
25: set(),
30: set()
}
return g
def test_valid_constructor():
g = Graph()
assert isinstance(g, Graph)
assert isinstance(g.graph, dict)
assert len(g.graph) == 0 and len(g) == 0
def test_invalid_constructor():
with pytest.raises(TypeError):
Graph(10)
def test_add_node_to_empty(graph_empty):
graph_empty.add_node(10)
assert 10 in graph_empty
assert isinstance(graph_empty[10], set) and len(graph_empty[10]) == 0
| from __future__ import unicode_literals
import pytest
from graph import Graph
@pytest.fixture()
def graph_empty():
g = Graph()
return g
@pytest.fixture()
def graph_filled():
g = Graph()
g.graph = {
5: set([10]),
10: set([5, 20, 15]),
15: set(),
20: set([5]),
25: set(),
30: set()
}
return g
def test_valid_constructor():
g = Graph()
assert isinstance(g, Graph)
assert isinstance(g.graph, dict)
assert len(g.graph) == 0 and len(g) == 0
def test_invalid_constructor():
with pytest.raises(TypeError):
Graph(10)
def test_add_node_to_empty(graph_empty):
graph_empty.add_node(40)
assert 40 in graph_empty
assert isinstance(graph_empty[40], set) and len(graph_empty[40]) == 0
def test_add_node_to_filled(graph_filled):
graph_filled.add_node(40)
assert 40 in graph_filled
assert isinstance(graph_filled[40], set)
assert len(graph_filled[40]) == 0
def test_add_node_to_filled_existing_node(graph_filled):
with pytest.raises(KeyError):
graph_filled.add_node(5)
def test_add_node_wrong_type(graph_empty):
with pytest.raises(TypeError):
graph_empty.add_node([1, 2, 3])
| Add further tests for add_node | Add further tests for add_node
| Python | mit | jonathanstallings/data-structures,jay-tyler/data-structures | from __future__ import unicode_literals
import pytest
from graph import Graph
@pytest.fixture()
def graph_empty():
g = Graph()
return g
@pytest.fixture()
def graph_filled():
g = Graph()
g.graph = {
5: set([10]),
10: set([5, 20, 15]),
15: set(),
20: set([5]),
25: set(),
30: set()
}
return g
def test_valid_constructor():
g = Graph()
assert isinstance(g, Graph)
assert isinstance(g.graph, dict)
assert len(g.graph) == 0 and len(g) == 0
def test_invalid_constructor():
with pytest.raises(TypeError):
Graph(10)
def test_add_node_to_empty(graph_empty):
- graph_empty.add_node(10)
+ graph_empty.add_node(40)
- assert 10 in graph_empty
+ assert 40 in graph_empty
- assert isinstance(graph_empty[10], set) and len(graph_empty[10]) == 0
+ assert isinstance(graph_empty[40], set) and len(graph_empty[40]) == 0
+ def test_add_node_to_filled(graph_filled):
+ graph_filled.add_node(40)
+ assert 40 in graph_filled
+ assert isinstance(graph_filled[40], set)
+ assert len(graph_filled[40]) == 0
+
+
+ def test_add_node_to_filled_existing_node(graph_filled):
+ with pytest.raises(KeyError):
+ graph_filled.add_node(5)
+
+
+ def test_add_node_wrong_type(graph_empty):
+ with pytest.raises(TypeError):
+ graph_empty.add_node([1, 2, 3])
+
+ | Add further tests for add_node | ## Code Before:
from __future__ import unicode_literals
import pytest
from graph import Graph
@pytest.fixture()
def graph_empty():
g = Graph()
return g
@pytest.fixture()
def graph_filled():
g = Graph()
g.graph = {
5: set([10]),
10: set([5, 20, 15]),
15: set(),
20: set([5]),
25: set(),
30: set()
}
return g
def test_valid_constructor():
g = Graph()
assert isinstance(g, Graph)
assert isinstance(g.graph, dict)
assert len(g.graph) == 0 and len(g) == 0
def test_invalid_constructor():
with pytest.raises(TypeError):
Graph(10)
def test_add_node_to_empty(graph_empty):
graph_empty.add_node(10)
assert 10 in graph_empty
assert isinstance(graph_empty[10], set) and len(graph_empty[10]) == 0
## Instruction:
Add further tests for add_node
## Code After:
from __future__ import unicode_literals
import pytest
from graph import Graph
@pytest.fixture()
def graph_empty():
g = Graph()
return g
@pytest.fixture()
def graph_filled():
g = Graph()
g.graph = {
5: set([10]),
10: set([5, 20, 15]),
15: set(),
20: set([5]),
25: set(),
30: set()
}
return g
def test_valid_constructor():
g = Graph()
assert isinstance(g, Graph)
assert isinstance(g.graph, dict)
assert len(g.graph) == 0 and len(g) == 0
def test_invalid_constructor():
with pytest.raises(TypeError):
Graph(10)
def test_add_node_to_empty(graph_empty):
graph_empty.add_node(40)
assert 40 in graph_empty
assert isinstance(graph_empty[40], set) and len(graph_empty[40]) == 0
def test_add_node_to_filled(graph_filled):
graph_filled.add_node(40)
assert 40 in graph_filled
assert isinstance(graph_filled[40], set)
assert len(graph_filled[40]) == 0
def test_add_node_to_filled_existing_node(graph_filled):
with pytest.raises(KeyError):
graph_filled.add_node(5)
def test_add_node_wrong_type(graph_empty):
with pytest.raises(TypeError):
graph_empty.add_node([1, 2, 3])
| // ... existing code ...
def test_add_node_to_empty(graph_empty):
graph_empty.add_node(40)
assert 40 in graph_empty
assert isinstance(graph_empty[40], set) and len(graph_empty[40]) == 0
def test_add_node_to_filled(graph_filled):
graph_filled.add_node(40)
assert 40 in graph_filled
assert isinstance(graph_filled[40], set)
assert len(graph_filled[40]) == 0
def test_add_node_to_filled_existing_node(graph_filled):
with pytest.raises(KeyError):
graph_filled.add_node(5)
def test_add_node_wrong_type(graph_empty):
with pytest.raises(TypeError):
graph_empty.add_node([1, 2, 3])
// ... rest of the code ... |
d9ffd877f646b3a5c020ed823d3541135af74fef | tests/test_question.py | tests/test_question.py | from pywatson.question.question import Question
class TestQuestion:
def test___init___basic(self, questions):
question = Question(questions[0]['questionText'])
assert question.question_text == questions[0]['questionText']
def test_ask_question_basic(self, watson):
answer = watson.ask_question('What is the Labour Code?')
assert type(answer) is Answer
| from pywatson.question.evidence_request import EvidenceRequest
from pywatson.question.filter import Filter
from pywatson.question.question import Question
class TestQuestion(object):
"""Unit tests for the Question class"""
def test___init___basic(self, questions):
"""Question is constructed properly with just question_text"""
question = Question(questions[0]['questionText'])
assert question.question_text == questions[0]['questionText']
def test___init___complete(self, questions):
"""Question is constructed properly with all parameters provided"""
q = questions[1]
er = q['evidenceRequest']
evidence_request = EvidenceRequest(er['items'], er['profile'])
filters = [Filter(f['filterType'], f['filterName'], f['values']) for f in q['filters']]
question = Question(question_text=q['questionText'],
answer_assertion=q['answerAssertion'],
category=q['category'],
context=q['context'],
evidence_request=evidence_request,
filters=filters,
formatted_answer=q['formattedAnswer'],
items=q['items'],
lat=q['lat'],
passthru=q['passthru'],
synonym_list=q['synonymList'])
assert question.question_text == q['questionText']
assert question.answer_assertion == q['answerAssertion']
assert question.category == q['category']
assert question.context == q['context']
assert question.evidence_request == er
assert question.filters == filters
| Add complete question constructor test | Add complete question constructor test
| Python | mit | sherlocke/pywatson | + from pywatson.question.evidence_request import EvidenceRequest
+ from pywatson.question.filter import Filter
from pywatson.question.question import Question
- class TestQuestion:
+ class TestQuestion(object):
+ """Unit tests for the Question class"""
+
def test___init___basic(self, questions):
+ """Question is constructed properly with just question_text"""
question = Question(questions[0]['questionText'])
assert question.question_text == questions[0]['questionText']
- def test_ask_question_basic(self, watson):
- answer = watson.ask_question('What is the Labour Code?')
- assert type(answer) is Answer
+ def test___init___complete(self, questions):
+ """Question is constructed properly with all parameters provided"""
+ q = questions[1]
+ er = q['evidenceRequest']
+ evidence_request = EvidenceRequest(er['items'], er['profile'])
+ filters = [Filter(f['filterType'], f['filterName'], f['values']) for f in q['filters']]
+ question = Question(question_text=q['questionText'],
+ answer_assertion=q['answerAssertion'],
+ category=q['category'],
+ context=q['context'],
+ evidence_request=evidence_request,
+ filters=filters,
+ formatted_answer=q['formattedAnswer'],
+ items=q['items'],
+ lat=q['lat'],
+ passthru=q['passthru'],
+ synonym_list=q['synonymList'])
+ assert question.question_text == q['questionText']
+ assert question.answer_assertion == q['answerAssertion']
+ assert question.category == q['category']
+ assert question.context == q['context']
+ assert question.evidence_request == er
+ assert question.filters == filters
+ | Add complete question constructor test | ## Code Before:
from pywatson.question.question import Question
class TestQuestion:
def test___init___basic(self, questions):
question = Question(questions[0]['questionText'])
assert question.question_text == questions[0]['questionText']
def test_ask_question_basic(self, watson):
answer = watson.ask_question('What is the Labour Code?')
assert type(answer) is Answer
## Instruction:
Add complete question constructor test
## Code After:
from pywatson.question.evidence_request import EvidenceRequest
from pywatson.question.filter import Filter
from pywatson.question.question import Question
class TestQuestion(object):
"""Unit tests for the Question class"""
def test___init___basic(self, questions):
"""Question is constructed properly with just question_text"""
question = Question(questions[0]['questionText'])
assert question.question_text == questions[0]['questionText']
def test___init___complete(self, questions):
"""Question is constructed properly with all parameters provided"""
q = questions[1]
er = q['evidenceRequest']
evidence_request = EvidenceRequest(er['items'], er['profile'])
filters = [Filter(f['filterType'], f['filterName'], f['values']) for f in q['filters']]
question = Question(question_text=q['questionText'],
answer_assertion=q['answerAssertion'],
category=q['category'],
context=q['context'],
evidence_request=evidence_request,
filters=filters,
formatted_answer=q['formattedAnswer'],
items=q['items'],
lat=q['lat'],
passthru=q['passthru'],
synonym_list=q['synonymList'])
assert question.question_text == q['questionText']
assert question.answer_assertion == q['answerAssertion']
assert question.category == q['category']
assert question.context == q['context']
assert question.evidence_request == er
assert question.filters == filters
| ...
from pywatson.question.evidence_request import EvidenceRequest
from pywatson.question.filter import Filter
from pywatson.question.question import Question
class TestQuestion(object):
"""Unit tests for the Question class"""
def test___init___basic(self, questions):
"""Question is constructed properly with just question_text"""
question = Question(questions[0]['questionText'])
assert question.question_text == questions[0]['questionText']
def test___init___complete(self, questions):
"""Question is constructed properly with all parameters provided"""
q = questions[1]
er = q['evidenceRequest']
evidence_request = EvidenceRequest(er['items'], er['profile'])
filters = [Filter(f['filterType'], f['filterName'], f['values']) for f in q['filters']]
question = Question(question_text=q['questionText'],
answer_assertion=q['answerAssertion'],
category=q['category'],
context=q['context'],
evidence_request=evidence_request,
filters=filters,
formatted_answer=q['formattedAnswer'],
items=q['items'],
lat=q['lat'],
passthru=q['passthru'],
synonym_list=q['synonymList'])
assert question.question_text == q['questionText']
assert question.answer_assertion == q['answerAssertion']
assert question.category == q['category']
assert question.context == q['context']
assert question.evidence_request == er
assert question.filters == filters
... |
969fcfa12bcb734720c3e48c508329b687f91bf6 | Cogs/Message.py | Cogs/Message.py | import asyncio
import discord
import textwrap
from discord.ext import commands
async def say(bot, msg, target, requestor, maxMessage : int = 5, characters : int = 2000):
"""A helper function to get the bot to cut his text into chunks."""
if not bot or not msg or not target:
return False
textList = textwrap.wrap(msg, characters, break_long_words=True, replace_whitespace=False)
if not len(textList):
return False
dmChannel = requestor.dm_channel
if len(textList) > maxMessage and dmChannel.id != target.id :
# PM the contents to the requestor
await target.send("Since this message is *{} pages* - I'm just going to DM it to you.".format(len(textList)))
target = requestor
for message in textList:
await target.send(message)
return True
| import asyncio
import discord
import textwrap
from discord.ext import commands
async def say(bot, msg, target, requestor, maxMessage : int = 5, characters : int = 2000):
"""A helper function to get the bot to cut his text into chunks."""
if not bot or not msg or not target:
return False
textList = textwrap.wrap(msg, characters, break_long_words=True, replace_whitespace=False)
if not len(textList):
return False
if not requestor.dm_channel:
# No dm channel - create it
await requestor.create_dm()
dmChannel = requestor.dm_channel
if len(textList) > maxMessage and dmChannel.id != target.id :
# PM the contents to the requestor
await target.send("Since this message is *{} pages* - I'm just going to DM it to you.".format(len(textList)))
target = requestor
for message in textList:
await target.send(message)
return True
| Create dm channel if it doesn't exist | Create dm channel if it doesn't exist | Python | mit | corpnewt/CorpBot.py,corpnewt/CorpBot.py | import asyncio
import discord
import textwrap
from discord.ext import commands
async def say(bot, msg, target, requestor, maxMessage : int = 5, characters : int = 2000):
"""A helper function to get the bot to cut his text into chunks."""
if not bot or not msg or not target:
return False
textList = textwrap.wrap(msg, characters, break_long_words=True, replace_whitespace=False)
if not len(textList):
return False
+ if not requestor.dm_channel:
+ # No dm channel - create it
+ await requestor.create_dm()
+
dmChannel = requestor.dm_channel
+
if len(textList) > maxMessage and dmChannel.id != target.id :
# PM the contents to the requestor
await target.send("Since this message is *{} pages* - I'm just going to DM it to you.".format(len(textList)))
target = requestor
for message in textList:
await target.send(message)
return True
| Create dm channel if it doesn't exist | ## Code Before:
import asyncio
import discord
import textwrap
from discord.ext import commands
async def say(bot, msg, target, requestor, maxMessage : int = 5, characters : int = 2000):
"""A helper function to get the bot to cut his text into chunks."""
if not bot or not msg or not target:
return False
textList = textwrap.wrap(msg, characters, break_long_words=True, replace_whitespace=False)
if not len(textList):
return False
dmChannel = requestor.dm_channel
if len(textList) > maxMessage and dmChannel.id != target.id :
# PM the contents to the requestor
await target.send("Since this message is *{} pages* - I'm just going to DM it to you.".format(len(textList)))
target = requestor
for message in textList:
await target.send(message)
return True
## Instruction:
Create dm channel if it doesn't exist
## Code After:
import asyncio
import discord
import textwrap
from discord.ext import commands
async def say(bot, msg, target, requestor, maxMessage : int = 5, characters : int = 2000):
"""A helper function to get the bot to cut his text into chunks."""
if not bot or not msg or not target:
return False
textList = textwrap.wrap(msg, characters, break_long_words=True, replace_whitespace=False)
if not len(textList):
return False
if not requestor.dm_channel:
# No dm channel - create it
await requestor.create_dm()
dmChannel = requestor.dm_channel
if len(textList) > maxMessage and dmChannel.id != target.id :
# PM the contents to the requestor
await target.send("Since this message is *{} pages* - I'm just going to DM it to you.".format(len(textList)))
target = requestor
for message in textList:
await target.send(message)
return True
| ...
return False
if not requestor.dm_channel:
# No dm channel - create it
await requestor.create_dm()
dmChannel = requestor.dm_channel
if len(textList) > maxMessage and dmChannel.id != target.id :
# PM the contents to the requestor
... |
c266fbd7a3478d582dc0d6c88fc5e3d8b7a8f62f | survey/views/survey_result.py | survey/views/survey_result.py |
import datetime
import os
from django.http.response import HttpResponse
from django.shortcuts import get_object_or_404
from survey.management.survey2csv import Survey2CSV
from survey.models import Survey
def serve_result_csv(request, pk):
survey = get_object_or_404(Survey, pk=pk)
try:
latest_answer = survey.latest_answer_date()
csv_modification_time = os.path.getmtime(Survey2CSV.file_name(survey))
csv_time = datetime.datetime.fromtimestamp(csv_modification_time)
csv_time = csv_time.replace(tzinfo=latest_answer.tzinfo)
if latest_answer > csv_time:
# If the file was generated before the last answer, generate it.
Survey2CSV.generate_file(survey)
except OSError:
# If the file do not exist, generate it.
Survey2CSV.generate_file(survey)
with open(Survey2CSV.file_name(survey), 'r') as f:
response = HttpResponse(f.read(), content_type='text/csv')
response['mimetype='] = 'application/force-download'
cd = u'attachment; filename="{}.csv"'.format(survey.name)
response['Content-Disposition'] = cd
return response
|
import datetime
import os
from django.http.response import HttpResponse
from django.shortcuts import get_object_or_404
from survey.management.survey2csv import Survey2CSV
from survey.models import Survey
def serve_result_csv(request, pk):
survey = get_object_or_404(Survey, pk=pk)
try:
latest_answer = survey.latest_answer_date()
csv_modification_time = os.path.getmtime(Survey2CSV.file_name(survey))
csv_time = datetime.datetime.fromtimestamp(csv_modification_time)
csv_time = csv_time.replace(tzinfo=latest_answer.tzinfo)
if latest_answer > csv_time:
# If the file was generated before the last answer, generate it.
Survey2CSV.generate_file(survey)
except OSError:
# If the file do not exist, generate it.
Survey2CSV.generate_file(survey)
with open(Survey2CSV.file_name(survey), 'r') as f:
response = HttpResponse(f.read(), content_type='text/csv')
cd = u'attachment; filename="{}.csv"'.format(survey.name)
response['Content-Disposition'] = cd
return response
| Fix - Apache error AH02429 | Fix - Apache error AH02429
Response header name 'mimetype=' contains invalid characters, aborting request
| Python | agpl-3.0 | Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey |
import datetime
import os
from django.http.response import HttpResponse
from django.shortcuts import get_object_or_404
from survey.management.survey2csv import Survey2CSV
from survey.models import Survey
def serve_result_csv(request, pk):
survey = get_object_or_404(Survey, pk=pk)
try:
latest_answer = survey.latest_answer_date()
csv_modification_time = os.path.getmtime(Survey2CSV.file_name(survey))
csv_time = datetime.datetime.fromtimestamp(csv_modification_time)
csv_time = csv_time.replace(tzinfo=latest_answer.tzinfo)
if latest_answer > csv_time:
# If the file was generated before the last answer, generate it.
Survey2CSV.generate_file(survey)
except OSError:
# If the file do not exist, generate it.
Survey2CSV.generate_file(survey)
with open(Survey2CSV.file_name(survey), 'r') as f:
response = HttpResponse(f.read(), content_type='text/csv')
- response['mimetype='] = 'application/force-download'
cd = u'attachment; filename="{}.csv"'.format(survey.name)
response['Content-Disposition'] = cd
return response
| Fix - Apache error AH02429 | ## Code Before:
import datetime
import os
from django.http.response import HttpResponse
from django.shortcuts import get_object_or_404
from survey.management.survey2csv import Survey2CSV
from survey.models import Survey
def serve_result_csv(request, pk):
survey = get_object_or_404(Survey, pk=pk)
try:
latest_answer = survey.latest_answer_date()
csv_modification_time = os.path.getmtime(Survey2CSV.file_name(survey))
csv_time = datetime.datetime.fromtimestamp(csv_modification_time)
csv_time = csv_time.replace(tzinfo=latest_answer.tzinfo)
if latest_answer > csv_time:
# If the file was generated before the last answer, generate it.
Survey2CSV.generate_file(survey)
except OSError:
# If the file do not exist, generate it.
Survey2CSV.generate_file(survey)
with open(Survey2CSV.file_name(survey), 'r') as f:
response = HttpResponse(f.read(), content_type='text/csv')
response['mimetype='] = 'application/force-download'
cd = u'attachment; filename="{}.csv"'.format(survey.name)
response['Content-Disposition'] = cd
return response
## Instruction:
Fix - Apache error AH02429
## Code After:
import datetime
import os
from django.http.response import HttpResponse
from django.shortcuts import get_object_or_404
from survey.management.survey2csv import Survey2CSV
from survey.models import Survey
def serve_result_csv(request, pk):
survey = get_object_or_404(Survey, pk=pk)
try:
latest_answer = survey.latest_answer_date()
csv_modification_time = os.path.getmtime(Survey2CSV.file_name(survey))
csv_time = datetime.datetime.fromtimestamp(csv_modification_time)
csv_time = csv_time.replace(tzinfo=latest_answer.tzinfo)
if latest_answer > csv_time:
# If the file was generated before the last answer, generate it.
Survey2CSV.generate_file(survey)
except OSError:
# If the file do not exist, generate it.
Survey2CSV.generate_file(survey)
with open(Survey2CSV.file_name(survey), 'r') as f:
response = HttpResponse(f.read(), content_type='text/csv')
cd = u'attachment; filename="{}.csv"'.format(survey.name)
response['Content-Disposition'] = cd
return response
| # ... existing code ...
with open(Survey2CSV.file_name(survey), 'r') as f:
response = HttpResponse(f.read(), content_type='text/csv')
cd = u'attachment; filename="{}.csv"'.format(survey.name)
response['Content-Disposition'] = cd
# ... rest of the code ... |
3e4360e831d98dadca3f9346f324f3d17769257f | alg_selection_sort.py | alg_selection_sort.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def selection_sort(a_list):
"""Selection Sort algortihm.
Time complexity: O(n^2).
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
a_list[select_slot], a_list[max_slot] = (
a_list[max_slot], a_list[select_slot])
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def selection_sort(ls):
"""Selection Sort algortihm.
Time complexity: O(n^2).
Space complexity: O(1).
"""
# Start from the last elemenet reversely: len(ls) - 1, ..., 0.
for i_max in reversed(range(len(ls))):
# Select the next max, and interchange it with corresponding element.
s = 0
for i in range(1, i_max + 1):
if ls[i] > ls[s]:
s = i
ls[s], ls[i_max] = ls[i_max], ls[s]
def main():
ls = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('List: {}'.format(ls))
print('By selection sort: ')
selection_sort(ls)
print(ls)
if __name__ == '__main__':
main()
| Refactor selection sort w/ adding comments | Refactor selection sort w/ adding comments
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
- def selection_sort(a_list):
+ def selection_sort(ls):
"""Selection Sort algortihm.
Time complexity: O(n^2).
+ Space complexity: O(1).
"""
+ # Start from the last elemenet reversely: len(ls) - 1, ..., 0.
- for max_slot in reversed(range(len(a_list))):
+ for i_max in reversed(range(len(ls))):
- select_slot = 0
+ # Select the next max, and interchange it with corresponding element.
+ s = 0
- for slot in range(1, max_slot + 1):
+ for i in range(1, i_max + 1):
+ if ls[i] > ls[s]:
+ s = i
+ ls[s], ls[i_max] = ls[i_max], ls[s]
- if a_list[slot] > a_list[select_slot]:
- select_slot = slot
-
- a_list[select_slot], a_list[max_slot] = (
- a_list[max_slot], a_list[select_slot])
def main():
- a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
+ ls = [54, 26, 93, 17, 77, 31, 44, 55, 20]
- print('a_list: {}'.format(a_list))
+ print('List: {}'.format(ls))
print('By selection sort: ')
- selection_sort(a_list)
+ selection_sort(ls)
- print(a_list)
+ print(ls)
if __name__ == '__main__':
main()
| Refactor selection sort w/ adding comments | ## Code Before:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def selection_sort(a_list):
"""Selection Sort algortihm.
Time complexity: O(n^2).
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
a_list[select_slot], a_list[max_slot] = (
a_list[max_slot], a_list[select_slot])
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
## Instruction:
Refactor selection sort w/ adding comments
## Code After:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def selection_sort(ls):
"""Selection Sort algortihm.
Time complexity: O(n^2).
Space complexity: O(1).
"""
# Start from the last elemenet reversely: len(ls) - 1, ..., 0.
for i_max in reversed(range(len(ls))):
# Select the next max, and interchange it with corresponding element.
s = 0
for i in range(1, i_max + 1):
if ls[i] > ls[s]:
s = i
ls[s], ls[i_max] = ls[i_max], ls[s]
def main():
ls = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('List: {}'.format(ls))
print('By selection sort: ')
selection_sort(ls)
print(ls)
if __name__ == '__main__':
main()
| # ... existing code ...
def selection_sort(ls):
"""Selection Sort algortihm.
Time complexity: O(n^2).
Space complexity: O(1).
"""
# Start from the last elemenet reversely: len(ls) - 1, ..., 0.
for i_max in reversed(range(len(ls))):
# Select the next max, and interchange it with corresponding element.
s = 0
for i in range(1, i_max + 1):
if ls[i] > ls[s]:
s = i
ls[s], ls[i_max] = ls[i_max], ls[s]
def main():
ls = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('List: {}'.format(ls))
print('By selection sort: ')
selection_sort(ls)
print(ls)
# ... rest of the code ... |
25ba4aea17d869022682fd70d4c3ccbade19955f | openfisca_country_template/situation_examples/__init__.py | openfisca_country_template/situation_examples/__init__.py | """This file provides a function to load json example situations."""
import json
import os
DIR_PATH = os.path.dirname(os.path.abspath(__file__))
def parse(file_name):
"""Load json example situations."""
file_path = os.path.join(DIR_PATH, file_name)
with open(file_path, "r") as file:
return json.loads(file.read())
single = parse("single.json")
couple = parse("couple.json")
| """This file provides a function to load json example situations."""
import json
import os
DIR_PATH = os.path.dirname(os.path.abspath(__file__))
def parse(file_name):
"""Load json example situations."""
file_path = os.path.join(DIR_PATH, file_name)
with open(file_path, "r", encoding="utf8") as file:
return json.loads(file.read())
single = parse("single.json")
couple = parse("couple.json")
| Add encoding to open file | Add encoding to open file
| Python | agpl-3.0 | openfisca/country-template,openfisca/country-template | """This file provides a function to load json example situations."""
import json
import os
DIR_PATH = os.path.dirname(os.path.abspath(__file__))
def parse(file_name):
"""Load json example situations."""
file_path = os.path.join(DIR_PATH, file_name)
- with open(file_path, "r") as file:
+ with open(file_path, "r", encoding="utf8") as file:
return json.loads(file.read())
single = parse("single.json")
couple = parse("couple.json")
| Add encoding to open file | ## Code Before:
"""This file provides a function to load json example situations."""
import json
import os
DIR_PATH = os.path.dirname(os.path.abspath(__file__))
def parse(file_name):
"""Load json example situations."""
file_path = os.path.join(DIR_PATH, file_name)
with open(file_path, "r") as file:
return json.loads(file.read())
single = parse("single.json")
couple = parse("couple.json")
## Instruction:
Add encoding to open file
## Code After:
"""This file provides a function to load json example situations."""
import json
import os
DIR_PATH = os.path.dirname(os.path.abspath(__file__))
def parse(file_name):
"""Load json example situations."""
file_path = os.path.join(DIR_PATH, file_name)
with open(file_path, "r", encoding="utf8") as file:
return json.loads(file.read())
single = parse("single.json")
couple = parse("couple.json")
| # ... existing code ...
"""Load json example situations."""
file_path = os.path.join(DIR_PATH, file_name)
with open(file_path, "r", encoding="utf8") as file:
return json.loads(file.read())
# ... rest of the code ... |
139346c72a09719eba3d444c67d1b54c1b68eae6 | uni_form/templatetags/uni_form_field.py | uni_form/templatetags/uni_form_field.py | from django import template
register = template.Library()
class_converter = {
"textinput":"textinput textInput",
"fileinput":"fileinput fileUpload"
}
@register.filter
def is_checkbox(field):
return field.field.widget.__class__.__name__.lower() == "checkboxinput"
@register.filter
def with_class(field):
class_name = field.field.widget.__class__.__name__.lower()
class_name = class_converter.get(class_name, class_name)
if "class" in field.field.widget.attrs:
css_class = field.field.widget.attrs['class']
if field.field.widget.attrs['class'].find(class_name) == -1:
css_class += " %s" % (class_name,)
else:
css_class = class_name
return field.as_widget(attrs={'class': css_class})
| from django import template
register = template.Library()
class_converter = {
"textinput":"textinput textInput",
"fileinput":"fileinput fileUpload",
"passwordinput":"passwordinput textInput"
}
@register.filter
def is_checkbox(field):
return field.field.widget.__class__.__name__.lower() == "checkboxinput"
@register.filter
def with_class(field):
class_name = field.field.widget.__class__.__name__.lower()
class_name = class_converter.get(class_name, class_name)
if "class" in field.field.widget.attrs:
css_class = field.field.widget.attrs['class']
if field.field.widget.attrs['class'].find(class_name) == -1:
css_class += " %s" % (class_name,)
else:
css_class = class_name
return field.as_widget(attrs={'class': css_class})
| Add "passwordinput" to class_converter, because it needs the textInput class too. | Add "passwordinput" to class_converter, because it needs the textInput class too.
| Python | mit | treyhunner/django-crispy-forms,uranusjr/django-crispy-forms-ng,alanwj/django-crispy-forms,iris-edu-int/django-crispy-forms,scuml/django-crispy-forms,RamezIssac/django-crispy-forms,PetrDlouhy/django-crispy-forms,zixan/django-crispy-forms,smirolo/django-crispy-forms,schrd/django-crispy-forms,CashStar/django-uni-form,pydanny/django-uni-form,ngenovictor/django-crispy-forms,eykanal/django-crispy-forms,eykanal/django-crispy-forms,treyhunner/django-crispy-forms,spectras/django-crispy-forms,IanLee1521/django-crispy-forms,django-crispy-forms/django-crispy-forms,carltongibson/django-crispy-forms,agepoly/django-crispy-forms,iris-edu-int/django-crispy-forms,PetrDlouhy/django-crispy-forms,avsd/django-crispy-forms,maraujop/django-crispy-forms,spectras/django-crispy-forms,saydulk/django-crispy-forms,jtyoung/django-crispy-forms,impulse-cloud/django-crispy-forms,iedparis8/django-crispy-forms,bouttier/django-crispy-forms,ngenovictor/django-crispy-forms,jtyoung/django-crispy-forms,jcomeauictx/django-crispy-forms,avsd/django-crispy-forms,iris-edu/django-crispy-forms,carltongibson/django-crispy-forms,zixan/django-crispy-forms,dessibelle/django-crispy-forms,pydanny/django-uni-form,davidszotten/django-crispy-forms,CashStar/django-uni-form,alanwj/django-crispy-forms,maraujop/django-crispy-forms,ionelmc/django-uni-form,rfleschenberg/django-crispy-forms,IanLee1521/django-crispy-forms,davidszotten/django-crispy-forms,rfleschenberg/django-crispy-forms,agepoly/django-crispy-forms,scuml/django-crispy-forms,VishvajitP/django-crispy-forms,iedparis8/django-crispy-forms,HungryCloud/django-crispy-forms,damienjones/django-crispy-forms,bouttier/django-crispy-forms,dzhuang/django-crispy-forms,RamezIssac/django-crispy-forms,schrd/django-crispy-forms,iris-edu/django-crispy-forms,VishvajitP/django-crispy-forms,tarunlnmiit/django-crispy-forms,jcomeauictx/django-crispy-forms,HungryCloud/django-crispy-forms,tarunlnmiit/django-crispy-forms,damienjones/django-crispy-forms,django-crispy-forms/django-crispy-forms,impulse-cloud/django-crispy-forms,pjdelport/django-crispy-forms,dzhuang/django-crispy-forms,Stranger6667/django-crispy-forms,Stranger6667/django-crispy-forms,uranusjr/django-crispy-forms-ng,dessibelle/django-crispy-forms,HungryCloud/django-crispy-forms,smirolo/django-crispy-forms,saydulk/django-crispy-forms | from django import template
register = template.Library()
class_converter = {
"textinput":"textinput textInput",
- "fileinput":"fileinput fileUpload"
+ "fileinput":"fileinput fileUpload",
+ "passwordinput":"passwordinput textInput"
}
@register.filter
def is_checkbox(field):
return field.field.widget.__class__.__name__.lower() == "checkboxinput"
@register.filter
def with_class(field):
class_name = field.field.widget.__class__.__name__.lower()
class_name = class_converter.get(class_name, class_name)
if "class" in field.field.widget.attrs:
css_class = field.field.widget.attrs['class']
if field.field.widget.attrs['class'].find(class_name) == -1:
css_class += " %s" % (class_name,)
else:
css_class = class_name
return field.as_widget(attrs={'class': css_class})
| Add "passwordinput" to class_converter, because it needs the textInput class too. | ## Code Before:
from django import template
register = template.Library()
class_converter = {
"textinput":"textinput textInput",
"fileinput":"fileinput fileUpload"
}
@register.filter
def is_checkbox(field):
return field.field.widget.__class__.__name__.lower() == "checkboxinput"
@register.filter
def with_class(field):
class_name = field.field.widget.__class__.__name__.lower()
class_name = class_converter.get(class_name, class_name)
if "class" in field.field.widget.attrs:
css_class = field.field.widget.attrs['class']
if field.field.widget.attrs['class'].find(class_name) == -1:
css_class += " %s" % (class_name,)
else:
css_class = class_name
return field.as_widget(attrs={'class': css_class})
## Instruction:
Add "passwordinput" to class_converter, because it needs the textInput class too.
## Code After:
from django import template
register = template.Library()
class_converter = {
"textinput":"textinput textInput",
"fileinput":"fileinput fileUpload",
"passwordinput":"passwordinput textInput"
}
@register.filter
def is_checkbox(field):
return field.field.widget.__class__.__name__.lower() == "checkboxinput"
@register.filter
def with_class(field):
class_name = field.field.widget.__class__.__name__.lower()
class_name = class_converter.get(class_name, class_name)
if "class" in field.field.widget.attrs:
css_class = field.field.widget.attrs['class']
if field.field.widget.attrs['class'].find(class_name) == -1:
css_class += " %s" % (class_name,)
else:
css_class = class_name
return field.as_widget(attrs={'class': css_class})
| // ... existing code ...
class_converter = {
"textinput":"textinput textInput",
"fileinput":"fileinput fileUpload",
"passwordinput":"passwordinput textInput"
}
// ... rest of the code ... |
6cfd296a86c1b475101c179a45a7453b76dcbfd5 | riak/util.py | riak/util.py | import collections
def quacks_like_dict(object):
"""Check if object is dict-like"""
return isinstance(object, collections.Mapping)
def deep_merge(a, b):
"""Merge two deep dicts non-destructively
Uses a stack to avoid maximum recursion depth exceptions
>>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
>>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
>>> c = merge(a, b)
>>> from pprint import pprint; pprint(c)
{'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd': {'z': [1, 2, 3]}}
"""
assert quacks_like_dict(a), quacks_like_dict(b)
dst = a.copy()
stack = [(dst, b)]
while stack:
current_dst, current_src = stack.pop()
for key in current_src:
if key not in current_dst:
current_dst[key] = current_src[key]
else:
if quacks_like_dict(current_src[key]) and quacks_like_dict(current_dst[key]) :
stack.append((current_dst[key], current_src[key]))
else:
current_dst[key] = current_src[key]
return dst
| try:
from collections import Mapping
except ImportError:
# compatibility with Python 2.5
Mapping = dict
def quacks_like_dict(object):
"""Check if object is dict-like"""
return isinstance(object, Mapping)
def deep_merge(a, b):
"""Merge two deep dicts non-destructively
Uses a stack to avoid maximum recursion depth exceptions
>>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
>>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
>>> c = merge(a, b)
>>> from pprint import pprint; pprint(c)
{'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd': {'z': [1, 2, 3]}}
"""
assert quacks_like_dict(a), quacks_like_dict(b)
dst = a.copy()
stack = [(dst, b)]
while stack:
current_dst, current_src = stack.pop()
for key in current_src:
if key not in current_dst:
current_dst[key] = current_src[key]
else:
if quacks_like_dict(current_src[key]) and quacks_like_dict(current_dst[key]) :
stack.append((current_dst[key], current_src[key]))
else:
current_dst[key] = current_src[key]
return dst
| Adjust for compatibility with Python 2.5 | Adjust for compatibility with Python 2.5
| Python | apache-2.0 | basho/riak-python-client,GabrielNicolasAvellaneda/riak-python-client,GabrielNicolasAvellaneda/riak-python-client,bmess/riak-python-client,basho/riak-python-client,basho/riak-python-client,bmess/riak-python-client | - import collections
+ try:
+ from collections import Mapping
+ except ImportError:
+ # compatibility with Python 2.5
+ Mapping = dict
def quacks_like_dict(object):
"""Check if object is dict-like"""
- return isinstance(object, collections.Mapping)
+ return isinstance(object, Mapping)
def deep_merge(a, b):
"""Merge two deep dicts non-destructively
Uses a stack to avoid maximum recursion depth exceptions
>>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
>>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
>>> c = merge(a, b)
>>> from pprint import pprint; pprint(c)
{'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd': {'z': [1, 2, 3]}}
"""
assert quacks_like_dict(a), quacks_like_dict(b)
dst = a.copy()
stack = [(dst, b)]
while stack:
current_dst, current_src = stack.pop()
for key in current_src:
if key not in current_dst:
current_dst[key] = current_src[key]
else:
if quacks_like_dict(current_src[key]) and quacks_like_dict(current_dst[key]) :
stack.append((current_dst[key], current_src[key]))
else:
current_dst[key] = current_src[key]
return dst
| Adjust for compatibility with Python 2.5 | ## Code Before:
import collections
def quacks_like_dict(object):
"""Check if object is dict-like"""
return isinstance(object, collections.Mapping)
def deep_merge(a, b):
"""Merge two deep dicts non-destructively
Uses a stack to avoid maximum recursion depth exceptions
>>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
>>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
>>> c = merge(a, b)
>>> from pprint import pprint; pprint(c)
{'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd': {'z': [1, 2, 3]}}
"""
assert quacks_like_dict(a), quacks_like_dict(b)
dst = a.copy()
stack = [(dst, b)]
while stack:
current_dst, current_src = stack.pop()
for key in current_src:
if key not in current_dst:
current_dst[key] = current_src[key]
else:
if quacks_like_dict(current_src[key]) and quacks_like_dict(current_dst[key]) :
stack.append((current_dst[key], current_src[key]))
else:
current_dst[key] = current_src[key]
return dst
## Instruction:
Adjust for compatibility with Python 2.5
## Code After:
try:
from collections import Mapping
except ImportError:
# compatibility with Python 2.5
Mapping = dict
def quacks_like_dict(object):
"""Check if object is dict-like"""
return isinstance(object, Mapping)
def deep_merge(a, b):
"""Merge two deep dicts non-destructively
Uses a stack to avoid maximum recursion depth exceptions
>>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
>>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
>>> c = merge(a, b)
>>> from pprint import pprint; pprint(c)
{'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd': {'z': [1, 2, 3]}}
"""
assert quacks_like_dict(a), quacks_like_dict(b)
dst = a.copy()
stack = [(dst, b)]
while stack:
current_dst, current_src = stack.pop()
for key in current_src:
if key not in current_dst:
current_dst[key] = current_src[key]
else:
if quacks_like_dict(current_src[key]) and quacks_like_dict(current_dst[key]) :
stack.append((current_dst[key], current_src[key]))
else:
current_dst[key] = current_src[key]
return dst
| ...
try:
from collections import Mapping
except ImportError:
# compatibility with Python 2.5
Mapping = dict
def quacks_like_dict(object):
"""Check if object is dict-like"""
return isinstance(object, Mapping)
def deep_merge(a, b):
... |
3c2663d4c8ca523d072b6e82bf872f412aba9321 | mrgeo-python/src/main/python/pymrgeo/rastermapop.py | mrgeo-python/src/main/python/pymrgeo/rastermapop.py | import copy
import json
from py4j.java_gateway import JavaClass, java_import
from pymrgeo.instance import is_instance_of as iio
class RasterMapOp(object):
mapop = None
gateway = None
context = None
job = None
def __init__(self, gateway=None, context=None, mapop=None, job=None):
self.gateway = gateway
self.context = context
self.mapop = mapop
self.job = job
@staticmethod
def nan():
return float('nan')
def clone(self):
return copy.copy(self)
def is_instance_of(self, java_object, java_class):
return iio(self.gateway, java_object, java_class)
def metadata(self):
if self.mapop is None:
return None
jvm = self.gateway.jvm
java_import(jvm, "org.mrgeo.mapalgebra.raster.RasterMapOp")
java_import(jvm, "org.mrgeo.image.MrsPyramidMetadata")
meta = self.mapop.metadata().getOrElse(None)
if meta is None:
return None
java_import(jvm, "com.fasterxml.jackson.databind.ObjectMapper")
mapper = jvm.com.fasterxml.jackson.databind.ObjectMapper()
jsonstr = mapper.writeValueAsString(meta)
# print(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(meta))
return json.loads(jsonstr)
| import copy
import json
from py4j.java_gateway import java_import
from pymrgeo.instance import is_instance_of as iio
class RasterMapOp(object):
mapop = None
gateway = None
context = None
job = None
def __init__(self, gateway=None, context=None, mapop=None, job=None):
self.gateway = gateway
self.context = context
self.mapop = mapop
self.job = job
@staticmethod
def nan():
return float('nan')
def clone(self):
return copy.copy(self)
def is_instance_of(self, java_object, java_class):
return iio(self.gateway, java_object, java_class)
def metadata(self):
if self.mapop is None:
return None
jvm = self.gateway.jvm
java_import(jvm, "org.mrgeo.mapalgebra.raster.RasterMapOp")
java_import(jvm, "org.mrgeo.image.MrsPyramidMetadata")
if self.mapop.metadata().isEmpty():
return None
meta = self.mapop.metadata().get()
java_import(jvm, "com.fasterxml.jackson.databind.ObjectMapper")
mapper = jvm.com.fasterxml.jackson.databind.ObjectMapper()
jsonstr = mapper.writeValueAsString(meta)
# print(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(meta))
return json.loads(jsonstr)
| Implement empty metadata a little differently | Implement empty metadata a little differently
| Python | apache-2.0 | ngageoint/mrgeo,ngageoint/mrgeo,ngageoint/mrgeo | import copy
import json
- from py4j.java_gateway import JavaClass, java_import
+ from py4j.java_gateway import java_import
from pymrgeo.instance import is_instance_of as iio
class RasterMapOp(object):
mapop = None
gateway = None
context = None
job = None
def __init__(self, gateway=None, context=None, mapop=None, job=None):
self.gateway = gateway
self.context = context
self.mapop = mapop
self.job = job
@staticmethod
def nan():
return float('nan')
def clone(self):
return copy.copy(self)
def is_instance_of(self, java_object, java_class):
return iio(self.gateway, java_object, java_class)
def metadata(self):
if self.mapop is None:
return None
jvm = self.gateway.jvm
java_import(jvm, "org.mrgeo.mapalgebra.raster.RasterMapOp")
java_import(jvm, "org.mrgeo.image.MrsPyramidMetadata")
+ if self.mapop.metadata().isEmpty():
- meta = self.mapop.metadata().getOrElse(None)
- if meta is None:
return None
+
+ meta = self.mapop.metadata().get()
java_import(jvm, "com.fasterxml.jackson.databind.ObjectMapper")
mapper = jvm.com.fasterxml.jackson.databind.ObjectMapper()
jsonstr = mapper.writeValueAsString(meta)
# print(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(meta))
return json.loads(jsonstr)
| Implement empty metadata a little differently | ## Code Before:
import copy
import json
from py4j.java_gateway import JavaClass, java_import
from pymrgeo.instance import is_instance_of as iio
class RasterMapOp(object):
mapop = None
gateway = None
context = None
job = None
def __init__(self, gateway=None, context=None, mapop=None, job=None):
self.gateway = gateway
self.context = context
self.mapop = mapop
self.job = job
@staticmethod
def nan():
return float('nan')
def clone(self):
return copy.copy(self)
def is_instance_of(self, java_object, java_class):
return iio(self.gateway, java_object, java_class)
def metadata(self):
if self.mapop is None:
return None
jvm = self.gateway.jvm
java_import(jvm, "org.mrgeo.mapalgebra.raster.RasterMapOp")
java_import(jvm, "org.mrgeo.image.MrsPyramidMetadata")
meta = self.mapop.metadata().getOrElse(None)
if meta is None:
return None
java_import(jvm, "com.fasterxml.jackson.databind.ObjectMapper")
mapper = jvm.com.fasterxml.jackson.databind.ObjectMapper()
jsonstr = mapper.writeValueAsString(meta)
# print(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(meta))
return json.loads(jsonstr)
## Instruction:
Implement empty metadata a little differently
## Code After:
import copy
import json
from py4j.java_gateway import java_import
from pymrgeo.instance import is_instance_of as iio
class RasterMapOp(object):
mapop = None
gateway = None
context = None
job = None
def __init__(self, gateway=None, context=None, mapop=None, job=None):
self.gateway = gateway
self.context = context
self.mapop = mapop
self.job = job
@staticmethod
def nan():
return float('nan')
def clone(self):
return copy.copy(self)
def is_instance_of(self, java_object, java_class):
return iio(self.gateway, java_object, java_class)
def metadata(self):
if self.mapop is None:
return None
jvm = self.gateway.jvm
java_import(jvm, "org.mrgeo.mapalgebra.raster.RasterMapOp")
java_import(jvm, "org.mrgeo.image.MrsPyramidMetadata")
if self.mapop.metadata().isEmpty():
return None
meta = self.mapop.metadata().get()
java_import(jvm, "com.fasterxml.jackson.databind.ObjectMapper")
mapper = jvm.com.fasterxml.jackson.databind.ObjectMapper()
jsonstr = mapper.writeValueAsString(meta)
# print(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(meta))
return json.loads(jsonstr)
| // ... existing code ...
import json
from py4j.java_gateway import java_import
from pymrgeo.instance import is_instance_of as iio
// ... modified code ...
java_import(jvm, "org.mrgeo.image.MrsPyramidMetadata")
if self.mapop.metadata().isEmpty():
return None
meta = self.mapop.metadata().get()
java_import(jvm, "com.fasterxml.jackson.databind.ObjectMapper")
// ... rest of the code ... |
452955ca8b7ba2ef01fc97800e5f350fee3e3a6e | tvnamer/renamer.py | tvnamer/renamer.py | import re
import os
import pytvdbapi.api as tvdb
class Renamer:
def __init__(self, api_key):
self.tvdb = tvdb.TVDB(api_key)
@staticmethod
def flat_file_list(directory):
directory = os.path.normpath(directory)
for dirpath, dirnames, filenames in os.walk(directory):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
# remove directory from the start of the full path
full_path = full_path[len(directory)+1:]
yield full_path
def rename_table(self, directory, input_regex, output_format):
input_pattern = re.compile(input_regex)
filenames = self.flat_file_list(directory)
for filename in filenames:
thing = input_pattern.search(filename)
if thing is not None:
params = thing.groupdict()
output_filename = output_format.format(**params)
yield filename, output_filename
| import re
import os
import pytvdbapi.api as tvdb
class Renamer:
def __init__(self, api_key):
self.tvdb = tvdb.TVDB(api_key)
@staticmethod
def flat_file_list(directory):
directory = os.path.normpath(directory)
for dirpath, dirnames, filenames in os.walk(directory):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
# remove directory from the start of the full path
full_path = full_path[len(directory)+1:]
yield full_path
@staticmethod
def normalise_params(params):
def normalise(key, value):
if key == "show":
return str(value)
elif key in ["episode", "season"]:
return int(value)
else:
raise ValueError("Unknown parameter: '{}'".format(key))
return {key: normalise(key, value) for key, value in params.items()}
def rename_table(self, directory, input_regex, output_format):
input_pattern = re.compile(input_regex)
filenames = self.flat_file_list(directory)
for filename in filenames:
thing = input_pattern.search(filename)
if thing is not None:
params = self.normalise_params(thing.groupdict())
output_filename = output_format.format(**params)
yield filename, output_filename
| Add normalising params from the regex input | Add normalising params from the regex input
| Python | mit | tomleese/tvnamer,thomasleese/tvnamer | import re
import os
import pytvdbapi.api as tvdb
class Renamer:
def __init__(self, api_key):
self.tvdb = tvdb.TVDB(api_key)
@staticmethod
def flat_file_list(directory):
directory = os.path.normpath(directory)
for dirpath, dirnames, filenames in os.walk(directory):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
# remove directory from the start of the full path
full_path = full_path[len(directory)+1:]
yield full_path
+ @staticmethod
+ def normalise_params(params):
+ def normalise(key, value):
+ if key == "show":
+ return str(value)
+ elif key in ["episode", "season"]:
+ return int(value)
+ else:
+ raise ValueError("Unknown parameter: '{}'".format(key))
+
+ return {key: normalise(key, value) for key, value in params.items()}
+
def rename_table(self, directory, input_regex, output_format):
input_pattern = re.compile(input_regex)
filenames = self.flat_file_list(directory)
for filename in filenames:
thing = input_pattern.search(filename)
if thing is not None:
- params = thing.groupdict()
+ params = self.normalise_params(thing.groupdict())
output_filename = output_format.format(**params)
yield filename, output_filename
| Add normalising params from the regex input | ## Code Before:
import re
import os
import pytvdbapi.api as tvdb
class Renamer:
def __init__(self, api_key):
self.tvdb = tvdb.TVDB(api_key)
@staticmethod
def flat_file_list(directory):
directory = os.path.normpath(directory)
for dirpath, dirnames, filenames in os.walk(directory):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
# remove directory from the start of the full path
full_path = full_path[len(directory)+1:]
yield full_path
def rename_table(self, directory, input_regex, output_format):
input_pattern = re.compile(input_regex)
filenames = self.flat_file_list(directory)
for filename in filenames:
thing = input_pattern.search(filename)
if thing is not None:
params = thing.groupdict()
output_filename = output_format.format(**params)
yield filename, output_filename
## Instruction:
Add normalising params from the regex input
## Code After:
import re
import os
import pytvdbapi.api as tvdb
class Renamer:
def __init__(self, api_key):
self.tvdb = tvdb.TVDB(api_key)
@staticmethod
def flat_file_list(directory):
directory = os.path.normpath(directory)
for dirpath, dirnames, filenames in os.walk(directory):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
# remove directory from the start of the full path
full_path = full_path[len(directory)+1:]
yield full_path
@staticmethod
def normalise_params(params):
def normalise(key, value):
if key == "show":
return str(value)
elif key in ["episode", "season"]:
return int(value)
else:
raise ValueError("Unknown parameter: '{}'".format(key))
return {key: normalise(key, value) for key, value in params.items()}
def rename_table(self, directory, input_regex, output_format):
input_pattern = re.compile(input_regex)
filenames = self.flat_file_list(directory)
for filename in filenames:
thing = input_pattern.search(filename)
if thing is not None:
params = self.normalise_params(thing.groupdict())
output_filename = output_format.format(**params)
yield filename, output_filename
| // ... existing code ...
yield full_path
@staticmethod
def normalise_params(params):
def normalise(key, value):
if key == "show":
return str(value)
elif key in ["episode", "season"]:
return int(value)
else:
raise ValueError("Unknown parameter: '{}'".format(key))
return {key: normalise(key, value) for key, value in params.items()}
def rename_table(self, directory, input_regex, output_format):
input_pattern = re.compile(input_regex)
// ... modified code ...
thing = input_pattern.search(filename)
if thing is not None:
params = self.normalise_params(thing.groupdict())
output_filename = output_format.format(**params)
yield filename, output_filename
// ... rest of the code ... |
474f213cf2cc4851f9cfcd17652a29ad74ab1f0d | write_csv.py | write_csv.py | import sqlite3
import csv
from datetime import datetime
current_date = datetime.now().strftime('%Y-%m-%d')
destination_file = 'srvy' + current_date + '.csv'
sqlite_file = 'srvy.db'
table_name = 'responses'
date_column = 'date'
time_column = 'time'
score_column = 'score'
question_column = 'question'
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
#c.execute("SELECT * FROM responses WHERE date LIKE '%"+ current_date +"%'")
c.execute("SELECT * FROM responses WHERE date LIKE ?", current_date)
csvWriter = csv.writer(open(destination_file, 'w'))
rows = c.fetchall()
for row in rows:
csvWriter.writerow(row)
| import sqlite3
import csv
from datetime import datetime
current_date = str(datetime.now().strftime('%Y-%m-%d'))
destination_file = 'srvy' + current_date + '.csv'
sqlite_file = 'srvy.db'
table_name = 'responses'
date_column = 'date'
time_column = 'time'
score_column = 'score'
question_column = 'question'
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
#c.execute("SELECT * FROM responses WHERE date LIKE '%"+ current_date +"%'")
c.execute("SELECT * FROM responses WHERE date = ?", (current_date,))
csvWriter = csv.writer(open(destination_file, 'w'))
rows = c.fetchall()
for row in rows:
csvWriter.writerow(row)
| Change current date in SQLite query to tuple | Change current date in SQLite query to tuple
| Python | mit | andrewlrogers/srvy | import sqlite3
import csv
from datetime import datetime
- current_date = datetime.now().strftime('%Y-%m-%d')
+ current_date = str(datetime.now().strftime('%Y-%m-%d'))
destination_file = 'srvy' + current_date + '.csv'
sqlite_file = 'srvy.db'
table_name = 'responses'
date_column = 'date'
time_column = 'time'
score_column = 'score'
question_column = 'question'
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
#c.execute("SELECT * FROM responses WHERE date LIKE '%"+ current_date +"%'")
- c.execute("SELECT * FROM responses WHERE date LIKE ?", current_date)
+ c.execute("SELECT * FROM responses WHERE date = ?", (current_date,))
csvWriter = csv.writer(open(destination_file, 'w'))
rows = c.fetchall()
for row in rows:
csvWriter.writerow(row)
| Change current date in SQLite query to tuple | ## Code Before:
import sqlite3
import csv
from datetime import datetime
current_date = datetime.now().strftime('%Y-%m-%d')
destination_file = 'srvy' + current_date + '.csv'
sqlite_file = 'srvy.db'
table_name = 'responses'
date_column = 'date'
time_column = 'time'
score_column = 'score'
question_column = 'question'
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
#c.execute("SELECT * FROM responses WHERE date LIKE '%"+ current_date +"%'")
c.execute("SELECT * FROM responses WHERE date LIKE ?", current_date)
csvWriter = csv.writer(open(destination_file, 'w'))
rows = c.fetchall()
for row in rows:
csvWriter.writerow(row)
## Instruction:
Change current date in SQLite query to tuple
## Code After:
import sqlite3
import csv
from datetime import datetime
current_date = str(datetime.now().strftime('%Y-%m-%d'))
destination_file = 'srvy' + current_date + '.csv'
sqlite_file = 'srvy.db'
table_name = 'responses'
date_column = 'date'
time_column = 'time'
score_column = 'score'
question_column = 'question'
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
#c.execute("SELECT * FROM responses WHERE date LIKE '%"+ current_date +"%'")
c.execute("SELECT * FROM responses WHERE date = ?", (current_date,))
csvWriter = csv.writer(open(destination_file, 'w'))
rows = c.fetchall()
for row in rows:
csvWriter.writerow(row)
| ...
current_date = str(datetime.now().strftime('%Y-%m-%d'))
destination_file = 'srvy' + current_date + '.csv'
...
#c.execute("SELECT * FROM responses WHERE date LIKE '%"+ current_date +"%'")
c.execute("SELECT * FROM responses WHERE date = ?", (current_date,))
csvWriter = csv.writer(open(destination_file, 'w'))
... |
5e66b10c3f99e683ffbab1c074583436dd791901 | tests/test_runner.py | tests/test_runner.py | import asyncio
from pytest import mark, raises
from oshino.run import main
from mock import patch
def create_loop():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return loop
@mark.integration
@patch("oshino.core.heart.forever", lambda: False)
@patch("oshino.core.heart.create_loop", create_loop)
def test_startup():
with raises(SystemExit):
main(("--config", "tests/data/test_config.yml", "--noop"))
@mark.integration
@patch("oshino.core.heart.forever", lambda: False)
@patch("oshino.core.heart.create_loop", create_loop)
@patch("dotenv.find_dotenv", lambda: raise RuntimeError("Simply failing"))
def test_dot_env_fail():
with raises(SystemExit):
main(("--config", "tests/data/test_config.yml", "--noop"))
| import asyncio
from pytest import mark, raises
from oshino.run import main
from mock import patch
def create_loop():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return loop
def error_stub():
raise RuntimeError("Simply failing")
@mark.integration
@patch("oshino.core.heart.forever", lambda: False)
@patch("oshino.core.heart.create_loop", create_loop)
def test_startup():
with raises(SystemExit):
main(("--config", "tests/data/test_config.yml", "--noop"))
@mark.integration
@patch("oshino.core.heart.forever", lambda: False)
@patch("oshino.core.heart.create_loop", create_loop)
@patch("dotenv.find_dotenv", error_stub)
def test_dot_env_fail():
with raises(SystemExit):
main(("--config", "tests/data/test_config.yml", "--noop"))
| Use normal function instead of lambda for this | Use normal function instead of lambda for this
| Python | mit | CodersOfTheNight/oshino | import asyncio
from pytest import mark, raises
from oshino.run import main
from mock import patch
def create_loop():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return loop
+ def error_stub():
+ raise RuntimeError("Simply failing")
+
@mark.integration
@patch("oshino.core.heart.forever", lambda: False)
@patch("oshino.core.heart.create_loop", create_loop)
def test_startup():
with raises(SystemExit):
main(("--config", "tests/data/test_config.yml", "--noop"))
@mark.integration
@patch("oshino.core.heart.forever", lambda: False)
@patch("oshino.core.heart.create_loop", create_loop)
- @patch("dotenv.find_dotenv", lambda: raise RuntimeError("Simply failing"))
+ @patch("dotenv.find_dotenv", error_stub)
def test_dot_env_fail():
with raises(SystemExit):
main(("--config", "tests/data/test_config.yml", "--noop"))
| Use normal function instead of lambda for this | ## Code Before:
import asyncio
from pytest import mark, raises
from oshino.run import main
from mock import patch
def create_loop():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return loop
@mark.integration
@patch("oshino.core.heart.forever", lambda: False)
@patch("oshino.core.heart.create_loop", create_loop)
def test_startup():
with raises(SystemExit):
main(("--config", "tests/data/test_config.yml", "--noop"))
@mark.integration
@patch("oshino.core.heart.forever", lambda: False)
@patch("oshino.core.heart.create_loop", create_loop)
@patch("dotenv.find_dotenv", lambda: raise RuntimeError("Simply failing"))
def test_dot_env_fail():
with raises(SystemExit):
main(("--config", "tests/data/test_config.yml", "--noop"))
## Instruction:
Use normal function instead of lambda for this
## Code After:
import asyncio
from pytest import mark, raises
from oshino.run import main
from mock import patch
def create_loop():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return loop
def error_stub():
raise RuntimeError("Simply failing")
@mark.integration
@patch("oshino.core.heart.forever", lambda: False)
@patch("oshino.core.heart.create_loop", create_loop)
def test_startup():
with raises(SystemExit):
main(("--config", "tests/data/test_config.yml", "--noop"))
@mark.integration
@patch("oshino.core.heart.forever", lambda: False)
@patch("oshino.core.heart.create_loop", create_loop)
@patch("dotenv.find_dotenv", error_stub)
def test_dot_env_fail():
with raises(SystemExit):
main(("--config", "tests/data/test_config.yml", "--noop"))
| // ... existing code ...
return loop
def error_stub():
raise RuntimeError("Simply failing")
@mark.integration
// ... modified code ...
@patch("oshino.core.heart.forever", lambda: False)
@patch("oshino.core.heart.create_loop", create_loop)
@patch("dotenv.find_dotenv", error_stub)
def test_dot_env_fail():
with raises(SystemExit):
// ... rest of the code ... |
966c8e549e1cb78c64ad2f359162bc5a2171a732 | fabfile.py | fabfile.py | from fabric.api import cd, env, local, lcd, run
PUPPET_MASTER_IP = '192.168.33.10'
def puppet():
env.hosts = [
'vagrant@' + PUPPET_MASTER_IP + ':22',
]
env.passwords = {
'vagrant@' + PUPPET_MASTER_IP + ':22': 'vagrant'
}
def test():
with lcd('puppet/modules'):
with lcd('nginx'):
local('rspec')
def deploy():
puppet()
test()
run('rm -rf puppet-untitled-2016')
run('git clone https://github.com/zkan/puppet-untitled-2016.git')
run('sudo rm -rf /etc/puppet/manifests')
run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/manifests /etc/puppet/manifests')
run('sudo rm -rf /etc/puppet/modules')
run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/modules /etc/puppet/modules')
| from fabric.api import cd, env, local, lcd, run
PUPPET_MASTER_IP = '192.168.33.10'
def puppet():
env.hosts = [
'vagrant@' + PUPPET_MASTER_IP + ':22',
]
env.passwords = {
'vagrant@' + PUPPET_MASTER_IP + ':22': 'vagrant'
}
def test():
with lcd('puppet/modules'):
with lcd('nginx'):
local('rspec')
def push():
with lcd('puppet'):
local('git add .')
local('git push origin master')
def deploy():
puppet()
test()
run('rm -rf puppet-untitled-2016')
run('git clone https://github.com/zkan/puppet-untitled-2016.git')
run('sudo rm -rf /etc/puppet/manifests')
run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/manifests /etc/puppet/manifests')
run('sudo rm -rf /etc/puppet/modules')
run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/modules /etc/puppet/modules')
| Add push task (but not use it yet) | Add push task (but not use it yet)
| Python | mit | zkan/puppet-untitled-2016,zkan/puppet-untitled-2016 | from fabric.api import cd, env, local, lcd, run
PUPPET_MASTER_IP = '192.168.33.10'
def puppet():
env.hosts = [
'vagrant@' + PUPPET_MASTER_IP + ':22',
]
env.passwords = {
'vagrant@' + PUPPET_MASTER_IP + ':22': 'vagrant'
}
def test():
with lcd('puppet/modules'):
with lcd('nginx'):
local('rspec')
+ def push():
+ with lcd('puppet'):
+ local('git add .')
+ local('git push origin master')
+
+
def deploy():
puppet()
test()
run('rm -rf puppet-untitled-2016')
run('git clone https://github.com/zkan/puppet-untitled-2016.git')
run('sudo rm -rf /etc/puppet/manifests')
run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/manifests /etc/puppet/manifests')
run('sudo rm -rf /etc/puppet/modules')
run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/modules /etc/puppet/modules')
| Add push task (but not use it yet) | ## Code Before:
from fabric.api import cd, env, local, lcd, run
PUPPET_MASTER_IP = '192.168.33.10'
def puppet():
env.hosts = [
'vagrant@' + PUPPET_MASTER_IP + ':22',
]
env.passwords = {
'vagrant@' + PUPPET_MASTER_IP + ':22': 'vagrant'
}
def test():
with lcd('puppet/modules'):
with lcd('nginx'):
local('rspec')
def deploy():
puppet()
test()
run('rm -rf puppet-untitled-2016')
run('git clone https://github.com/zkan/puppet-untitled-2016.git')
run('sudo rm -rf /etc/puppet/manifests')
run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/manifests /etc/puppet/manifests')
run('sudo rm -rf /etc/puppet/modules')
run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/modules /etc/puppet/modules')
## Instruction:
Add push task (but not use it yet)
## Code After:
from fabric.api import cd, env, local, lcd, run
PUPPET_MASTER_IP = '192.168.33.10'
def puppet():
env.hosts = [
'vagrant@' + PUPPET_MASTER_IP + ':22',
]
env.passwords = {
'vagrant@' + PUPPET_MASTER_IP + ':22': 'vagrant'
}
def test():
with lcd('puppet/modules'):
with lcd('nginx'):
local('rspec')
def push():
with lcd('puppet'):
local('git add .')
local('git push origin master')
def deploy():
puppet()
test()
run('rm -rf puppet-untitled-2016')
run('git clone https://github.com/zkan/puppet-untitled-2016.git')
run('sudo rm -rf /etc/puppet/manifests')
run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/manifests /etc/puppet/manifests')
run('sudo rm -rf /etc/puppet/modules')
run('sudo ln -sf /home/vagrant/puppet-untitled-2016/puppet/modules /etc/puppet/modules')
| ...
def push():
with lcd('puppet'):
local('git add .')
local('git push origin master')
def deploy():
puppet()
... |
e1888771261878d576b05bab806e1abfdc1d25bb | ExpandVariables.py | ExpandVariables.py | import sublime, string, platform
def expand_variables(the_dict, the_vars):
return _expand_variables_recursive(the_dict, the_vars)
def _expand_variables_recursive(the_dict, the_vars):
for key, value in the_dict.items():
if isinstance(value, dict):
value = expand_variables(value, the_vars)
elif isinstance(value, str):
the_dict[key] = string.Template(value).substitute(the_vars)
else:
continue
return the_dict
| import sublime, string, platform
def expand_variables(the_dict, the_vars):
the_vars['machine'] = platform.machine()
the_vars['processor'] = platform.processor()
return _expand_variables_recursive(the_dict, the_vars)
def _expand_variables_recursive(the_dict, the_vars):
for key, value in the_dict.items():
if isinstance(value, dict):
value = expand_variables(value, the_vars)
elif isinstance(value, str):
the_dict[key] = string.Template(value).substitute(the_vars)
else:
continue
return the_dict
| Add extra vars "machine" and "processor" for the cmake dictionary. | Add extra vars "machine" and "processor" for the cmake dictionary.
| Python | mit | rwols/CMakeBuilder | import sublime, string, platform
def expand_variables(the_dict, the_vars):
+ the_vars['machine'] = platform.machine()
+ the_vars['processor'] = platform.processor()
return _expand_variables_recursive(the_dict, the_vars)
def _expand_variables_recursive(the_dict, the_vars):
for key, value in the_dict.items():
if isinstance(value, dict):
value = expand_variables(value, the_vars)
elif isinstance(value, str):
the_dict[key] = string.Template(value).substitute(the_vars)
else:
continue
return the_dict
| Add extra vars "machine" and "processor" for the cmake dictionary. | ## Code Before:
import sublime, string, platform
def expand_variables(the_dict, the_vars):
return _expand_variables_recursive(the_dict, the_vars)
def _expand_variables_recursive(the_dict, the_vars):
for key, value in the_dict.items():
if isinstance(value, dict):
value = expand_variables(value, the_vars)
elif isinstance(value, str):
the_dict[key] = string.Template(value).substitute(the_vars)
else:
continue
return the_dict
## Instruction:
Add extra vars "machine" and "processor" for the cmake dictionary.
## Code After:
import sublime, string, platform
def expand_variables(the_dict, the_vars):
the_vars['machine'] = platform.machine()
the_vars['processor'] = platform.processor()
return _expand_variables_recursive(the_dict, the_vars)
def _expand_variables_recursive(the_dict, the_vars):
for key, value in the_dict.items():
if isinstance(value, dict):
value = expand_variables(value, the_vars)
elif isinstance(value, str):
the_dict[key] = string.Template(value).substitute(the_vars)
else:
continue
return the_dict
| # ... existing code ...
def expand_variables(the_dict, the_vars):
the_vars['machine'] = platform.machine()
the_vars['processor'] = platform.processor()
return _expand_variables_recursive(the_dict, the_vars)
# ... rest of the code ... |
7c3a3283b3da0c01da012bb823d781036d1847b6 | packages/syft/src/syft/core/node/common/node_table/node_route.py | packages/syft/src/syft/core/node/common/node_table/node_route.py | from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
# relative
from . import Base
class NodeRoute(Base):
__tablename__ = "node_route"
id = Column(Integer(), primary_key=True, autoincrement=True)
node_id = Column(Integer, ForeignKey("node.id"))
host_or_ip = Column(String(255))
is_vpn = Column(Boolean(), default=False)
| from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
# relative
from . import Base
class NodeRoute(Base):
__tablename__ = "node_route"
id = Column(Integer(), primary_key=True, autoincrement=True)
node_id = Column(Integer, ForeignKey("node.id"))
host_or_ip = Column(String(255), default="")
is_vpn = Column(Boolean(), default=False)
vpn_endpoint = Column(String(255), default="")
vpn_key = Column(String(255), default="")
| ADD vpn_endpoint and vpn_key columns | ADD vpn_endpoint and vpn_key columns
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
# relative
from . import Base
class NodeRoute(Base):
__tablename__ = "node_route"
id = Column(Integer(), primary_key=True, autoincrement=True)
node_id = Column(Integer, ForeignKey("node.id"))
- host_or_ip = Column(String(255))
+ host_or_ip = Column(String(255), default="")
is_vpn = Column(Boolean(), default=False)
+ vpn_endpoint = Column(String(255), default="")
+ vpn_key = Column(String(255), default="")
| ADD vpn_endpoint and vpn_key columns | ## Code Before:
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
# relative
from . import Base
class NodeRoute(Base):
__tablename__ = "node_route"
id = Column(Integer(), primary_key=True, autoincrement=True)
node_id = Column(Integer, ForeignKey("node.id"))
host_or_ip = Column(String(255))
is_vpn = Column(Boolean(), default=False)
## Instruction:
ADD vpn_endpoint and vpn_key columns
## Code After:
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
# relative
from . import Base
class NodeRoute(Base):
__tablename__ = "node_route"
id = Column(Integer(), primary_key=True, autoincrement=True)
node_id = Column(Integer, ForeignKey("node.id"))
host_or_ip = Column(String(255), default="")
is_vpn = Column(Boolean(), default=False)
vpn_endpoint = Column(String(255), default="")
vpn_key = Column(String(255), default="")
| // ... existing code ...
id = Column(Integer(), primary_key=True, autoincrement=True)
node_id = Column(Integer, ForeignKey("node.id"))
host_or_ip = Column(String(255), default="")
is_vpn = Column(Boolean(), default=False)
vpn_endpoint = Column(String(255), default="")
vpn_key = Column(String(255), default="")
// ... rest of the code ... |
adee7a2530d22d1242f89cddc84795efd1d02653 | imagesift/cms_plugins.py | imagesift/cms_plugins.py | import datetime
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import GalleryPlugin
class ImagesiftPlugin(CMSPluginBase):
model = GalleryPlugin
name = _('Imagesift Plugin')
render_template = "imagesift_plugin.html"
def date_digest(self, images):
"""
return a list of unique dates, for all the images passed
"""
dates = {}
for i in images:
dates.setdefault(i.overrideable_date().date(), None)
return sorted(dates.keys())
def render(self, context, instance, placeholder):
url = context['request'].get_full_path()
date = context['request'].GET.get('date')
limit = instance.thumbnail_limit
qs = instance.get_images_queryset()
if limit:
qs = qs[:limit]
filtered = False
if date:
date = datetime.datetime.strptime(date, "%Y-%m-%d").date()
qs = list(qs)
qs = [i for i in qs if i.overrideable_date().date() == date]
filtered = _('The set of images is filtered to %s' % unicode(date))
context.update({
'dates': [d.isoformat() for d in self.date_digest(qs)],
'filtered':filtered,
'images': qs,
'instance': instance,
'placeholder': placeholder,
'url':url,
})
return context
plugin_pool.register_plugin(ImagesiftPlugin) | import datetime
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import GalleryPlugin
class ImagesiftPlugin(CMSPluginBase):
model = GalleryPlugin
name = _('Imagesift Plugin')
render_template = "imagesift_plugin.html"
def date_digest(self, images):
"""
return a list of unique dates, for all the images passed
"""
dates = {}
for i in images:
dates.setdefault(i.overrideable_date().date(), None)
return sorted(dates.keys())
def render(self, context, instance, placeholder):
url = context['request'].get_full_path()
date = context['request'].GET.get('date')
limit = instance.thumbnail_limit
qs = instance.get_images_queryset()
# there's no way around listing, sorry.
qs = list(qs)
filtered = False
if date:
date = datetime.datetime.strptime(date, "%Y-%m-%d").date()
qs = [i for i in qs if i.overrideable_date().date() == date]
filtered = _('The set of images is filtered to %s' % unicode(date))
# sort before limit
qs.sort(key=lambda i: i.overrideable_date())
if limit:
qs = qs[:limit]
context.update({
'dates': [d.isoformat() for d in self.date_digest(qs)],
'filtered':filtered,
'images': qs,
'instance': instance,
'placeholder': placeholder,
'url':url,
})
return context
plugin_pool.register_plugin(ImagesiftPlugin) | Sort returned images by date, taking into account overrides | Sort returned images by date, taking into account overrides
| Python | bsd-3-clause | topiaruss/cmsplugin-imagesift,topiaruss/cmsplugin-imagesift,topiaruss/cmsplugin-imagesift | import datetime
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import GalleryPlugin
class ImagesiftPlugin(CMSPluginBase):
model = GalleryPlugin
name = _('Imagesift Plugin')
render_template = "imagesift_plugin.html"
def date_digest(self, images):
"""
return a list of unique dates, for all the images passed
"""
dates = {}
for i in images:
dates.setdefault(i.overrideable_date().date(), None)
return sorted(dates.keys())
def render(self, context, instance, placeholder):
url = context['request'].get_full_path()
date = context['request'].GET.get('date')
limit = instance.thumbnail_limit
qs = instance.get_images_queryset()
- if limit:
- qs = qs[:limit]
+ # there's no way around listing, sorry.
+ qs = list(qs)
+
filtered = False
if date:
date = datetime.datetime.strptime(date, "%Y-%m-%d").date()
- qs = list(qs)
qs = [i for i in qs if i.overrideable_date().date() == date]
filtered = _('The set of images is filtered to %s' % unicode(date))
+
+ # sort before limit
+ qs.sort(key=lambda i: i.overrideable_date())
+
+ if limit:
+ qs = qs[:limit]
context.update({
'dates': [d.isoformat() for d in self.date_digest(qs)],
'filtered':filtered,
'images': qs,
'instance': instance,
'placeholder': placeholder,
'url':url,
})
return context
plugin_pool.register_plugin(ImagesiftPlugin) | Sort returned images by date, taking into account overrides | ## Code Before:
import datetime
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import GalleryPlugin
class ImagesiftPlugin(CMSPluginBase):
model = GalleryPlugin
name = _('Imagesift Plugin')
render_template = "imagesift_plugin.html"
def date_digest(self, images):
"""
return a list of unique dates, for all the images passed
"""
dates = {}
for i in images:
dates.setdefault(i.overrideable_date().date(), None)
return sorted(dates.keys())
def render(self, context, instance, placeholder):
url = context['request'].get_full_path()
date = context['request'].GET.get('date')
limit = instance.thumbnail_limit
qs = instance.get_images_queryset()
if limit:
qs = qs[:limit]
filtered = False
if date:
date = datetime.datetime.strptime(date, "%Y-%m-%d").date()
qs = list(qs)
qs = [i for i in qs if i.overrideable_date().date() == date]
filtered = _('The set of images is filtered to %s' % unicode(date))
context.update({
'dates': [d.isoformat() for d in self.date_digest(qs)],
'filtered':filtered,
'images': qs,
'instance': instance,
'placeholder': placeholder,
'url':url,
})
return context
plugin_pool.register_plugin(ImagesiftPlugin)
## Instruction:
Sort returned images by date, taking into account overrides
## Code After:
import datetime
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import GalleryPlugin
class ImagesiftPlugin(CMSPluginBase):
model = GalleryPlugin
name = _('Imagesift Plugin')
render_template = "imagesift_plugin.html"
def date_digest(self, images):
"""
return a list of unique dates, for all the images passed
"""
dates = {}
for i in images:
dates.setdefault(i.overrideable_date().date(), None)
return sorted(dates.keys())
def render(self, context, instance, placeholder):
url = context['request'].get_full_path()
date = context['request'].GET.get('date')
limit = instance.thumbnail_limit
qs = instance.get_images_queryset()
# there's no way around listing, sorry.
qs = list(qs)
filtered = False
if date:
date = datetime.datetime.strptime(date, "%Y-%m-%d").date()
qs = [i for i in qs if i.overrideable_date().date() == date]
filtered = _('The set of images is filtered to %s' % unicode(date))
# sort before limit
qs.sort(key=lambda i: i.overrideable_date())
if limit:
qs = qs[:limit]
context.update({
'dates': [d.isoformat() for d in self.date_digest(qs)],
'filtered':filtered,
'images': qs,
'instance': instance,
'placeholder': placeholder,
'url':url,
})
return context
plugin_pool.register_plugin(ImagesiftPlugin) | ...
limit = instance.thumbnail_limit
qs = instance.get_images_queryset()
# there's no way around listing, sorry.
qs = list(qs)
filtered = False
if date:
date = datetime.datetime.strptime(date, "%Y-%m-%d").date()
qs = [i for i in qs if i.overrideable_date().date() == date]
filtered = _('The set of images is filtered to %s' % unicode(date))
# sort before limit
qs.sort(key=lambda i: i.overrideable_date())
if limit:
qs = qs[:limit]
context.update({
... |
cc2f0900b02891e0ab23133778065a6f6768cd5c | setup.py | setup.py | from distutils.core import setup
setup(
name = 'furs_fiscal',
packages = ['furs_fiscal'],
version = '0.1.0',
description = 'Python library for simplified communication with FURS (Financna uprava Republike Slovenije).',
author = 'Boris Savic',
author_email = '[email protected]',
url = 'https://github.com/boris-savic/python-furs-fiscal',
download_url = 'https://github.com/boris-savic/python-furs-fiscal/tarball/0.1',
keywords = ['FURS', 'fiscal', 'fiscal register', 'davcne blagajne'],
classifiers = [],
install_requires=[
'requests',
'python-jose',
'pyOpenSSL',
'urllib3',
'pyasn1',
'ndg-httpsclient'
]
) | from distutils.core import setup
setup(
name = 'furs_fiscal',
packages = ['furs_fiscal'],
version = '0.1.3',
description = 'Python library for simplified communication with FURS (Financna uprava Republike Slovenije).',
author = 'Boris Savic',
author_email = '[email protected]',
url = 'https://github.com/boris-savic/python-furs-fiscal',
download_url = 'https://github.com/boris-savic/python-furs-fiscal/tarball/0.1.3',
keywords = ['FURS', 'fiscal', 'fiscal register', 'davcne blagajne'],
classifiers = [],
package_data={'furs_fiscal': ['certs/*.pem']},
install_requires=[
'requests',
'python-jose',
'pyOpenSSL',
'urllib3',
'pyasn1',
'ndg-httpsclient'
]
) | Add test_certificate.pem to the release | Add test_certificate.pem to the release
| Python | mit | boris-savic/python-furs-fiscal | from distutils.core import setup
setup(
name = 'furs_fiscal',
packages = ['furs_fiscal'],
- version = '0.1.0',
+ version = '0.1.3',
description = 'Python library for simplified communication with FURS (Financna uprava Republike Slovenije).',
author = 'Boris Savic',
author_email = '[email protected]',
url = 'https://github.com/boris-savic/python-furs-fiscal',
- download_url = 'https://github.com/boris-savic/python-furs-fiscal/tarball/0.1',
+ download_url = 'https://github.com/boris-savic/python-furs-fiscal/tarball/0.1.3',
keywords = ['FURS', 'fiscal', 'fiscal register', 'davcne blagajne'],
classifiers = [],
+ package_data={'furs_fiscal': ['certs/*.pem']},
install_requires=[
'requests',
'python-jose',
'pyOpenSSL',
'urllib3',
'pyasn1',
'ndg-httpsclient'
]
) | Add test_certificate.pem to the release | ## Code Before:
from distutils.core import setup
setup(
name = 'furs_fiscal',
packages = ['furs_fiscal'],
version = '0.1.0',
description = 'Python library for simplified communication with FURS (Financna uprava Republike Slovenije).',
author = 'Boris Savic',
author_email = '[email protected]',
url = 'https://github.com/boris-savic/python-furs-fiscal',
download_url = 'https://github.com/boris-savic/python-furs-fiscal/tarball/0.1',
keywords = ['FURS', 'fiscal', 'fiscal register', 'davcne blagajne'],
classifiers = [],
install_requires=[
'requests',
'python-jose',
'pyOpenSSL',
'urllib3',
'pyasn1',
'ndg-httpsclient'
]
)
## Instruction:
Add test_certificate.pem to the release
## Code After:
from distutils.core import setup
setup(
name = 'furs_fiscal',
packages = ['furs_fiscal'],
version = '0.1.3',
description = 'Python library for simplified communication with FURS (Financna uprava Republike Slovenije).',
author = 'Boris Savic',
author_email = '[email protected]',
url = 'https://github.com/boris-savic/python-furs-fiscal',
download_url = 'https://github.com/boris-savic/python-furs-fiscal/tarball/0.1.3',
keywords = ['FURS', 'fiscal', 'fiscal register', 'davcne blagajne'],
classifiers = [],
package_data={'furs_fiscal': ['certs/*.pem']},
install_requires=[
'requests',
'python-jose',
'pyOpenSSL',
'urllib3',
'pyasn1',
'ndg-httpsclient'
]
) | # ... existing code ...
name = 'furs_fiscal',
packages = ['furs_fiscal'],
version = '0.1.3',
description = 'Python library for simplified communication with FURS (Financna uprava Republike Slovenije).',
author = 'Boris Savic',
# ... modified code ...
author_email = '[email protected]',
url = 'https://github.com/boris-savic/python-furs-fiscal',
download_url = 'https://github.com/boris-savic/python-furs-fiscal/tarball/0.1.3',
keywords = ['FURS', 'fiscal', 'fiscal register', 'davcne blagajne'],
classifiers = [],
package_data={'furs_fiscal': ['certs/*.pem']},
install_requires=[
'requests',
# ... rest of the code ... |
a364196814c3b33e7fd51a42b4c3a48a3aaeaee8 | volaparrot/constants.py | volaparrot/constants.py | ADMINFAG = ["RealDolos"]
PARROTFAG = "Parrot"
BLACKFAGS = [i.casefold() for i in (
"kalyx", "merc", "loliq", "annoying", "bot", "RootBeats", "JEW2FORU", "quag", "mire", "perici")]
OBAMAS = [i.casefold() for i in (
"counselor", "briseis", "apha", "bread", "ark3", "jizzbomb", "acid", "elkoalemos", "tarta")]
BLACKROOMS = "e7u-CG", "jAzmc3", "f66jeG", "24_zFd"
WHITEROOMS = "9pdLvy"
| ADMINFAG = ["RealDolos"]
PARROTFAG = "Parrot"
BLACKFAGS = [i.casefold() for i in (
"kalyx", "merc", "loliq", "annoying", "RootBeats", "JEW2FORU", "quag", "mire", "perici", "Voldemort", "briseis", "brisis", "GNUsuks", "rhooes", "n1sm4n", "honeyhole", "Printer", "yume1")]
OBAMAS = [i.casefold() for i in (
"counselor", "briseis", "apha", "bread", "ark3", "jizzbomb", "acid", "elkoalemos", "tarta", "counselor", "myon")]
BLACKROOMS = "e7u-CG", "jAzmc3", "f66jeG", "24_zFd", "BHfjGvT", "BHI0pxg",
WHITEROOMS = "BEEPi",
| Update list of extraordinary gentlemen | Update list of extraordinary gentlemen
| Python | mit | RealDolos/volaparrot | ADMINFAG = ["RealDolos"]
PARROTFAG = "Parrot"
BLACKFAGS = [i.casefold() for i in (
- "kalyx", "merc", "loliq", "annoying", "bot", "RootBeats", "JEW2FORU", "quag", "mire", "perici")]
+ "kalyx", "merc", "loliq", "annoying", "RootBeats", "JEW2FORU", "quag", "mire", "perici", "Voldemort", "briseis", "brisis", "GNUsuks", "rhooes", "n1sm4n", "honeyhole", "Printer", "yume1")]
OBAMAS = [i.casefold() for i in (
- "counselor", "briseis", "apha", "bread", "ark3", "jizzbomb", "acid", "elkoalemos", "tarta")]
+ "counselor", "briseis", "apha", "bread", "ark3", "jizzbomb", "acid", "elkoalemos", "tarta", "counselor", "myon")]
- BLACKROOMS = "e7u-CG", "jAzmc3", "f66jeG", "24_zFd"
+ BLACKROOMS = "e7u-CG", "jAzmc3", "f66jeG", "24_zFd", "BHfjGvT", "BHI0pxg",
- WHITEROOMS = "9pdLvy"
+ WHITEROOMS = "BEEPi",
| Update list of extraordinary gentlemen | ## Code Before:
ADMINFAG = ["RealDolos"]
PARROTFAG = "Parrot"
BLACKFAGS = [i.casefold() for i in (
"kalyx", "merc", "loliq", "annoying", "bot", "RootBeats", "JEW2FORU", "quag", "mire", "perici")]
OBAMAS = [i.casefold() for i in (
"counselor", "briseis", "apha", "bread", "ark3", "jizzbomb", "acid", "elkoalemos", "tarta")]
BLACKROOMS = "e7u-CG", "jAzmc3", "f66jeG", "24_zFd"
WHITEROOMS = "9pdLvy"
## Instruction:
Update list of extraordinary gentlemen
## Code After:
ADMINFAG = ["RealDolos"]
PARROTFAG = "Parrot"
BLACKFAGS = [i.casefold() for i in (
"kalyx", "merc", "loliq", "annoying", "RootBeats", "JEW2FORU", "quag", "mire", "perici", "Voldemort", "briseis", "brisis", "GNUsuks", "rhooes", "n1sm4n", "honeyhole", "Printer", "yume1")]
OBAMAS = [i.casefold() for i in (
"counselor", "briseis", "apha", "bread", "ark3", "jizzbomb", "acid", "elkoalemos", "tarta", "counselor", "myon")]
BLACKROOMS = "e7u-CG", "jAzmc3", "f66jeG", "24_zFd", "BHfjGvT", "BHI0pxg",
WHITEROOMS = "BEEPi",
| // ... existing code ...
BLACKFAGS = [i.casefold() for i in (
"kalyx", "merc", "loliq", "annoying", "RootBeats", "JEW2FORU", "quag", "mire", "perici", "Voldemort", "briseis", "brisis", "GNUsuks", "rhooes", "n1sm4n", "honeyhole", "Printer", "yume1")]
OBAMAS = [i.casefold() for i in (
"counselor", "briseis", "apha", "bread", "ark3", "jizzbomb", "acid", "elkoalemos", "tarta", "counselor", "myon")]
BLACKROOMS = "e7u-CG", "jAzmc3", "f66jeG", "24_zFd", "BHfjGvT", "BHI0pxg",
WHITEROOMS = "BEEPi",
// ... rest of the code ... |
3fd7c331273f9fadacae1fcb0ff51b9817b009e3 | telethon/network/connection/tcpfull.py | telethon/network/connection/tcpfull.py | import struct
from zlib import crc32
from .connection import Connection
from ...errors import InvalidChecksumError
class ConnectionTcpFull(Connection):
"""
Default Telegram mode. Sends 12 additional bytes and
needs to calculate the CRC value of the packet itself.
"""
def __init__(self, ip, port, *, loop):
super().__init__(ip, port, loop=loop)
self._send_counter = 0
def _send(self, data):
# https://core.telegram.org/mtproto#tcp-transport
# total length, sequence number, packet and checksum (CRC32)
length = len(data) + 12
data = struct.pack('<ii', length, self._send_counter) + data
crc = struct.pack('<I', crc32(data))
self._send_counter += 1
self._writer.write(data + crc)
async def _recv(self):
packet_len_seq = await self._reader.readexactly(8) # 4 and 4
packet_len, seq = struct.unpack('<ii', packet_len_seq)
body = await self._reader.readexactly(packet_len - 8)
checksum = struct.unpack('<I', body[-4:])[0]
body = body[:-4]
valid_checksum = crc32(packet_len_seq + body)
if checksum != valid_checksum:
raise InvalidChecksumError(checksum, valid_checksum)
return body
| import struct
from zlib import crc32
from .connection import Connection
from ...errors import InvalidChecksumError
class ConnectionTcpFull(Connection):
"""
Default Telegram mode. Sends 12 additional bytes and
needs to calculate the CRC value of the packet itself.
"""
def __init__(self, ip, port, *, loop):
super().__init__(ip, port, loop=loop)
self._send_counter = 0
async def connect(self):
await super().connect()
self._send_counter = 0 # Important or Telegram won't reply
def _send(self, data):
# https://core.telegram.org/mtproto#tcp-transport
# total length, sequence number, packet and checksum (CRC32)
length = len(data) + 12
data = struct.pack('<ii', length, self._send_counter) + data
crc = struct.pack('<I', crc32(data))
self._send_counter += 1
self._writer.write(data + crc)
async def _recv(self):
packet_len_seq = await self._reader.readexactly(8) # 4 and 4
packet_len, seq = struct.unpack('<ii', packet_len_seq)
body = await self._reader.readexactly(packet_len - 8)
checksum = struct.unpack('<I', body[-4:])[0]
body = body[:-4]
valid_checksum = crc32(packet_len_seq + body)
if checksum != valid_checksum:
raise InvalidChecksumError(checksum, valid_checksum)
return body
| Fix automatic reconnect (e.g. on bad auth key) | Fix automatic reconnect (e.g. on bad auth key)
This took more time than it should have to debug.
| Python | mit | LonamiWebs/Telethon,expectocode/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon | import struct
from zlib import crc32
from .connection import Connection
from ...errors import InvalidChecksumError
class ConnectionTcpFull(Connection):
"""
Default Telegram mode. Sends 12 additional bytes and
needs to calculate the CRC value of the packet itself.
"""
def __init__(self, ip, port, *, loop):
super().__init__(ip, port, loop=loop)
self._send_counter = 0
+
+ async def connect(self):
+ await super().connect()
+ self._send_counter = 0 # Important or Telegram won't reply
def _send(self, data):
# https://core.telegram.org/mtproto#tcp-transport
# total length, sequence number, packet and checksum (CRC32)
length = len(data) + 12
data = struct.pack('<ii', length, self._send_counter) + data
crc = struct.pack('<I', crc32(data))
self._send_counter += 1
self._writer.write(data + crc)
async def _recv(self):
packet_len_seq = await self._reader.readexactly(8) # 4 and 4
packet_len, seq = struct.unpack('<ii', packet_len_seq)
body = await self._reader.readexactly(packet_len - 8)
checksum = struct.unpack('<I', body[-4:])[0]
body = body[:-4]
valid_checksum = crc32(packet_len_seq + body)
if checksum != valid_checksum:
raise InvalidChecksumError(checksum, valid_checksum)
return body
| Fix automatic reconnect (e.g. on bad auth key) | ## Code Before:
import struct
from zlib import crc32
from .connection import Connection
from ...errors import InvalidChecksumError
class ConnectionTcpFull(Connection):
"""
Default Telegram mode. Sends 12 additional bytes and
needs to calculate the CRC value of the packet itself.
"""
def __init__(self, ip, port, *, loop):
super().__init__(ip, port, loop=loop)
self._send_counter = 0
def _send(self, data):
# https://core.telegram.org/mtproto#tcp-transport
# total length, sequence number, packet and checksum (CRC32)
length = len(data) + 12
data = struct.pack('<ii', length, self._send_counter) + data
crc = struct.pack('<I', crc32(data))
self._send_counter += 1
self._writer.write(data + crc)
async def _recv(self):
packet_len_seq = await self._reader.readexactly(8) # 4 and 4
packet_len, seq = struct.unpack('<ii', packet_len_seq)
body = await self._reader.readexactly(packet_len - 8)
checksum = struct.unpack('<I', body[-4:])[0]
body = body[:-4]
valid_checksum = crc32(packet_len_seq + body)
if checksum != valid_checksum:
raise InvalidChecksumError(checksum, valid_checksum)
return body
## Instruction:
Fix automatic reconnect (e.g. on bad auth key)
## Code After:
import struct
from zlib import crc32
from .connection import Connection
from ...errors import InvalidChecksumError
class ConnectionTcpFull(Connection):
"""
Default Telegram mode. Sends 12 additional bytes and
needs to calculate the CRC value of the packet itself.
"""
def __init__(self, ip, port, *, loop):
super().__init__(ip, port, loop=loop)
self._send_counter = 0
async def connect(self):
await super().connect()
self._send_counter = 0 # Important or Telegram won't reply
def _send(self, data):
# https://core.telegram.org/mtproto#tcp-transport
# total length, sequence number, packet and checksum (CRC32)
length = len(data) + 12
data = struct.pack('<ii', length, self._send_counter) + data
crc = struct.pack('<I', crc32(data))
self._send_counter += 1
self._writer.write(data + crc)
async def _recv(self):
packet_len_seq = await self._reader.readexactly(8) # 4 and 4
packet_len, seq = struct.unpack('<ii', packet_len_seq)
body = await self._reader.readexactly(packet_len - 8)
checksum = struct.unpack('<I', body[-4:])[0]
body = body[:-4]
valid_checksum = crc32(packet_len_seq + body)
if checksum != valid_checksum:
raise InvalidChecksumError(checksum, valid_checksum)
return body
| # ... existing code ...
super().__init__(ip, port, loop=loop)
self._send_counter = 0
async def connect(self):
await super().connect()
self._send_counter = 0 # Important or Telegram won't reply
def _send(self, data):
# ... rest of the code ... |
2fb1e51d7131f089b6cedbdf227eddb79e3641bf | zerver/webhooks/dropbox/view.py | zerver/webhooks/dropbox/view.py | from django.http import HttpRequest, HttpResponse
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import check_send_webhook_message
from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view
from zerver.models import UserProfile
@api_key_only_webhook_view('Dropbox')
@has_request_variables
def api_dropbox_webhook(request: HttpRequest, user_profile: UserProfile,
notify_bot_owner_on_invalid_json=False) -> HttpResponse:
if request.method == 'GET':
return HttpResponse(request.GET['challenge'])
elif request.method == 'POST':
topic = 'Dropbox'
check_send_webhook_message(request, user_profile, topic,
"File has been updated on Dropbox!")
return json_success()
| from django.http import HttpRequest, HttpResponse
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import check_send_webhook_message
from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view
from zerver.models import UserProfile
@api_key_only_webhook_view('Dropbox', notify_bot_owner_on_invalid_json=False)
@has_request_variables
def api_dropbox_webhook(request: HttpRequest, user_profile: UserProfile) -> HttpResponse:
if request.method == 'GET':
return HttpResponse(request.GET['challenge'])
elif request.method == 'POST':
topic = 'Dropbox'
check_send_webhook_message(request, user_profile, topic,
"File has been updated on Dropbox!")
return json_success()
| Fix incorrect placement of notify_bot_owner_on_invalid_json. | dropbox: Fix incorrect placement of notify_bot_owner_on_invalid_json.
This was an error I introduced in editing
b79213d2602291a4c7ccbafe0f775f77db60665b.
| Python | apache-2.0 | punchagan/zulip,brainwane/zulip,andersk/zulip,dhcrzf/zulip,rht/zulip,rishig/zulip,dhcrzf/zulip,andersk/zulip,showell/zulip,punchagan/zulip,rishig/zulip,showell/zulip,kou/zulip,kou/zulip,hackerkid/zulip,brainwane/zulip,synicalsyntax/zulip,hackerkid/zulip,rishig/zulip,jackrzhang/zulip,kou/zulip,andersk/zulip,rht/zulip,timabbott/zulip,punchagan/zulip,jackrzhang/zulip,hackerkid/zulip,showell/zulip,dhcrzf/zulip,shubhamdhama/zulip,jackrzhang/zulip,kou/zulip,brainwane/zulip,shubhamdhama/zulip,dhcrzf/zulip,timabbott/zulip,kou/zulip,showell/zulip,timabbott/zulip,punchagan/zulip,timabbott/zulip,dhcrzf/zulip,rishig/zulip,synicalsyntax/zulip,jackrzhang/zulip,rht/zulip,rishig/zulip,brainwane/zulip,timabbott/zulip,synicalsyntax/zulip,synicalsyntax/zulip,zulip/zulip,shubhamdhama/zulip,hackerkid/zulip,jackrzhang/zulip,tommyip/zulip,kou/zulip,tommyip/zulip,eeshangarg/zulip,brainwane/zulip,andersk/zulip,andersk/zulip,zulip/zulip,timabbott/zulip,rht/zulip,shubhamdhama/zulip,tommyip/zulip,zulip/zulip,punchagan/zulip,dhcrzf/zulip,andersk/zulip,brainwane/zulip,synicalsyntax/zulip,jackrzhang/zulip,zulip/zulip,shubhamdhama/zulip,eeshangarg/zulip,andersk/zulip,shubhamdhama/zulip,rishig/zulip,synicalsyntax/zulip,synicalsyntax/zulip,zulip/zulip,tommyip/zulip,hackerkid/zulip,showell/zulip,tommyip/zulip,hackerkid/zulip,punchagan/zulip,dhcrzf/zulip,rht/zulip,shubhamdhama/zulip,jackrzhang/zulip,timabbott/zulip,brainwane/zulip,zulip/zulip,rishig/zulip,kou/zulip,eeshangarg/zulip,rht/zulip,hackerkid/zulip,eeshangarg/zulip,tommyip/zulip,rht/zulip,eeshangarg/zulip,showell/zulip,eeshangarg/zulip,punchagan/zulip,zulip/zulip,tommyip/zulip,eeshangarg/zulip,showell/zulip | from django.http import HttpRequest, HttpResponse
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import check_send_webhook_message
from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view
from zerver.models import UserProfile
- @api_key_only_webhook_view('Dropbox')
+ @api_key_only_webhook_view('Dropbox', notify_bot_owner_on_invalid_json=False)
@has_request_variables
- def api_dropbox_webhook(request: HttpRequest, user_profile: UserProfile,
+ def api_dropbox_webhook(request: HttpRequest, user_profile: UserProfile) -> HttpResponse:
- notify_bot_owner_on_invalid_json=False) -> HttpResponse:
if request.method == 'GET':
return HttpResponse(request.GET['challenge'])
elif request.method == 'POST':
topic = 'Dropbox'
check_send_webhook_message(request, user_profile, topic,
"File has been updated on Dropbox!")
return json_success()
| Fix incorrect placement of notify_bot_owner_on_invalid_json. | ## Code Before:
from django.http import HttpRequest, HttpResponse
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import check_send_webhook_message
from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view
from zerver.models import UserProfile
@api_key_only_webhook_view('Dropbox')
@has_request_variables
def api_dropbox_webhook(request: HttpRequest, user_profile: UserProfile,
notify_bot_owner_on_invalid_json=False) -> HttpResponse:
if request.method == 'GET':
return HttpResponse(request.GET['challenge'])
elif request.method == 'POST':
topic = 'Dropbox'
check_send_webhook_message(request, user_profile, topic,
"File has been updated on Dropbox!")
return json_success()
## Instruction:
Fix incorrect placement of notify_bot_owner_on_invalid_json.
## Code After:
from django.http import HttpRequest, HttpResponse
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import check_send_webhook_message
from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view
from zerver.models import UserProfile
@api_key_only_webhook_view('Dropbox', notify_bot_owner_on_invalid_json=False)
@has_request_variables
def api_dropbox_webhook(request: HttpRequest, user_profile: UserProfile) -> HttpResponse:
if request.method == 'GET':
return HttpResponse(request.GET['challenge'])
elif request.method == 'POST':
topic = 'Dropbox'
check_send_webhook_message(request, user_profile, topic,
"File has been updated on Dropbox!")
return json_success()
| ...
from zerver.models import UserProfile
@api_key_only_webhook_view('Dropbox', notify_bot_owner_on_invalid_json=False)
@has_request_variables
def api_dropbox_webhook(request: HttpRequest, user_profile: UserProfile) -> HttpResponse:
if request.method == 'GET':
return HttpResponse(request.GET['challenge'])
... |
ba75572bd7de9a441cad72fe90d7ec233e9c1a15 | test/adapt.py | test/adapt.py |
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
from __init__ import TestCase
from html5_parser import parse
HTML = '''
<html lang="en" xml:lang="en">
<head><script>a < & " b</script><title>title</title></head>
<body>
<p>A <span>test</span> of text and tail
<p><svg viewbox="v"><image xlink:href="h">
</body>
<!-- A -- comment --->
</html>
'''
class AdaptTest(TestCase):
def test_etree(self):
from xml.etree.ElementTree import tostring
root = parse(HTML, treebuilder='etree')
self.ae(root.tag, 'html')
self.ae(root.attrib, {'xml:lang': 'en', 'lang': 'en'})
self.ae(root.find('./head/script').text, 'a < & " b')
self.ae(
tostring(root.find('body').find('p'), method='text').decode('ascii'),
'A test of text and tail\n')
if sys.version_info.major > 2:
self.assertIn('<!-- A -- comment --->', tostring(root))
|
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
from __init__ import TestCase
from html5_parser import parse
HTML = '''
<html lang="en" xml:lang="en">
<head><script>a < & " b</script><title>title</title></head>
<body>
<p>A <span>test</span> of text and tail
<p><svg viewbox="v"><image xlink:href="h">
</body>
<!-- A -- comment --->
</html>
'''
class AdaptTest(TestCase):
def test_etree(self):
from xml.etree.ElementTree import tostring
root = parse(HTML, treebuilder='etree')
self.ae(root.tag, 'html')
self.ae(root.attrib, {'xml:lang': 'en', 'lang': 'en'})
self.ae(root.find('./head/script').text, 'a < & " b')
self.ae(
tostring(root.find('body').find('p'), method='text').decode('ascii'),
'A test of text and tail\n')
if sys.version_info.major > 2:
self.assertIn('<!-- A -- comment --->', tostring(root).decode('ascii'))
| Fix test failing on python 3 | Fix test failing on python 3
| Python | apache-2.0 | kovidgoyal/html5-parser,kovidgoyal/html5-parser |
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
from __init__ import TestCase
from html5_parser import parse
HTML = '''
<html lang="en" xml:lang="en">
<head><script>a < & " b</script><title>title</title></head>
<body>
<p>A <span>test</span> of text and tail
<p><svg viewbox="v"><image xlink:href="h">
</body>
<!-- A -- comment --->
</html>
'''
class AdaptTest(TestCase):
def test_etree(self):
from xml.etree.ElementTree import tostring
root = parse(HTML, treebuilder='etree')
self.ae(root.tag, 'html')
self.ae(root.attrib, {'xml:lang': 'en', 'lang': 'en'})
self.ae(root.find('./head/script').text, 'a < & " b')
self.ae(
tostring(root.find('body').find('p'), method='text').decode('ascii'),
'A test of text and tail\n')
if sys.version_info.major > 2:
- self.assertIn('<!-- A -- comment --->', tostring(root))
+ self.assertIn('<!-- A -- comment --->', tostring(root).decode('ascii'))
| Fix test failing on python 3 | ## Code Before:
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
from __init__ import TestCase
from html5_parser import parse
HTML = '''
<html lang="en" xml:lang="en">
<head><script>a < & " b</script><title>title</title></head>
<body>
<p>A <span>test</span> of text and tail
<p><svg viewbox="v"><image xlink:href="h">
</body>
<!-- A -- comment --->
</html>
'''
class AdaptTest(TestCase):
def test_etree(self):
from xml.etree.ElementTree import tostring
root = parse(HTML, treebuilder='etree')
self.ae(root.tag, 'html')
self.ae(root.attrib, {'xml:lang': 'en', 'lang': 'en'})
self.ae(root.find('./head/script').text, 'a < & " b')
self.ae(
tostring(root.find('body').find('p'), method='text').decode('ascii'),
'A test of text and tail\n')
if sys.version_info.major > 2:
self.assertIn('<!-- A -- comment --->', tostring(root))
## Instruction:
Fix test failing on python 3
## Code After:
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
from __init__ import TestCase
from html5_parser import parse
HTML = '''
<html lang="en" xml:lang="en">
<head><script>a < & " b</script><title>title</title></head>
<body>
<p>A <span>test</span> of text and tail
<p><svg viewbox="v"><image xlink:href="h">
</body>
<!-- A -- comment --->
</html>
'''
class AdaptTest(TestCase):
def test_etree(self):
from xml.etree.ElementTree import tostring
root = parse(HTML, treebuilder='etree')
self.ae(root.tag, 'html')
self.ae(root.attrib, {'xml:lang': 'en', 'lang': 'en'})
self.ae(root.find('./head/script').text, 'a < & " b')
self.ae(
tostring(root.find('body').find('p'), method='text').decode('ascii'),
'A test of text and tail\n')
if sys.version_info.major > 2:
self.assertIn('<!-- A -- comment --->', tostring(root).decode('ascii'))
| // ... existing code ...
'A test of text and tail\n')
if sys.version_info.major > 2:
self.assertIn('<!-- A -- comment --->', tostring(root).decode('ascii'))
// ... rest of the code ... |
3c95ba7e4eda0762d735503b718119e361eb7295 | tests/basics/try-finally-return.py | tests/basics/try-finally-return.py | def func1():
try:
return "it worked"
finally:
print("finally 1")
print(func1())
| def func1():
try:
return "it worked"
finally:
print("finally 1")
print(func1())
def func2():
try:
return "it worked"
finally:
print("finally 2")
def func3():
try:
s = func2()
return s + ", did this work?"
finally:
print("finally 3")
print(func3())
| Add additional testcase for finally/return. | Add additional testcase for finally/return.
| Python | mit | heisewangluo/micropython,noahchense/micropython,henriknelson/micropython,alex-robbins/micropython,aethaniel/micropython,pramasoul/micropython,jlillest/micropython,noahwilliamsson/micropython,henriknelson/micropython,warner83/micropython,ruffy91/micropython,adafruit/circuitpython,mianos/micropython,dhylands/micropython,tralamazza/micropython,swegener/micropython,tralamazza/micropython,oopy/micropython,toolmacher/micropython,paul-xxx/micropython,orionrobots/micropython,oopy/micropython,ceramos/micropython,matthewelse/micropython,hosaka/micropython,EcmaXp/micropython,alex-robbins/micropython,xyb/micropython,galenhz/micropython,neilh10/micropython,drrk/micropython,cloudformdesign/micropython,Peetz0r/micropython-esp32,Timmenem/micropython,jimkmc/micropython,swegener/micropython,skybird6672/micropython,pfalcon/micropython,warner83/micropython,drrk/micropython,danicampora/micropython,lowRISC/micropython,ernesto-g/micropython,kostyll/micropython,HenrikSolver/micropython,cwyark/micropython,methoxid/micropystat,vriera/micropython,Timmenem/micropython,vitiral/micropython,supergis/micropython,MrSurly/micropython-esp32,stonegithubs/micropython,omtinez/micropython,martinribelotta/micropython,firstval/micropython,heisewangluo/micropython,supergis/micropython,emfcamp/micropython,utopiaprince/micropython,noahwilliamsson/micropython,KISSMonX/micropython,rubencabrera/micropython,hiway/micropython,hiway/micropython,chrisdearman/micropython,torwag/micropython,methoxid/micropystat,SungEun-Steve-Kim/test-mp,TDAbboud/micropython,mgyenik/micropython,neilh10/micropython,infinnovation/micropython,praemdonck/micropython,supergis/micropython,adamkh/micropython,mpalomer/micropython,PappaPeppar/micropython,dhylands/micropython,TDAbboud/micropython,turbinenreiter/micropython,rubencabrera/micropython,dinau/micropython,Vogtinator/micropython,EcmaXp/micropython,bvernoux/micropython,ChuckM/micropython,PappaPeppar/micropython,redbear/micropython,turbinenreiter/micropython,torwag/micropython,infinnovation/micropython,PappaPeppar/micropython,mianos/micropython,SHA2017-badge/micropython-esp32,AriZuu/micropython,hosaka/micropython,supergis/micropython,turbinenreiter/micropython,torwag/micropython,ahotam/micropython,drrk/micropython,deshipu/micropython,methoxid/micropystat,alex-march/micropython,hosaka/micropython,praemdonck/micropython,stonegithubs/micropython,xuxiaoxin/micropython,slzatz/micropython,selste/micropython,swegener/micropython,adafruit/micropython,jimkmc/micropython,Vogtinator/micropython,toolmacher/micropython,stonegithubs/micropython,toolmacher/micropython,galenhz/micropython,adafruit/micropython,mianos/micropython,alex-robbins/micropython,matthewelse/micropython,HenrikSolver/micropython,tuc-osg/micropython,praemdonck/micropython,firstval/micropython,blazewicz/micropython,feilongfl/micropython,pramasoul/micropython,dxxb/micropython,cwyark/micropython,martinribelotta/micropython,adafruit/circuitpython,TDAbboud/micropython,blazewicz/micropython,ceramos/micropython,adamkh/micropython,utopiaprince/micropython,tdautc19841202/micropython,dinau/micropython,lbattraw/micropython,xhat/micropython,MrSurly/micropython-esp32,ahotam/micropython,galenhz/micropython,dinau/micropython,jmarcelino/pycom-micropython,ryannathans/micropython,SungEun-Steve-Kim/test-mp,ChuckM/micropython,mhoffma/micropython,ruffy91/micropython,micropython/micropython-esp32,dxxb/micropython,martinribelotta/micropython,rubencabrera/micropython,ericsnowcurrently/micropython,vriera/micropython,danicampora/micropython,xuxiaoxin/micropython,vriera/micropython,kostyll/micropython,firstval/micropython,dhylands/micropython,pfalcon/micropython,supergis/micropython,redbear/micropython,pfalcon/micropython,MrSurly/micropython,alex-robbins/micropython,jlillest/micropython,pramasoul/micropython,cnoviello/micropython,pozetroninc/micropython,ryannathans/micropython,adafruit/circuitpython,galenhz/micropython,bvernoux/micropython,Timmenem/micropython,tdautc19841202/micropython,danicampora/micropython,noahchense/micropython,suda/micropython,cnoviello/micropython,hosaka/micropython,torwag/micropython,SHA2017-badge/micropython-esp32,tobbad/micropython,blmorris/micropython,xyb/micropython,noahchense/micropython,kerneltask/micropython,ruffy91/micropython,deshipu/micropython,cloudformdesign/micropython,firstval/micropython,SungEun-Steve-Kim/test-mp,orionrobots/micropython,dinau/micropython,warner83/micropython,aethaniel/micropython,jlillest/micropython,blazewicz/micropython,jimkmc/micropython,neilh10/micropython,stonegithubs/micropython,KISSMonX/micropython,pfalcon/micropython,ceramos/micropython,TDAbboud/micropython,deshipu/micropython,feilongfl/micropython,SHA2017-badge/micropython-esp32,cnoviello/micropython,mianos/micropython,trezor/micropython,swegener/micropython,blazewicz/micropython,alex-robbins/micropython,skybird6672/micropython,blmorris/micropython,Peetz0r/micropython-esp32,KISSMonX/micropython,aitjcize/micropython,dinau/micropython,mianos/micropython,chrisdearman/micropython,warner83/micropython,micropython/micropython-esp32,ruffy91/micropython,kerneltask/micropython,orionrobots/micropython,jlillest/micropython,MrSurly/micropython,infinnovation/micropython,bvernoux/micropython,adafruit/micropython,danicampora/micropython,ganshun666/micropython,tobbad/micropython,trezor/micropython,omtinez/micropython,misterdanb/micropython,mhoffma/micropython,ChuckM/micropython,adafruit/circuitpython,tdautc19841202/micropython,vriera/micropython,cnoviello/micropython,lbattraw/micropython,xhat/micropython,cwyark/micropython,tdautc19841202/micropython,mhoffma/micropython,pramasoul/micropython,mhoffma/micropython,ceramos/micropython,adafruit/micropython,misterdanb/micropython,infinnovation/micropython,vriera/micropython,PappaPeppar/micropython,ryannathans/micropython,swegener/micropython,kostyll/micropython,pfalcon/micropython,AriZuu/micropython,toolmacher/micropython,trezor/micropython,micropython/micropython-esp32,xyb/micropython,selste/micropython,rubencabrera/micropython,vitiral/micropython,toolmacher/micropython,blmorris/micropython,kostyll/micropython,martinribelotta/micropython,redbear/micropython,dmazzella/micropython,ruffy91/micropython,tdautc19841202/micropython,xuxiaoxin/micropython,praemdonck/micropython,tralamazza/micropython,emfcamp/micropython,drrk/micropython,vitiral/micropython,emfcamp/micropython,ernesto-g/micropython,emfcamp/micropython,misterdanb/micropython,skybird6672/micropython,noahchense/micropython,misterdanb/micropython,MrSurly/micropython-esp32,mpalomer/micropython,henriknelson/micropython,omtinez/micropython,pozetroninc/micropython,redbear/micropython,jimkmc/micropython,cloudformdesign/micropython,ganshun666/micropython,methoxid/micropystat,alex-march/micropython,micropython/micropython-esp32,xyb/micropython,noahwilliamsson/micropython,Timmenem/micropython,SHA2017-badge/micropython-esp32,feilongfl/micropython,selste/micropython,pozetroninc/micropython,xhat/micropython,lowRISC/micropython,TDAbboud/micropython,skybird6672/micropython,hiway/micropython,selste/micropython,slzatz/micropython,pramasoul/micropython,tuc-osg/micropython,mpalomer/micropython,ganshun666/micropython,paul-xxx/micropython,utopiaprince/micropython,matthewelse/micropython,hosaka/micropython,oopy/micropython,jimkmc/micropython,puuu/micropython,xyb/micropython,galenhz/micropython,adamkh/micropython,lbattraw/micropython,feilongfl/micropython,ahotam/micropython,mgyenik/micropython,matthewelse/micropython,paul-xxx/micropython,cnoviello/micropython,ChuckM/micropython,MrSurly/micropython,bvernoux/micropython,Vogtinator/micropython,trezor/micropython,Peetz0r/micropython-esp32,alex-march/micropython,utopiaprince/micropython,lowRISC/micropython,adamkh/micropython,suda/micropython,noahwilliamsson/micropython,chrisdearman/micropython,SHA2017-badge/micropython-esp32,slzatz/micropython,chrisdearman/micropython,Timmenem/micropython,vitiral/micropython,lbattraw/micropython,matthewelse/micropython,utopiaprince/micropython,jlillest/micropython,lowRISC/micropython,adamkh/micropython,mgyenik/micropython,ryannathans/micropython,KISSMonX/micropython,emfcamp/micropython,MrSurly/micropython,aethaniel/micropython,xhat/micropython,skybird6672/micropython,noahwilliamsson/micropython,EcmaXp/micropython,danicampora/micropython,redbear/micropython,Vogtinator/micropython,AriZuu/micropython,dhylands/micropython,tobbad/micropython,blmorris/micropython,dmazzella/micropython,SungEun-Steve-Kim/test-mp,ChuckM/micropython,drrk/micropython,HenrikSolver/micropython,trezor/micropython,jmarcelino/pycom-micropython,cwyark/micropython,oopy/micropython,EcmaXp/micropython,blazewicz/micropython,ericsnowcurrently/micropython,lowRISC/micropython,SungEun-Steve-Kim/test-mp,ahotam/micropython,orionrobots/micropython,adafruit/micropython,MrSurly/micropython-esp32,cloudformdesign/micropython,mhoffma/micropython,oopy/micropython,dmazzella/micropython,vitiral/micropython,tralamazza/micropython,Peetz0r/micropython-esp32,chrisdearman/micropython,slzatz/micropython,PappaPeppar/micropython,suda/micropython,tuc-osg/micropython,tobbad/micropython,aitjcize/micropython,mpalomer/micropython,pozetroninc/micropython,ahotam/micropython,micropython/micropython-esp32,misterdanb/micropython,AriZuu/micropython,ganshun666/micropython,kerneltask/micropython,deshipu/micropython,warner83/micropython,ceramos/micropython,dxxb/micropython,KISSMonX/micropython,ericsnowcurrently/micropython,jmarcelino/pycom-micropython,tobbad/micropython,omtinez/micropython,kerneltask/micropython,kerneltask/micropython,adafruit/circuitpython,HenrikSolver/micropython,blmorris/micropython,henriknelson/micropython,EcmaXp/micropython,xuxiaoxin/micropython,tuc-osg/micropython,bvernoux/micropython,turbinenreiter/micropython,pozetroninc/micropython,feilongfl/micropython,firstval/micropython,jmarcelino/pycom-micropython,martinribelotta/micropython,ernesto-g/micropython,jmarcelino/pycom-micropython,aitjcize/micropython,adafruit/circuitpython,suda/micropython,omtinez/micropython,tuc-osg/micropython,aitjcize/micropython,aethaniel/micropython,puuu/micropython,methoxid/micropystat,Vogtinator/micropython,paul-xxx/micropython,ericsnowcurrently/micropython,ernesto-g/micropython,paul-xxx/micropython,ericsnowcurrently/micropython,dxxb/micropython,ryannathans/micropython,AriZuu/micropython,HenrikSolver/micropython,praemdonck/micropython,suda/micropython,heisewangluo/micropython,slzatz/micropython,puuu/micropython,puuu/micropython,noahchense/micropython,cwyark/micropython,mgyenik/micropython,neilh10/micropython,torwag/micropython,rubencabrera/micropython,matthewelse/micropython,aethaniel/micropython,puuu/micropython,dhylands/micropython,dxxb/micropython,MrSurly/micropython-esp32,turbinenreiter/micropython,hiway/micropython,xhat/micropython,alex-march/micropython,cloudformdesign/micropython,deshipu/micropython,xuxiaoxin/micropython,stonegithubs/micropython,infinnovation/micropython,lbattraw/micropython,heisewangluo/micropython,mgyenik/micropython,alex-march/micropython,ernesto-g/micropython,henriknelson/micropython,orionrobots/micropython,Peetz0r/micropython-esp32,ganshun666/micropython,heisewangluo/micropython,selste/micropython,mpalomer/micropython,dmazzella/micropython,hiway/micropython,kostyll/micropython,neilh10/micropython,MrSurly/micropython | def func1():
try:
return "it worked"
finally:
print("finally 1")
print(func1())
+
+ def func2():
+ try:
+ return "it worked"
+ finally:
+ print("finally 2")
+
+ def func3():
+ try:
+ s = func2()
+ return s + ", did this work?"
+ finally:
+ print("finally 3")
+
+ print(func3())
+ | Add additional testcase for finally/return. | ## Code Before:
def func1():
try:
return "it worked"
finally:
print("finally 1")
print(func1())
## Instruction:
Add additional testcase for finally/return.
## Code After:
def func1():
try:
return "it worked"
finally:
print("finally 1")
print(func1())
def func2():
try:
return "it worked"
finally:
print("finally 2")
def func3():
try:
s = func2()
return s + ", did this work?"
finally:
print("finally 3")
print(func3())
| ...
print(func1())
def func2():
try:
return "it worked"
finally:
print("finally 2")
def func3():
try:
s = func2()
return s + ", did this work?"
finally:
print("finally 3")
print(func3())
... |
87b051a4d97f54af16c37c118be654243c8b36cd | application.py | application.py | from paste.deploy import loadapp
from waitress import serve
from opreturnninja.config import config
if __name__ == "__main__":
app = loadapp('config:production.ini', relative_to='.')
serve(app, host='0.0.0.0', port=config.PORT)
| from paste.deploy import loadapp
from waitress import serve
from opreturnninja.config import config
if __name__ == "__main__":
print("Loading application.py")
app = loadapp('config:production.ini', relative_to='.')
serve(app, host='0.0.0.0', port=config.PORT)
| Add a print statement; heroku not building :/ | Add a print statement; heroku not building :/
| Python | mit | XertroV/opreturn-ninja,XertroV/opreturn-ninja,XertroV/opreturn-ninja | from paste.deploy import loadapp
from waitress import serve
from opreturnninja.config import config
if __name__ == "__main__":
+ print("Loading application.py")
app = loadapp('config:production.ini', relative_to='.')
serve(app, host='0.0.0.0', port=config.PORT)
| Add a print statement; heroku not building :/ | ## Code Before:
from paste.deploy import loadapp
from waitress import serve
from opreturnninja.config import config
if __name__ == "__main__":
app = loadapp('config:production.ini', relative_to='.')
serve(app, host='0.0.0.0', port=config.PORT)
## Instruction:
Add a print statement; heroku not building :/
## Code After:
from paste.deploy import loadapp
from waitress import serve
from opreturnninja.config import config
if __name__ == "__main__":
print("Loading application.py")
app = loadapp('config:production.ini', relative_to='.')
serve(app, host='0.0.0.0', port=config.PORT)
| ...
if __name__ == "__main__":
print("Loading application.py")
app = loadapp('config:production.ini', relative_to='.')
serve(app, host='0.0.0.0', port=config.PORT)
... |
4ca25c413494d43b9ecebcebca0ea79b213992a3 | test_suite.py | test_suite.py | import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django # noqa
if django.__version__ >= (1, 7):
django.setup()
from django.core import management # noqa
management.call_command('test', 'tests')
| import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django # noqa
if django.VERSION >= (1, 7):
django.setup()
from django.core import management # noqa
management.call_command('test', 'tests')
| Fix name of Django version attribute | Fix name of Django version attribute
Signed-off-by: Byron Ruth <[email protected]>
| Python | bsd-2-clause | bruth/django-preserialize,scottp-dpaw/django-preserialize | import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django # noqa
- if django.__version__ >= (1, 7):
+ if django.VERSION >= (1, 7):
django.setup()
from django.core import management # noqa
management.call_command('test', 'tests')
| Fix name of Django version attribute | ## Code Before:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django # noqa
if django.__version__ >= (1, 7):
django.setup()
from django.core import management # noqa
management.call_command('test', 'tests')
## Instruction:
Fix name of Django version attribute
## Code After:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django # noqa
if django.VERSION >= (1, 7):
django.setup()
from django.core import management # noqa
management.call_command('test', 'tests')
| # ... existing code ...
import django # noqa
if django.VERSION >= (1, 7):
django.setup()
# ... rest of the code ... |
aaa0f03a91f3326dc893175510a4ad35649ec371 | pltpreview/view.py | pltpreview/view.py | """Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt
def show(image, blocking=False, **kwargs):
"""Show *image*. If *blocking* is False the call is nonblocking.
*kwargs* are passed to matplotlib's ``imshow`` function. This command
always creates a new figure. Returns matplotlib's ``AxesImage``.
"""
plt.figure()
mpl_image = plt.imshow(image, **kwargs)
plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8))
plt.show(blocking)
return mpl_image
def plot(*args, **kwargs):
"""Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*.
*kwargs* are infected with *blocking* and if False or not specified,
the call is nonblocking.
"""
blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking')
plt.plot(*args, **kwargs)
plt.show(blocking)
| """Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt
def show(image, blocking=False, **kwargs):
"""Show *image*. If *blocking* is False the call is nonblocking.
*kwargs* are passed to matplotlib's ``imshow`` function. This command
always creates a new figure. Returns matplotlib's ``AxesImage``.
"""
plt.figure()
mpl_image = plt.imshow(image, **kwargs)
plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8))
plt.show(blocking)
return mpl_image
def plot(*args, **kwargs):
"""Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*.
*kwargs* are infected with *blocking* and if False or not specified,
the call is nonblocking. This command always creates a new figure.
"""
blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking')
plt.figure()
plt.plot(*args, **kwargs)
plt.show(blocking)
| Create new figure in plot command | Create new figure in plot command
| Python | mit | tfarago/pltpreview | """Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt
def show(image, blocking=False, **kwargs):
"""Show *image*. If *blocking* is False the call is nonblocking.
*kwargs* are passed to matplotlib's ``imshow`` function. This command
always creates a new figure. Returns matplotlib's ``AxesImage``.
"""
plt.figure()
mpl_image = plt.imshow(image, **kwargs)
plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8))
plt.show(blocking)
return mpl_image
def plot(*args, **kwargs):
"""Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*.
*kwargs* are infected with *blocking* and if False or not specified,
- the call is nonblocking.
+ the call is nonblocking. This command always creates a new figure.
"""
blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking')
+ plt.figure()
plt.plot(*args, **kwargs)
plt.show(blocking)
| Create new figure in plot command | ## Code Before:
"""Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt
def show(image, blocking=False, **kwargs):
"""Show *image*. If *blocking* is False the call is nonblocking.
*kwargs* are passed to matplotlib's ``imshow`` function. This command
always creates a new figure. Returns matplotlib's ``AxesImage``.
"""
plt.figure()
mpl_image = plt.imshow(image, **kwargs)
plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8))
plt.show(blocking)
return mpl_image
def plot(*args, **kwargs):
"""Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*.
*kwargs* are infected with *blocking* and if False or not specified,
the call is nonblocking.
"""
blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking')
plt.plot(*args, **kwargs)
plt.show(blocking)
## Instruction:
Create new figure in plot command
## Code After:
"""Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt
def show(image, blocking=False, **kwargs):
"""Show *image*. If *blocking* is False the call is nonblocking.
*kwargs* are passed to matplotlib's ``imshow`` function. This command
always creates a new figure. Returns matplotlib's ``AxesImage``.
"""
plt.figure()
mpl_image = plt.imshow(image, **kwargs)
plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8))
plt.show(blocking)
return mpl_image
def plot(*args, **kwargs):
"""Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*.
*kwargs* are infected with *blocking* and if False or not specified,
the call is nonblocking. This command always creates a new figure.
"""
blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking')
plt.figure()
plt.plot(*args, **kwargs)
plt.show(blocking)
| ...
"""Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*.
*kwargs* are infected with *blocking* and if False or not specified,
the call is nonblocking. This command always creates a new figure.
"""
blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking')
plt.figure()
plt.plot(*args, **kwargs)
plt.show(blocking)
... |
d3de354717fdb15d6e883f38d87eba4806fd5cc7 | wafer/pages/urls.py | wafer/pages/urls.py | from django.conf.urls import patterns, url, include
from django.core.urlresolvers import get_script_prefix
from django.views.generic import RedirectView
from rest_framework import routers
from wafer.pages.views import PageViewSet
router = routers.DefaultRouter()
router.register(r'pages', PageViewSet)
urlpatterns = patterns(
'wafer.pages.views',
url(r'^api/', include(router.urls)),
url('^index(?:\.html)?/?$', RedirectView.as_view(
url=get_script_prefix(), permanent=True, query_string=True)),
url(r'^(?:(.+)/)?$', 'slug', name='wafer_page'),
)
| from django.conf.urls import patterns, url, include
from rest_framework import routers
from wafer.pages.views import PageViewSet
router = routers.DefaultRouter()
router.register(r'pages', PageViewSet)
urlpatterns = patterns(
'wafer.pages.views',
url(r'^api/', include(router.urls)),
url(r'^(?:(.+)/)?$', 'slug', name='wafer_page'),
)
| Drop index redirect, no longer needed | Drop index redirect, no longer needed
| Python | isc | CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer | from django.conf.urls import patterns, url, include
- from django.core.urlresolvers import get_script_prefix
- from django.views.generic import RedirectView
from rest_framework import routers
from wafer.pages.views import PageViewSet
router = routers.DefaultRouter()
router.register(r'pages', PageViewSet)
urlpatterns = patterns(
'wafer.pages.views',
url(r'^api/', include(router.urls)),
- url('^index(?:\.html)?/?$', RedirectView.as_view(
- url=get_script_prefix(), permanent=True, query_string=True)),
url(r'^(?:(.+)/)?$', 'slug', name='wafer_page'),
)
| Drop index redirect, no longer needed | ## Code Before:
from django.conf.urls import patterns, url, include
from django.core.urlresolvers import get_script_prefix
from django.views.generic import RedirectView
from rest_framework import routers
from wafer.pages.views import PageViewSet
router = routers.DefaultRouter()
router.register(r'pages', PageViewSet)
urlpatterns = patterns(
'wafer.pages.views',
url(r'^api/', include(router.urls)),
url('^index(?:\.html)?/?$', RedirectView.as_view(
url=get_script_prefix(), permanent=True, query_string=True)),
url(r'^(?:(.+)/)?$', 'slug', name='wafer_page'),
)
## Instruction:
Drop index redirect, no longer needed
## Code After:
from django.conf.urls import patterns, url, include
from rest_framework import routers
from wafer.pages.views import PageViewSet
router = routers.DefaultRouter()
router.register(r'pages', PageViewSet)
urlpatterns = patterns(
'wafer.pages.views',
url(r'^api/', include(router.urls)),
url(r'^(?:(.+)/)?$', 'slug', name='wafer_page'),
)
| ...
from django.conf.urls import patterns, url, include
from rest_framework import routers
...
'wafer.pages.views',
url(r'^api/', include(router.urls)),
url(r'^(?:(.+)/)?$', 'slug', name='wafer_page'),
)
... |
57b1dbc45e7b78f7aa272fd5b7d4bd022850beb9 | lametro/migrations/0007_update_packet_links.py | lametro/migrations/0007_update_packet_links.py |
from django.db import migrations
def resave_packets(apps, schema_editor):
'''
Re-save all existing packets to update their URLs based on the
new value of MERGE_HOST.
'''
for packet in ('BillPacket', 'EventPacket'):
packet_model = apps.get_model('lametro', packet)
for p in packet_model.objects.all():
p.save(merge=False)
class Migration(migrations.Migration):
dependencies = [
('lametro', '0006_add_plan_program_policy'),
]
operations = [
migrations.RunPython(resave_packets),
]
|
from django.db import migrations
def resave_packets(apps, schema_editor):
'''
Re-save all existing packets to update their URLs based on the
new value of MERGE_HOST.
'''
# for packet in ('BillPacket', 'EventPacket'):
# packet_model = apps.get_model('lametro', packet)
# for p in packet_model.objects.all():
# p.save(merge=False)
return
class Migration(migrations.Migration):
dependencies = [
('lametro', '0006_add_plan_program_policy'),
]
operations = [
migrations.RunPython(resave_packets),
]
| Disable data migration for deployment | Disable data migration for deployment
| Python | mit | datamade/la-metro-councilmatic,datamade/la-metro-councilmatic,datamade/la-metro-councilmatic,datamade/la-metro-councilmatic |
from django.db import migrations
def resave_packets(apps, schema_editor):
'''
Re-save all existing packets to update their URLs based on the
new value of MERGE_HOST.
'''
- for packet in ('BillPacket', 'EventPacket'):
+ # for packet in ('BillPacket', 'EventPacket'):
- packet_model = apps.get_model('lametro', packet)
+ # packet_model = apps.get_model('lametro', packet)
- for p in packet_model.objects.all():
+ # for p in packet_model.objects.all():
- p.save(merge=False)
+ # p.save(merge=False)
+ return
class Migration(migrations.Migration):
dependencies = [
('lametro', '0006_add_plan_program_policy'),
]
operations = [
migrations.RunPython(resave_packets),
]
| Disable data migration for deployment | ## Code Before:
from django.db import migrations
def resave_packets(apps, schema_editor):
'''
Re-save all existing packets to update their URLs based on the
new value of MERGE_HOST.
'''
for packet in ('BillPacket', 'EventPacket'):
packet_model = apps.get_model('lametro', packet)
for p in packet_model.objects.all():
p.save(merge=False)
class Migration(migrations.Migration):
dependencies = [
('lametro', '0006_add_plan_program_policy'),
]
operations = [
migrations.RunPython(resave_packets),
]
## Instruction:
Disable data migration for deployment
## Code After:
from django.db import migrations
def resave_packets(apps, schema_editor):
'''
Re-save all existing packets to update their URLs based on the
new value of MERGE_HOST.
'''
# for packet in ('BillPacket', 'EventPacket'):
# packet_model = apps.get_model('lametro', packet)
# for p in packet_model.objects.all():
# p.save(merge=False)
return
class Migration(migrations.Migration):
dependencies = [
('lametro', '0006_add_plan_program_policy'),
]
operations = [
migrations.RunPython(resave_packets),
]
| # ... existing code ...
new value of MERGE_HOST.
'''
# for packet in ('BillPacket', 'EventPacket'):
# packet_model = apps.get_model('lametro', packet)
# for p in packet_model.objects.all():
# p.save(merge=False)
return
# ... rest of the code ... |
60087afcf8f0130fb9cd6e154a9fb7290c0fde2e | tools/test.py | tools/test.py |
import os
import string
import subprocess
import sys
import utils
def Main():
args = sys.argv[1:]
tools_dir = os.path.dirname(os.path.realpath(__file__))
dart_script_name = 'test.dart'
dart_test_script = string.join([tools_dir, dart_script_name], os.sep)
command = [utils.CheckedInSdkExecutable(),
'--checked', dart_test_script] + args
exit_code = subprocess.call(command)
utils.DiagnoseExitCode(exit_code, command)
return exit_code
if __name__ == '__main__':
sys.exit(Main())
|
import os
import string
import subprocess
import sys
import utils
def Main():
args = sys.argv[1:]
tools_dir = os.path.dirname(os.path.realpath(__file__))
dart_script_name = 'test.dart'
dart_test_script = string.join([tools_dir, dart_script_name], os.sep)
command = [utils.CheckedInSdkExecutable(),
'--checked', dart_test_script] + args
# The testing script potentially needs the android platform tools in PATH so
# we do that in ./tools/test.py (a similar logic exists in ./tools/build.py).
android_platform_tools = os.path.normpath(os.path.join(
tools_dir,
'../third_party/android_tools/sdk/platform-tools'))
if os.path.isdir(android_platform_tools):
os.environ['PATH'] = '%s%s%s' % (
os.environ['PATH'], os.pathsep, android_platform_tools)
exit_code = subprocess.call(command)
utils.DiagnoseExitCode(exit_code, command)
return exit_code
if __name__ == '__main__':
sys.exit(Main())
| Add third_party/android_tools/sdk/platform-tools to PATH if available | Add third_party/android_tools/sdk/platform-tools to PATH if available
[email protected]
Review URL: https://codereview.chromium.org/1938973002 .
| Python | bsd-3-clause | dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-lang/sdk,dartino/dart-sdk,dartino/dart-sdk |
import os
import string
import subprocess
import sys
import utils
def Main():
args = sys.argv[1:]
tools_dir = os.path.dirname(os.path.realpath(__file__))
dart_script_name = 'test.dart'
dart_test_script = string.join([tools_dir, dart_script_name], os.sep)
command = [utils.CheckedInSdkExecutable(),
'--checked', dart_test_script] + args
+
+ # The testing script potentially needs the android platform tools in PATH so
+ # we do that in ./tools/test.py (a similar logic exists in ./tools/build.py).
+ android_platform_tools = os.path.normpath(os.path.join(
+ tools_dir,
+ '../third_party/android_tools/sdk/platform-tools'))
+ if os.path.isdir(android_platform_tools):
+ os.environ['PATH'] = '%s%s%s' % (
+ os.environ['PATH'], os.pathsep, android_platform_tools)
+
exit_code = subprocess.call(command)
utils.DiagnoseExitCode(exit_code, command)
return exit_code
if __name__ == '__main__':
sys.exit(Main())
| Add third_party/android_tools/sdk/platform-tools to PATH if available | ## Code Before:
import os
import string
import subprocess
import sys
import utils
def Main():
args = sys.argv[1:]
tools_dir = os.path.dirname(os.path.realpath(__file__))
dart_script_name = 'test.dart'
dart_test_script = string.join([tools_dir, dart_script_name], os.sep)
command = [utils.CheckedInSdkExecutable(),
'--checked', dart_test_script] + args
exit_code = subprocess.call(command)
utils.DiagnoseExitCode(exit_code, command)
return exit_code
if __name__ == '__main__':
sys.exit(Main())
## Instruction:
Add third_party/android_tools/sdk/platform-tools to PATH if available
## Code After:
import os
import string
import subprocess
import sys
import utils
def Main():
args = sys.argv[1:]
tools_dir = os.path.dirname(os.path.realpath(__file__))
dart_script_name = 'test.dart'
dart_test_script = string.join([tools_dir, dart_script_name], os.sep)
command = [utils.CheckedInSdkExecutable(),
'--checked', dart_test_script] + args
# The testing script potentially needs the android platform tools in PATH so
# we do that in ./tools/test.py (a similar logic exists in ./tools/build.py).
android_platform_tools = os.path.normpath(os.path.join(
tools_dir,
'../third_party/android_tools/sdk/platform-tools'))
if os.path.isdir(android_platform_tools):
os.environ['PATH'] = '%s%s%s' % (
os.environ['PATH'], os.pathsep, android_platform_tools)
exit_code = subprocess.call(command)
utils.DiagnoseExitCode(exit_code, command)
return exit_code
if __name__ == '__main__':
sys.exit(Main())
| ...
command = [utils.CheckedInSdkExecutable(),
'--checked', dart_test_script] + args
# The testing script potentially needs the android platform tools in PATH so
# we do that in ./tools/test.py (a similar logic exists in ./tools/build.py).
android_platform_tools = os.path.normpath(os.path.join(
tools_dir,
'../third_party/android_tools/sdk/platform-tools'))
if os.path.isdir(android_platform_tools):
os.environ['PATH'] = '%s%s%s' % (
os.environ['PATH'], os.pathsep, android_platform_tools)
exit_code = subprocess.call(command)
utils.DiagnoseExitCode(exit_code, command)
... |
6e2a484ac46279c6a077fb135d7e5f66605e9b88 | mox/app.py | mox/app.py | from flask import Flask
from flask.ext.mongoengine import MongoEngine
from views import mocks
import os
app = Flask(__name__)
app.config["MONGODB_SETTINGS"] = {
"db": "mox"
}
app.config["SECRET_KEY"] = "KeepThisS3cr3t"
if os.environ.get('PRODUCTION'):
app.config["MONGODB_SETTINGS"]["host"] = os.environ.get("PROD_MONGODB")
db = MongoEngine(app)
app.register_blueprint(mocks)
if __name__ == '__main__':
app.run() | from flask import Flask
from flask.ext.mongoengine import MongoEngine
from views import mocks
import os
app = Flask(__name__)
app.config["MONGODB_SETTINGS"] = {
"db": "mox"
}
app.config["SECRET_KEY"] = "KeepThisS3cr3t"
if os.environ.get('HEROKU') == 1:
app.config["MONGODB_SETTINGS"]["host"] = os.environ.get("MONGODB_URI")
db = MongoEngine(app)
app.register_blueprint(mocks)
if __name__ == '__main__':
app.run() | Fix up settings for Heroku | Fix up settings for Heroku
| Python | mit | abouzek/mox,abouzek/mox | from flask import Flask
from flask.ext.mongoengine import MongoEngine
from views import mocks
import os
app = Flask(__name__)
app.config["MONGODB_SETTINGS"] = {
"db": "mox"
}
app.config["SECRET_KEY"] = "KeepThisS3cr3t"
- if os.environ.get('PRODUCTION'):
+ if os.environ.get('HEROKU') == 1:
- app.config["MONGODB_SETTINGS"]["host"] = os.environ.get("PROD_MONGODB")
+ app.config["MONGODB_SETTINGS"]["host"] = os.environ.get("MONGODB_URI")
db = MongoEngine(app)
app.register_blueprint(mocks)
if __name__ == '__main__':
app.run() | Fix up settings for Heroku | ## Code Before:
from flask import Flask
from flask.ext.mongoengine import MongoEngine
from views import mocks
import os
app = Flask(__name__)
app.config["MONGODB_SETTINGS"] = {
"db": "mox"
}
app.config["SECRET_KEY"] = "KeepThisS3cr3t"
if os.environ.get('PRODUCTION'):
app.config["MONGODB_SETTINGS"]["host"] = os.environ.get("PROD_MONGODB")
db = MongoEngine(app)
app.register_blueprint(mocks)
if __name__ == '__main__':
app.run()
## Instruction:
Fix up settings for Heroku
## Code After:
from flask import Flask
from flask.ext.mongoengine import MongoEngine
from views import mocks
import os
app = Flask(__name__)
app.config["MONGODB_SETTINGS"] = {
"db": "mox"
}
app.config["SECRET_KEY"] = "KeepThisS3cr3t"
if os.environ.get('HEROKU') == 1:
app.config["MONGODB_SETTINGS"]["host"] = os.environ.get("MONGODB_URI")
db = MongoEngine(app)
app.register_blueprint(mocks)
if __name__ == '__main__':
app.run() | # ... existing code ...
app.config["SECRET_KEY"] = "KeepThisS3cr3t"
if os.environ.get('HEROKU') == 1:
app.config["MONGODB_SETTINGS"]["host"] = os.environ.get("MONGODB_URI")
db = MongoEngine(app)
# ... rest of the code ... |
6d7d04b095eacb413b07ebcb3fed9684dc40fc80 | utils/gyb_syntax_support/protocolsMap.py | utils/gyb_syntax_support/protocolsMap.py | SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
'DeclBuildable': [
'CodeBlockItem',
'MemberDeclListItem',
'SyntaxBuildable'
],
'ExprList': [
'ConditionElement',
'SyntaxBuildable'
],
'IdentifierPattern': [
'PatternBuildable'
],
'MemberDeclList': [
'MemberDeclBlock'
],
'SimpleTypeIdentifier': [
'TypeAnnotation',
'TypeBuildable',
'TypeExpr'
],
'StmtBuildable': [
'CodeBlockItem',
'SyntaxBuildable'
]
}
| SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
'DeclBuildable': [
'CodeBlockItem',
'MemberDeclListItem',
'SyntaxBuildable'
],
'ExprList': [
'ConditionElement',
'SyntaxBuildable'
],
'IdentifierPattern': [
'PatternBuildable'
],
'MemberDeclList': [
'MemberDeclBlock'
],
'SimpleTypeIdentifier': [
'TypeAnnotation',
'TypeBuildable',
'TypeExpr'
],
'StmtBuildable': [
'CodeBlockItem',
'SyntaxBuildable'
],
'TokenSyntax': [
'BinaryOperatorExpr'
]
}
| Add convenience initializer for `BinaryOperatorExpr` | [SwiftSyntax] Add convenience initializer for `BinaryOperatorExpr`
| Python | apache-2.0 | atrick/swift,atrick/swift,apple/swift,rudkx/swift,benlangmuir/swift,roambotics/swift,rudkx/swift,glessard/swift,atrick/swift,ahoppen/swift,glessard/swift,JGiola/swift,atrick/swift,ahoppen/swift,ahoppen/swift,apple/swift,glessard/swift,JGiola/swift,rudkx/swift,rudkx/swift,atrick/swift,roambotics/swift,apple/swift,roambotics/swift,glessard/swift,benlangmuir/swift,atrick/swift,benlangmuir/swift,apple/swift,benlangmuir/swift,ahoppen/swift,benlangmuir/swift,roambotics/swift,apple/swift,gregomni/swift,JGiola/swift,gregomni/swift,gregomni/swift,apple/swift,gregomni/swift,gregomni/swift,JGiola/swift,ahoppen/swift,glessard/swift,glessard/swift,roambotics/swift,JGiola/swift,benlangmuir/swift,ahoppen/swift,roambotics/swift,rudkx/swift,rudkx/swift,gregomni/swift,JGiola/swift | SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
'DeclBuildable': [
'CodeBlockItem',
'MemberDeclListItem',
'SyntaxBuildable'
],
'ExprList': [
'ConditionElement',
'SyntaxBuildable'
],
'IdentifierPattern': [
'PatternBuildable'
],
'MemberDeclList': [
'MemberDeclBlock'
],
'SimpleTypeIdentifier': [
'TypeAnnotation',
'TypeBuildable',
'TypeExpr'
],
'StmtBuildable': [
'CodeBlockItem',
'SyntaxBuildable'
+ ],
+ 'TokenSyntax': [
+ 'BinaryOperatorExpr'
]
}
| Add convenience initializer for `BinaryOperatorExpr` | ## Code Before:
SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
'DeclBuildable': [
'CodeBlockItem',
'MemberDeclListItem',
'SyntaxBuildable'
],
'ExprList': [
'ConditionElement',
'SyntaxBuildable'
],
'IdentifierPattern': [
'PatternBuildable'
],
'MemberDeclList': [
'MemberDeclBlock'
],
'SimpleTypeIdentifier': [
'TypeAnnotation',
'TypeBuildable',
'TypeExpr'
],
'StmtBuildable': [
'CodeBlockItem',
'SyntaxBuildable'
]
}
## Instruction:
Add convenience initializer for `BinaryOperatorExpr`
## Code After:
SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = {
'DeclBuildable': [
'CodeBlockItem',
'MemberDeclListItem',
'SyntaxBuildable'
],
'ExprList': [
'ConditionElement',
'SyntaxBuildable'
],
'IdentifierPattern': [
'PatternBuildable'
],
'MemberDeclList': [
'MemberDeclBlock'
],
'SimpleTypeIdentifier': [
'TypeAnnotation',
'TypeBuildable',
'TypeExpr'
],
'StmtBuildable': [
'CodeBlockItem',
'SyntaxBuildable'
],
'TokenSyntax': [
'BinaryOperatorExpr'
]
}
| ...
'CodeBlockItem',
'SyntaxBuildable'
],
'TokenSyntax': [
'BinaryOperatorExpr'
]
}
... |
6281da3b846bfea26ea68e3fe480c738a5181506 | runtests.py | runtests.py |
import optparse
import sys
import unittest
from walrus import tests
def runtests(verbose=False, failfast=False, names=None):
if names:
suite = unittest.TestLoader().loadTestsFromNames(names, tests)
else:
suite = unittest.TestLoader().loadTestsFromModule(tests)
runner = unittest.TextTestRunner(verbosity=2 if verbose else 1,
failfast=failfast)
return runner.run(suite)
if __name__ == '__main__':
try:
from redis import Redis
except ImportError:
raise RuntimeError('redis-py must be installed.')
else:
try:
Redis().info()
except:
raise RuntimeError('redis server does not appear to be running')
parser = optparse.OptionParser()
parser.add_option('-v', '--verbose', action='store_true', default=False,
dest='verbose', help='Verbose output.')
parser.add_option('-f', '--failfast', action='store_true', default=False,
help='Stop on first failure or error.')
options, args = parser.parse_args()
result = runtests(
verbose=options.verbose,
failfast=options.failfast,
names=args)
if result.failures:
sys.exit(1)
elif result.errors:
sys.exit(2)
|
import optparse
import os
import sys
import unittest
def runtests(verbose=False, failfast=False, names=None):
if names:
suite = unittest.TestLoader().loadTestsFromNames(names, tests)
else:
suite = unittest.TestLoader().loadTestsFromModule(tests)
runner = unittest.TextTestRunner(verbosity=2 if verbose else 1,
failfast=failfast)
return runner.run(suite)
if __name__ == '__main__':
try:
from redis import Redis
except ImportError:
raise RuntimeError('redis-py must be installed.')
else:
try:
Redis().info()
except:
raise RuntimeError('redis server does not appear to be running')
parser = optparse.OptionParser()
parser.add_option('-v', '--verbose', action='store_true', default=False,
dest='verbose', help='Verbose output.')
parser.add_option('-f', '--failfast', action='store_true', default=False,
help='Stop on first failure or error.')
parser.add_option('-z', '--zpop', action='store_true',
help='Run ZPOP* tests.')
options, args = parser.parse_args()
if options.zpop:
os.environ['TEST_ZPOP'] = '1'
from walrus import tests
result = runtests(
verbose=options.verbose,
failfast=options.failfast,
names=args)
if result.failures:
sys.exit(1)
elif result.errors:
sys.exit(2)
| Add test-runner option to run zpop* tests. | Add test-runner option to run zpop* tests.
| Python | mit | coleifer/walrus |
import optparse
+ import os
import sys
import unittest
-
- from walrus import tests
def runtests(verbose=False, failfast=False, names=None):
if names:
suite = unittest.TestLoader().loadTestsFromNames(names, tests)
else:
suite = unittest.TestLoader().loadTestsFromModule(tests)
runner = unittest.TextTestRunner(verbosity=2 if verbose else 1,
failfast=failfast)
return runner.run(suite)
if __name__ == '__main__':
try:
from redis import Redis
except ImportError:
raise RuntimeError('redis-py must be installed.')
else:
try:
Redis().info()
except:
raise RuntimeError('redis server does not appear to be running')
parser = optparse.OptionParser()
parser.add_option('-v', '--verbose', action='store_true', default=False,
dest='verbose', help='Verbose output.')
parser.add_option('-f', '--failfast', action='store_true', default=False,
help='Stop on first failure or error.')
+ parser.add_option('-z', '--zpop', action='store_true',
+ help='Run ZPOP* tests.')
options, args = parser.parse_args()
+ if options.zpop:
+ os.environ['TEST_ZPOP'] = '1'
+
+ from walrus import tests
+
result = runtests(
verbose=options.verbose,
failfast=options.failfast,
names=args)
if result.failures:
sys.exit(1)
elif result.errors:
sys.exit(2)
| Add test-runner option to run zpop* tests. | ## Code Before:
import optparse
import sys
import unittest
from walrus import tests
def runtests(verbose=False, failfast=False, names=None):
if names:
suite = unittest.TestLoader().loadTestsFromNames(names, tests)
else:
suite = unittest.TestLoader().loadTestsFromModule(tests)
runner = unittest.TextTestRunner(verbosity=2 if verbose else 1,
failfast=failfast)
return runner.run(suite)
if __name__ == '__main__':
try:
from redis import Redis
except ImportError:
raise RuntimeError('redis-py must be installed.')
else:
try:
Redis().info()
except:
raise RuntimeError('redis server does not appear to be running')
parser = optparse.OptionParser()
parser.add_option('-v', '--verbose', action='store_true', default=False,
dest='verbose', help='Verbose output.')
parser.add_option('-f', '--failfast', action='store_true', default=False,
help='Stop on first failure or error.')
options, args = parser.parse_args()
result = runtests(
verbose=options.verbose,
failfast=options.failfast,
names=args)
if result.failures:
sys.exit(1)
elif result.errors:
sys.exit(2)
## Instruction:
Add test-runner option to run zpop* tests.
## Code After:
import optparse
import os
import sys
import unittest
def runtests(verbose=False, failfast=False, names=None):
if names:
suite = unittest.TestLoader().loadTestsFromNames(names, tests)
else:
suite = unittest.TestLoader().loadTestsFromModule(tests)
runner = unittest.TextTestRunner(verbosity=2 if verbose else 1,
failfast=failfast)
return runner.run(suite)
if __name__ == '__main__':
try:
from redis import Redis
except ImportError:
raise RuntimeError('redis-py must be installed.')
else:
try:
Redis().info()
except:
raise RuntimeError('redis server does not appear to be running')
parser = optparse.OptionParser()
parser.add_option('-v', '--verbose', action='store_true', default=False,
dest='verbose', help='Verbose output.')
parser.add_option('-f', '--failfast', action='store_true', default=False,
help='Stop on first failure or error.')
parser.add_option('-z', '--zpop', action='store_true',
help='Run ZPOP* tests.')
options, args = parser.parse_args()
if options.zpop:
os.environ['TEST_ZPOP'] = '1'
from walrus import tests
result = runtests(
verbose=options.verbose,
failfast=options.failfast,
names=args)
if result.failures:
sys.exit(1)
elif result.errors:
sys.exit(2)
| ...
import optparse
import os
import sys
import unittest
def runtests(verbose=False, failfast=False, names=None):
...
parser.add_option('-f', '--failfast', action='store_true', default=False,
help='Stop on first failure or error.')
parser.add_option('-z', '--zpop', action='store_true',
help='Run ZPOP* tests.')
options, args = parser.parse_args()
if options.zpop:
os.environ['TEST_ZPOP'] = '1'
from walrus import tests
result = runtests(
verbose=options.verbose,
... |
ec30e6355fd9ea9cc22217ece7c9dab2640f6786 | filmfest/settings/pytest.py | filmfest/settings/pytest.py | from .base import * # noqa
SECRET_KEY = 'test'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'test_db.sqlite3'),
}
}
| from .base import * # noqa
SECRET_KEY = 'test'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'test_db.sqlite3'),
}
}
WAGTAILSEARCH_BACKENDS = {
'default': {
'BACKEND': 'wagtail.wagtailsearch.backends.db',
}
}
| Use db search backend instead of elastic in tests | Use db search backend instead of elastic in tests
| Python | unlicense | nott/next.filmfest.by,kinaklub/next.filmfest.by,kinaklub/next.filmfest.by,kinaklub/next.filmfest.by,kinaklub/next.filmfest.by,nott/next.filmfest.by,nott/next.filmfest.by,nott/next.filmfest.by | from .base import * # noqa
SECRET_KEY = 'test'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'test_db.sqlite3'),
}
}
+
+ WAGTAILSEARCH_BACKENDS = {
+ 'default': {
+ 'BACKEND': 'wagtail.wagtailsearch.backends.db',
+ }
+ }
+ | Use db search backend instead of elastic in tests | ## Code Before:
from .base import * # noqa
SECRET_KEY = 'test'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'test_db.sqlite3'),
}
}
## Instruction:
Use db search backend instead of elastic in tests
## Code After:
from .base import * # noqa
SECRET_KEY = 'test'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'test_db.sqlite3'),
}
}
WAGTAILSEARCH_BACKENDS = {
'default': {
'BACKEND': 'wagtail.wagtailsearch.backends.db',
}
}
| // ... existing code ...
}
}
WAGTAILSEARCH_BACKENDS = {
'default': {
'BACKEND': 'wagtail.wagtailsearch.backends.db',
}
}
// ... rest of the code ... |
a800bacf217ef903fd266e1fbf8103365ab64c94 | source/segue/frontend/exporter.py | source/segue/frontend/exporter.py |
from PySide import QtGui
from .selector import SelectorWidget
from .options import OptionsWidget
class ExporterWidget(QtGui.QWidget):
'''Manage exporting.'''
def __init__(self, host, parent=None):
'''Initialise with *host* application and *parent*.'''
super(ExporterWidget, self).__init__(parent=parent)
self.host = host
self.build()
self.post_build()
def build(self):
'''Build and layout the interface.'''
self.setLayout(QtGui.QVBoxLayout())
self.selector_widget = SelectorWidget(host=self.host)
self.selector_widget.setFrameStyle(
QtGui.QFrame.StyledPanel
)
self.layout().addWidget(self.selector_widget)
self.options_widget = OptionsWidget(host=self.host)
self.options_widget.setFrameStyle(
QtGui.QFrame.StyledPanel
)
self.layout().addWidget(self.options_widget)
self.export_button = QtGui.QPushButton('Export')
self.layout().addWidget(self.export_button)
def post_build(self):
'''Perform post-build operations.'''
self.setWindowTitle('Segue Exporter')
|
from PySide import QtGui
from .selector import SelectorWidget
from .options import OptionsWidget
class ExporterWidget(QtGui.QWidget):
'''Manage exporting.'''
def __init__(self, host, parent=None):
'''Initialise with *host* application and *parent*.'''
super(ExporterWidget, self).__init__(parent=parent)
self.host = host
self.build()
self.post_build()
def build(self):
'''Build and layout the interface.'''
self.setLayout(QtGui.QVBoxLayout())
self.selector_widget = SelectorWidget(host=self.host)
self.selector_widget.setFrameStyle(
QtGui.QFrame.StyledPanel
)
self.layout().addWidget(self.selector_widget)
self.options_widget = OptionsWidget(host=self.host)
self.options_widget.setFrameStyle(
QtGui.QFrame.StyledPanel
)
self.layout().addWidget(self.options_widget)
self.export_button = QtGui.QPushButton('Export')
self.layout().addWidget(self.export_button)
def post_build(self):
'''Perform post-build operations.'''
self.setWindowTitle('Segue Exporter')
self.selector_widget.added.connect(self.on_selection_changed)
self.selector_widget.removed.connect(self.on_selection_changed)
self.validate()
def on_selection_changed(self, items):
'''Handle selection change.'''
self.validate()
def validate(self):
'''Validate options and update UI state.'''
self.export_button.setEnabled(False)
if not self.selector_widget.items():
return
self.export_button.setEnabled(True)
| Add basic validation of ui state. | Add basic validation of ui state.
| Python | apache-2.0 | 4degrees/segue |
from PySide import QtGui
from .selector import SelectorWidget
from .options import OptionsWidget
class ExporterWidget(QtGui.QWidget):
'''Manage exporting.'''
def __init__(self, host, parent=None):
'''Initialise with *host* application and *parent*.'''
super(ExporterWidget, self).__init__(parent=parent)
self.host = host
self.build()
self.post_build()
def build(self):
'''Build and layout the interface.'''
self.setLayout(QtGui.QVBoxLayout())
self.selector_widget = SelectorWidget(host=self.host)
self.selector_widget.setFrameStyle(
QtGui.QFrame.StyledPanel
)
self.layout().addWidget(self.selector_widget)
self.options_widget = OptionsWidget(host=self.host)
self.options_widget.setFrameStyle(
QtGui.QFrame.StyledPanel
)
self.layout().addWidget(self.options_widget)
self.export_button = QtGui.QPushButton('Export')
self.layout().addWidget(self.export_button)
def post_build(self):
'''Perform post-build operations.'''
self.setWindowTitle('Segue Exporter')
+ self.selector_widget.added.connect(self.on_selection_changed)
+ self.selector_widget.removed.connect(self.on_selection_changed)
+
+ self.validate()
+
+ def on_selection_changed(self, items):
+ '''Handle selection change.'''
+ self.validate()
+
+ def validate(self):
+ '''Validate options and update UI state.'''
+ self.export_button.setEnabled(False)
+
+ if not self.selector_widget.items():
+ return
+
+ self.export_button.setEnabled(True)
+
+ | Add basic validation of ui state. | ## Code Before:
from PySide import QtGui
from .selector import SelectorWidget
from .options import OptionsWidget
class ExporterWidget(QtGui.QWidget):
'''Manage exporting.'''
def __init__(self, host, parent=None):
'''Initialise with *host* application and *parent*.'''
super(ExporterWidget, self).__init__(parent=parent)
self.host = host
self.build()
self.post_build()
def build(self):
'''Build and layout the interface.'''
self.setLayout(QtGui.QVBoxLayout())
self.selector_widget = SelectorWidget(host=self.host)
self.selector_widget.setFrameStyle(
QtGui.QFrame.StyledPanel
)
self.layout().addWidget(self.selector_widget)
self.options_widget = OptionsWidget(host=self.host)
self.options_widget.setFrameStyle(
QtGui.QFrame.StyledPanel
)
self.layout().addWidget(self.options_widget)
self.export_button = QtGui.QPushButton('Export')
self.layout().addWidget(self.export_button)
def post_build(self):
'''Perform post-build operations.'''
self.setWindowTitle('Segue Exporter')
## Instruction:
Add basic validation of ui state.
## Code After:
from PySide import QtGui
from .selector import SelectorWidget
from .options import OptionsWidget
class ExporterWidget(QtGui.QWidget):
'''Manage exporting.'''
def __init__(self, host, parent=None):
'''Initialise with *host* application and *parent*.'''
super(ExporterWidget, self).__init__(parent=parent)
self.host = host
self.build()
self.post_build()
def build(self):
'''Build and layout the interface.'''
self.setLayout(QtGui.QVBoxLayout())
self.selector_widget = SelectorWidget(host=self.host)
self.selector_widget.setFrameStyle(
QtGui.QFrame.StyledPanel
)
self.layout().addWidget(self.selector_widget)
self.options_widget = OptionsWidget(host=self.host)
self.options_widget.setFrameStyle(
QtGui.QFrame.StyledPanel
)
self.layout().addWidget(self.options_widget)
self.export_button = QtGui.QPushButton('Export')
self.layout().addWidget(self.export_button)
def post_build(self):
'''Perform post-build operations.'''
self.setWindowTitle('Segue Exporter')
self.selector_widget.added.connect(self.on_selection_changed)
self.selector_widget.removed.connect(self.on_selection_changed)
self.validate()
def on_selection_changed(self, items):
'''Handle selection change.'''
self.validate()
def validate(self):
'''Validate options and update UI state.'''
self.export_button.setEnabled(False)
if not self.selector_widget.items():
return
self.export_button.setEnabled(True)
| ...
self.setWindowTitle('Segue Exporter')
self.selector_widget.added.connect(self.on_selection_changed)
self.selector_widget.removed.connect(self.on_selection_changed)
self.validate()
def on_selection_changed(self, items):
'''Handle selection change.'''
self.validate()
def validate(self):
'''Validate options and update UI state.'''
self.export_button.setEnabled(False)
if not self.selector_widget.items():
return
self.export_button.setEnabled(True)
... |
47d69320261a3126637229c9deaf02ba425998af | members/models.py | members/models.py | from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
faculty_number = models.CharField(max_length=8)
def __unicode__(self):
return unicode(self.username)
def attended_meetings(self):
return self.protocols.all()
| from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
faculty_number = models.CharField(max_length=8)
def __unicode__(self):
return unicode(self.username)
def attended_meetings(self):
return self.meetings_attend.all()
def absent_meetings(self):
return self.meetings_absent.all()
| Add attended_meetings and absent_meetings methos to User class | Add attended_meetings and absent_meetings methos to User class
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
faculty_number = models.CharField(max_length=8)
def __unicode__(self):
return unicode(self.username)
def attended_meetings(self):
- return self.protocols.all()
+ return self.meetings_attend.all()
+ def absent_meetings(self):
+ return self.meetings_absent.all()
+ | Add attended_meetings and absent_meetings methos to User class | ## Code Before:
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
faculty_number = models.CharField(max_length=8)
def __unicode__(self):
return unicode(self.username)
def attended_meetings(self):
return self.protocols.all()
## Instruction:
Add attended_meetings and absent_meetings methos to User class
## Code After:
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
faculty_number = models.CharField(max_length=8)
def __unicode__(self):
return unicode(self.username)
def attended_meetings(self):
return self.meetings_attend.all()
def absent_meetings(self):
return self.meetings_absent.all()
| // ... existing code ...
def attended_meetings(self):
return self.meetings_attend.all()
def absent_meetings(self):
return self.meetings_absent.all()
// ... rest of the code ... |
c576acc020e60e704dad55f8cd281c4ebb26ad28 | plenario/apiary/views.py | plenario/apiary/views.py | from flask import Blueprint, request
from json import dumps, loads
from redis import Redis
from plenario.settings import REDIS_HOST_SAFE
blueprint = Blueprint("apiary", __name__)
redis = Redis(REDIS_HOST_SAFE)
@blueprint.route("/apiary/send_message", methods=["POST"])
def send_message():
try:
data = loads(request.data)
redis.set(name="AOTMapper_" + data["name"], value=dumps(data["value"]))
except (KeyError, ValueError):
pass
| from collections import defaultdict
from json import dumps, loads
from traceback import format_exc
from flask import Blueprint, make_response, request
from redis import Redis
from plenario.auth import login_required
from plenario.settings import REDIS_HOST_SAFE
blueprint = Blueprint("apiary", __name__)
redis = Redis(REDIS_HOST_SAFE)
# @login_required
@blueprint.route("/apiary/send_message", methods=["POST"])
def send_message():
try:
data = loads(request.data)
redis.set(name="AOTMapper_" + data["name"], value=dumps(data["value"]))
return make_response("Message received successfully!", 200)
except (KeyError, ValueError):
return make_response(format_exc(), 500)
@login_required
@blueprint.route("/apiary/mapper_errors", methods=["GET"])
def mapper_errors():
errors = defaultdict(list)
for key in redis.scan_iter(match="AOTMapper_*"):
errors[key].append(redis.get(key))
return make_response(dumps(errors), 200) | Add a rudimentary view for tracking mapper errors | Add a rudimentary view for tracking mapper errors
| Python | mit | UrbanCCD-UChicago/plenario,UrbanCCD-UChicago/plenario,UrbanCCD-UChicago/plenario | - from flask import Blueprint, request
+ from collections import defaultdict
from json import dumps, loads
+ from traceback import format_exc
+
+ from flask import Blueprint, make_response, request
from redis import Redis
+ from plenario.auth import login_required
from plenario.settings import REDIS_HOST_SAFE
-
blueprint = Blueprint("apiary", __name__)
redis = Redis(REDIS_HOST_SAFE)
+ # @login_required
@blueprint.route("/apiary/send_message", methods=["POST"])
def send_message():
try:
data = loads(request.data)
redis.set(name="AOTMapper_" + data["name"], value=dumps(data["value"]))
+ return make_response("Message received successfully!", 200)
except (KeyError, ValueError):
- pass
+ return make_response(format_exc(), 500)
+
+ @login_required
+ @blueprint.route("/apiary/mapper_errors", methods=["GET"])
+ def mapper_errors():
+ errors = defaultdict(list)
+ for key in redis.scan_iter(match="AOTMapper_*"):
+ errors[key].append(redis.get(key))
+ return make_response(dumps(errors), 200) | Add a rudimentary view for tracking mapper errors | ## Code Before:
from flask import Blueprint, request
from json import dumps, loads
from redis import Redis
from plenario.settings import REDIS_HOST_SAFE
blueprint = Blueprint("apiary", __name__)
redis = Redis(REDIS_HOST_SAFE)
@blueprint.route("/apiary/send_message", methods=["POST"])
def send_message():
try:
data = loads(request.data)
redis.set(name="AOTMapper_" + data["name"], value=dumps(data["value"]))
except (KeyError, ValueError):
pass
## Instruction:
Add a rudimentary view for tracking mapper errors
## Code After:
from collections import defaultdict
from json import dumps, loads
from traceback import format_exc
from flask import Blueprint, make_response, request
from redis import Redis
from plenario.auth import login_required
from plenario.settings import REDIS_HOST_SAFE
blueprint = Blueprint("apiary", __name__)
redis = Redis(REDIS_HOST_SAFE)
# @login_required
@blueprint.route("/apiary/send_message", methods=["POST"])
def send_message():
try:
data = loads(request.data)
redis.set(name="AOTMapper_" + data["name"], value=dumps(data["value"]))
return make_response("Message received successfully!", 200)
except (KeyError, ValueError):
return make_response(format_exc(), 500)
@login_required
@blueprint.route("/apiary/mapper_errors", methods=["GET"])
def mapper_errors():
errors = defaultdict(list)
for key in redis.scan_iter(match="AOTMapper_*"):
errors[key].append(redis.get(key))
return make_response(dumps(errors), 200) | # ... existing code ...
from collections import defaultdict
from json import dumps, loads
from traceback import format_exc
from flask import Blueprint, make_response, request
from redis import Redis
from plenario.auth import login_required
from plenario.settings import REDIS_HOST_SAFE
blueprint = Blueprint("apiary", __name__)
# ... modified code ...
# @login_required
@blueprint.route("/apiary/send_message", methods=["POST"])
def send_message():
...
data = loads(request.data)
redis.set(name="AOTMapper_" + data["name"], value=dumps(data["value"]))
return make_response("Message received successfully!", 200)
except (KeyError, ValueError):
return make_response(format_exc(), 500)
@login_required
@blueprint.route("/apiary/mapper_errors", methods=["GET"])
def mapper_errors():
errors = defaultdict(list)
for key in redis.scan_iter(match="AOTMapper_*"):
errors[key].append(redis.get(key))
return make_response(dumps(errors), 200)
# ... rest of the code ... |
4ed0272e82c3bdef548643f4b9bce8f6bc510a42 | classes.py | classes.py | from collections import namedtuple
class User:
def __init__(self, id_, first_name, last_name='', username=''):
self.id = id_
self.first_name = first_name
self.last_name = last_name
self.username = username
@classmethod
def from_database(cls, user):
return cls(*user)
@classmethod
def from_telegram(cls, user):
copy = user.copy()
copy['id_'] = copy['id']
del copy['id']
return cls(**copy)
class Quote:
def __init__(self, id_, chat_id, message_id, sent_at, sent_by,
content, quoted_by=None):
self.id = id_
self.chat_id = chat_id
self.message_id = message_id
self.sent_at = sent_at
self.sent_by = sent_by
self.content = content
self.quoted_by = quoted_by
@classmethod
def from_database(cls, quote):
return cls(*quote)
Result = namedtuple('Result', ['quote', 'user'])
| from collections import namedtuple
class User:
def __init__(self, id_, first_name, last_name='', username='',
language_code=''):
self.id = id_
self.first_name = first_name
self.last_name = last_name
self.username = username
@classmethod
def from_database(cls, user):
return cls(*user)
@classmethod
def from_telegram(cls, user):
copy = user.copy()
copy['id_'] = copy['id']
del copy['id']
return cls(**copy)
class Quote:
def __init__(self, id_, chat_id, message_id, sent_at, sent_by,
content, quoted_by=None):
self.id = id_
self.chat_id = chat_id
self.message_id = message_id
self.sent_at = sent_at
self.sent_by = sent_by
self.content = content
self.quoted_by = quoted_by
@classmethod
def from_database(cls, quote):
return cls(*quote)
Result = namedtuple('Result', ['quote', 'user'])
| Update User class to match Telegram API | Update User class to match Telegram API
| Python | mit | Doktor/soup-dumpling | from collections import namedtuple
class User:
- def __init__(self, id_, first_name, last_name='', username=''):
+ def __init__(self, id_, first_name, last_name='', username='',
+ language_code=''):
self.id = id_
self.first_name = first_name
self.last_name = last_name
self.username = username
@classmethod
def from_database(cls, user):
return cls(*user)
@classmethod
def from_telegram(cls, user):
copy = user.copy()
copy['id_'] = copy['id']
del copy['id']
return cls(**copy)
class Quote:
def __init__(self, id_, chat_id, message_id, sent_at, sent_by,
content, quoted_by=None):
self.id = id_
self.chat_id = chat_id
self.message_id = message_id
self.sent_at = sent_at
self.sent_by = sent_by
self.content = content
self.quoted_by = quoted_by
@classmethod
def from_database(cls, quote):
return cls(*quote)
Result = namedtuple('Result', ['quote', 'user'])
| Update User class to match Telegram API | ## Code Before:
from collections import namedtuple
class User:
def __init__(self, id_, first_name, last_name='', username=''):
self.id = id_
self.first_name = first_name
self.last_name = last_name
self.username = username
@classmethod
def from_database(cls, user):
return cls(*user)
@classmethod
def from_telegram(cls, user):
copy = user.copy()
copy['id_'] = copy['id']
del copy['id']
return cls(**copy)
class Quote:
def __init__(self, id_, chat_id, message_id, sent_at, sent_by,
content, quoted_by=None):
self.id = id_
self.chat_id = chat_id
self.message_id = message_id
self.sent_at = sent_at
self.sent_by = sent_by
self.content = content
self.quoted_by = quoted_by
@classmethod
def from_database(cls, quote):
return cls(*quote)
Result = namedtuple('Result', ['quote', 'user'])
## Instruction:
Update User class to match Telegram API
## Code After:
from collections import namedtuple
class User:
def __init__(self, id_, first_name, last_name='', username='',
language_code=''):
self.id = id_
self.first_name = first_name
self.last_name = last_name
self.username = username
@classmethod
def from_database(cls, user):
return cls(*user)
@classmethod
def from_telegram(cls, user):
copy = user.copy()
copy['id_'] = copy['id']
del copy['id']
return cls(**copy)
class Quote:
def __init__(self, id_, chat_id, message_id, sent_at, sent_by,
content, quoted_by=None):
self.id = id_
self.chat_id = chat_id
self.message_id = message_id
self.sent_at = sent_at
self.sent_by = sent_by
self.content = content
self.quoted_by = quoted_by
@classmethod
def from_database(cls, quote):
return cls(*quote)
Result = namedtuple('Result', ['quote', 'user'])
| // ... existing code ...
class User:
def __init__(self, id_, first_name, last_name='', username='',
language_code=''):
self.id = id_
self.first_name = first_name
// ... rest of the code ... |
0a2f63367cdb8bffdf762da78fb4888bef9c7d22 | run_tests.py | run_tests.py | import sys
sys.path.append('lib/sdks/google_appengine_1.7.1/google_appengine')
import dev_appserver
import unittest
dev_appserver.fix_sys_path()
suites = unittest.loader.TestLoader().discover("src/givabit", pattern="*_test.py")
if len(sys.argv) > 1:
def GetTestCases(caseorsuite, acc=None):
if acc is None:
acc = []
if isinstance(caseorsuite, unittest.TestCase):
acc.append(caseorsuite)
return acc
for child in caseorsuite:
GetTestCases(child, acc)
return acc
all_tests = GetTestCases(suites)
tests = [test for test in all_tests if test.id().startswith(sys.argv[1])]
suites = unittest.TestSuite(tests)
unittest.TextTestRunner(verbosity=1).run(suites)
| import sys
sys.path.append('lib/sdks/google_appengine_1.7.1/google_appengine')
import dev_appserver
import unittest
dev_appserver.fix_sys_path()
suites = unittest.loader.TestLoader().discover("src/givabit", pattern="*_test.py")
if len(sys.argv) > 1:
def GetTestCases(caseorsuite, acc=None):
if acc is None:
acc = []
if isinstance(caseorsuite, unittest.TestCase):
acc.append(caseorsuite)
return acc
for child in caseorsuite:
GetTestCases(child, acc)
return acc
all_tests = GetTestCases(suites)
tests = [test for test in all_tests if test.id().startswith(sys.argv[1]) or test.id().endswith(sys.argv[1])]
suites = unittest.TestSuite(tests)
unittest.TextTestRunner(verbosity=1).run(suites)
| Support running test just by test name | Support running test just by test name
| Python | apache-2.0 | illicitonion/givabit,illicitonion/givabit,illicitonion/givabit,illicitonion/givabit,illicitonion/givabit,illicitonion/givabit,illicitonion/givabit,illicitonion/givabit | import sys
sys.path.append('lib/sdks/google_appengine_1.7.1/google_appengine')
import dev_appserver
import unittest
dev_appserver.fix_sys_path()
suites = unittest.loader.TestLoader().discover("src/givabit", pattern="*_test.py")
if len(sys.argv) > 1:
def GetTestCases(caseorsuite, acc=None):
if acc is None:
acc = []
if isinstance(caseorsuite, unittest.TestCase):
acc.append(caseorsuite)
return acc
for child in caseorsuite:
GetTestCases(child, acc)
return acc
all_tests = GetTestCases(suites)
- tests = [test for test in all_tests if test.id().startswith(sys.argv[1])]
+ tests = [test for test in all_tests if test.id().startswith(sys.argv[1]) or test.id().endswith(sys.argv[1])]
suites = unittest.TestSuite(tests)
unittest.TextTestRunner(verbosity=1).run(suites)
| Support running test just by test name | ## Code Before:
import sys
sys.path.append('lib/sdks/google_appengine_1.7.1/google_appengine')
import dev_appserver
import unittest
dev_appserver.fix_sys_path()
suites = unittest.loader.TestLoader().discover("src/givabit", pattern="*_test.py")
if len(sys.argv) > 1:
def GetTestCases(caseorsuite, acc=None):
if acc is None:
acc = []
if isinstance(caseorsuite, unittest.TestCase):
acc.append(caseorsuite)
return acc
for child in caseorsuite:
GetTestCases(child, acc)
return acc
all_tests = GetTestCases(suites)
tests = [test for test in all_tests if test.id().startswith(sys.argv[1])]
suites = unittest.TestSuite(tests)
unittest.TextTestRunner(verbosity=1).run(suites)
## Instruction:
Support running test just by test name
## Code After:
import sys
sys.path.append('lib/sdks/google_appengine_1.7.1/google_appengine')
import dev_appserver
import unittest
dev_appserver.fix_sys_path()
suites = unittest.loader.TestLoader().discover("src/givabit", pattern="*_test.py")
if len(sys.argv) > 1:
def GetTestCases(caseorsuite, acc=None):
if acc is None:
acc = []
if isinstance(caseorsuite, unittest.TestCase):
acc.append(caseorsuite)
return acc
for child in caseorsuite:
GetTestCases(child, acc)
return acc
all_tests = GetTestCases(suites)
tests = [test for test in all_tests if test.id().startswith(sys.argv[1]) or test.id().endswith(sys.argv[1])]
suites = unittest.TestSuite(tests)
unittest.TextTestRunner(verbosity=1).run(suites)
| # ... existing code ...
return acc
all_tests = GetTestCases(suites)
tests = [test for test in all_tests if test.id().startswith(sys.argv[1]) or test.id().endswith(sys.argv[1])]
suites = unittest.TestSuite(tests)
# ... rest of the code ... |
9d162a2919a1c9b56ded74d40963fa022fc7943b | src/config/settings/testing.py | src/config/settings/testing.py | """Django configuration for testing and CI environments."""
from .common import *
# Use in-memory file storage
DEFAULT_FILE_STORAGE = 'inmemorystorage.InMemoryStorage'
# Speed!
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
'TEST': {}
}
}
env = get_secret("ENVIRONMENT")
import sys
if os.path.isdir('/Volumes/RAMDisk') and not env == 'ci' and not 'create-db' in sys.argv:
# and this allows you to use --reuse-db to skip re-creating the db,
# even faster!
#
# To create the RAMDisk, use bash:
# $ hdiutil attach -nomount ram://$((2 * 1024 * SIZE_IN_MB))
# /dev/disk2
# $ diskutil eraseVolume HFS+ RAMDisk /dev/disk2
DATABASES['default']['TEST']['NAME'] = '/Volumes/RAMDisk/unkenmathe.test.db.sqlite3'
| """Django configuration for testing and CI environments."""
from .common import *
# Use in-memory file storage
DEFAULT_FILE_STORAGE = 'inmemorystorage.InMemoryStorage'
# Speed!
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
'TEST': {}
}
}
# Disable logging
import logging
logging.disable(logging.CRITICAL)
env = get_secret("ENVIRONMENT")
import sys
if os.path.isdir('/Volumes/RAMDisk') and not env == 'ci' and not 'create-db' in sys.argv:
# and this allows you to use --reuse-db to skip re-creating the db,
# even faster!
#
# To create the RAMDisk, use bash:
# $ hdiutil attach -nomount ram://$((2 * 1024 * SIZE_IN_MB))
# /dev/disk2
# $ diskutil eraseVolume HFS+ RAMDisk /dev/disk2
DATABASES['default']['TEST']['NAME'] = '/Volumes/RAMDisk/unkenmathe.test.db.sqlite3'
| Disable logging in test runs | Disable logging in test runs
SPEED!
| Python | agpl-3.0 | FlowFX/unkenmathe.de,FlowFX/unkenmathe.de,FlowFX/unkenmathe.de,FlowFX/unkenmathe.de | """Django configuration for testing and CI environments."""
from .common import *
# Use in-memory file storage
DEFAULT_FILE_STORAGE = 'inmemorystorage.InMemoryStorage'
# Speed!
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
'TEST': {}
}
}
+ # Disable logging
+ import logging
+ logging.disable(logging.CRITICAL)
+
env = get_secret("ENVIRONMENT")
import sys
if os.path.isdir('/Volumes/RAMDisk') and not env == 'ci' and not 'create-db' in sys.argv:
# and this allows you to use --reuse-db to skip re-creating the db,
# even faster!
#
# To create the RAMDisk, use bash:
# $ hdiutil attach -nomount ram://$((2 * 1024 * SIZE_IN_MB))
# /dev/disk2
# $ diskutil eraseVolume HFS+ RAMDisk /dev/disk2
DATABASES['default']['TEST']['NAME'] = '/Volumes/RAMDisk/unkenmathe.test.db.sqlite3'
| Disable logging in test runs | ## Code Before:
"""Django configuration for testing and CI environments."""
from .common import *
# Use in-memory file storage
DEFAULT_FILE_STORAGE = 'inmemorystorage.InMemoryStorage'
# Speed!
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
'TEST': {}
}
}
env = get_secret("ENVIRONMENT")
import sys
if os.path.isdir('/Volumes/RAMDisk') and not env == 'ci' and not 'create-db' in sys.argv:
# and this allows you to use --reuse-db to skip re-creating the db,
# even faster!
#
# To create the RAMDisk, use bash:
# $ hdiutil attach -nomount ram://$((2 * 1024 * SIZE_IN_MB))
# /dev/disk2
# $ diskutil eraseVolume HFS+ RAMDisk /dev/disk2
DATABASES['default']['TEST']['NAME'] = '/Volumes/RAMDisk/unkenmathe.test.db.sqlite3'
## Instruction:
Disable logging in test runs
## Code After:
"""Django configuration for testing and CI environments."""
from .common import *
# Use in-memory file storage
DEFAULT_FILE_STORAGE = 'inmemorystorage.InMemoryStorage'
# Speed!
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
'TEST': {}
}
}
# Disable logging
import logging
logging.disable(logging.CRITICAL)
env = get_secret("ENVIRONMENT")
import sys
if os.path.isdir('/Volumes/RAMDisk') and not env == 'ci' and not 'create-db' in sys.argv:
# and this allows you to use --reuse-db to skip re-creating the db,
# even faster!
#
# To create the RAMDisk, use bash:
# $ hdiutil attach -nomount ram://$((2 * 1024 * SIZE_IN_MB))
# /dev/disk2
# $ diskutil eraseVolume HFS+ RAMDisk /dev/disk2
DATABASES['default']['TEST']['NAME'] = '/Volumes/RAMDisk/unkenmathe.test.db.sqlite3'
| ...
}
# Disable logging
import logging
logging.disable(logging.CRITICAL)
env = get_secret("ENVIRONMENT")
... |
77138f52d63be6c58d94f5ba9e0928a12b15125b | vumi/application/__init__.py | vumi/application/__init__.py | """The vumi.application API."""
__all__ = ["ApplicationWorker", "SessionManager", "TagpoolManager",
"MessageStore"]
from vumi.application.base import ApplicationWorker
from vumi.application.session import SessionManager
from vumi.application.tagpool import TagpoolManager
from vumi.application.message_store import MessageStore
| """The vumi.application API."""
__all__ = ["ApplicationWorker", "SessionManager", "TagpoolManager",
"MessageStore", "HTTPRelayApplication"]
from vumi.application.base import ApplicationWorker
from vumi.application.session import SessionManager
from vumi.application.tagpool import TagpoolManager
from vumi.application.message_store import MessageStore
from vumi.application.http_relay import HTTPRelayApplication
| Add HTTPRelayApplication to vumi.application package API. | Add HTTPRelayApplication to vumi.application package API.
| Python | bsd-3-clause | harrissoerja/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,harrissoerja/vumi | """The vumi.application API."""
__all__ = ["ApplicationWorker", "SessionManager", "TagpoolManager",
- "MessageStore"]
+ "MessageStore", "HTTPRelayApplication"]
from vumi.application.base import ApplicationWorker
from vumi.application.session import SessionManager
from vumi.application.tagpool import TagpoolManager
from vumi.application.message_store import MessageStore
+ from vumi.application.http_relay import HTTPRelayApplication
| Add HTTPRelayApplication to vumi.application package API. | ## Code Before:
"""The vumi.application API."""
__all__ = ["ApplicationWorker", "SessionManager", "TagpoolManager",
"MessageStore"]
from vumi.application.base import ApplicationWorker
from vumi.application.session import SessionManager
from vumi.application.tagpool import TagpoolManager
from vumi.application.message_store import MessageStore
## Instruction:
Add HTTPRelayApplication to vumi.application package API.
## Code After:
"""The vumi.application API."""
__all__ = ["ApplicationWorker", "SessionManager", "TagpoolManager",
"MessageStore", "HTTPRelayApplication"]
from vumi.application.base import ApplicationWorker
from vumi.application.session import SessionManager
from vumi.application.tagpool import TagpoolManager
from vumi.application.message_store import MessageStore
from vumi.application.http_relay import HTTPRelayApplication
| // ... existing code ...
__all__ = ["ApplicationWorker", "SessionManager", "TagpoolManager",
"MessageStore", "HTTPRelayApplication"]
from vumi.application.base import ApplicationWorker
// ... modified code ...
from vumi.application.tagpool import TagpoolManager
from vumi.application.message_store import MessageStore
from vumi.application.http_relay import HTTPRelayApplication
// ... rest of the code ... |
841235452d92ea4e40853c8df51568e01b39dba8 | stackoverflow/21180496/except.py | stackoverflow/21180496/except.py |
import unittest
class MyException(Exception):
def __init__(self, message):
self.message = message
def RaiseException(message):
raise MyException(message)
class ExceptionTest(unittest.TestCase):
def verifyComplexException(self, exception_class, message, callable, *args):
with self.assertRaises(exception_class) as cm:
callable(*args)
exception = cm.exception
self.assertEqual(exception.message, message)
def testRaises(self):
self.verifyComplexException(MyException, 'asdf', RaiseException, 'asdf')
if __name__ == '__main__':
unittest.main()
|
"""Demonstration of catching an exception and verifying its fields."""
import unittest
class MyException(Exception):
def __init__(self, message):
self.message = message
def RaiseException(message):
raise MyException(message)
class ExceptionTest(unittest.TestCase):
def verifyComplexException(self, exception_class, message, callable, *args):
with self.assertRaises(exception_class) as cm:
callable(*args)
exception = cm.exception
self.assertEqual(exception.message, message)
def testRaises(self):
self.verifyComplexException(MyException, 'asdf', RaiseException, 'asdf')
if __name__ == '__main__':
unittest.main()
| Convert top-level-comment to a docstring. | Convert top-level-comment to a docstring.
| Python | apache-2.0 | mbrukman/stackexchange-answers,mbrukman/stackexchange-answers | +
+ """Demonstration of catching an exception and verifying its fields."""
import unittest
class MyException(Exception):
def __init__(self, message):
self.message = message
def RaiseException(message):
raise MyException(message)
class ExceptionTest(unittest.TestCase):
def verifyComplexException(self, exception_class, message, callable, *args):
with self.assertRaises(exception_class) as cm:
callable(*args)
exception = cm.exception
self.assertEqual(exception.message, message)
def testRaises(self):
self.verifyComplexException(MyException, 'asdf', RaiseException, 'asdf')
if __name__ == '__main__':
unittest.main()
| Convert top-level-comment to a docstring. | ## Code Before:
import unittest
class MyException(Exception):
def __init__(self, message):
self.message = message
def RaiseException(message):
raise MyException(message)
class ExceptionTest(unittest.TestCase):
def verifyComplexException(self, exception_class, message, callable, *args):
with self.assertRaises(exception_class) as cm:
callable(*args)
exception = cm.exception
self.assertEqual(exception.message, message)
def testRaises(self):
self.verifyComplexException(MyException, 'asdf', RaiseException, 'asdf')
if __name__ == '__main__':
unittest.main()
## Instruction:
Convert top-level-comment to a docstring.
## Code After:
"""Demonstration of catching an exception and verifying its fields."""
import unittest
class MyException(Exception):
def __init__(self, message):
self.message = message
def RaiseException(message):
raise MyException(message)
class ExceptionTest(unittest.TestCase):
def verifyComplexException(self, exception_class, message, callable, *args):
with self.assertRaises(exception_class) as cm:
callable(*args)
exception = cm.exception
self.assertEqual(exception.message, message)
def testRaises(self):
self.verifyComplexException(MyException, 'asdf', RaiseException, 'asdf')
if __name__ == '__main__':
unittest.main()
| # ... existing code ...
"""Demonstration of catching an exception and verifying its fields."""
import unittest
# ... rest of the code ... |
7418079606a6e24cb0dccfa148b47c3f736e985f | zou/app/blueprints/persons/resources.py | zou/app/blueprints/persons/resources.py | from flask import abort
from flask_restful import Resource, reqparse
from flask_jwt_extended import jwt_required
from zou.app.services import persons_service
from zou.app.utils import auth, permissions
class NewPersonResource(Resource):
@jwt_required
def post(self):
permissions.check_admin_permissions()
data = self.get_arguments()
person = persons_service.create_person(
data["email"],
auth.encrypt_password("default"),
data["first_name"],
data["last_name"],
data["phone"]
)
return person, 201
def get_arguments(self):
parser = reqparse.RequestParser()
parser.add_argument(
"email",
help="The email is required.",
required=True
)
parser.add_argument(
"first_name",
help="The first name is required.",
required=True
)
parser.add_argument(
"last_name",
help="The last name is required.",
required=True
)
parser.add_argument("phone", default="")
args = parser.parse_args()
return args
| from flask import abort
from flask_restful import Resource, reqparse
from flask_jwt_extended import jwt_required
from zou.app.services import persons_service
from zou.app.utils import auth, permissions
class NewPersonResource(Resource):
@jwt_required
def post(self):
permissions.check_admin_permissions()
data = self.get_arguments()
person = persons_service.create_person(
data["email"],
auth.encrypt_password("default"),
data["first_name"],
data["last_name"],
data["phone"],
role=data["role"]
)
return person, 201
def get_arguments(self):
parser = reqparse.RequestParser()
parser.add_argument(
"email",
help="The email is required.",
required=True
)
parser.add_argument(
"first_name",
help="The first name is required.",
required=True
)
parser.add_argument(
"last_name",
help="The last name is required.",
required=True
)
parser.add_argument("phone", default="")
parser.add_argument("role", default="user")
args = parser.parse_args()
return args
| Allow to set role while creating a person | Allow to set role while creating a person
| Python | agpl-3.0 | cgwire/zou | from flask import abort
from flask_restful import Resource, reqparse
from flask_jwt_extended import jwt_required
from zou.app.services import persons_service
from zou.app.utils import auth, permissions
class NewPersonResource(Resource):
@jwt_required
def post(self):
permissions.check_admin_permissions()
data = self.get_arguments()
person = persons_service.create_person(
data["email"],
auth.encrypt_password("default"),
data["first_name"],
data["last_name"],
- data["phone"]
+ data["phone"],
+ role=data["role"]
)
return person, 201
def get_arguments(self):
parser = reqparse.RequestParser()
parser.add_argument(
"email",
help="The email is required.",
required=True
)
parser.add_argument(
"first_name",
help="The first name is required.",
required=True
)
parser.add_argument(
"last_name",
help="The last name is required.",
required=True
)
parser.add_argument("phone", default="")
+ parser.add_argument("role", default="user")
args = parser.parse_args()
return args
| Allow to set role while creating a person | ## Code Before:
from flask import abort
from flask_restful import Resource, reqparse
from flask_jwt_extended import jwt_required
from zou.app.services import persons_service
from zou.app.utils import auth, permissions
class NewPersonResource(Resource):
@jwt_required
def post(self):
permissions.check_admin_permissions()
data = self.get_arguments()
person = persons_service.create_person(
data["email"],
auth.encrypt_password("default"),
data["first_name"],
data["last_name"],
data["phone"]
)
return person, 201
def get_arguments(self):
parser = reqparse.RequestParser()
parser.add_argument(
"email",
help="The email is required.",
required=True
)
parser.add_argument(
"first_name",
help="The first name is required.",
required=True
)
parser.add_argument(
"last_name",
help="The last name is required.",
required=True
)
parser.add_argument("phone", default="")
args = parser.parse_args()
return args
## Instruction:
Allow to set role while creating a person
## Code After:
from flask import abort
from flask_restful import Resource, reqparse
from flask_jwt_extended import jwt_required
from zou.app.services import persons_service
from zou.app.utils import auth, permissions
class NewPersonResource(Resource):
@jwt_required
def post(self):
permissions.check_admin_permissions()
data = self.get_arguments()
person = persons_service.create_person(
data["email"],
auth.encrypt_password("default"),
data["first_name"],
data["last_name"],
data["phone"],
role=data["role"]
)
return person, 201
def get_arguments(self):
parser = reqparse.RequestParser()
parser.add_argument(
"email",
help="The email is required.",
required=True
)
parser.add_argument(
"first_name",
help="The first name is required.",
required=True
)
parser.add_argument(
"last_name",
help="The last name is required.",
required=True
)
parser.add_argument("phone", default="")
parser.add_argument("role", default="user")
args = parser.parse_args()
return args
| // ... existing code ...
data["first_name"],
data["last_name"],
data["phone"],
role=data["role"]
)
return person, 201
// ... modified code ...
)
parser.add_argument("phone", default="")
parser.add_argument("role", default="user")
args = parser.parse_args()
return args
// ... rest of the code ... |
679c2daceb7f4e9d193e345ee42b0334dd576c64 | changes/web/index.py | changes/web/index.py | import changes
import urlparse
from flask import render_template, current_app, redirect, url_for, session
from flask.views import MethodView
class IndexView(MethodView):
def get(self, path=''):
# require auth
if not session.get('email'):
return redirect(url_for('login'))
if current_app.config['SENTRY_DSN']:
parsed = urlparse.urlparse(current_app.config['SENTRY_DSN'])
dsn = '%s://%s@%s/%s' % (
parsed.scheme,
parsed.username,
parsed.hostname + (':%s' % (parsed.port,) if parsed.port else ''),
parsed.path,
)
else:
dsn = None
return render_template('index.html', **{
'SENTRY_PUBLIC_DSN': dsn,
'VERSION': changes.get_version(),
})
| import changes
import urlparse
from flask import render_template, current_app, redirect, url_for, session
from flask.views import MethodView
class IndexView(MethodView):
def get(self, path=''):
# require auth
if not session.get('email'):
return redirect(url_for('login'))
if current_app.config['SENTRY_DSN'] and False:
parsed = urlparse.urlparse(current_app.config['SENTRY_DSN'])
dsn = '%s://%s@%s/%s' % (
parsed.scheme,
parsed.username,
parsed.hostname + (':%s' % (parsed.port,) if parsed.port else ''),
parsed.path,
)
else:
dsn = None
return render_template('index.html', **{
'SENTRY_PUBLIC_DSN': dsn,
'VERSION': changes.get_version(),
})
| Disable Sentry due to sync behavior | Disable Sentry due to sync behavior
| Python | apache-2.0 | bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes | import changes
import urlparse
from flask import render_template, current_app, redirect, url_for, session
from flask.views import MethodView
class IndexView(MethodView):
def get(self, path=''):
# require auth
if not session.get('email'):
return redirect(url_for('login'))
- if current_app.config['SENTRY_DSN']:
+ if current_app.config['SENTRY_DSN'] and False:
parsed = urlparse.urlparse(current_app.config['SENTRY_DSN'])
dsn = '%s://%s@%s/%s' % (
parsed.scheme,
parsed.username,
parsed.hostname + (':%s' % (parsed.port,) if parsed.port else ''),
parsed.path,
)
else:
dsn = None
return render_template('index.html', **{
'SENTRY_PUBLIC_DSN': dsn,
'VERSION': changes.get_version(),
})
| Disable Sentry due to sync behavior | ## Code Before:
import changes
import urlparse
from flask import render_template, current_app, redirect, url_for, session
from flask.views import MethodView
class IndexView(MethodView):
def get(self, path=''):
# require auth
if not session.get('email'):
return redirect(url_for('login'))
if current_app.config['SENTRY_DSN']:
parsed = urlparse.urlparse(current_app.config['SENTRY_DSN'])
dsn = '%s://%s@%s/%s' % (
parsed.scheme,
parsed.username,
parsed.hostname + (':%s' % (parsed.port,) if parsed.port else ''),
parsed.path,
)
else:
dsn = None
return render_template('index.html', **{
'SENTRY_PUBLIC_DSN': dsn,
'VERSION': changes.get_version(),
})
## Instruction:
Disable Sentry due to sync behavior
## Code After:
import changes
import urlparse
from flask import render_template, current_app, redirect, url_for, session
from flask.views import MethodView
class IndexView(MethodView):
def get(self, path=''):
# require auth
if not session.get('email'):
return redirect(url_for('login'))
if current_app.config['SENTRY_DSN'] and False:
parsed = urlparse.urlparse(current_app.config['SENTRY_DSN'])
dsn = '%s://%s@%s/%s' % (
parsed.scheme,
parsed.username,
parsed.hostname + (':%s' % (parsed.port,) if parsed.port else ''),
parsed.path,
)
else:
dsn = None
return render_template('index.html', **{
'SENTRY_PUBLIC_DSN': dsn,
'VERSION': changes.get_version(),
})
| # ... existing code ...
return redirect(url_for('login'))
if current_app.config['SENTRY_DSN'] and False:
parsed = urlparse.urlparse(current_app.config['SENTRY_DSN'])
dsn = '%s://%s@%s/%s' % (
# ... rest of the code ... |
f15c623374f6ca955a37a90d3c90bd19fb781f00 | dallinger/experiments/__init__.py | dallinger/experiments/__init__.py | import logging
from pkg_resources import iter_entry_points
from ..experiment import Experiment
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
# Avoid PEP-8 warning, we want this to be importable from this location
Experiment = Experiment
for entry_point in iter_entry_points(group='dallinger.experiments'):
try:
globals()[entry_point.name] = entry_point.load()
except ImportError:
logger.exception('Could not import registered entry point {}'.format(
entry_point.name
))
| import logging
from pkg_resources import iter_entry_points
from ..config import get_config
from ..experiment import Experiment
config = get_config()
config.load()
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
# Avoid PEP-8 warning, we want this to be importable from this location
Experiment = Experiment
for entry_point in iter_entry_points(group='dallinger.experiments'):
try:
globals()[entry_point.name] = entry_point.load()
except ImportError:
logger.exception('Could not import registered entry point {}'.format(
entry_point.name
))
| Load config when loading dallinger.experiments | Load config when loading dallinger.experiments
| Python | mit | Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger | import logging
from pkg_resources import iter_entry_points
+
+ from ..config import get_config
from ..experiment import Experiment
+
+ config = get_config()
+ config.load()
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
# Avoid PEP-8 warning, we want this to be importable from this location
Experiment = Experiment
for entry_point in iter_entry_points(group='dallinger.experiments'):
try:
globals()[entry_point.name] = entry_point.load()
except ImportError:
logger.exception('Could not import registered entry point {}'.format(
entry_point.name
))
| Load config when loading dallinger.experiments | ## Code Before:
import logging
from pkg_resources import iter_entry_points
from ..experiment import Experiment
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
# Avoid PEP-8 warning, we want this to be importable from this location
Experiment = Experiment
for entry_point in iter_entry_points(group='dallinger.experiments'):
try:
globals()[entry_point.name] = entry_point.load()
except ImportError:
logger.exception('Could not import registered entry point {}'.format(
entry_point.name
))
## Instruction:
Load config when loading dallinger.experiments
## Code After:
import logging
from pkg_resources import iter_entry_points
from ..config import get_config
from ..experiment import Experiment
config = get_config()
config.load()
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
# Avoid PEP-8 warning, we want this to be importable from this location
Experiment = Experiment
for entry_point in iter_entry_points(group='dallinger.experiments'):
try:
globals()[entry_point.name] = entry_point.load()
except ImportError:
logger.exception('Could not import registered entry point {}'.format(
entry_point.name
))
| ...
import logging
from pkg_resources import iter_entry_points
from ..config import get_config
from ..experiment import Experiment
config = get_config()
config.load()
logger = logging.getLogger(__name__)
... |
0725be7d78e8049dd3e3cc1819644443a1a1da3b | backend/uclapi/gunicorn_config.py | backend/uclapi/gunicorn_config.py | import multiprocessing
bind = "127.0.0.1:9000"
# Run cores * 4 + 1 workers in gunicorn
# This is set deliberately high in case of long Oracle transactions locking Django up
workers = multiprocessing.cpu_count() * 4 + 1
threads = multiprocessing.cpu_count() * 4
# Using gaiohttp because of the long blocking calls to the Oracle database
worker_class = "gaiohttp"
daemon = False
proc_name = "uclapi_gunicorn"
timeout = 600 | import multiprocessing
bind = "127.0.0.1:9000"
# Run cores * 4 + 1 workers in gunicorn
# This is set deliberately high in case of long Oracle transactions locking Django up
workers = multiprocessing.cpu_count() * 4 + 1
threads = multiprocessing.cpu_count() * 4
# Using gaiohttp because of the long blocking calls to the Oracle database
worker_class = "gaiohttp"
daemon = False
proc_name = "uclapi_gunicorn"
timeout = 600
greaceful_timeout = 600
| Update gunicorn graceful timeout value to match general timeout | Hotfix: Update gunicorn graceful timeout value to match general timeout
| Python | mit | uclapi/uclapi,uclapi/uclapi,uclapi/uclapi,uclapi/uclapi | import multiprocessing
bind = "127.0.0.1:9000"
# Run cores * 4 + 1 workers in gunicorn
# This is set deliberately high in case of long Oracle transactions locking Django up
workers = multiprocessing.cpu_count() * 4 + 1
threads = multiprocessing.cpu_count() * 4
# Using gaiohttp because of the long blocking calls to the Oracle database
worker_class = "gaiohttp"
daemon = False
proc_name = "uclapi_gunicorn"
- timeout = 600
+ timeout = 600
+ greaceful_timeout = 600
+ | Update gunicorn graceful timeout value to match general timeout | ## Code Before:
import multiprocessing
bind = "127.0.0.1:9000"
# Run cores * 4 + 1 workers in gunicorn
# This is set deliberately high in case of long Oracle transactions locking Django up
workers = multiprocessing.cpu_count() * 4 + 1
threads = multiprocessing.cpu_count() * 4
# Using gaiohttp because of the long blocking calls to the Oracle database
worker_class = "gaiohttp"
daemon = False
proc_name = "uclapi_gunicorn"
timeout = 600
## Instruction:
Update gunicorn graceful timeout value to match general timeout
## Code After:
import multiprocessing
bind = "127.0.0.1:9000"
# Run cores * 4 + 1 workers in gunicorn
# This is set deliberately high in case of long Oracle transactions locking Django up
workers = multiprocessing.cpu_count() * 4 + 1
threads = multiprocessing.cpu_count() * 4
# Using gaiohttp because of the long blocking calls to the Oracle database
worker_class = "gaiohttp"
daemon = False
proc_name = "uclapi_gunicorn"
timeout = 600
greaceful_timeout = 600
| # ... existing code ...
timeout = 600
greaceful_timeout = 600
# ... rest of the code ... |
3d00536041d52900a4ace5304b5b07eba4c11efb | wmt/flask/names/models.py | wmt/flask/names/models.py | from standard_names import StandardName
from ..core import db
class Name(db.Model):
__tablename__ = 'names'
__bind_key__ = 'names'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Name %r>' % self.name
def to_resource(self, brief=False):
if brief:
return {'id': self.id, 'name': self.name}
else:
sn = StandardName(self.name)
return {
'id': self.id,
'href': '/api/names/%d' % self.id,
'name': self.name,
'object': sn.object,
'quantity': sn.quantity,
'operators': sn.operators,
}
| from flask import url_for
from standard_names import StandardName
from ..core import db, JsonMixin
class NameJsonSerializer(JsonMixin):
__public_fields__ = set(['href', 'id', 'name', 'object', 'quantity',
'operators'])
class Name(NameJsonSerializer, db.Model):
__tablename__ = 'names'
__bind_key__ = 'names'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
@property
def href(self):
return url_for('names.name', id=self.id)
@property
def object(self):
return StandardName(self.name).object
@property
def quantity(self):
return StandardName(self.name).quantity
@property
def operators(self):
return StandardName(self.name).operators
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Name %r>' % self.name
| Use the JsonMixin for the names model. | Use the JsonMixin for the names model.
| Python | mit | mcflugen/wmt-rest,mcflugen/wmt-rest | + from flask import url_for
+
from standard_names import StandardName
- from ..core import db
+ from ..core import db, JsonMixin
- class Name(db.Model):
+ class NameJsonSerializer(JsonMixin):
+ __public_fields__ = set(['href', 'id', 'name', 'object', 'quantity',
+ 'operators'])
+
+
+ class Name(NameJsonSerializer, db.Model):
__tablename__ = 'names'
__bind_key__ = 'names'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
+
+ @property
+ def href(self):
+ return url_for('names.name', id=self.id)
+
+ @property
+ def object(self):
+ return StandardName(self.name).object
+
+ @property
+ def quantity(self):
+ return StandardName(self.name).quantity
+
+ @property
+ def operators(self):
+ return StandardName(self.name).operators
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Name %r>' % self.name
- def to_resource(self, brief=False):
- if brief:
- return {'id': self.id, 'name': self.name}
- else:
- sn = StandardName(self.name)
- return {
- 'id': self.id,
- 'href': '/api/names/%d' % self.id,
- 'name': self.name,
- 'object': sn.object,
- 'quantity': sn.quantity,
- 'operators': sn.operators,
- }
- | Use the JsonMixin for the names model. | ## Code Before:
from standard_names import StandardName
from ..core import db
class Name(db.Model):
__tablename__ = 'names'
__bind_key__ = 'names'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Name %r>' % self.name
def to_resource(self, brief=False):
if brief:
return {'id': self.id, 'name': self.name}
else:
sn = StandardName(self.name)
return {
'id': self.id,
'href': '/api/names/%d' % self.id,
'name': self.name,
'object': sn.object,
'quantity': sn.quantity,
'operators': sn.operators,
}
## Instruction:
Use the JsonMixin for the names model.
## Code After:
from flask import url_for
from standard_names import StandardName
from ..core import db, JsonMixin
class NameJsonSerializer(JsonMixin):
__public_fields__ = set(['href', 'id', 'name', 'object', 'quantity',
'operators'])
class Name(NameJsonSerializer, db.Model):
__tablename__ = 'names'
__bind_key__ = 'names'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
@property
def href(self):
return url_for('names.name', id=self.id)
@property
def object(self):
return StandardName(self.name).object
@property
def quantity(self):
return StandardName(self.name).quantity
@property
def operators(self):
return StandardName(self.name).operators
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Name %r>' % self.name
| // ... existing code ...
from flask import url_for
from standard_names import StandardName
from ..core import db, JsonMixin
class NameJsonSerializer(JsonMixin):
__public_fields__ = set(['href', 'id', 'name', 'object', 'quantity',
'operators'])
class Name(NameJsonSerializer, db.Model):
__tablename__ = 'names'
__bind_key__ = 'names'
// ... modified code ...
name = db.Column(db.Text)
@property
def href(self):
return url_for('names.name', id=self.id)
@property
def object(self):
return StandardName(self.name).object
@property
def quantity(self):
return StandardName(self.name).quantity
@property
def operators(self):
return StandardName(self.name).operators
def __init__(self, name):
self.name = name
...
def __repr__(self):
return '<Name %r>' % self.name
// ... rest of the code ... |
aac0f52fa97f75ca6ec5a2744cd1c0942a57c283 | src/pybel/struct/utils.py | src/pybel/struct/utils.py |
from collections import defaultdict
def hash_dict(d):
"""Hashes a dictionary
:param dict d: A dictionary to recursively hash
:return: the hash value of the dictionary
:rtype: int
"""
h = 0
for k, v in sorted(d.items()):
h += hash(k)
if isinstance(v, (set, list)):
h += hash(tuple(sorted(v)))
if isinstance(v, dict):
h += hash_dict(v)
if isinstance(v, (bool, int, tuple, str)):
h += hash(v)
return hash(h)
def stratify_hash_edges(graph):
"""Splits all qualified and unqualified edges by different indexing strategies
:param BELGraph graph: A BEL network
:rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]]
"""
qualified_edges = defaultdict(dict)
unqualified_edges = defaultdict(lambda: defaultdict(set))
for u, v, k, d in graph.edges_iter(keys=True, data=True):
hashed_data = hash_dict(d)
if k < 0:
unqualified_edges[u, v][k].add(hashed_data)
else:
qualified_edges[u, v][hashed_data] = k
return dict(qualified_edges), dict(unqualified_edges)
|
from collections import defaultdict
from ..utils import hash_edge
def stratify_hash_edges(graph):
"""Splits all qualified and unqualified edges by different indexing strategies
:param BELGraph graph: A BEL network
:rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]]
"""
qualified_edges = defaultdict(dict)
unqualified_edges = defaultdict(lambda: defaultdict(set))
for u, v, k, d in graph.edges_iter(keys=True, data=True):
hashed_data = hash_edge(u, v, k, d)
if k < 0:
unqualified_edges[u, v][k].add(hashed_data)
else:
qualified_edges[u, v][hashed_data] = k
return dict(qualified_edges), dict(unqualified_edges)
| Cut out old hash function | Cut out old hash function
| Python | mit | pybel/pybel,pybel/pybel,pybel/pybel |
from collections import defaultdict
+ from ..utils import hash_edge
-
- def hash_dict(d):
- """Hashes a dictionary
-
- :param dict d: A dictionary to recursively hash
- :return: the hash value of the dictionary
- :rtype: int
- """
- h = 0
- for k, v in sorted(d.items()):
- h += hash(k)
-
- if isinstance(v, (set, list)):
- h += hash(tuple(sorted(v)))
-
- if isinstance(v, dict):
- h += hash_dict(v)
-
- if isinstance(v, (bool, int, tuple, str)):
- h += hash(v)
-
- return hash(h)
def stratify_hash_edges(graph):
"""Splits all qualified and unqualified edges by different indexing strategies
:param BELGraph graph: A BEL network
:rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]]
"""
qualified_edges = defaultdict(dict)
unqualified_edges = defaultdict(lambda: defaultdict(set))
for u, v, k, d in graph.edges_iter(keys=True, data=True):
- hashed_data = hash_dict(d)
+ hashed_data = hash_edge(u, v, k, d)
if k < 0:
unqualified_edges[u, v][k].add(hashed_data)
else:
qualified_edges[u, v][hashed_data] = k
return dict(qualified_edges), dict(unqualified_edges)
| Cut out old hash function | ## Code Before:
from collections import defaultdict
def hash_dict(d):
"""Hashes a dictionary
:param dict d: A dictionary to recursively hash
:return: the hash value of the dictionary
:rtype: int
"""
h = 0
for k, v in sorted(d.items()):
h += hash(k)
if isinstance(v, (set, list)):
h += hash(tuple(sorted(v)))
if isinstance(v, dict):
h += hash_dict(v)
if isinstance(v, (bool, int, tuple, str)):
h += hash(v)
return hash(h)
def stratify_hash_edges(graph):
"""Splits all qualified and unqualified edges by different indexing strategies
:param BELGraph graph: A BEL network
:rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]]
"""
qualified_edges = defaultdict(dict)
unqualified_edges = defaultdict(lambda: defaultdict(set))
for u, v, k, d in graph.edges_iter(keys=True, data=True):
hashed_data = hash_dict(d)
if k < 0:
unqualified_edges[u, v][k].add(hashed_data)
else:
qualified_edges[u, v][hashed_data] = k
return dict(qualified_edges), dict(unqualified_edges)
## Instruction:
Cut out old hash function
## Code After:
from collections import defaultdict
from ..utils import hash_edge
def stratify_hash_edges(graph):
"""Splits all qualified and unqualified edges by different indexing strategies
:param BELGraph graph: A BEL network
:rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]]
"""
qualified_edges = defaultdict(dict)
unqualified_edges = defaultdict(lambda: defaultdict(set))
for u, v, k, d in graph.edges_iter(keys=True, data=True):
hashed_data = hash_edge(u, v, k, d)
if k < 0:
unqualified_edges[u, v][k].add(hashed_data)
else:
qualified_edges[u, v][hashed_data] = k
return dict(qualified_edges), dict(unqualified_edges)
| ...
from collections import defaultdict
from ..utils import hash_edge
...
for u, v, k, d in graph.edges_iter(keys=True, data=True):
hashed_data = hash_edge(u, v, k, d)
if k < 0:
... |
fb2cfe4759fb98de644932af17a247428b2cc0f5 | api/auth.py | api/auth.py | from django.http import HttpResponseForbidden
from django.contrib.auth.models import AnonymousUser
from api.models import AuthAPIKey
class APIKeyAuthentication(object):
def is_authenticated(self, request):
params = {}
for key,value in request.GET.items():
params[key.lower()] = value
if params['apikey']:
try:
keyobj = AuthAPIKey.objects.get(key=params['apikey'])
except:
keyobj = None
if keyobj and keyobj.active:
request.user = AnonymousUser()
return True
return False
def challenge(self):
return HttpResponseForbidden('Access Denied, use a API Key')
| from django.http import HttpResponseForbidden
from django.contrib.auth.models import AnonymousUser
from api.models import AuthAPIKey
class APIKeyAuthentication(object):
def is_authenticated(self, request):
params = {}
for key,value in request.GET.items():
params[key.lower()] = value
if 'apikey' in params:
try:
keyobj = AuthAPIKey.objects.get(key=params['apikey'])
except:
keyobj = None
if keyobj and keyobj.active:
request.user = AnonymousUser()
return True
return False
def challenge(self):
return HttpResponseForbidden('Access Denied, use a API Key')
| Fix Auth API key check causing error 500s | Fix Auth API key check causing error 500s
| Python | bsd-3-clause | nikdoof/test-auth | from django.http import HttpResponseForbidden
from django.contrib.auth.models import AnonymousUser
from api.models import AuthAPIKey
class APIKeyAuthentication(object):
def is_authenticated(self, request):
params = {}
for key,value in request.GET.items():
params[key.lower()] = value
- if params['apikey']:
+ if 'apikey' in params:
try:
keyobj = AuthAPIKey.objects.get(key=params['apikey'])
except:
keyobj = None
if keyobj and keyobj.active:
request.user = AnonymousUser()
return True
return False
def challenge(self):
return HttpResponseForbidden('Access Denied, use a API Key')
| Fix Auth API key check causing error 500s | ## Code Before:
from django.http import HttpResponseForbidden
from django.contrib.auth.models import AnonymousUser
from api.models import AuthAPIKey
class APIKeyAuthentication(object):
def is_authenticated(self, request):
params = {}
for key,value in request.GET.items():
params[key.lower()] = value
if params['apikey']:
try:
keyobj = AuthAPIKey.objects.get(key=params['apikey'])
except:
keyobj = None
if keyobj and keyobj.active:
request.user = AnonymousUser()
return True
return False
def challenge(self):
return HttpResponseForbidden('Access Denied, use a API Key')
## Instruction:
Fix Auth API key check causing error 500s
## Code After:
from django.http import HttpResponseForbidden
from django.contrib.auth.models import AnonymousUser
from api.models import AuthAPIKey
class APIKeyAuthentication(object):
def is_authenticated(self, request):
params = {}
for key,value in request.GET.items():
params[key.lower()] = value
if 'apikey' in params:
try:
keyobj = AuthAPIKey.objects.get(key=params['apikey'])
except:
keyobj = None
if keyobj and keyobj.active:
request.user = AnonymousUser()
return True
return False
def challenge(self):
return HttpResponseForbidden('Access Denied, use a API Key')
| ...
params[key.lower()] = value
if 'apikey' in params:
try:
keyobj = AuthAPIKey.objects.get(key=params['apikey'])
... |
f684692a013e80d0c4d07b1c0eba204bd94d2314 | config.py | config.py | HOST = "0.0.0.0"
# Port to listen on
PORT = 8000
# File to store the JSON server list data in.
FILENAME = "list.json"
# Ammount of time, is seconds, after which servers are removed from the list
# if they haven't updated their listings. Note: By default Minetest servers
# only announce once every 5 minutes, so this should be more than 300.
PURGE_TIME = 350
# List of banned IP addresses.
BANLIST = []
# Creates server entries if a server sends an 'update' and there is no entry yet
# This should only be used to populate the server list after list.json was deleted.
ALLOW_UPDATE_WITHOUT_OLD = False
| HOST = "0.0.0.0"
# Port to listen on
PORT = 8000
# File to store the JSON server list data in.
FILENAME = "list.json"
# Ammount of time, is seconds, after which servers are removed from the list
# if they haven't updated their listings. Note: By default Minetest servers
# only announce once every 5 minutes, so this should be more than 300.
PURGE_TIME = 350
# List of banned IP addresses.
BANLIST = []
# Creates server entries if a server sends an 'update' and there is no entry yet
# This should only be used to populate the server list after list.json was deleted.
# This WILL cause problems such as mapgen, mods and privilege information missing from the list
ALLOW_UPDATE_WITHOUT_OLD = False
| Add note that 'ALLOW_UPDATE_WITHOUT_OLD' causes problems | Add note that 'ALLOW_UPDATE_WITHOUT_OLD' causes problems
| Python | lgpl-2.1 | minetest/master-server,minetest/master-server,minetest/master-server | HOST = "0.0.0.0"
# Port to listen on
PORT = 8000
# File to store the JSON server list data in.
FILENAME = "list.json"
# Ammount of time, is seconds, after which servers are removed from the list
# if they haven't updated their listings. Note: By default Minetest servers
# only announce once every 5 minutes, so this should be more than 300.
PURGE_TIME = 350
# List of banned IP addresses.
BANLIST = []
# Creates server entries if a server sends an 'update' and there is no entry yet
# This should only be used to populate the server list after list.json was deleted.
+ # This WILL cause problems such as mapgen, mods and privilege information missing from the list
ALLOW_UPDATE_WITHOUT_OLD = False
| Add note that 'ALLOW_UPDATE_WITHOUT_OLD' causes problems | ## Code Before:
HOST = "0.0.0.0"
# Port to listen on
PORT = 8000
# File to store the JSON server list data in.
FILENAME = "list.json"
# Ammount of time, is seconds, after which servers are removed from the list
# if they haven't updated their listings. Note: By default Minetest servers
# only announce once every 5 minutes, so this should be more than 300.
PURGE_TIME = 350
# List of banned IP addresses.
BANLIST = []
# Creates server entries if a server sends an 'update' and there is no entry yet
# This should only be used to populate the server list after list.json was deleted.
ALLOW_UPDATE_WITHOUT_OLD = False
## Instruction:
Add note that 'ALLOW_UPDATE_WITHOUT_OLD' causes problems
## Code After:
HOST = "0.0.0.0"
# Port to listen on
PORT = 8000
# File to store the JSON server list data in.
FILENAME = "list.json"
# Ammount of time, is seconds, after which servers are removed from the list
# if they haven't updated their listings. Note: By default Minetest servers
# only announce once every 5 minutes, so this should be more than 300.
PURGE_TIME = 350
# List of banned IP addresses.
BANLIST = []
# Creates server entries if a server sends an 'update' and there is no entry yet
# This should only be used to populate the server list after list.json was deleted.
# This WILL cause problems such as mapgen, mods and privilege information missing from the list
ALLOW_UPDATE_WITHOUT_OLD = False
| # ... existing code ...
# Creates server entries if a server sends an 'update' and there is no entry yet
# This should only be used to populate the server list after list.json was deleted.
# This WILL cause problems such as mapgen, mods and privilege information missing from the list
ALLOW_UPDATE_WITHOUT_OLD = False
# ... rest of the code ... |
764f8d9d7818076555cde5fcad29f3052b523771 | company/autocomplete_light_registry.py | company/autocomplete_light_registry.py | import autocomplete_light
from .models import Company
class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['^name']
model = Company
autocomplete_light.register(CompanyAutocomplete)
| import autocomplete_light
from .models import Company
class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['name', 'official_name', 'common_name']
model = Company
autocomplete_light.register(CompanyAutocomplete)
| Add more search fields to autocomplete | Add more search fields to autocomplete
| Python | bsd-3-clause | KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend | import autocomplete_light
from .models import Company
class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase):
- search_fields = ['^name']
+ search_fields = ['name', 'official_name', 'common_name']
model = Company
autocomplete_light.register(CompanyAutocomplete)
| Add more search fields to autocomplete | ## Code Before:
import autocomplete_light
from .models import Company
class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['^name']
model = Company
autocomplete_light.register(CompanyAutocomplete)
## Instruction:
Add more search fields to autocomplete
## Code After:
import autocomplete_light
from .models import Company
class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['name', 'official_name', 'common_name']
model = Company
autocomplete_light.register(CompanyAutocomplete)
| // ... existing code ...
class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['name', 'official_name', 'common_name']
model = Company
autocomplete_light.register(CompanyAutocomplete)
// ... rest of the code ... |
8b1818aefd6180548cf3b9770eb7a4d93e827fd7 | alignak_app/__init__.py | alignak_app/__init__.py |
# Specific Application
from alignak_app import alignak_data, application, launch
# Application version and manifest
VERSION = (0, 2, 0)
__application__ = u"Alignak-App"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Estrada Matthieu"
__copyright__ = u"2015-2016 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak monitoring application AppIndicator"
__releasenotes__ = u"""Alignak monitoring application AppIndicator"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-app"
# Application Manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
|
# Application version and manifest
VERSION = (0, 2, 0)
__application__ = u"Alignak-App"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Estrada Matthieu"
__copyright__ = u"2015-2016 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak monitoring application AppIndicator"
__releasenotes__ = u"""Alignak monitoring application AppIndicator"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-app"
# Application Manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
| Remove import of all Class app | Remove import of all Class app
| Python | agpl-3.0 | Alignak-monitoring-contrib/alignak-app,Alignak-monitoring-contrib/alignak-app | -
- # Specific Application
- from alignak_app import alignak_data, application, launch
# Application version and manifest
VERSION = (0, 2, 0)
__application__ = u"Alignak-App"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Estrada Matthieu"
__copyright__ = u"2015-2016 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak monitoring application AppIndicator"
__releasenotes__ = u"""Alignak monitoring application AppIndicator"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-app"
# Application Manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
| Remove import of all Class app | ## Code Before:
# Specific Application
from alignak_app import alignak_data, application, launch
# Application version and manifest
VERSION = (0, 2, 0)
__application__ = u"Alignak-App"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Estrada Matthieu"
__copyright__ = u"2015-2016 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak monitoring application AppIndicator"
__releasenotes__ = u"""Alignak monitoring application AppIndicator"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-app"
# Application Manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
## Instruction:
Remove import of all Class app
## Code After:
# Application version and manifest
VERSION = (0, 2, 0)
__application__ = u"Alignak-App"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Estrada Matthieu"
__copyright__ = u"2015-2016 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak monitoring application AppIndicator"
__releasenotes__ = u"""Alignak monitoring application AppIndicator"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-app"
# Application Manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
| # ... existing code ...
# Application version and manifest
# ... rest of the code ... |
4095b95930a57e78e35592dba413a776959adcde | logistic_order/model/sale_order.py | logistic_order/model/sale_order.py |
from openerp.osv import orm, fields
class sale_order(orm.Model):
_inherit = 'sale.order'
_columns = {
# override only to change the 'string' argument
# from 'Customer' to 'Requesting Entity'
'partner_id': fields.many2one(
'res.partner',
'Requesting Entity',
readonly=True,
states={'draft': [('readonly', False)],
'sent': [('readonly', False)]},
required=True,
change_default=True,
select=True,
track_visibility='always'),
'consignee_id': fields.many2one(
'res.partner',
string='Consignee',
required=True),
'incoterm_address': fields.char(
'Incoterm Place',
help="Incoterm Place of Delivery. "
"International Commercial Terms are a series of "
"predefined commercial terms used in "
"international transactions."),
'requested_by': fields.text('Requested By'),
}
|
from openerp.osv import orm, fields
class sale_order(orm.Model):
_inherit = 'sale.order'
_columns = {
# override only to change the 'string' argument
# from 'Customer' to 'Requesting Entity'
'partner_id': fields.many2one(
'res.partner',
'Requesting Entity',
readonly=True,
states={'draft': [('readonly', False)],
'sent': [('readonly', False)]},
required=True,
change_default=True,
select=True,
track_visibility='always'),
'consignee_id': fields.many2one(
'res.partner',
string='Consignee',
required=True),
'incoterm_address': fields.char(
'Incoterm Place',
help="Incoterm Place of Delivery. "
"International Commercial Terms are a series of "
"predefined commercial terms used in "
"international transactions."),
'requested_by': fields.text('Requested By'),
'state': fields.selection([
('draft', 'Draft Cost Estimate'),
('sent', 'Cost Estimate Sent'),
('cancel', 'Cancelled'),
('waiting_date', 'Waiting Schedule'),
('progress', 'Logistic Order'),
('manual', 'Logistic Order to Invoice'),
('invoice_except', 'Invoice Exception'),
('done', 'Done'),
], 'Status', readonly=True, track_visibility='onchange',
help="Gives the status of the cost estimate or logistic order. \nThe exception status is automatically set when a cancel operation occurs in the processing of a document linked to the logistic order. \nThe 'Waiting Schedule' status is set when the invoice is confirmed but waiting for the scheduler to run on the order date.", select=True),
}
| Rename state of SO according to LO and Cost Estimate | [IMP] Rename state of SO according to LO and Cost Estimate
| Python | agpl-3.0 | yvaucher/vertical-ngo,mdietrichc2c/vertical-ngo,jorsea/vertical-ngo,gurneyalex/vertical-ngo,jorsea/vertical-ngo,jgrandguillaume/vertical-ngo |
from openerp.osv import orm, fields
class sale_order(orm.Model):
_inherit = 'sale.order'
_columns = {
# override only to change the 'string' argument
# from 'Customer' to 'Requesting Entity'
'partner_id': fields.many2one(
'res.partner',
'Requesting Entity',
readonly=True,
states={'draft': [('readonly', False)],
'sent': [('readonly', False)]},
required=True,
change_default=True,
select=True,
track_visibility='always'),
'consignee_id': fields.many2one(
'res.partner',
string='Consignee',
required=True),
'incoterm_address': fields.char(
'Incoterm Place',
help="Incoterm Place of Delivery. "
"International Commercial Terms are a series of "
"predefined commercial terms used in "
"international transactions."),
'requested_by': fields.text('Requested By'),
+ 'state': fields.selection([
+ ('draft', 'Draft Cost Estimate'),
+ ('sent', 'Cost Estimate Sent'),
+ ('cancel', 'Cancelled'),
+ ('waiting_date', 'Waiting Schedule'),
+ ('progress', 'Logistic Order'),
+ ('manual', 'Logistic Order to Invoice'),
+ ('invoice_except', 'Invoice Exception'),
+ ('done', 'Done'),
+ ], 'Status', readonly=True, track_visibility='onchange',
+ help="Gives the status of the cost estimate or logistic order. \nThe exception status is automatically set when a cancel operation occurs in the processing of a document linked to the logistic order. \nThe 'Waiting Schedule' status is set when the invoice is confirmed but waiting for the scheduler to run on the order date.", select=True),
+
}
| Rename state of SO according to LO and Cost Estimate | ## Code Before:
from openerp.osv import orm, fields
class sale_order(orm.Model):
_inherit = 'sale.order'
_columns = {
# override only to change the 'string' argument
# from 'Customer' to 'Requesting Entity'
'partner_id': fields.many2one(
'res.partner',
'Requesting Entity',
readonly=True,
states={'draft': [('readonly', False)],
'sent': [('readonly', False)]},
required=True,
change_default=True,
select=True,
track_visibility='always'),
'consignee_id': fields.many2one(
'res.partner',
string='Consignee',
required=True),
'incoterm_address': fields.char(
'Incoterm Place',
help="Incoterm Place of Delivery. "
"International Commercial Terms are a series of "
"predefined commercial terms used in "
"international transactions."),
'requested_by': fields.text('Requested By'),
}
## Instruction:
Rename state of SO according to LO and Cost Estimate
## Code After:
from openerp.osv import orm, fields
class sale_order(orm.Model):
_inherit = 'sale.order'
_columns = {
# override only to change the 'string' argument
# from 'Customer' to 'Requesting Entity'
'partner_id': fields.many2one(
'res.partner',
'Requesting Entity',
readonly=True,
states={'draft': [('readonly', False)],
'sent': [('readonly', False)]},
required=True,
change_default=True,
select=True,
track_visibility='always'),
'consignee_id': fields.many2one(
'res.partner',
string='Consignee',
required=True),
'incoterm_address': fields.char(
'Incoterm Place',
help="Incoterm Place of Delivery. "
"International Commercial Terms are a series of "
"predefined commercial terms used in "
"international transactions."),
'requested_by': fields.text('Requested By'),
'state': fields.selection([
('draft', 'Draft Cost Estimate'),
('sent', 'Cost Estimate Sent'),
('cancel', 'Cancelled'),
('waiting_date', 'Waiting Schedule'),
('progress', 'Logistic Order'),
('manual', 'Logistic Order to Invoice'),
('invoice_except', 'Invoice Exception'),
('done', 'Done'),
], 'Status', readonly=True, track_visibility='onchange',
help="Gives the status of the cost estimate or logistic order. \nThe exception status is automatically set when a cancel operation occurs in the processing of a document linked to the logistic order. \nThe 'Waiting Schedule' status is set when the invoice is confirmed but waiting for the scheduler to run on the order date.", select=True),
}
| # ... existing code ...
"international transactions."),
'requested_by': fields.text('Requested By'),
'state': fields.selection([
('draft', 'Draft Cost Estimate'),
('sent', 'Cost Estimate Sent'),
('cancel', 'Cancelled'),
('waiting_date', 'Waiting Schedule'),
('progress', 'Logistic Order'),
('manual', 'Logistic Order to Invoice'),
('invoice_except', 'Invoice Exception'),
('done', 'Done'),
], 'Status', readonly=True, track_visibility='onchange',
help="Gives the status of the cost estimate or logistic order. \nThe exception status is automatically set when a cancel operation occurs in the processing of a document linked to the logistic order. \nThe 'Waiting Schedule' status is set when the invoice is confirmed but waiting for the scheduler to run on the order date.", select=True),
}
# ... rest of the code ... |
52584725e462ab304bc2e976fa691f0d830e7efb | Speech/processor.py | Speech/processor.py |
import urllib, convert, re, os
# from speech_py import speech_to_text_offline as STT_o
# from speech_py import speech_to_text_google as STT
from speech_py import speech_to_text_ibm_rest as STT
def transcribe(audio_url):
if not os.path.isdir('./audio/retrieved_audio'):
os.makedirs('./audio/retrieved_audio')
reg_ex = '\w+.mp4'
file_name = re.search(reg_ex, audio_url).group(0)
urllib.urlretrieve(audio_url, './audio/retrieved_audio/{}'.format(file_name))
convert.convert('./audio/retrieved_audio/{}'.format(file_name))
# Converted in: ./converted/{name}.wav
return STT('./audio/converted/{}'.format(file_name[:-4]+".wav"))
|
import urllib, convert, re, os
# from speech_py import speech_to_text_google as STT
from speech_py import speech_to_text_ibm_rest as STT
def transcribe(audio_url):
if not os.path.isdir('./audio/retrieved_audio'):
os.makedirs('./audio/retrieved_audio')
reg_ex = '\w+.mp4'
file_name = re.search(reg_ex, audio_url).group(0)
urllib.urlretrieve(audio_url, './audio/retrieved_audio/{}'.format(file_name))
convert.convert('./audio/retrieved_audio/{}'.format(file_name))
# Converted in: ./converted/{name}.wav
return STT('./audio/converted/{}'.format(file_name[:-4]+".wav"))
| Modify ffmpeg path heroku 3 | Modify ffmpeg path heroku 3
| Python | mit | hungtraan/FacebookBot,hungtraan/FacebookBot,hungtraan/FacebookBot |
import urllib, convert, re, os
- # from speech_py import speech_to_text_offline as STT_o
# from speech_py import speech_to_text_google as STT
from speech_py import speech_to_text_ibm_rest as STT
def transcribe(audio_url):
if not os.path.isdir('./audio/retrieved_audio'):
os.makedirs('./audio/retrieved_audio')
reg_ex = '\w+.mp4'
file_name = re.search(reg_ex, audio_url).group(0)
urllib.urlretrieve(audio_url, './audio/retrieved_audio/{}'.format(file_name))
convert.convert('./audio/retrieved_audio/{}'.format(file_name))
# Converted in: ./converted/{name}.wav
return STT('./audio/converted/{}'.format(file_name[:-4]+".wav"))
| Modify ffmpeg path heroku 3 | ## Code Before:
import urllib, convert, re, os
# from speech_py import speech_to_text_offline as STT_o
# from speech_py import speech_to_text_google as STT
from speech_py import speech_to_text_ibm_rest as STT
def transcribe(audio_url):
if not os.path.isdir('./audio/retrieved_audio'):
os.makedirs('./audio/retrieved_audio')
reg_ex = '\w+.mp4'
file_name = re.search(reg_ex, audio_url).group(0)
urllib.urlretrieve(audio_url, './audio/retrieved_audio/{}'.format(file_name))
convert.convert('./audio/retrieved_audio/{}'.format(file_name))
# Converted in: ./converted/{name}.wav
return STT('./audio/converted/{}'.format(file_name[:-4]+".wav"))
## Instruction:
Modify ffmpeg path heroku 3
## Code After:
import urllib, convert, re, os
# from speech_py import speech_to_text_google as STT
from speech_py import speech_to_text_ibm_rest as STT
def transcribe(audio_url):
if not os.path.isdir('./audio/retrieved_audio'):
os.makedirs('./audio/retrieved_audio')
reg_ex = '\w+.mp4'
file_name = re.search(reg_ex, audio_url).group(0)
urllib.urlretrieve(audio_url, './audio/retrieved_audio/{}'.format(file_name))
convert.convert('./audio/retrieved_audio/{}'.format(file_name))
# Converted in: ./converted/{name}.wav
return STT('./audio/converted/{}'.format(file_name[:-4]+".wav"))
| ...
import urllib, convert, re, os
# from speech_py import speech_to_text_google as STT
from speech_py import speech_to_text_ibm_rest as STT
... |
d6e4aa32b7b79adc734dfc2b058509cedf771944 | munigeo/migrations/0004_building.py | munigeo/migrations/0004_building.py | from __future__ import unicode_literals
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('munigeo', '0003_add_modified_time_to_address_and_street'),
]
operations = [
migrations.CreateModel(
name='Building',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('origin_id', models.CharField(db_index=True, max_length=40)),
('geometry', django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326)),
('modified_at', models.DateTimeField(auto_now=True, help_text='Time when the information was last changed')),
('addresses', models.ManyToManyField(blank=True, to='munigeo.Address')),
('municipality', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='munigeo.Municipality')),
],
options={
'ordering': ['municipality', 'origin_id'],
},
),
]
| from __future__ import unicode_literals
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
from munigeo.utils import get_default_srid
DEFAULT_SRID = get_default_srid()
class Migration(migrations.Migration):
dependencies = [
('munigeo', '0003_add_modified_time_to_address_and_street'),
]
operations = [
migrations.CreateModel(
name='Building',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('origin_id', models.CharField(db_index=True, max_length=40)),
('geometry', django.contrib.gis.db.models.fields.MultiPolygonField(srid=DEFAULT_SRID)),
('modified_at', models.DateTimeField(auto_now=True, help_text='Time when the information was last changed')),
('addresses', models.ManyToManyField(blank=True, to='munigeo.Address')),
('municipality', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='munigeo.Municipality')),
],
options={
'ordering': ['municipality', 'origin_id'],
},
),
]
| Fix building migration SRID logic | Fix building migration SRID logic
Hardcoding the SRID in the migration could result in a mismatch
between the model srid and the migration srid.
| Python | agpl-3.0 | City-of-Helsinki/munigeo | from __future__ import unicode_literals
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
+
+ from munigeo.utils import get_default_srid
+ DEFAULT_SRID = get_default_srid()
class Migration(migrations.Migration):
dependencies = [
('munigeo', '0003_add_modified_time_to_address_and_street'),
]
operations = [
migrations.CreateModel(
name='Building',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('origin_id', models.CharField(db_index=True, max_length=40)),
- ('geometry', django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326)),
+ ('geometry', django.contrib.gis.db.models.fields.MultiPolygonField(srid=DEFAULT_SRID)),
('modified_at', models.DateTimeField(auto_now=True, help_text='Time when the information was last changed')),
('addresses', models.ManyToManyField(blank=True, to='munigeo.Address')),
('municipality', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='munigeo.Municipality')),
],
options={
'ordering': ['municipality', 'origin_id'],
},
),
]
| Fix building migration SRID logic | ## Code Before:
from __future__ import unicode_literals
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('munigeo', '0003_add_modified_time_to_address_and_street'),
]
operations = [
migrations.CreateModel(
name='Building',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('origin_id', models.CharField(db_index=True, max_length=40)),
('geometry', django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326)),
('modified_at', models.DateTimeField(auto_now=True, help_text='Time when the information was last changed')),
('addresses', models.ManyToManyField(blank=True, to='munigeo.Address')),
('municipality', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='munigeo.Municipality')),
],
options={
'ordering': ['municipality', 'origin_id'],
},
),
]
## Instruction:
Fix building migration SRID logic
## Code After:
from __future__ import unicode_literals
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
from munigeo.utils import get_default_srid
DEFAULT_SRID = get_default_srid()
class Migration(migrations.Migration):
dependencies = [
('munigeo', '0003_add_modified_time_to_address_and_street'),
]
operations = [
migrations.CreateModel(
name='Building',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('origin_id', models.CharField(db_index=True, max_length=40)),
('geometry', django.contrib.gis.db.models.fields.MultiPolygonField(srid=DEFAULT_SRID)),
('modified_at', models.DateTimeField(auto_now=True, help_text='Time when the information was last changed')),
('addresses', models.ManyToManyField(blank=True, to='munigeo.Address')),
('municipality', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='munigeo.Municipality')),
],
options={
'ordering': ['municipality', 'origin_id'],
},
),
]
| // ... existing code ...
from django.db import migrations, models
import django.db.models.deletion
from munigeo.utils import get_default_srid
DEFAULT_SRID = get_default_srid()
// ... modified code ...
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('origin_id', models.CharField(db_index=True, max_length=40)),
('geometry', django.contrib.gis.db.models.fields.MultiPolygonField(srid=DEFAULT_SRID)),
('modified_at', models.DateTimeField(auto_now=True, help_text='Time when the information was last changed')),
('addresses', models.ManyToManyField(blank=True, to='munigeo.Address')),
// ... rest of the code ... |
a59d756072a72e3110875058729e15f17a4b7f8a | bibliopixel/util/log_errors.py | bibliopixel/util/log_errors.py | from .. util import class_name, log
class LogErrors:
"""
Wraps a function call to catch and report exceptions.
"""
def __init__(self, function, max_errors=-1):
"""
:param function: the function to wrap
:param int max_errors: if ``max_errors`` is non-zero, then only the
first ``max_errors`` error messages are printed
"""
self.function = function
self.max_errors = max_errors
self.errors = 0
def __call__(self, *args, **kwds):
"""
Calls ``self.function`` with the given arguments and keywords, and
returns its value - or if the call throws an exception, returns None.
If is ``self.max_errors`` is `0`, all the exceptions are reported,
otherwise just the first ``self.max_errors`` are.
"""
try:
return self.function(*args, **kwds)
except Exception as e:
args = (class_name.class_name(e),) + e.args
raise
self.errors += 1
if self.max_errors < 0 or self.errors <= self.max_errors:
log.error(str(args))
elif self.errors == self.max_errors + 1:
log.error('Exceeded max_errors of %d', self.max_errors)
| from .. util import class_name, log
class LogErrors:
"""
Wraps a function call to catch and report exceptions.
"""
def __init__(self, function, max_errors=-1):
"""
:param function: the function to wrap
:param int max_errors: if ``max_errors`` is non-zero, then only the
first ``max_errors`` error messages are printed
"""
self.function = function
self.max_errors = max_errors
self.errors = 0
def __call__(self, *args, **kwds):
"""
Calls ``self.function`` with the given arguments and keywords, and
returns its value - or if the call throws an exception, returns None.
If is ``self.max_errors`` is `0`, all the exceptions are reported,
otherwise just the first ``self.max_errors`` are.
"""
try:
return self.function(*args, **kwds)
except Exception as e:
args = (class_name.class_name(e),) + e.args
self.errors += 1
if self.max_errors < 0 or self.errors <= self.max_errors:
log.error(str(args))
elif self.errors == self.max_errors + 1:
log.error('Exceeded max_errors of %d', self.max_errors)
| Fix log_error so it now catches exceptions | Fix log_error so it now catches exceptions
* This got accidentally disabled
| Python | mit | rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel | from .. util import class_name, log
class LogErrors:
"""
Wraps a function call to catch and report exceptions.
"""
def __init__(self, function, max_errors=-1):
"""
:param function: the function to wrap
:param int max_errors: if ``max_errors`` is non-zero, then only the
first ``max_errors`` error messages are printed
"""
self.function = function
self.max_errors = max_errors
self.errors = 0
def __call__(self, *args, **kwds):
"""
Calls ``self.function`` with the given arguments and keywords, and
returns its value - or if the call throws an exception, returns None.
If is ``self.max_errors`` is `0`, all the exceptions are reported,
otherwise just the first ``self.max_errors`` are.
"""
try:
return self.function(*args, **kwds)
except Exception as e:
args = (class_name.class_name(e),) + e.args
- raise
self.errors += 1
if self.max_errors < 0 or self.errors <= self.max_errors:
log.error(str(args))
elif self.errors == self.max_errors + 1:
log.error('Exceeded max_errors of %d', self.max_errors)
| Fix log_error so it now catches exceptions | ## Code Before:
from .. util import class_name, log
class LogErrors:
"""
Wraps a function call to catch and report exceptions.
"""
def __init__(self, function, max_errors=-1):
"""
:param function: the function to wrap
:param int max_errors: if ``max_errors`` is non-zero, then only the
first ``max_errors`` error messages are printed
"""
self.function = function
self.max_errors = max_errors
self.errors = 0
def __call__(self, *args, **kwds):
"""
Calls ``self.function`` with the given arguments and keywords, and
returns its value - or if the call throws an exception, returns None.
If is ``self.max_errors`` is `0`, all the exceptions are reported,
otherwise just the first ``self.max_errors`` are.
"""
try:
return self.function(*args, **kwds)
except Exception as e:
args = (class_name.class_name(e),) + e.args
raise
self.errors += 1
if self.max_errors < 0 or self.errors <= self.max_errors:
log.error(str(args))
elif self.errors == self.max_errors + 1:
log.error('Exceeded max_errors of %d', self.max_errors)
## Instruction:
Fix log_error so it now catches exceptions
## Code After:
from .. util import class_name, log
class LogErrors:
"""
Wraps a function call to catch and report exceptions.
"""
def __init__(self, function, max_errors=-1):
"""
:param function: the function to wrap
:param int max_errors: if ``max_errors`` is non-zero, then only the
first ``max_errors`` error messages are printed
"""
self.function = function
self.max_errors = max_errors
self.errors = 0
def __call__(self, *args, **kwds):
"""
Calls ``self.function`` with the given arguments and keywords, and
returns its value - or if the call throws an exception, returns None.
If is ``self.max_errors`` is `0`, all the exceptions are reported,
otherwise just the first ``self.max_errors`` are.
"""
try:
return self.function(*args, **kwds)
except Exception as e:
args = (class_name.class_name(e),) + e.args
self.errors += 1
if self.max_errors < 0 or self.errors <= self.max_errors:
log.error(str(args))
elif self.errors == self.max_errors + 1:
log.error('Exceeded max_errors of %d', self.max_errors)
| // ... existing code ...
except Exception as e:
args = (class_name.class_name(e),) + e.args
self.errors += 1
// ... rest of the code ... |
9ce7de86b7d9c1e9288fa5c09f97414516cabc63 | corehq/apps/reports/filters/urls.py | corehq/apps/reports/filters/urls.py | from django.conf.urls import url
from .api import (
EmwfOptionsView,
CaseListFilterOptions,
DeviceLogUsers,
DeviceLogIds,
MobileWorkersOptionsView,
ReassignCaseOptions,
)
from .location import LocationGroupFilterOptions
urlpatterns = [
url(r'^emwf_options/$', EmwfOptionsView.as_view(), name='emwf_options'),
url(r'^users_options/$', MobileWorkersOptionsView.as_view(), name=MobileWorkersOptionsView.urlname),
url(r'^new_emwf_options/$', LocationRestrictedEmwfOptions.as_view(), name='new_emwf_options'),
url(r'^case_list_options/$', CaseListFilterOptions.as_view(), name='case_list_options'),
url(r'^reassign_case_options/$', ReassignCaseOptions.as_view(), name='reassign_case_options'),
url(r'^grouplocationfilter_options/$', LocationGroupFilterOptions.as_view(),
name='grouplocationfilter_options'
),
url(r'^device_log_users/$', DeviceLogUsers.as_view(), name='device_log_users'),
url(r'^device_log_ids/$', DeviceLogIds.as_view(), name='device_log_ids'),
]
| from django.conf.urls import url
from .api import (
EmwfOptionsView,
CaseListFilterOptions,
DeviceLogUsers,
DeviceLogIds,
MobileWorkersOptionsView,
ReassignCaseOptions,
)
from .location import LocationGroupFilterOptions
urlpatterns = [
url(r'^emwf_options/$', EmwfOptionsView.as_view(), name='emwf_options'),
url(r'^users_options/$', MobileWorkersOptionsView.as_view(), name=MobileWorkersOptionsView.urlname),
url(r'^case_list_options/$', CaseListFilterOptions.as_view(), name='case_list_options'),
url(r'^reassign_case_options/$', ReassignCaseOptions.as_view(), name='reassign_case_options'),
url(r'^grouplocationfilter_options/$', LocationGroupFilterOptions.as_view(),
name='grouplocationfilter_options'
),
url(r'^device_log_users/$', DeviceLogUsers.as_view(), name='device_log_users'),
url(r'^device_log_ids/$', DeviceLogIds.as_view(), name='device_log_ids'),
]
| Fix bad merge and formatting | Fix bad merge and formatting
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | from django.conf.urls import url
from .api import (
EmwfOptionsView,
CaseListFilterOptions,
DeviceLogUsers,
DeviceLogIds,
MobileWorkersOptionsView,
ReassignCaseOptions,
)
from .location import LocationGroupFilterOptions
urlpatterns = [
- url(r'^emwf_options/$', EmwfOptionsView.as_view(), name='emwf_options'),
+ url(r'^emwf_options/$', EmwfOptionsView.as_view(), name='emwf_options'),
- url(r'^users_options/$', MobileWorkersOptionsView.as_view(), name=MobileWorkersOptionsView.urlname),
+ url(r'^users_options/$', MobileWorkersOptionsView.as_view(), name=MobileWorkersOptionsView.urlname),
- url(r'^new_emwf_options/$', LocationRestrictedEmwfOptions.as_view(), name='new_emwf_options'),
- url(r'^case_list_options/$', CaseListFilterOptions.as_view(), name='case_list_options'),
+ url(r'^case_list_options/$', CaseListFilterOptions.as_view(), name='case_list_options'),
- url(r'^reassign_case_options/$', ReassignCaseOptions.as_view(), name='reassign_case_options'),
+ url(r'^reassign_case_options/$', ReassignCaseOptions.as_view(), name='reassign_case_options'),
- url(r'^grouplocationfilter_options/$', LocationGroupFilterOptions.as_view(),
+ url(r'^grouplocationfilter_options/$', LocationGroupFilterOptions.as_view(),
- name='grouplocationfilter_options'
+ name='grouplocationfilter_options'
- ),
+ ),
- url(r'^device_log_users/$', DeviceLogUsers.as_view(), name='device_log_users'),
+ url(r'^device_log_users/$', DeviceLogUsers.as_view(), name='device_log_users'),
- url(r'^device_log_ids/$', DeviceLogIds.as_view(), name='device_log_ids'),
+ url(r'^device_log_ids/$', DeviceLogIds.as_view(), name='device_log_ids'),
]
| Fix bad merge and formatting | ## Code Before:
from django.conf.urls import url
from .api import (
EmwfOptionsView,
CaseListFilterOptions,
DeviceLogUsers,
DeviceLogIds,
MobileWorkersOptionsView,
ReassignCaseOptions,
)
from .location import LocationGroupFilterOptions
urlpatterns = [
url(r'^emwf_options/$', EmwfOptionsView.as_view(), name='emwf_options'),
url(r'^users_options/$', MobileWorkersOptionsView.as_view(), name=MobileWorkersOptionsView.urlname),
url(r'^new_emwf_options/$', LocationRestrictedEmwfOptions.as_view(), name='new_emwf_options'),
url(r'^case_list_options/$', CaseListFilterOptions.as_view(), name='case_list_options'),
url(r'^reassign_case_options/$', ReassignCaseOptions.as_view(), name='reassign_case_options'),
url(r'^grouplocationfilter_options/$', LocationGroupFilterOptions.as_view(),
name='grouplocationfilter_options'
),
url(r'^device_log_users/$', DeviceLogUsers.as_view(), name='device_log_users'),
url(r'^device_log_ids/$', DeviceLogIds.as_view(), name='device_log_ids'),
]
## Instruction:
Fix bad merge and formatting
## Code After:
from django.conf.urls import url
from .api import (
EmwfOptionsView,
CaseListFilterOptions,
DeviceLogUsers,
DeviceLogIds,
MobileWorkersOptionsView,
ReassignCaseOptions,
)
from .location import LocationGroupFilterOptions
urlpatterns = [
url(r'^emwf_options/$', EmwfOptionsView.as_view(), name='emwf_options'),
url(r'^users_options/$', MobileWorkersOptionsView.as_view(), name=MobileWorkersOptionsView.urlname),
url(r'^case_list_options/$', CaseListFilterOptions.as_view(), name='case_list_options'),
url(r'^reassign_case_options/$', ReassignCaseOptions.as_view(), name='reassign_case_options'),
url(r'^grouplocationfilter_options/$', LocationGroupFilterOptions.as_view(),
name='grouplocationfilter_options'
),
url(r'^device_log_users/$', DeviceLogUsers.as_view(), name='device_log_users'),
url(r'^device_log_ids/$', DeviceLogIds.as_view(), name='device_log_ids'),
]
| # ... existing code ...
urlpatterns = [
url(r'^emwf_options/$', EmwfOptionsView.as_view(), name='emwf_options'),
url(r'^users_options/$', MobileWorkersOptionsView.as_view(), name=MobileWorkersOptionsView.urlname),
url(r'^case_list_options/$', CaseListFilterOptions.as_view(), name='case_list_options'),
url(r'^reassign_case_options/$', ReassignCaseOptions.as_view(), name='reassign_case_options'),
url(r'^grouplocationfilter_options/$', LocationGroupFilterOptions.as_view(),
name='grouplocationfilter_options'
),
url(r'^device_log_users/$', DeviceLogUsers.as_view(), name='device_log_users'),
url(r'^device_log_ids/$', DeviceLogIds.as_view(), name='device_log_ids'),
]
# ... rest of the code ... |
e7149a488eaa85baecacfdf78a5d190b51dc46d7 | tests/test_upgrade.py | tests/test_upgrade.py | import shutil
import tempfile
from os import path
import unittest
from libs.qpanel.upgrader import __first_line as firstline, get_current_version
class UpgradeTestClass(unittest.TestCase):
def setUp(self):
# Create a temporary directory
self.test_dir = tempfile.mkdtemp()
def tearDown(self):
# Remove the directory after the test
shutil.rmtree(self.test_dir)
def test_first_line(self):
content = 'a\n\b\t\b'
self.assertEqual(firstline(content), 'a')
self.assertNotEqual(firstline(content), 'ab')
def test_version(self):
version = '0.10'
version_file = path.join(self.test_dir, 'VERSION')
f = open(version_file, 'w')
f.write(version)
f.close()
self.assertEqual(get_current_version(version_file), version)
# runs the unit tests
if __name__ == '__main__':
unittest.main()
| import shutil
import tempfile
from os import path
import unittest
from libs.qpanel.upgrader import __first_line as firstline, get_current_version
class UpgradeTestClass(unittest.TestCase):
def setUp(self):
# Create a temporary directory
self.test_dir = tempfile.mkdtemp()
def tearDown(self):
# Remove the directory after the test
shutil.rmtree(self.test_dir)
def test_first_line(self):
content = 'a\n\b\t\b'
self.assertEqual(firstline(content), 'a')
self.assertNotEqual(firstline(content), 'ab')
def test_version(self):
version = '0.10'
version_file = path.join(self.test_dir, 'VERSION')
f = open(version_file, 'w')
f.write(version)
f.close()
self.assertEqual(get_current_version(version_file), version)
self.assertNotEqual(get_current_version(version_file), '0.11.0')
# runs the unit tests
if __name__ == '__main__':
unittest.main()
| Add not equals test for version function | Add not equals test for version function
| Python | mit | roramirez/qpanel,skazancev/qpanel,roramirez/qpanel,skazancev/qpanel,roramirez/qpanel,skazancev/qpanel,skazancev/qpanel,roramirez/qpanel | import shutil
import tempfile
from os import path
import unittest
from libs.qpanel.upgrader import __first_line as firstline, get_current_version
class UpgradeTestClass(unittest.TestCase):
def setUp(self):
# Create a temporary directory
self.test_dir = tempfile.mkdtemp()
def tearDown(self):
# Remove the directory after the test
shutil.rmtree(self.test_dir)
def test_first_line(self):
content = 'a\n\b\t\b'
self.assertEqual(firstline(content), 'a')
self.assertNotEqual(firstline(content), 'ab')
def test_version(self):
version = '0.10'
version_file = path.join(self.test_dir, 'VERSION')
f = open(version_file, 'w')
f.write(version)
f.close()
self.assertEqual(get_current_version(version_file), version)
+ self.assertNotEqual(get_current_version(version_file), '0.11.0')
# runs the unit tests
if __name__ == '__main__':
unittest.main()
| Add not equals test for version function | ## Code Before:
import shutil
import tempfile
from os import path
import unittest
from libs.qpanel.upgrader import __first_line as firstline, get_current_version
class UpgradeTestClass(unittest.TestCase):
def setUp(self):
# Create a temporary directory
self.test_dir = tempfile.mkdtemp()
def tearDown(self):
# Remove the directory after the test
shutil.rmtree(self.test_dir)
def test_first_line(self):
content = 'a\n\b\t\b'
self.assertEqual(firstline(content), 'a')
self.assertNotEqual(firstline(content), 'ab')
def test_version(self):
version = '0.10'
version_file = path.join(self.test_dir, 'VERSION')
f = open(version_file, 'w')
f.write(version)
f.close()
self.assertEqual(get_current_version(version_file), version)
# runs the unit tests
if __name__ == '__main__':
unittest.main()
## Instruction:
Add not equals test for version function
## Code After:
import shutil
import tempfile
from os import path
import unittest
from libs.qpanel.upgrader import __first_line as firstline, get_current_version
class UpgradeTestClass(unittest.TestCase):
def setUp(self):
# Create a temporary directory
self.test_dir = tempfile.mkdtemp()
def tearDown(self):
# Remove the directory after the test
shutil.rmtree(self.test_dir)
def test_first_line(self):
content = 'a\n\b\t\b'
self.assertEqual(firstline(content), 'a')
self.assertNotEqual(firstline(content), 'ab')
def test_version(self):
version = '0.10'
version_file = path.join(self.test_dir, 'VERSION')
f = open(version_file, 'w')
f.write(version)
f.close()
self.assertEqual(get_current_version(version_file), version)
self.assertNotEqual(get_current_version(version_file), '0.11.0')
# runs the unit tests
if __name__ == '__main__':
unittest.main()
| ...
f.close()
self.assertEqual(get_current_version(version_file), version)
self.assertNotEqual(get_current_version(version_file), '0.11.0')
... |
384d57efa59665f0dd47c07062a8177a2eedde9a | run_tests.py | run_tests.py | import optparse
import sys
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation"""
def main(sdk_path, test_pattern):
sys.path.insert(0, sdk_path)
import dev_appserver
dev_appserver.fix_sys_path()
suite = unittest2.loader.TestLoader().discover("tests", test_pattern)
tests = unittest2.TextTestRunner(verbosity=2).run(suite)
if tests.wasSuccessful() == True:
sys.exit(0)
else:
sys.exit(1)
if __name__ == '__main__':
parser = optparse.OptionParser(USAGE)
options, args = parser.parse_args()
if len(args) < 1:
print 'Warning: Trying default SDK path.'
sdk_path = "/usr/local/google_appengine"
else:
sdk_path = args[0]
test_pattern = "test*.py"
if len(args) > 1:
test_pattern = args[1]
main(sdk_path, test_pattern) | import optparse
import sys
import warnings
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation"""
def main(sdk_path, test_pattern):
sys.path.insert(0, sdk_path)
import dev_appserver
dev_appserver.fix_sys_path()
suite = unittest2.loader.TestLoader().discover("tests", test_pattern)
tests = unittest2.TextTestRunner(verbosity=2).run(suite)
if tests.wasSuccessful() == True:
sys.exit(0)
else:
sys.exit(1)
if __name__ == '__main__':
parser = optparse.OptionParser(USAGE)
options, args = parser.parse_args()
if len(args) < 1:
warnings.warn('Trying default SDK path.', RuntimeWarning)
sdk_path = "/usr/local/google_appengine"
else:
sdk_path = args[0]
test_pattern = "test*.py"
if len(args) > 1:
test_pattern = args[1]
main(sdk_path, test_pattern) | Replace print statement with `warnings.warn`. | Replace print statement with `warnings.warn`.
Also so that it doesn't need to be converted for Python3 compat.
| Python | mit | verycumbersome/the-blue-alliance,the-blue-alliance/the-blue-alliance,1fish2/the-blue-alliance,phil-lopreiato/the-blue-alliance,tsteward/the-blue-alliance,verycumbersome/the-blue-alliance,bdaroz/the-blue-alliance,verycumbersome/the-blue-alliance,bdaroz/the-blue-alliance,nwalters512/the-blue-alliance,synth3tk/the-blue-alliance,fangeugene/the-blue-alliance,phil-lopreiato/the-blue-alliance,bdaroz/the-blue-alliance,nwalters512/the-blue-alliance,josephbisch/the-blue-alliance,jaredhasenklein/the-blue-alliance,synth3tk/the-blue-alliance,bvisness/the-blue-alliance,synth3tk/the-blue-alliance,tsteward/the-blue-alliance,the-blue-alliance/the-blue-alliance,bvisness/the-blue-alliance,josephbisch/the-blue-alliance,synth3tk/the-blue-alliance,jaredhasenklein/the-blue-alliance,synth3tk/the-blue-alliance,jaredhasenklein/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,fangeugene/the-blue-alliance,nwalters512/the-blue-alliance,nwalters512/the-blue-alliance,phil-lopreiato/the-blue-alliance,bvisness/the-blue-alliance,1fish2/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,phil-lopreiato/the-blue-alliance,tsteward/the-blue-alliance,jaredhasenklein/the-blue-alliance,bvisness/the-blue-alliance,josephbisch/the-blue-alliance,josephbisch/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,jaredhasenklein/the-blue-alliance,tsteward/the-blue-alliance,the-blue-alliance/the-blue-alliance,josephbisch/the-blue-alliance,synth3tk/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,1fish2/the-blue-alliance,bvisness/the-blue-alliance,josephbisch/the-blue-alliance,verycumbersome/the-blue-alliance,bvisness/the-blue-alliance,jaredhasenklein/the-blue-alliance,fangeugene/the-blue-alliance,1fish2/the-blue-alliance,tsteward/the-blue-alliance,phil-lopreiato/the-blue-alliance,nwalters512/the-blue-alliance,fangeugene/the-blue-alliance,1fish2/the-blue-alliance,verycumbersome/the-blue-alliance,1fish2/the-blue-alliance,the-blue-alliance/the-blue-alliance,verycumbersome/the-blue-alliance,nwalters512/the-blue-alliance,bdaroz/the-blue-alliance | import optparse
import sys
+ import warnings
+
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation"""
def main(sdk_path, test_pattern):
sys.path.insert(0, sdk_path)
import dev_appserver
dev_appserver.fix_sys_path()
suite = unittest2.loader.TestLoader().discover("tests", test_pattern)
tests = unittest2.TextTestRunner(verbosity=2).run(suite)
if tests.wasSuccessful() == True:
sys.exit(0)
else:
sys.exit(1)
if __name__ == '__main__':
parser = optparse.OptionParser(USAGE)
options, args = parser.parse_args()
if len(args) < 1:
- print 'Warning: Trying default SDK path.'
+ warnings.warn('Trying default SDK path.', RuntimeWarning)
sdk_path = "/usr/local/google_appengine"
else:
sdk_path = args[0]
test_pattern = "test*.py"
if len(args) > 1:
test_pattern = args[1]
main(sdk_path, test_pattern) | Replace print statement with `warnings.warn`. | ## Code Before:
import optparse
import sys
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation"""
def main(sdk_path, test_pattern):
sys.path.insert(0, sdk_path)
import dev_appserver
dev_appserver.fix_sys_path()
suite = unittest2.loader.TestLoader().discover("tests", test_pattern)
tests = unittest2.TextTestRunner(verbosity=2).run(suite)
if tests.wasSuccessful() == True:
sys.exit(0)
else:
sys.exit(1)
if __name__ == '__main__':
parser = optparse.OptionParser(USAGE)
options, args = parser.parse_args()
if len(args) < 1:
print 'Warning: Trying default SDK path.'
sdk_path = "/usr/local/google_appengine"
else:
sdk_path = args[0]
test_pattern = "test*.py"
if len(args) > 1:
test_pattern = args[1]
main(sdk_path, test_pattern)
## Instruction:
Replace print statement with `warnings.warn`.
## Code After:
import optparse
import sys
import warnings
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation"""
def main(sdk_path, test_pattern):
sys.path.insert(0, sdk_path)
import dev_appserver
dev_appserver.fix_sys_path()
suite = unittest2.loader.TestLoader().discover("tests", test_pattern)
tests = unittest2.TextTestRunner(verbosity=2).run(suite)
if tests.wasSuccessful() == True:
sys.exit(0)
else:
sys.exit(1)
if __name__ == '__main__':
parser = optparse.OptionParser(USAGE)
options, args = parser.parse_args()
if len(args) < 1:
warnings.warn('Trying default SDK path.', RuntimeWarning)
sdk_path = "/usr/local/google_appengine"
else:
sdk_path = args[0]
test_pattern = "test*.py"
if len(args) > 1:
test_pattern = args[1]
main(sdk_path, test_pattern) | # ... existing code ...
import optparse
import sys
import warnings
# Install the Python unittest2 package before you run this script.
import unittest2
# ... modified code ...
options, args = parser.parse_args()
if len(args) < 1:
warnings.warn('Trying default SDK path.', RuntimeWarning)
sdk_path = "/usr/local/google_appengine"
else:
# ... rest of the code ... |
bc16915aa3c4a7cef456da4193bdcdc34117eab0 | tests/test_classes.py | tests/test_classes.py | import unittest
import os
import gzip
import bs4
import logging
from classes import (
NbaTeam
)
class MockRequests:
def get(self, url):
pass
class TestNbaTeamPage(unittest.TestCase):
# read html file and ungzip
@classmethod
def setUpClass(cls):
requester = MockRequests()
# file_path = os.path.join(os.path.dirname(__file__), 'mock_data/nba_roster_lakers.htm.gz')
# f = gzip.open(file_path)
# content = f.read()
cls.nba_team = NbaTeam('okc', requester, bs4)
cls.roster_text = content
def test_get_page(self):
team_page = self.nba_team.get_page(self.nba_team.url)
self.assertFalse(self.nba_team.failed)
if __name__ == '__main__':
unittest.main() | import unittest
import os
import gzip
import bs4
import logging
from classes import (
NbaTeam
)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
class MockRequests:
def get(self, url):
pass
class TestNbaTeamPage(unittest.TestCase):
# read html file and ungzip
@classmethod
def setUpClass(cls):
file_path = os.path.join(os.path.dirname(__file__), 'mock_data/nba_roster_lakers.htm.gz')
cls.roster_text = gzip.open(file_path).read()
cls.requester = MockRequests()
@classmethod
def setUp(cls):
cls.nba_team = NbaTeam('okc', cls.requester, bs4)
cls.parsed = cls.nba_team.convert_page(cls.roster_text)
def test_get_page_should_not_fail(self):
team_page = self.nba_team.get_page(self.nba_team.url)
self.assertFalse(self.nba_team.failed)
def test_convert_page_should_not_fail(self):
parsed_page = self.nba_team.convert_page(self.roster_text)
self.assertFalse(self.nba_team.failed)
def test_parse_roster_should_return_player_ids(self):
expected = ['5383', '4285', '5357', '3824', '5329', '5601', '4794', '5487', '5762',
'5318', '5011', '5433', '3339', '4294', '5663']
player_ids = self.nba_team.parse_roster(self.parsed)
self.assertEqual(expected, player_ids)
if __name__ == '__main__':
unittest.main() | Add more NbaTeam class tests | Add more NbaTeam class tests
| Python | mit | arosenberg01/asdata | import unittest
import os
import gzip
import bs4
import logging
from classes import (
NbaTeam
)
+
+ logger = logging.getLogger()
+ logger.setLevel(logging.INFO)
+ logger.addHandler(logging.StreamHandler())
class MockRequests:
def get(self, url):
pass
class TestNbaTeamPage(unittest.TestCase):
# read html file and ungzip
@classmethod
def setUpClass(cls):
- requester = MockRequests()
- # file_path = os.path.join(os.path.dirname(__file__), 'mock_data/nba_roster_lakers.htm.gz')
+ file_path = os.path.join(os.path.dirname(__file__), 'mock_data/nba_roster_lakers.htm.gz')
- # f = gzip.open(file_path)
- # content = f.read()
+ cls.roster_text = gzip.open(file_path).read()
+ cls.requester = MockRequests()
+ @classmethod
+ def setUp(cls):
- cls.nba_team = NbaTeam('okc', requester, bs4)
+ cls.nba_team = NbaTeam('okc', cls.requester, bs4)
- cls.roster_text = content
+ cls.parsed = cls.nba_team.convert_page(cls.roster_text)
-
- def test_get_page(self):
+ def test_get_page_should_not_fail(self):
team_page = self.nba_team.get_page(self.nba_team.url)
self.assertFalse(self.nba_team.failed)
+ def test_convert_page_should_not_fail(self):
+ parsed_page = self.nba_team.convert_page(self.roster_text)
+ self.assertFalse(self.nba_team.failed)
+
+ def test_parse_roster_should_return_player_ids(self):
+ expected = ['5383', '4285', '5357', '3824', '5329', '5601', '4794', '5487', '5762',
+ '5318', '5011', '5433', '3339', '4294', '5663']
+ player_ids = self.nba_team.parse_roster(self.parsed)
+ self.assertEqual(expected, player_ids)
+
if __name__ == '__main__':
unittest.main() | Add more NbaTeam class tests | ## Code Before:
import unittest
import os
import gzip
import bs4
import logging
from classes import (
NbaTeam
)
class MockRequests:
def get(self, url):
pass
class TestNbaTeamPage(unittest.TestCase):
# read html file and ungzip
@classmethod
def setUpClass(cls):
requester = MockRequests()
# file_path = os.path.join(os.path.dirname(__file__), 'mock_data/nba_roster_lakers.htm.gz')
# f = gzip.open(file_path)
# content = f.read()
cls.nba_team = NbaTeam('okc', requester, bs4)
cls.roster_text = content
def test_get_page(self):
team_page = self.nba_team.get_page(self.nba_team.url)
self.assertFalse(self.nba_team.failed)
if __name__ == '__main__':
unittest.main()
## Instruction:
Add more NbaTeam class tests
## Code After:
import unittest
import os
import gzip
import bs4
import logging
from classes import (
NbaTeam
)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
class MockRequests:
def get(self, url):
pass
class TestNbaTeamPage(unittest.TestCase):
# read html file and ungzip
@classmethod
def setUpClass(cls):
file_path = os.path.join(os.path.dirname(__file__), 'mock_data/nba_roster_lakers.htm.gz')
cls.roster_text = gzip.open(file_path).read()
cls.requester = MockRequests()
@classmethod
def setUp(cls):
cls.nba_team = NbaTeam('okc', cls.requester, bs4)
cls.parsed = cls.nba_team.convert_page(cls.roster_text)
def test_get_page_should_not_fail(self):
team_page = self.nba_team.get_page(self.nba_team.url)
self.assertFalse(self.nba_team.failed)
def test_convert_page_should_not_fail(self):
parsed_page = self.nba_team.convert_page(self.roster_text)
self.assertFalse(self.nba_team.failed)
def test_parse_roster_should_return_player_ids(self):
expected = ['5383', '4285', '5357', '3824', '5329', '5601', '4794', '5487', '5762',
'5318', '5011', '5433', '3339', '4294', '5663']
player_ids = self.nba_team.parse_roster(self.parsed)
self.assertEqual(expected, player_ids)
if __name__ == '__main__':
unittest.main() | // ... existing code ...
NbaTeam
)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
class MockRequests:
// ... modified code ...
@classmethod
def setUpClass(cls):
file_path = os.path.join(os.path.dirname(__file__), 'mock_data/nba_roster_lakers.htm.gz')
cls.roster_text = gzip.open(file_path).read()
cls.requester = MockRequests()
@classmethod
def setUp(cls):
cls.nba_team = NbaTeam('okc', cls.requester, bs4)
cls.parsed = cls.nba_team.convert_page(cls.roster_text)
def test_get_page_should_not_fail(self):
team_page = self.nba_team.get_page(self.nba_team.url)
self.assertFalse(self.nba_team.failed)
def test_convert_page_should_not_fail(self):
parsed_page = self.nba_team.convert_page(self.roster_text)
self.assertFalse(self.nba_team.failed)
def test_parse_roster_should_return_player_ids(self):
expected = ['5383', '4285', '5357', '3824', '5329', '5601', '4794', '5487', '5762',
'5318', '5011', '5433', '3339', '4294', '5663']
player_ids = self.nba_team.parse_roster(self.parsed)
self.assertEqual(expected, player_ids)
if __name__ == '__main__':
unittest.main()
// ... rest of the code ... |
6d84cdb641d2d873118cb6cb26c5a7521ae40bd8 | dcclient/dcclient.py | dcclient/dcclient.py |
import rpc
from xml_manager.manager import ManagedXml
from oslo.config import cfg
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
self.xml.addVlan(vlan)
self._update()
|
import rpc
from xml_manager.manager import ManagedXml
from neutron.openstack.common import log as logger
from oslo.config import cfg
LOG = logger.getLogger(__name__)
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
try:
self.xml.addVlan(vlan)
self._update()
except:
LOG.info("Trying to create already existing network %d:", vlan)
| Add error treatment for existing network | Add error treatment for existing network
| Python | apache-2.0 | NeutronUfscarDatacom/DriverDatacom |
import rpc
from xml_manager.manager import ManagedXml
+ from neutron.openstack.common import log as logger
from oslo.config import cfg
+
+ LOG = logger.getLogger(__name__)
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
+ try:
- self.xml.addVlan(vlan)
+ self.xml.addVlan(vlan)
- self._update()
+ self._update()
+ except:
+ LOG.info("Trying to create already existing network %d:", vlan)
| Add error treatment for existing network | ## Code Before:
import rpc
from xml_manager.manager import ManagedXml
from oslo.config import cfg
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
self.xml.addVlan(vlan)
self._update()
## Instruction:
Add error treatment for existing network
## Code After:
import rpc
from xml_manager.manager import ManagedXml
from neutron.openstack.common import log as logger
from oslo.config import cfg
LOG = logger.getLogger(__name__)
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
try:
self.xml.addVlan(vlan)
self._update()
except:
LOG.info("Trying to create already existing network %d:", vlan)
| # ... existing code ...
from neutron.openstack.common import log as logger
from oslo.config import cfg
LOG = logger.getLogger(__name__)
class Manager:
# ... modified code ...
""" Creates a new network on the switch, if it does not exist already.
"""
try:
self.xml.addVlan(vlan)
self._update()
except:
LOG.info("Trying to create already existing network %d:", vlan)
# ... rest of the code ... |
83d45c0fa64da347eec6b96f46c5eb1fbfe516d4 | plugins/call_bad_permissions.py | plugins/call_bad_permissions.py |
import bandit
import stat
from bandit.test_selector import *
@checks_functions
def call_bad_permissions(context):
if 'chmod' in context.call_function_name:
if context.call_args_count == 2:
mode = context.get_call_arg_at_position(1)
if mode is not None and (mode & stat.S_IWOTH or mode & stat.S_IXGRP):
filename = context.get_call_arg_at_position(0)
if filename is None:
filename = 'NOT PARSED'
return(bandit.ERROR, 'Chmod setting a permissive mask %s on '
'file (%s).' % (oct(mode), filename))
|
import bandit
import stat
from bandit.test_selector import *
@checks_functions
def call_bad_permissions(context):
if 'chmod' in context.call_function_name:
if context.call_args_count == 2:
mode = context.get_call_arg_at_position(1)
if(mode is not None and type(mode) == int and
(mode & stat.S_IWOTH or mode & stat.S_IXGRP)):
filename = context.get_call_arg_at_position(0)
if filename is None:
filename = 'NOT PARSED'
return(bandit.ERROR, 'Chmod setting a permissive mask %s on '
'file (%s).' % (oct(mode), filename))
| Fix bug with permissions matching | Fix bug with permissions matching
| Python | apache-2.0 | chair6/bandit,stackforge/bandit,austin987/bandit,pombredanne/bandit,stackforge/bandit,pombredanne/bandit |
import bandit
import stat
from bandit.test_selector import *
@checks_functions
def call_bad_permissions(context):
if 'chmod' in context.call_function_name:
if context.call_args_count == 2:
mode = context.get_call_arg_at_position(1)
+ if(mode is not None and type(mode) == int and
- if mode is not None and (mode & stat.S_IWOTH or mode & stat.S_IXGRP):
+ (mode & stat.S_IWOTH or mode & stat.S_IXGRP)):
filename = context.get_call_arg_at_position(0)
if filename is None:
filename = 'NOT PARSED'
return(bandit.ERROR, 'Chmod setting a permissive mask %s on '
'file (%s).' % (oct(mode), filename))
| Fix bug with permissions matching | ## Code Before:
import bandit
import stat
from bandit.test_selector import *
@checks_functions
def call_bad_permissions(context):
if 'chmod' in context.call_function_name:
if context.call_args_count == 2:
mode = context.get_call_arg_at_position(1)
if mode is not None and (mode & stat.S_IWOTH or mode & stat.S_IXGRP):
filename = context.get_call_arg_at_position(0)
if filename is None:
filename = 'NOT PARSED'
return(bandit.ERROR, 'Chmod setting a permissive mask %s on '
'file (%s).' % (oct(mode), filename))
## Instruction:
Fix bug with permissions matching
## Code After:
import bandit
import stat
from bandit.test_selector import *
@checks_functions
def call_bad_permissions(context):
if 'chmod' in context.call_function_name:
if context.call_args_count == 2:
mode = context.get_call_arg_at_position(1)
if(mode is not None and type(mode) == int and
(mode & stat.S_IWOTH or mode & stat.S_IXGRP)):
filename = context.get_call_arg_at_position(0)
if filename is None:
filename = 'NOT PARSED'
return(bandit.ERROR, 'Chmod setting a permissive mask %s on '
'file (%s).' % (oct(mode), filename))
| # ... existing code ...
mode = context.get_call_arg_at_position(1)
if(mode is not None and type(mode) == int and
(mode & stat.S_IWOTH or mode & stat.S_IXGRP)):
filename = context.get_call_arg_at_position(0)
if filename is None:
# ... rest of the code ... |
423243bce63da26ca4c5ea784376488ea8997873 | reg/__init__.py | reg/__init__.py | from .dispatch import dispatch, dispatch_method, auto_methodify
from .mapply import mapply
from .arginfo import arginfo
from .argextract import KeyExtractor
from .sentinel import Sentinel, NOT_FOUND
from .error import RegistrationError, KeyExtractorError
from .predicate import (Predicate, PredicateRegistry, KeyIndex, ClassIndex,
key_predicate, class_predicate,
match_key, match_instance, match_argname,
match_class, CachingKeyLookup, Lookup)
| from .dispatch import (dispatch, dispatch_method,
auto_methodify, clean_dispatch_methods)
from .mapply import mapply
from .arginfo import arginfo
from .argextract import KeyExtractor
from .sentinel import Sentinel, NOT_FOUND
from .error import RegistrationError, KeyExtractorError
from .predicate import (Predicate, PredicateRegistry, KeyIndex, ClassIndex,
key_predicate, class_predicate,
match_key, match_instance, match_argname,
match_class, CachingKeyLookup, Lookup)
| Clean dispatch methods exposed to api. | Clean dispatch methods exposed to api.
| Python | bsd-3-clause | taschini/reg,morepath/reg | - from .dispatch import dispatch, dispatch_method, auto_methodify
+ from .dispatch import (dispatch, dispatch_method,
+ auto_methodify, clean_dispatch_methods)
from .mapply import mapply
from .arginfo import arginfo
from .argextract import KeyExtractor
from .sentinel import Sentinel, NOT_FOUND
from .error import RegistrationError, KeyExtractorError
from .predicate import (Predicate, PredicateRegistry, KeyIndex, ClassIndex,
key_predicate, class_predicate,
match_key, match_instance, match_argname,
match_class, CachingKeyLookup, Lookup)
| Clean dispatch methods exposed to api. | ## Code Before:
from .dispatch import dispatch, dispatch_method, auto_methodify
from .mapply import mapply
from .arginfo import arginfo
from .argextract import KeyExtractor
from .sentinel import Sentinel, NOT_FOUND
from .error import RegistrationError, KeyExtractorError
from .predicate import (Predicate, PredicateRegistry, KeyIndex, ClassIndex,
key_predicate, class_predicate,
match_key, match_instance, match_argname,
match_class, CachingKeyLookup, Lookup)
## Instruction:
Clean dispatch methods exposed to api.
## Code After:
from .dispatch import (dispatch, dispatch_method,
auto_methodify, clean_dispatch_methods)
from .mapply import mapply
from .arginfo import arginfo
from .argextract import KeyExtractor
from .sentinel import Sentinel, NOT_FOUND
from .error import RegistrationError, KeyExtractorError
from .predicate import (Predicate, PredicateRegistry, KeyIndex, ClassIndex,
key_predicate, class_predicate,
match_key, match_instance, match_argname,
match_class, CachingKeyLookup, Lookup)
| // ... existing code ...
from .dispatch import (dispatch, dispatch_method,
auto_methodify, clean_dispatch_methods)
from .mapply import mapply
from .arginfo import arginfo
// ... rest of the code ... |
b60f9f22703d97cfaeaa69e36fe283d1ef5d2f5d | download_data.py | download_data.py | import bz2
import urllib.request
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = urllib.request.urlopen(url)
decompressor = bz2.BZ2Decompressor()
with open(dest_file, 'wb') as dest_file:
while True:
data = source.read(CHUNK)
if not data:
break
dest_file.write(decompressor.decompress(data))
if __name__ == '__main__':
download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
| import bz2
import urllib.request
import os
import os.path
DATA_DIR = 'data'
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = urllib.request.urlopen(url)
decompressor = bz2.BZ2Decompressor()
with open(dest_file, 'wb') as dest_file:
while True:
data = source.read(CHUNK)
if not data:
break
dest_file.write(decompressor.decompress(data))
if __name__ == '__main__':
if not os.path.isdir(DATA_DIR):
os.mkdir(DATA_DIR)
download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
| Create dir before data downloading | Create dir before data downloading
| Python | mit | Nizametdinov/cnn-pos-tagger | import bz2
import urllib.request
+ import os
+ import os.path
+ DATA_DIR = 'data'
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = urllib.request.urlopen(url)
decompressor = bz2.BZ2Decompressor()
with open(dest_file, 'wb') as dest_file:
while True:
data = source.read(CHUNK)
if not data:
break
dest_file.write(decompressor.decompress(data))
if __name__ == '__main__':
+ if not os.path.isdir(DATA_DIR):
+ os.mkdir(DATA_DIR)
download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
| Create dir before data downloading | ## Code Before:
import bz2
import urllib.request
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = urllib.request.urlopen(url)
decompressor = bz2.BZ2Decompressor()
with open(dest_file, 'wb') as dest_file:
while True:
data = source.read(CHUNK)
if not data:
break
dest_file.write(decompressor.decompress(data))
if __name__ == '__main__':
download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
## Instruction:
Create dir before data downloading
## Code After:
import bz2
import urllib.request
import os
import os.path
DATA_DIR = 'data'
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = urllib.request.urlopen(url)
decompressor = bz2.BZ2Decompressor()
with open(dest_file, 'wb') as dest_file:
while True:
data = source.read(CHUNK)
if not data:
break
dest_file.write(decompressor.decompress(data))
if __name__ == '__main__':
if not os.path.isdir(DATA_DIR):
os.mkdir(DATA_DIR)
download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
| ...
import bz2
import urllib.request
import os
import os.path
DATA_DIR = 'data'
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
...
if __name__ == '__main__':
if not os.path.isdir(DATA_DIR):
os.mkdir(DATA_DIR)
download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
... |
9a4cf8d594708ef57e41113bad4c76f26f3adc13 | apps/accounts/managers.py | apps/accounts/managers.py |
from django.db import models
class UserProfileManager(models.Manager):
"""
Manager class for the ``UserProfile`` data model.
"""
def get_subscribers_for_newsletter(self):
"""
Return a queryset of all users accepting to receive the newsletter.
"""
return self.filter(accept_newsletter=True)
|
import datetime
from django.db import models
from django.utils import timezone
from .settings import ONLINE_USER_TIME_WINDOW_SECONDS
class UserProfileManager(models.Manager):
"""
Manager class for the ``UserProfile`` data model.
"""
def get_subscribers_for_newsletter(self):
"""
Return a queryset of all user accounts who accept to receive the newsletter.
"""
return self.filter(accept_newsletter=True)
def get_online_users_accounts(self):
"""
Return a queryset of all user accounts currently online.
"""
offline_threshold = timezone.now() - datetime.timedelta(seconds=ONLINE_USER_TIME_WINDOW_SECONDS)
return self.filter(online_status_public=True,
last_activity_date__isnull=False,
last_activity_date__gt=offline_threshold)
def get_active_users_accounts(self):
"""
Return a queryset of all active users.
"""
return self.filter(user__is_active=True)
| Move the get_online_users and get_active_users methods to the manager class. | Move the get_online_users and get_active_users methods to the manager class.
| Python | agpl-3.0 | TamiaLab/carnetdumaker,TamiaLab/carnetdumaker,TamiaLab/carnetdumaker,TamiaLab/carnetdumaker | +
+ import datetime
from django.db import models
+ from django.utils import timezone
+
+ from .settings import ONLINE_USER_TIME_WINDOW_SECONDS
class UserProfileManager(models.Manager):
"""
Manager class for the ``UserProfile`` data model.
"""
def get_subscribers_for_newsletter(self):
"""
- Return a queryset of all users accepting to receive the newsletter.
+ Return a queryset of all user accounts who accept to receive the newsletter.
"""
return self.filter(accept_newsletter=True)
+ def get_online_users_accounts(self):
+ """
+ Return a queryset of all user accounts currently online.
+ """
+ offline_threshold = timezone.now() - datetime.timedelta(seconds=ONLINE_USER_TIME_WINDOW_SECONDS)
+ return self.filter(online_status_public=True,
+ last_activity_date__isnull=False,
+ last_activity_date__gt=offline_threshold)
+
+ def get_active_users_accounts(self):
+ """
+ Return a queryset of all active users.
+ """
+ return self.filter(user__is_active=True)
+ | Move the get_online_users and get_active_users methods to the manager class. | ## Code Before:
from django.db import models
class UserProfileManager(models.Manager):
"""
Manager class for the ``UserProfile`` data model.
"""
def get_subscribers_for_newsletter(self):
"""
Return a queryset of all users accepting to receive the newsletter.
"""
return self.filter(accept_newsletter=True)
## Instruction:
Move the get_online_users and get_active_users methods to the manager class.
## Code After:
import datetime
from django.db import models
from django.utils import timezone
from .settings import ONLINE_USER_TIME_WINDOW_SECONDS
class UserProfileManager(models.Manager):
"""
Manager class for the ``UserProfile`` data model.
"""
def get_subscribers_for_newsletter(self):
"""
Return a queryset of all user accounts who accept to receive the newsletter.
"""
return self.filter(accept_newsletter=True)
def get_online_users_accounts(self):
"""
Return a queryset of all user accounts currently online.
"""
offline_threshold = timezone.now() - datetime.timedelta(seconds=ONLINE_USER_TIME_WINDOW_SECONDS)
return self.filter(online_status_public=True,
last_activity_date__isnull=False,
last_activity_date__gt=offline_threshold)
def get_active_users_accounts(self):
"""
Return a queryset of all active users.
"""
return self.filter(user__is_active=True)
| // ... existing code ...
import datetime
from django.db import models
from django.utils import timezone
from .settings import ONLINE_USER_TIME_WINDOW_SECONDS
// ... modified code ...
def get_subscribers_for_newsletter(self):
"""
Return a queryset of all user accounts who accept to receive the newsletter.
"""
return self.filter(accept_newsletter=True)
def get_online_users_accounts(self):
"""
Return a queryset of all user accounts currently online.
"""
offline_threshold = timezone.now() - datetime.timedelta(seconds=ONLINE_USER_TIME_WINDOW_SECONDS)
return self.filter(online_status_public=True,
last_activity_date__isnull=False,
last_activity_date__gt=offline_threshold)
def get_active_users_accounts(self):
"""
Return a queryset of all active users.
"""
return self.filter(user__is_active=True)
// ... rest of the code ... |
7e2565007c926765750641b048607ed29b8aada0 | cmsplugin_zinnia/admin.py | cmsplugin_zinnia/admin.py | """Admin of Zinnia CMS Plugins"""
from django.contrib import admin
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from cms.plugin_rendering import render_placeholder
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from zinnia.models import Entry
from zinnia.admin.entry import EntryAdmin
from zinnia.settings import ENTRY_BASE_MODEL
class EntryPlaceholderAdmin(PlaceholderAdminMixin, EntryAdmin):
"""
EntryPlaceholder Admin
"""
fieldsets = (
(_('Content'), {'fields': (('title', 'status'), 'image')}),) + \
EntryAdmin.fieldsets[1:]
def save_model(self, request, entry, form, change):
"""
Fill the content field with the interpretation
of the placeholder
"""
context = RequestContext(request)
try:
content = render_placeholder(entry.content_placeholder, context)
entry.content = content or ''
except KeyError:
entry.content = ''
super(EntryPlaceholderAdmin, self).save_model(
request, entry, form, change)
if ENTRY_BASE_MODEL == 'cmsplugin_zinnia.placeholder.EntryPlaceholder':
admin.site.register(Entry, EntryPlaceholderAdmin)
| """Admin of Zinnia CMS Plugins"""
from django.contrib import admin
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from cms.plugin_rendering import render_placeholder
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from zinnia.models import Entry
from zinnia.admin.entry import EntryAdmin
from zinnia.settings import ENTRY_BASE_MODEL
class EntryPlaceholderAdmin(PlaceholderAdminMixin, EntryAdmin):
"""
EntryPlaceholder Admin
"""
fieldsets = (
(_('Content'), {'fields': (('title', 'status'), 'image')}),) + \
EntryAdmin.fieldsets[1:]
def save_model(self, request, entry, form, change):
"""
Fill the content field with the interpretation
of the placeholder
"""
context = RequestContext(request)
try:
content = render_placeholder(entry.content_placeholder, context)
entry.content = content or ''
except KeyError:
# https://github.com/django-blog-zinnia/cmsplugin-zinnia/pull/61
entry.content = ''
super(EntryPlaceholderAdmin, self).save_model(
request, entry, form, change)
if ENTRY_BASE_MODEL == 'cmsplugin_zinnia.placeholder.EntryPlaceholder':
admin.site.register(Entry, EntryPlaceholderAdmin)
| Add comment about why excepting KeyError | Add comment about why excepting KeyError
| Python | bsd-3-clause | bittner/cmsplugin-zinnia,django-blog-zinnia/cmsplugin-zinnia,django-blog-zinnia/cmsplugin-zinnia,bittner/cmsplugin-zinnia,django-blog-zinnia/cmsplugin-zinnia,bittner/cmsplugin-zinnia | """Admin of Zinnia CMS Plugins"""
from django.contrib import admin
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from cms.plugin_rendering import render_placeholder
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from zinnia.models import Entry
from zinnia.admin.entry import EntryAdmin
from zinnia.settings import ENTRY_BASE_MODEL
class EntryPlaceholderAdmin(PlaceholderAdminMixin, EntryAdmin):
"""
EntryPlaceholder Admin
"""
fieldsets = (
(_('Content'), {'fields': (('title', 'status'), 'image')}),) + \
EntryAdmin.fieldsets[1:]
def save_model(self, request, entry, form, change):
"""
Fill the content field with the interpretation
of the placeholder
"""
context = RequestContext(request)
try:
content = render_placeholder(entry.content_placeholder, context)
entry.content = content or ''
except KeyError:
+ # https://github.com/django-blog-zinnia/cmsplugin-zinnia/pull/61
entry.content = ''
super(EntryPlaceholderAdmin, self).save_model(
request, entry, form, change)
if ENTRY_BASE_MODEL == 'cmsplugin_zinnia.placeholder.EntryPlaceholder':
admin.site.register(Entry, EntryPlaceholderAdmin)
| Add comment about why excepting KeyError | ## Code Before:
"""Admin of Zinnia CMS Plugins"""
from django.contrib import admin
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from cms.plugin_rendering import render_placeholder
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from zinnia.models import Entry
from zinnia.admin.entry import EntryAdmin
from zinnia.settings import ENTRY_BASE_MODEL
class EntryPlaceholderAdmin(PlaceholderAdminMixin, EntryAdmin):
"""
EntryPlaceholder Admin
"""
fieldsets = (
(_('Content'), {'fields': (('title', 'status'), 'image')}),) + \
EntryAdmin.fieldsets[1:]
def save_model(self, request, entry, form, change):
"""
Fill the content field with the interpretation
of the placeholder
"""
context = RequestContext(request)
try:
content = render_placeholder(entry.content_placeholder, context)
entry.content = content or ''
except KeyError:
entry.content = ''
super(EntryPlaceholderAdmin, self).save_model(
request, entry, form, change)
if ENTRY_BASE_MODEL == 'cmsplugin_zinnia.placeholder.EntryPlaceholder':
admin.site.register(Entry, EntryPlaceholderAdmin)
## Instruction:
Add comment about why excepting KeyError
## Code After:
"""Admin of Zinnia CMS Plugins"""
from django.contrib import admin
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from cms.plugin_rendering import render_placeholder
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from zinnia.models import Entry
from zinnia.admin.entry import EntryAdmin
from zinnia.settings import ENTRY_BASE_MODEL
class EntryPlaceholderAdmin(PlaceholderAdminMixin, EntryAdmin):
"""
EntryPlaceholder Admin
"""
fieldsets = (
(_('Content'), {'fields': (('title', 'status'), 'image')}),) + \
EntryAdmin.fieldsets[1:]
def save_model(self, request, entry, form, change):
"""
Fill the content field with the interpretation
of the placeholder
"""
context = RequestContext(request)
try:
content = render_placeholder(entry.content_placeholder, context)
entry.content = content or ''
except KeyError:
# https://github.com/django-blog-zinnia/cmsplugin-zinnia/pull/61
entry.content = ''
super(EntryPlaceholderAdmin, self).save_model(
request, entry, form, change)
if ENTRY_BASE_MODEL == 'cmsplugin_zinnia.placeholder.EntryPlaceholder':
admin.site.register(Entry, EntryPlaceholderAdmin)
| # ... existing code ...
entry.content = content or ''
except KeyError:
# https://github.com/django-blog-zinnia/cmsplugin-zinnia/pull/61
entry.content = ''
super(EntryPlaceholderAdmin, self).save_model(
# ... rest of the code ... |
2f2f6cba331515b8d563d0e2f7869111df4227c3 | txlege84/core/management/commands/updateconveningtimes.py | txlege84/core/management/commands/updateconveningtimes.py | from django.core.management.base import BaseCommand
from core.models import ConveneTime
from legislators.models import Chamber
import requests
class Command(BaseCommand):
help = u'Scrape TLO for convening times.'
def handle(self, *args, **kwargs):
self.update_time('House')
self.update_time('Senate')
def update_time(self, chamber):
self.stdout.write(u'Updating {} convening time...'.format(chamber))
page = requests.get('http://www.capitol.state.tx.us/tlodocs'
'/SessionTime/{}SessTime.js'.format(chamber))
time_string = page.text.strip()[16:-3]
ConveneTime.objects.update_or_create(
chamber=Chamber.objects.get(name='Texas {}'.format(chamber)),
defaults={
'time_string': time_string,
}
)
self.stdout.write(u'Now set to: {}'.format(time_string))
| from django.core.management.base import BaseCommand
from django.utils import timezone
from core.models import ConveneTime
from legislators.models import Chamber
from dateutil.parser import parse
import requests
class Command(BaseCommand):
help = u'Scrape TLO for convening times.'
def handle(self, *args, **kwargs):
self.update_time('House')
self.update_time('Senate')
def update_time(self, chamber):
self.stdout.write(u'Updating {} convening time...'.format(chamber))
page = requests.get('http://www.capitol.state.tx.us/tlodocs'
'/SessionTime/{}SessTime.js'.format(chamber))
time_string = page.text.strip()[16:-3]
status, time = time_string.split(' until ')
time = timezone.make_aware(
parse(time.replace(' noon', '')), timezone.get_default_timezone())
ConveneTime.objects.update_or_create(
chamber=Chamber.objects.get(name='Texas {}'.format(chamber)),
defaults={
'time_string': time_string,
'status': status,
'time': time,
}
)
self.stdout.write(u'Now set to: {}'.format(time_string))
| Update scraper to account for new fields | Update scraper to account for new fields
| Python | mit | texastribune/txlege84,texastribune/txlege84,texastribune/txlege84,texastribune/txlege84 | from django.core.management.base import BaseCommand
+ from django.utils import timezone
from core.models import ConveneTime
from legislators.models import Chamber
+ from dateutil.parser import parse
import requests
class Command(BaseCommand):
help = u'Scrape TLO for convening times.'
def handle(self, *args, **kwargs):
self.update_time('House')
self.update_time('Senate')
def update_time(self, chamber):
self.stdout.write(u'Updating {} convening time...'.format(chamber))
page = requests.get('http://www.capitol.state.tx.us/tlodocs'
'/SessionTime/{}SessTime.js'.format(chamber))
time_string = page.text.strip()[16:-3]
+ status, time = time_string.split(' until ')
+ time = timezone.make_aware(
+ parse(time.replace(' noon', '')), timezone.get_default_timezone())
ConveneTime.objects.update_or_create(
chamber=Chamber.objects.get(name='Texas {}'.format(chamber)),
defaults={
'time_string': time_string,
+ 'status': status,
+ 'time': time,
}
)
self.stdout.write(u'Now set to: {}'.format(time_string))
| Update scraper to account for new fields | ## Code Before:
from django.core.management.base import BaseCommand
from core.models import ConveneTime
from legislators.models import Chamber
import requests
class Command(BaseCommand):
help = u'Scrape TLO for convening times.'
def handle(self, *args, **kwargs):
self.update_time('House')
self.update_time('Senate')
def update_time(self, chamber):
self.stdout.write(u'Updating {} convening time...'.format(chamber))
page = requests.get('http://www.capitol.state.tx.us/tlodocs'
'/SessionTime/{}SessTime.js'.format(chamber))
time_string = page.text.strip()[16:-3]
ConveneTime.objects.update_or_create(
chamber=Chamber.objects.get(name='Texas {}'.format(chamber)),
defaults={
'time_string': time_string,
}
)
self.stdout.write(u'Now set to: {}'.format(time_string))
## Instruction:
Update scraper to account for new fields
## Code After:
from django.core.management.base import BaseCommand
from django.utils import timezone
from core.models import ConveneTime
from legislators.models import Chamber
from dateutil.parser import parse
import requests
class Command(BaseCommand):
help = u'Scrape TLO for convening times.'
def handle(self, *args, **kwargs):
self.update_time('House')
self.update_time('Senate')
def update_time(self, chamber):
self.stdout.write(u'Updating {} convening time...'.format(chamber))
page = requests.get('http://www.capitol.state.tx.us/tlodocs'
'/SessionTime/{}SessTime.js'.format(chamber))
time_string = page.text.strip()[16:-3]
status, time = time_string.split(' until ')
time = timezone.make_aware(
parse(time.replace(' noon', '')), timezone.get_default_timezone())
ConveneTime.objects.update_or_create(
chamber=Chamber.objects.get(name='Texas {}'.format(chamber)),
defaults={
'time_string': time_string,
'status': status,
'time': time,
}
)
self.stdout.write(u'Now set to: {}'.format(time_string))
| // ... existing code ...
from django.core.management.base import BaseCommand
from django.utils import timezone
from core.models import ConveneTime
// ... modified code ...
from legislators.models import Chamber
from dateutil.parser import parse
import requests
...
time_string = page.text.strip()[16:-3]
status, time = time_string.split(' until ')
time = timezone.make_aware(
parse(time.replace(' noon', '')), timezone.get_default_timezone())
ConveneTime.objects.update_or_create(
...
defaults={
'time_string': time_string,
'status': status,
'time': time,
}
)
// ... rest of the code ... |
33922c93c66d236b238863bffd08a520456846b6 | tests/integration/modules/test_win_dns_client.py | tests/integration/modules/test_win_dns_client.py | from __future__ import absolute_import
# Import Salt Testing libs
from tests.support.case import ModuleCase
from tests.support.unit import skipIf
from tests.support.helpers import destructiveTest
# Import Salt libs
import salt.utils.platform
@skipIf(not salt.utils.platform.is_windows(), 'windows test only')
class WinDNSTest(ModuleCase):
'''
Test for salt.modules.win_dns_client
'''
@destructiveTest
def test_add_remove_dns(self):
'''
Test add and removing a dns server
'''
dns = '8.8.8.8'
interface = 'Ethernet'
# add dns server
self.assertTrue(self.run_function('win_dns_client.add_dns', [dns, interface], index=42))
srvs = self.run_function('win_dns_client.get_dns_servers', interface=interface)
self.assertIn(dns, srvs)
# remove dns server
self.assertTrue(self.run_function('win_dns_client.rm_dns', [dns], interface=interface))
srvs = self.run_function('win_dns_client.get_dns_servers', interface=interface)
self.assertNotIn(dns, srvs)
| from __future__ import absolute_import
# Import Salt Testing libs
from tests.support.case import ModuleCase
from tests.support.unit import skipIf
from tests.support.helpers import destructiveTest
# Import Salt libs
import salt.utils.platform
@skipIf(not salt.utils.platform.is_windows(), 'windows test only')
class WinDNSTest(ModuleCase):
'''
Test for salt.modules.win_dns_client
'''
@destructiveTest
def test_add_remove_dns(self):
'''
Test add and removing a dns server
'''
# Get a list of interfaces on the system
interfaces = self.run_function('network.interfaces_names')
skipIf(interfaces.count == 0, 'This test requires a network interface')
interface = interfaces[0]
dns = '8.8.8.8'
# add dns server
self.assertTrue(self.run_function('win_dns_client.add_dns', [dns, interface], index=42))
srvs = self.run_function('win_dns_client.get_dns_servers', interface=interface)
self.assertIn(dns, srvs)
# remove dns server
self.assertTrue(self.run_function('win_dns_client.rm_dns', [dns], interface=interface))
srvs = self.run_function('win_dns_client.get_dns_servers', interface=interface)
self.assertNotIn(dns, srvs)
| Fix the failing dns test on Windows | Fix the failing dns test on Windows
Gets the name of the first interface on the system. Windows network
interfaces don't have the same name across Window systems. YOu can even
go as far as naming them whatever you want. The test was failing because
the interface name was hard-coded as 'Ethernet'.
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | from __future__ import absolute_import
# Import Salt Testing libs
from tests.support.case import ModuleCase
from tests.support.unit import skipIf
from tests.support.helpers import destructiveTest
# Import Salt libs
import salt.utils.platform
@skipIf(not salt.utils.platform.is_windows(), 'windows test only')
class WinDNSTest(ModuleCase):
'''
Test for salt.modules.win_dns_client
'''
@destructiveTest
def test_add_remove_dns(self):
'''
Test add and removing a dns server
'''
+ # Get a list of interfaces on the system
+ interfaces = self.run_function('network.interfaces_names')
+ skipIf(interfaces.count == 0, 'This test requires a network interface')
+
+ interface = interfaces[0]
dns = '8.8.8.8'
- interface = 'Ethernet'
# add dns server
self.assertTrue(self.run_function('win_dns_client.add_dns', [dns, interface], index=42))
srvs = self.run_function('win_dns_client.get_dns_servers', interface=interface)
self.assertIn(dns, srvs)
# remove dns server
self.assertTrue(self.run_function('win_dns_client.rm_dns', [dns], interface=interface))
srvs = self.run_function('win_dns_client.get_dns_servers', interface=interface)
self.assertNotIn(dns, srvs)
| Fix the failing dns test on Windows | ## Code Before:
from __future__ import absolute_import
# Import Salt Testing libs
from tests.support.case import ModuleCase
from tests.support.unit import skipIf
from tests.support.helpers import destructiveTest
# Import Salt libs
import salt.utils.platform
@skipIf(not salt.utils.platform.is_windows(), 'windows test only')
class WinDNSTest(ModuleCase):
'''
Test for salt.modules.win_dns_client
'''
@destructiveTest
def test_add_remove_dns(self):
'''
Test add and removing a dns server
'''
dns = '8.8.8.8'
interface = 'Ethernet'
# add dns server
self.assertTrue(self.run_function('win_dns_client.add_dns', [dns, interface], index=42))
srvs = self.run_function('win_dns_client.get_dns_servers', interface=interface)
self.assertIn(dns, srvs)
# remove dns server
self.assertTrue(self.run_function('win_dns_client.rm_dns', [dns], interface=interface))
srvs = self.run_function('win_dns_client.get_dns_servers', interface=interface)
self.assertNotIn(dns, srvs)
## Instruction:
Fix the failing dns test on Windows
## Code After:
from __future__ import absolute_import
# Import Salt Testing libs
from tests.support.case import ModuleCase
from tests.support.unit import skipIf
from tests.support.helpers import destructiveTest
# Import Salt libs
import salt.utils.platform
@skipIf(not salt.utils.platform.is_windows(), 'windows test only')
class WinDNSTest(ModuleCase):
'''
Test for salt.modules.win_dns_client
'''
@destructiveTest
def test_add_remove_dns(self):
'''
Test add and removing a dns server
'''
# Get a list of interfaces on the system
interfaces = self.run_function('network.interfaces_names')
skipIf(interfaces.count == 0, 'This test requires a network interface')
interface = interfaces[0]
dns = '8.8.8.8'
# add dns server
self.assertTrue(self.run_function('win_dns_client.add_dns', [dns, interface], index=42))
srvs = self.run_function('win_dns_client.get_dns_servers', interface=interface)
self.assertIn(dns, srvs)
# remove dns server
self.assertTrue(self.run_function('win_dns_client.rm_dns', [dns], interface=interface))
srvs = self.run_function('win_dns_client.get_dns_servers', interface=interface)
self.assertNotIn(dns, srvs)
| # ... existing code ...
Test add and removing a dns server
'''
# Get a list of interfaces on the system
interfaces = self.run_function('network.interfaces_names')
skipIf(interfaces.count == 0, 'This test requires a network interface')
interface = interfaces[0]
dns = '8.8.8.8'
# add dns server
self.assertTrue(self.run_function('win_dns_client.add_dns', [dns, interface], index=42))
# ... rest of the code ... |
56aba3ab7a23dd8bf322a9d577fa64e686dfc9ef | serrano/middleware.py | serrano/middleware.py | class SessionMiddleware(object):
def process_request(self, request):
if getattr(request, 'user', None) and request.user.is_authenticated():
return
session = request.session
# Ensure the session is created view processing, but only if a cookie
# had been previously set. This is to prevent creating exorbitant
# numbers of sessions non-browser clients, such as bots.
if session.session_key is None:
if session.test_cookie_worked():
session.delete_test_cookie()
request.session.create()
else:
session.set_test_cookie()
| from .tokens import get_request_token
class SessionMiddleware(object):
def process_request(self, request):
if getattr(request, 'user', None) and request.user.is_authenticated():
return
# Token-based authentication is attempting to be used, bypass CSRF
# check
if get_request_token(request):
request.csrf_processing_done = True
return
session = request.session
# Ensure the session is created view processing, but only if a cookie
# had been previously set. This is to prevent creating exorbitant
# numbers of sessions for non-browser clients, such as bots.
if session.session_key is None:
if session.test_cookie_worked():
session.delete_test_cookie()
request.session.create()
else:
session.set_test_cookie()
| Update SessionMiddleware to bypass CSRF if request token is present | Update SessionMiddleware to bypass CSRF if request token is present
For non-session-based authentication, Serrano resources handle
authenticating using a token based approach. If it is present, CSRF
must be turned off to exempt the resources from the check.
| Python | bsd-2-clause | rv816/serrano_night,chop-dbhi/serrano,chop-dbhi/serrano,rv816/serrano_night | + from .tokens import get_request_token
+
+
class SessionMiddleware(object):
def process_request(self, request):
if getattr(request, 'user', None) and request.user.is_authenticated():
return
+
+ # Token-based authentication is attempting to be used, bypass CSRF
+ # check
+ if get_request_token(request):
+ request.csrf_processing_done = True
+ return
+
session = request.session
# Ensure the session is created view processing, but only if a cookie
# had been previously set. This is to prevent creating exorbitant
- # numbers of sessions non-browser clients, such as bots.
+ # numbers of sessions for non-browser clients, such as bots.
if session.session_key is None:
if session.test_cookie_worked():
session.delete_test_cookie()
request.session.create()
else:
session.set_test_cookie()
| Update SessionMiddleware to bypass CSRF if request token is present | ## Code Before:
class SessionMiddleware(object):
def process_request(self, request):
if getattr(request, 'user', None) and request.user.is_authenticated():
return
session = request.session
# Ensure the session is created view processing, but only if a cookie
# had been previously set. This is to prevent creating exorbitant
# numbers of sessions non-browser clients, such as bots.
if session.session_key is None:
if session.test_cookie_worked():
session.delete_test_cookie()
request.session.create()
else:
session.set_test_cookie()
## Instruction:
Update SessionMiddleware to bypass CSRF if request token is present
## Code After:
from .tokens import get_request_token
class SessionMiddleware(object):
def process_request(self, request):
if getattr(request, 'user', None) and request.user.is_authenticated():
return
# Token-based authentication is attempting to be used, bypass CSRF
# check
if get_request_token(request):
request.csrf_processing_done = True
return
session = request.session
# Ensure the session is created view processing, but only if a cookie
# had been previously set. This is to prevent creating exorbitant
# numbers of sessions for non-browser clients, such as bots.
if session.session_key is None:
if session.test_cookie_worked():
session.delete_test_cookie()
request.session.create()
else:
session.set_test_cookie()
| # ... existing code ...
from .tokens import get_request_token
class SessionMiddleware(object):
def process_request(self, request):
# ... modified code ...
if getattr(request, 'user', None) and request.user.is_authenticated():
return
# Token-based authentication is attempting to be used, bypass CSRF
# check
if get_request_token(request):
request.csrf_processing_done = True
return
session = request.session
# Ensure the session is created view processing, but only if a cookie
# had been previously set. This is to prevent creating exorbitant
# numbers of sessions for non-browser clients, such as bots.
if session.session_key is None:
if session.test_cookie_worked():
# ... rest of the code ... |
edd06989628e90d4fdfa98e4af84720d815322f9 | pinax/likes/migrations/0001_initial.py | pinax/likes/migrations/0001_initial.py | from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Like',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('receiver_object_id', models.PositiveIntegerField()),
('timestamp', models.DateTimeField(default=django.utils.timezone.now)),
('receiver_content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
('sender', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='liking', to=settings.AUTH_USER_MODEL)),
],
),
migrations.AlterUniqueTogether(
name='like',
unique_together=set([('sender', 'receiver_content_type', 'receiver_object_id')]),
),
]
| from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Like',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('receiver_object_id', models.PositiveIntegerField()),
('timestamp', models.DateTimeField(default=django.utils.timezone.now)),
('receiver_content_type', models.ForeignKey('contenttypes.ContentType', on_delete=django.db.models.deletion.CASCADE)),
('sender', models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=django.db.models.deletion.CASCADE, related_name='liking')),
],
),
migrations.AlterUniqueTogether(
name='like',
unique_together=set([('sender', 'receiver_content_type', 'receiver_object_id')]),
),
]
| Drop features removed in Django 2.0 | Drop features removed in Django 2.0
Field.rel and Field.remote_field.to are removed
https://docs.djangoproject.com/en/dev/releases/2.0/#features-removed-in-2-0
| Python | mit | pinax/pinax-likes | from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Like',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('receiver_object_id', models.PositiveIntegerField()),
('timestamp', models.DateTimeField(default=django.utils.timezone.now)),
- ('receiver_content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
+ ('receiver_content_type', models.ForeignKey('contenttypes.ContentType', on_delete=django.db.models.deletion.CASCADE)),
- ('sender', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='liking', to=settings.AUTH_USER_MODEL)),
+ ('sender', models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=django.db.models.deletion.CASCADE, related_name='liking')),
],
),
migrations.AlterUniqueTogether(
name='like',
unique_together=set([('sender', 'receiver_content_type', 'receiver_object_id')]),
),
]
| Drop features removed in Django 2.0 | ## Code Before:
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Like',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('receiver_object_id', models.PositiveIntegerField()),
('timestamp', models.DateTimeField(default=django.utils.timezone.now)),
('receiver_content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
('sender', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='liking', to=settings.AUTH_USER_MODEL)),
],
),
migrations.AlterUniqueTogether(
name='like',
unique_together=set([('sender', 'receiver_content_type', 'receiver_object_id')]),
),
]
## Instruction:
Drop features removed in Django 2.0
## Code After:
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Like',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('receiver_object_id', models.PositiveIntegerField()),
('timestamp', models.DateTimeField(default=django.utils.timezone.now)),
('receiver_content_type', models.ForeignKey('contenttypes.ContentType', on_delete=django.db.models.deletion.CASCADE)),
('sender', models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=django.db.models.deletion.CASCADE, related_name='liking')),
],
),
migrations.AlterUniqueTogether(
name='like',
unique_together=set([('sender', 'receiver_content_type', 'receiver_object_id')]),
),
]
| // ... existing code ...
('receiver_object_id', models.PositiveIntegerField()),
('timestamp', models.DateTimeField(default=django.utils.timezone.now)),
('receiver_content_type', models.ForeignKey('contenttypes.ContentType', on_delete=django.db.models.deletion.CASCADE)),
('sender', models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=django.db.models.deletion.CASCADE, related_name='liking')),
],
),
// ... rest of the code ... |
9de0a05d28c83742224c0e708e80b8add198a8a8 | froide/comments/apps.py | froide/comments/apps.py | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class CommentConfig(AppConfig):
name = 'froide.comments'
verbose_name = _('Comments')
def ready(self):
from froide.account import account_canceled
account_canceled.connect(cancel_user)
def cancel_user(sender, user=None, **kwargs):
from .models import FroideComment
if user is None:
return
FroideComment.objects.filter(user=user).update(
user_name='',
user_email='',
user_url=''
)
| import json
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class CommentConfig(AppConfig):
name = 'froide.comments'
verbose_name = _('Comments')
def ready(self):
from froide.account import account_canceled
from froide.account.export import registry
account_canceled.connect(cancel_user)
registry.register(export_user_data)
def cancel_user(sender, user=None, **kwargs):
from .models import FroideComment
if user is None:
return
FroideComment.objects.filter(user=user).update(
user_name='',
user_email='',
user_url=''
)
def export_user_data(user):
from .models import FroideComment
comments = FroideComment.objects.filter(user=user)
if not comments:
return
yield ('comments.json', json.dumps([
{
'submit_date': (
c.submit_date.isoformat() if c.submit_date else None
),
'comment': c.comment,
'is_public': c.is_public,
'is_removed': c.is_removed,
'url': c.get_absolute_url(),
}
for c in comments]).encode('utf-8')
)
| Add user data export for comments | Add user data export for comments | Python | mit | stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide | + import json
+
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class CommentConfig(AppConfig):
name = 'froide.comments'
verbose_name = _('Comments')
def ready(self):
from froide.account import account_canceled
+ from froide.account.export import registry
account_canceled.connect(cancel_user)
+ registry.register(export_user_data)
def cancel_user(sender, user=None, **kwargs):
from .models import FroideComment
if user is None:
return
FroideComment.objects.filter(user=user).update(
user_name='',
user_email='',
user_url=''
)
+
+ def export_user_data(user):
+ from .models import FroideComment
+
+ comments = FroideComment.objects.filter(user=user)
+ if not comments:
+ return
+ yield ('comments.json', json.dumps([
+ {
+ 'submit_date': (
+ c.submit_date.isoformat() if c.submit_date else None
+ ),
+ 'comment': c.comment,
+ 'is_public': c.is_public,
+ 'is_removed': c.is_removed,
+ 'url': c.get_absolute_url(),
+ }
+ for c in comments]).encode('utf-8')
+ )
+ | Add user data export for comments | ## Code Before:
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class CommentConfig(AppConfig):
name = 'froide.comments'
verbose_name = _('Comments')
def ready(self):
from froide.account import account_canceled
account_canceled.connect(cancel_user)
def cancel_user(sender, user=None, **kwargs):
from .models import FroideComment
if user is None:
return
FroideComment.objects.filter(user=user).update(
user_name='',
user_email='',
user_url=''
)
## Instruction:
Add user data export for comments
## Code After:
import json
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class CommentConfig(AppConfig):
name = 'froide.comments'
verbose_name = _('Comments')
def ready(self):
from froide.account import account_canceled
from froide.account.export import registry
account_canceled.connect(cancel_user)
registry.register(export_user_data)
def cancel_user(sender, user=None, **kwargs):
from .models import FroideComment
if user is None:
return
FroideComment.objects.filter(user=user).update(
user_name='',
user_email='',
user_url=''
)
def export_user_data(user):
from .models import FroideComment
comments = FroideComment.objects.filter(user=user)
if not comments:
return
yield ('comments.json', json.dumps([
{
'submit_date': (
c.submit_date.isoformat() if c.submit_date else None
),
'comment': c.comment,
'is_public': c.is_public,
'is_removed': c.is_removed,
'url': c.get_absolute_url(),
}
for c in comments]).encode('utf-8')
)
| // ... existing code ...
import json
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
// ... modified code ...
def ready(self):
from froide.account import account_canceled
from froide.account.export import registry
account_canceled.connect(cancel_user)
registry.register(export_user_data)
...
user_url=''
)
def export_user_data(user):
from .models import FroideComment
comments = FroideComment.objects.filter(user=user)
if not comments:
return
yield ('comments.json', json.dumps([
{
'submit_date': (
c.submit_date.isoformat() if c.submit_date else None
),
'comment': c.comment,
'is_public': c.is_public,
'is_removed': c.is_removed,
'url': c.get_absolute_url(),
}
for c in comments]).encode('utf-8')
)
// ... rest of the code ... |
abadd7880d690cebfea865f8afd81c6fc585884c | scripts/bedpe2bed.py | scripts/bedpe2bed.py | import sys
import os
import argparse
import fileinput
import subprocess
parser = argparse.ArgumentParser(description = "Convert BEDPE into a BED file of fragments.", formatter_class = argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--maxFragmentLength", help = "Maximum fragment length between two pairs of reads.", default = "1000")
args = parser.parse_args()
for line in fileinput.input("-"):
line = line.rstrip()
fields = line.split("\t")
#Check for chimereas
if fields[0] == fields[3]:
if fields[0] != ".":
fragment_length = int(fields[5]) - int(fields[1])
if fragment_length < int(args.maxFragmentLength):
out = "\t".join([fields[0], fields[1], fields[5], fields[6], str(fragment_length)])
print(out) | import sys
import os
import argparse
import fileinput
import subprocess
parser = argparse.ArgumentParser(description = "Convert BEDPE into a BED file of fragments.", formatter_class = argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--maxFragmentLength", help = "Maximum fragment length between two pairs of reads.", default = "1000")
parser.add_argument("--minFragmentLength", help = "Minimum fragment length between two pairs of reads.", default = "30")
args = parser.parse_args()
for line in fileinput.input("-"):
line = line.rstrip()
fields = line.split("\t")
#Check for chimereas
if fields[0] == fields[3]:
if fields[0] != ".":
fragment_length = int(fields[5]) - int(fields[1])
if (fragment_length < int(args.maxFragmentLength)) and (fragment_length > int(args.minFragmentLength)):
out = "\t".join([fields[0], fields[1], fields[5], fields[6], str(fragment_length)])
print(out) | Add minimum fragment length filtering. | Add minimum fragment length filtering.
| Python | apache-2.0 | kauralasoo/Blood_ATAC,kauralasoo/Blood_ATAC,kauralasoo/Blood_ATAC | import sys
import os
import argparse
import fileinput
import subprocess
parser = argparse.ArgumentParser(description = "Convert BEDPE into a BED file of fragments.", formatter_class = argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--maxFragmentLength", help = "Maximum fragment length between two pairs of reads.", default = "1000")
+ parser.add_argument("--minFragmentLength", help = "Minimum fragment length between two pairs of reads.", default = "30")
args = parser.parse_args()
for line in fileinput.input("-"):
line = line.rstrip()
fields = line.split("\t")
#Check for chimereas
if fields[0] == fields[3]:
if fields[0] != ".":
fragment_length = int(fields[5]) - int(fields[1])
- if fragment_length < int(args.maxFragmentLength):
+ if (fragment_length < int(args.maxFragmentLength)) and (fragment_length > int(args.minFragmentLength)):
out = "\t".join([fields[0], fields[1], fields[5], fields[6], str(fragment_length)])
print(out) | Add minimum fragment length filtering. | ## Code Before:
import sys
import os
import argparse
import fileinput
import subprocess
parser = argparse.ArgumentParser(description = "Convert BEDPE into a BED file of fragments.", formatter_class = argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--maxFragmentLength", help = "Maximum fragment length between two pairs of reads.", default = "1000")
args = parser.parse_args()
for line in fileinput.input("-"):
line = line.rstrip()
fields = line.split("\t")
#Check for chimereas
if fields[0] == fields[3]:
if fields[0] != ".":
fragment_length = int(fields[5]) - int(fields[1])
if fragment_length < int(args.maxFragmentLength):
out = "\t".join([fields[0], fields[1], fields[5], fields[6], str(fragment_length)])
print(out)
## Instruction:
Add minimum fragment length filtering.
## Code After:
import sys
import os
import argparse
import fileinput
import subprocess
parser = argparse.ArgumentParser(description = "Convert BEDPE into a BED file of fragments.", formatter_class = argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--maxFragmentLength", help = "Maximum fragment length between two pairs of reads.", default = "1000")
parser.add_argument("--minFragmentLength", help = "Minimum fragment length between two pairs of reads.", default = "30")
args = parser.parse_args()
for line in fileinput.input("-"):
line = line.rstrip()
fields = line.split("\t")
#Check for chimereas
if fields[0] == fields[3]:
if fields[0] != ".":
fragment_length = int(fields[5]) - int(fields[1])
if (fragment_length < int(args.maxFragmentLength)) and (fragment_length > int(args.minFragmentLength)):
out = "\t".join([fields[0], fields[1], fields[5], fields[6], str(fragment_length)])
print(out) | # ... existing code ...
parser = argparse.ArgumentParser(description = "Convert BEDPE into a BED file of fragments.", formatter_class = argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--maxFragmentLength", help = "Maximum fragment length between two pairs of reads.", default = "1000")
parser.add_argument("--minFragmentLength", help = "Minimum fragment length between two pairs of reads.", default = "30")
args = parser.parse_args()
# ... modified code ...
if fields[0] != ".":
fragment_length = int(fields[5]) - int(fields[1])
if (fragment_length < int(args.maxFragmentLength)) and (fragment_length > int(args.minFragmentLength)):
out = "\t".join([fields[0], fields[1], fields[5], fields[6], str(fragment_length)])
print(out)
# ... rest of the code ... |
3838e44a397fdb4b605ead875b7c6ebc5787644d | jal_stats/stats/serializers.py | jal_stats/stats/serializers.py | from rest_framework import serializers
from .models import Activity, Datapoint
class ActivitySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Activity
fields = ('user', 'full_description', 'units', 'url')
class DatapointSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Datapoint
fields = ('user', 'activity', 'reps', 'timestamp', 'url')
| from rest_framework import serializers
from .models import Activity, Datapoint
class ActivitySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Activity
fields = ('id', 'user', 'full_description', 'units', 'url')
class DatapointSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Datapoint
fields = ('id', 'user', 'activity', 'reps', 'timestamp', 'url')
| Add 'id' to both Serializers | Add 'id' to both Serializers
| Python | mit | jal-stats/django | from rest_framework import serializers
from .models import Activity, Datapoint
class ActivitySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Activity
- fields = ('user', 'full_description', 'units', 'url')
+ fields = ('id', 'user', 'full_description', 'units', 'url')
class DatapointSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Datapoint
- fields = ('user', 'activity', 'reps', 'timestamp', 'url')
+ fields = ('id', 'user', 'activity', 'reps', 'timestamp', 'url')
| Add 'id' to both Serializers | ## Code Before:
from rest_framework import serializers
from .models import Activity, Datapoint
class ActivitySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Activity
fields = ('user', 'full_description', 'units', 'url')
class DatapointSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Datapoint
fields = ('user', 'activity', 'reps', 'timestamp', 'url')
## Instruction:
Add 'id' to both Serializers
## Code After:
from rest_framework import serializers
from .models import Activity, Datapoint
class ActivitySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Activity
fields = ('id', 'user', 'full_description', 'units', 'url')
class DatapointSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Datapoint
fields = ('id', 'user', 'activity', 'reps', 'timestamp', 'url')
| # ... existing code ...
class Meta:
model = Activity
fields = ('id', 'user', 'full_description', 'units', 'url')
# ... modified code ...
class Meta:
model = Datapoint
fields = ('id', 'user', 'activity', 'reps', 'timestamp', 'url')
# ... rest of the code ... |
2e941cf1f6208b9ac2f6039681c24502b324ab5f | planner/models.py | planner/models.py | import datetime
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class Milestone(models.Model):
date = models.DateTimeField()
@python_2_unicode_compatible
class School(models.Model):
name = models.TextField()
slug = models.SlugField(max_length=256, unique=True)
url = models.URLField(unique=True)
milestones_url = models.URLField()
def __str__(self):
return self.name
class Semester(models.Model):
active = models.BooleanField(default=True)
date = models.DateField()
# XXX: This is locked in for the default value of the initial migration.
# I'm not sure what needs to be done to let me safely delete this and
# have migrations continue to work.
def current_year():
today = datetime.date.today()
return today.year
@python_2_unicode_compatible
class Student(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='students')
first_name = models.TextField()
last_name = models.TextField()
# XXX: Remove null constraint after migration.
matriculation_semester = models.ForeignKey(
Semester, null=True, on_delete=models.PROTECT)
def __str__(self):
return '{} {}'.format(self.first_name, self.last_name)
| import datetime
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class Milestone(models.Model):
date = models.DateTimeField()
@python_2_unicode_compatible
class School(models.Model):
name = models.TextField()
slug = models.SlugField(max_length=256, unique=True)
url = models.URLField(unique=True)
milestones_url = models.URLField()
def __str__(self):
return self.name
@python_2_unicode_compatible
class Semester(models.Model):
active = models.BooleanField(default=True)
date = models.DateField()
def __str__(self):
return str(self.date)
# XXX: This is locked in for the default value of the initial migration.
# I'm not sure what needs to be done to let me safely delete this and
# have migrations continue to work.
def current_year():
today = datetime.date.today()
return today.year
@python_2_unicode_compatible
class Student(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='students')
first_name = models.TextField()
last_name = models.TextField()
# XXX: Remove null constraint after migration.
matriculation_semester = models.ForeignKey(
Semester, null=True, on_delete=models.PROTECT)
def __str__(self):
return '{} {}'.format(self.first_name, self.last_name)
| Add Semester str method for admin interface. | Add Semester str method for admin interface.
Fixes #149
| Python | bsd-2-clause | mblayman/lcp,mblayman/lcp,mblayman/lcp | import datetime
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class Milestone(models.Model):
date = models.DateTimeField()
@python_2_unicode_compatible
class School(models.Model):
name = models.TextField()
slug = models.SlugField(max_length=256, unique=True)
url = models.URLField(unique=True)
milestones_url = models.URLField()
def __str__(self):
return self.name
+ @python_2_unicode_compatible
class Semester(models.Model):
active = models.BooleanField(default=True)
date = models.DateField()
+
+ def __str__(self):
+ return str(self.date)
# XXX: This is locked in for the default value of the initial migration.
# I'm not sure what needs to be done to let me safely delete this and
# have migrations continue to work.
def current_year():
today = datetime.date.today()
return today.year
@python_2_unicode_compatible
class Student(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='students')
first_name = models.TextField()
last_name = models.TextField()
# XXX: Remove null constraint after migration.
matriculation_semester = models.ForeignKey(
Semester, null=True, on_delete=models.PROTECT)
def __str__(self):
return '{} {}'.format(self.first_name, self.last_name)
| Add Semester str method for admin interface. | ## Code Before:
import datetime
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class Milestone(models.Model):
date = models.DateTimeField()
@python_2_unicode_compatible
class School(models.Model):
name = models.TextField()
slug = models.SlugField(max_length=256, unique=True)
url = models.URLField(unique=True)
milestones_url = models.URLField()
def __str__(self):
return self.name
class Semester(models.Model):
active = models.BooleanField(default=True)
date = models.DateField()
# XXX: This is locked in for the default value of the initial migration.
# I'm not sure what needs to be done to let me safely delete this and
# have migrations continue to work.
def current_year():
today = datetime.date.today()
return today.year
@python_2_unicode_compatible
class Student(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='students')
first_name = models.TextField()
last_name = models.TextField()
# XXX: Remove null constraint after migration.
matriculation_semester = models.ForeignKey(
Semester, null=True, on_delete=models.PROTECT)
def __str__(self):
return '{} {}'.format(self.first_name, self.last_name)
## Instruction:
Add Semester str method for admin interface.
## Code After:
import datetime
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class Milestone(models.Model):
date = models.DateTimeField()
@python_2_unicode_compatible
class School(models.Model):
name = models.TextField()
slug = models.SlugField(max_length=256, unique=True)
url = models.URLField(unique=True)
milestones_url = models.URLField()
def __str__(self):
return self.name
@python_2_unicode_compatible
class Semester(models.Model):
active = models.BooleanField(default=True)
date = models.DateField()
def __str__(self):
return str(self.date)
# XXX: This is locked in for the default value of the initial migration.
# I'm not sure what needs to be done to let me safely delete this and
# have migrations continue to work.
def current_year():
today = datetime.date.today()
return today.year
@python_2_unicode_compatible
class Student(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='students')
first_name = models.TextField()
last_name = models.TextField()
# XXX: Remove null constraint after migration.
matriculation_semester = models.ForeignKey(
Semester, null=True, on_delete=models.PROTECT)
def __str__(self):
return '{} {}'.format(self.first_name, self.last_name)
| # ... existing code ...
@python_2_unicode_compatible
class Semester(models.Model):
active = models.BooleanField(default=True)
date = models.DateField()
def __str__(self):
return str(self.date)
# ... rest of the code ... |
2833e2296cff6a52ab75c2c88563e81372902035 | src/heartbeat/checkers/build.py | src/heartbeat/checkers/build.py | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from pkg_resources import get_distribution, DistributionNotFound
def check(request):
package_name = settings.HEARTBEAT.get('package_name')
if not package_name:
raise ImproperlyConfigured(
'Missing package_name key from heartbeat configuration')
try:
distro = get_distribution(package_name)
except DistributionNotFound:
return dict(error='no distribution found for {}'.format(package_name))
return dict(name=distro.project_name, version=distro.version)
| from pkg_resources import Requirement, WorkingSet
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
def check(request):
package_name = settings.HEARTBEAT.get('package_name')
if not package_name:
raise ImproperlyConfigured(
'Missing package_name key from heartbeat configuration')
sys_path_distros = WorkingSet()
package_req = Requirement.parse(package_name)
distro = sys_path_distros.find(package_req)
if not distro:
return dict(error='no distribution found for {}'.format(package_name))
return dict(name=distro.project_name, version=distro.version)
| Package name should be searched through the same distros list we use for listing installed packages. get_distribution is using the global working_set which may not contain the requested package if the initialization(pkg_resources import time) happened before the project name to appear in the sys.path. | Package name should be searched through the same distros list
we use for listing installed packages. get_distribution is using
the global working_set which may not contain the requested package
if the initialization(pkg_resources import time) happened before
the project name to appear in the sys.path.
| Python | mit | pbs/django-heartbeat | + from pkg_resources import Requirement, WorkingSet
+
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
- from pkg_resources import get_distribution, DistributionNotFound
def check(request):
package_name = settings.HEARTBEAT.get('package_name')
if not package_name:
raise ImproperlyConfigured(
'Missing package_name key from heartbeat configuration')
- try:
- distro = get_distribution(package_name)
- except DistributionNotFound:
+ sys_path_distros = WorkingSet()
+ package_req = Requirement.parse(package_name)
+
+ distro = sys_path_distros.find(package_req)
+ if not distro:
return dict(error='no distribution found for {}'.format(package_name))
return dict(name=distro.project_name, version=distro.version)
| Package name should be searched through the same distros list we use for listing installed packages. get_distribution is using the global working_set which may not contain the requested package if the initialization(pkg_resources import time) happened before the project name to appear in the sys.path. | ## Code Before:
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from pkg_resources import get_distribution, DistributionNotFound
def check(request):
package_name = settings.HEARTBEAT.get('package_name')
if not package_name:
raise ImproperlyConfigured(
'Missing package_name key from heartbeat configuration')
try:
distro = get_distribution(package_name)
except DistributionNotFound:
return dict(error='no distribution found for {}'.format(package_name))
return dict(name=distro.project_name, version=distro.version)
## Instruction:
Package name should be searched through the same distros list we use for listing installed packages. get_distribution is using the global working_set which may not contain the requested package if the initialization(pkg_resources import time) happened before the project name to appear in the sys.path.
## Code After:
from pkg_resources import Requirement, WorkingSet
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
def check(request):
package_name = settings.HEARTBEAT.get('package_name')
if not package_name:
raise ImproperlyConfigured(
'Missing package_name key from heartbeat configuration')
sys_path_distros = WorkingSet()
package_req = Requirement.parse(package_name)
distro = sys_path_distros.find(package_req)
if not distro:
return dict(error='no distribution found for {}'.format(package_name))
return dict(name=distro.project_name, version=distro.version)
| ...
from pkg_resources import Requirement, WorkingSet
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
...
'Missing package_name key from heartbeat configuration')
sys_path_distros = WorkingSet()
package_req = Requirement.parse(package_name)
distro = sys_path_distros.find(package_req)
if not distro:
return dict(error='no distribution found for {}'.format(package_name))
... |
fff0087f82c3f79d5e60e32071a4e89478d8b85e | tests/test_element.py | tests/test_element.py | import pkg_resources
pkg_resources.require('cothread')
import cothread
import rml.element
def test_create_element():
e = rml.element.Element('BPM', 6.0)
assert e.get_type() == 'BPM'
assert e.get_length() == 6.0
def test_add_element_to_family():
e = rml.element.Element('dummy', 0.0)
e.add_to_family('fam')
assert 'fam' in e.get_families()
def test_get_pv_value():
PV = 'SR22C-DI-EBPM-04:SA:X'
e = rml.element.Element('dummy', 0.0, pv=PV)
result = e.get_pv('x')
assert isinstance(result, float)
| import pkg_resources
pkg_resources.require('cothread')
import cothread
import rml
import rml.element
def test_create_element():
e = rml.element.Element('BPM', 6.0)
assert e.get_type() == 'BPM'
assert e.get_length() == 6.0
def test_add_element_to_family():
e = rml.element.Element('dummy', 0.0)
e.add_to_family('fam')
assert 'fam' in e.get_families()
def test_get_pv_value():
PV = 'SR22C-DI-EBPM-04:SA:X'
e = rml.element.Element('dummy', 0.0)
e.set_pv('x', PV)
result = e.get_pv('x')
assert isinstance(result, float)
with pytest.raises(rml.ConfigException):
e.get_pv('y')
| Make pvs in Element behave more realistically. | Make pvs in Element behave more realistically.
| Python | apache-2.0 | razvanvasile/RML,willrogers/pml,willrogers/pml | import pkg_resources
pkg_resources.require('cothread')
import cothread
+ import rml
import rml.element
def test_create_element():
e = rml.element.Element('BPM', 6.0)
assert e.get_type() == 'BPM'
assert e.get_length() == 6.0
def test_add_element_to_family():
e = rml.element.Element('dummy', 0.0)
e.add_to_family('fam')
assert 'fam' in e.get_families()
def test_get_pv_value():
PV = 'SR22C-DI-EBPM-04:SA:X'
- e = rml.element.Element('dummy', 0.0, pv=PV)
+ e = rml.element.Element('dummy', 0.0)
+ e.set_pv('x', PV)
result = e.get_pv('x')
assert isinstance(result, float)
+ with pytest.raises(rml.ConfigException):
+ e.get_pv('y')
| Make pvs in Element behave more realistically. | ## Code Before:
import pkg_resources
pkg_resources.require('cothread')
import cothread
import rml.element
def test_create_element():
e = rml.element.Element('BPM', 6.0)
assert e.get_type() == 'BPM'
assert e.get_length() == 6.0
def test_add_element_to_family():
e = rml.element.Element('dummy', 0.0)
e.add_to_family('fam')
assert 'fam' in e.get_families()
def test_get_pv_value():
PV = 'SR22C-DI-EBPM-04:SA:X'
e = rml.element.Element('dummy', 0.0, pv=PV)
result = e.get_pv('x')
assert isinstance(result, float)
## Instruction:
Make pvs in Element behave more realistically.
## Code After:
import pkg_resources
pkg_resources.require('cothread')
import cothread
import rml
import rml.element
def test_create_element():
e = rml.element.Element('BPM', 6.0)
assert e.get_type() == 'BPM'
assert e.get_length() == 6.0
def test_add_element_to_family():
e = rml.element.Element('dummy', 0.0)
e.add_to_family('fam')
assert 'fam' in e.get_families()
def test_get_pv_value():
PV = 'SR22C-DI-EBPM-04:SA:X'
e = rml.element.Element('dummy', 0.0)
e.set_pv('x', PV)
result = e.get_pv('x')
assert isinstance(result, float)
with pytest.raises(rml.ConfigException):
e.get_pv('y')
| # ... existing code ...
pkg_resources.require('cothread')
import cothread
import rml
import rml.element
# ... modified code ...
def test_get_pv_value():
PV = 'SR22C-DI-EBPM-04:SA:X'
e = rml.element.Element('dummy', 0.0)
e.set_pv('x', PV)
result = e.get_pv('x')
assert isinstance(result, float)
with pytest.raises(rml.ConfigException):
e.get_pv('y')
# ... rest of the code ... |
7b5ffcef89fe12576885bf4d29651829a5ed6249 | gala/__init__.py | gala/__init__.py |
__author__ = 'Juan Nunez-Iglesias <[email protected]>, '+\
'Ryan Kennedy <[email protected]>'
del sys, logging
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
'stack_np', 'app_logger', 'option_manager', 'features', 'filter']
__version__ = '0.4dev'
|
__author__ = 'Juan Nunez-Iglesias <[email protected]>, '+\
'Ryan Kennedy <[email protected]>'
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
'stack_np', 'app_logger', 'option_manager', 'features', 'filter']
__version__ = '0.4dev'
| Remove no longer valid del sys statement | Remove no longer valid del sys statement
| Python | bsd-3-clause | jni/gala,janelia-flyem/gala |
__author__ = 'Juan Nunez-Iglesias <[email protected]>, '+\
'Ryan Kennedy <[email protected]>'
- del sys, logging
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
'stack_np', 'app_logger', 'option_manager', 'features', 'filter']
__version__ = '0.4dev'
| Remove no longer valid del sys statement | ## Code Before:
__author__ = 'Juan Nunez-Iglesias <[email protected]>, '+\
'Ryan Kennedy <[email protected]>'
del sys, logging
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
'stack_np', 'app_logger', 'option_manager', 'features', 'filter']
__version__ = '0.4dev'
## Instruction:
Remove no longer valid del sys statement
## Code After:
__author__ = 'Juan Nunez-Iglesias <[email protected]>, '+\
'Ryan Kennedy <[email protected]>'
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
'stack_np', 'app_logger', 'option_manager', 'features', 'filter']
__version__ = '0.4dev'
| ...
__author__ = 'Juan Nunez-Iglesias <[email protected]>, '+\
'Ryan Kennedy <[email protected]>'
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
... |
def9d7037a3c629f63e1a0d8c1721501abc110cd | linguee_api/downloaders/httpx_downloader.py | linguee_api/downloaders/httpx_downloader.py | import httpx
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
class HTTPXDownloader(IDownloader):
"""
Real downloader.
Sends request to linguee.com to read the page.
"""
async def download(self, url: str) -> str:
async with httpx.AsyncClient() as client:
try:
response = await client.get(url)
except httpx.ConnectError as e:
raise DownloaderError(str(e)) from e
if response.status_code != 200:
raise DownloaderError(
f"The Linguee server returned {response.status_code}"
)
return response.text
| import httpx
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
ERROR_503 = (
"The Linguee server returned 503. The API proxy was temporarily blocked by "
"Linguee. For more details, see https://github.com/imankulov/linguee-api#"
"the-api-server-returns-the-linguee-server-returned-503"
)
class HTTPXDownloader(IDownloader):
"""
Real downloader.
Sends request to linguee.com to read the page.
"""
async def download(self, url: str) -> str:
async with httpx.AsyncClient() as client:
try:
response = await client.get(url)
except httpx.ConnectError as e:
raise DownloaderError(str(e)) from e
if response.status_code == 503:
raise DownloaderError(ERROR_503)
if response.status_code != 200:
raise DownloaderError(
f"The Linguee server returned {response.status_code}"
)
return response.text
| Update the 503 error message. | Update the 503 error message.
| Python | mit | imankulov/linguee-api | import httpx
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
+
+ ERROR_503 = (
+ "The Linguee server returned 503. The API proxy was temporarily blocked by "
+ "Linguee. For more details, see https://github.com/imankulov/linguee-api#"
+ "the-api-server-returns-the-linguee-server-returned-503"
+ )
class HTTPXDownloader(IDownloader):
"""
Real downloader.
Sends request to linguee.com to read the page.
"""
async def download(self, url: str) -> str:
async with httpx.AsyncClient() as client:
try:
response = await client.get(url)
except httpx.ConnectError as e:
raise DownloaderError(str(e)) from e
+
+ if response.status_code == 503:
+ raise DownloaderError(ERROR_503)
+
if response.status_code != 200:
raise DownloaderError(
f"The Linguee server returned {response.status_code}"
)
return response.text
| Update the 503 error message. | ## Code Before:
import httpx
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
class HTTPXDownloader(IDownloader):
"""
Real downloader.
Sends request to linguee.com to read the page.
"""
async def download(self, url: str) -> str:
async with httpx.AsyncClient() as client:
try:
response = await client.get(url)
except httpx.ConnectError as e:
raise DownloaderError(str(e)) from e
if response.status_code != 200:
raise DownloaderError(
f"The Linguee server returned {response.status_code}"
)
return response.text
## Instruction:
Update the 503 error message.
## Code After:
import httpx
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
ERROR_503 = (
"The Linguee server returned 503. The API proxy was temporarily blocked by "
"Linguee. For more details, see https://github.com/imankulov/linguee-api#"
"the-api-server-returns-the-linguee-server-returned-503"
)
class HTTPXDownloader(IDownloader):
"""
Real downloader.
Sends request to linguee.com to read the page.
"""
async def download(self, url: str) -> str:
async with httpx.AsyncClient() as client:
try:
response = await client.get(url)
except httpx.ConnectError as e:
raise DownloaderError(str(e)) from e
if response.status_code == 503:
raise DownloaderError(ERROR_503)
if response.status_code != 200:
raise DownloaderError(
f"The Linguee server returned {response.status_code}"
)
return response.text
| ...
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
ERROR_503 = (
"The Linguee server returned 503. The API proxy was temporarily blocked by "
"Linguee. For more details, see https://github.com/imankulov/linguee-api#"
"the-api-server-returns-the-linguee-server-returned-503"
)
...
except httpx.ConnectError as e:
raise DownloaderError(str(e)) from e
if response.status_code == 503:
raise DownloaderError(ERROR_503)
if response.status_code != 200:
raise DownloaderError(
... |
27e137ef5f3b6c4f6c8679edc6412b2c237b8fb4 | plasmapy/physics/tests/test_parameters_cython.py | plasmapy/physics/tests/test_parameters_cython.py | """Tests for functions that calculate plasma parameters using cython."""
import numpy as np
import pytest
from astropy import units as u
from warnings import simplefilter
from ...utils.exceptions import RelativityWarning, RelativityError
from ...utils.exceptions import PhysicsError
from ...constants import c, m_p, m_e, e, mu0
from ..parameters_cython import (thermal_speed,
)
def test_thermal_speed():
r"""Test for cythonized version of thermal_speed()."""
trueVal = 593083.619464999
T = 11604
methodVal = thermal_speed(T, particle="e", method="most_probable")
testTrue = np.isclose(methodVal,
trueVal,
rtol=0.0,
atol=1e-16)
exceptStr = f'Thermal speed value is {methodVal}, should be {trueVal}.'
assert testTrue, exceptStr | """Tests for functions that calculate plasma parameters using cython."""
import numpy as np
import pytest
from astropy import units as u
from warnings import simplefilter
from plasmapy.utils.exceptions import RelativityWarning, RelativityError
from plasmapy.utils.exceptions import PhysicsError
from plasmapy.constants import c, m_p, m_e, e, mu0
from plasmapy.physics.parameters_cython import (thermal_speed,
)
def test_thermal_speed():
r"""Test for cythonized version of thermal_speed()."""
trueVal = 593083.619464999
T = 11604
methodVal = thermal_speed(T, particle="e", method="most_probable")
testTrue = np.isclose(methodVal,
trueVal,
rtol=0.0,
atol=1e-16)
exceptStr = f'Thermal speed value is {methodVal}, should be {trueVal}.'
assert testTrue, exceptStr | Update tests for cython parameters | Update tests for cython parameters
| Python | bsd-3-clause | StanczakDominik/PlasmaPy | """Tests for functions that calculate plasma parameters using cython."""
import numpy as np
import pytest
from astropy import units as u
from warnings import simplefilter
- from ...utils.exceptions import RelativityWarning, RelativityError
+ from plasmapy.utils.exceptions import RelativityWarning, RelativityError
- from ...utils.exceptions import PhysicsError
+ from plasmapy.utils.exceptions import PhysicsError
- from ...constants import c, m_p, m_e, e, mu0
+ from plasmapy.constants import c, m_p, m_e, e, mu0
- from ..parameters_cython import (thermal_speed,
+ from plasmapy.physics.parameters_cython import (thermal_speed,
)
-
def test_thermal_speed():
r"""Test for cythonized version of thermal_speed()."""
trueVal = 593083.619464999
T = 11604
methodVal = thermal_speed(T, particle="e", method="most_probable")
testTrue = np.isclose(methodVal,
trueVal,
rtol=0.0,
atol=1e-16)
exceptStr = f'Thermal speed value is {methodVal}, should be {trueVal}.'
assert testTrue, exceptStr | Update tests for cython parameters | ## Code Before:
"""Tests for functions that calculate plasma parameters using cython."""
import numpy as np
import pytest
from astropy import units as u
from warnings import simplefilter
from ...utils.exceptions import RelativityWarning, RelativityError
from ...utils.exceptions import PhysicsError
from ...constants import c, m_p, m_e, e, mu0
from ..parameters_cython import (thermal_speed,
)
def test_thermal_speed():
r"""Test for cythonized version of thermal_speed()."""
trueVal = 593083.619464999
T = 11604
methodVal = thermal_speed(T, particle="e", method="most_probable")
testTrue = np.isclose(methodVal,
trueVal,
rtol=0.0,
atol=1e-16)
exceptStr = f'Thermal speed value is {methodVal}, should be {trueVal}.'
assert testTrue, exceptStr
## Instruction:
Update tests for cython parameters
## Code After:
"""Tests for functions that calculate plasma parameters using cython."""
import numpy as np
import pytest
from astropy import units as u
from warnings import simplefilter
from plasmapy.utils.exceptions import RelativityWarning, RelativityError
from plasmapy.utils.exceptions import PhysicsError
from plasmapy.constants import c, m_p, m_e, e, mu0
from plasmapy.physics.parameters_cython import (thermal_speed,
)
def test_thermal_speed():
r"""Test for cythonized version of thermal_speed()."""
trueVal = 593083.619464999
T = 11604
methodVal = thermal_speed(T, particle="e", method="most_probable")
testTrue = np.isclose(methodVal,
trueVal,
rtol=0.0,
atol=1e-16)
exceptStr = f'Thermal speed value is {methodVal}, should be {trueVal}.'
assert testTrue, exceptStr | // ... existing code ...
from warnings import simplefilter
from plasmapy.utils.exceptions import RelativityWarning, RelativityError
from plasmapy.utils.exceptions import PhysicsError
from plasmapy.constants import c, m_p, m_e, e, mu0
from plasmapy.physics.parameters_cython import (thermal_speed,
)
def test_thermal_speed():
r"""Test for cythonized version of thermal_speed()."""
// ... rest of the code ... |
936234e5de71267faec3b081e96d937098ff6d51 | portfolio/tests/__init__.py | portfolio/tests/__init__.py | from .models import *
| from portfolio.tests.models import *
| Fix test broken in Python 2.5 by commit 414cdb8b274. | Fix test broken in Python 2.5 by commit 414cdb8b274. | Python | bsd-3-clause | benspaulding/django-portfolio,blturner/django-portfolio,blturner/django-portfolio | - from .models import *
+ from portfolio.tests.models import *
| Fix test broken in Python 2.5 by commit 414cdb8b274. | ## Code Before:
from .models import *
## Instruction:
Fix test broken in Python 2.5 by commit 414cdb8b274.
## Code After:
from portfolio.tests.models import *
| ...
from portfolio.tests.models import *
... |
215746e2fd7e5f78b6dae031aae6a935ab164dd1 | pyjokes/pyjokes.py | pyjokes/pyjokes.py | from __future__ import absolute_import
import random
import importlib
def get_joke(category='neutral', language='en'):
"""
Parameters
----------
category: str
Choices: 'neutral', 'explicit', 'chuck', 'all'
lang: str
Choices: 'en', 'de', 'es'
Returns
-------
joke: str
"""
if language == 'en':
from .jokes_en import jokes
elif language == 'de':
from .jokes_de import jokes
elif language == 'es':
from .jokes_es import jokes
try:
jokes = jokes[category]
except:
return 'Could not get the joke. Choose another category.'
else:
return random.choice(jokes)
| from __future__ import absolute_import
import random
from .jokes_en import jokes as jokes_en
from .jokes_de import jokes as jokes_de
from .jokes_es import jokes as jokes_es
all_jokes = {
'en': jokes_en,
'de': jokes_de,
'es': jokes_es,
}
class LanguageNotFoundError(Exception):
pass
class CategoryNotFoundError(Exception):
pass
def get_joke(category='neutral', language='en'):
"""
Parameters
----------
category: str
Choices: 'neutral', 'explicit', 'chuck', 'all'
lang: str
Choices: 'en', 'de', 'es'
Returns
-------
joke: str
"""
if language in all_jokes:
jokes = all_jokes[language]
else:
raise LanguageNotFoundError('No such language %s' % language)
if category in jokes:
jokes = jokes[category]
return random.choice(jokes)
else:
raise CategoryNotFound('No such category %s' % category)
| Use dict not if/else, add exceptions | Use dict not if/else, add exceptions
| Python | bsd-3-clause | borjaayerdi/pyjokes,birdsarah/pyjokes,pyjokes/pyjokes,bennuttall/pyjokes,trojjer/pyjokes,gmarkall/pyjokes,martinohanlon/pyjokes,ElectronicsGeek/pyjokes | from __future__ import absolute_import
import random
- import importlib
+
+ from .jokes_en import jokes as jokes_en
+ from .jokes_de import jokes as jokes_de
+ from .jokes_es import jokes as jokes_es
+
+
+ all_jokes = {
+ 'en': jokes_en,
+ 'de': jokes_de,
+ 'es': jokes_es,
+ }
+
+
+ class LanguageNotFoundError(Exception):
+ pass
+
+
+ class CategoryNotFoundError(Exception):
+ pass
+
def get_joke(category='neutral', language='en'):
"""
Parameters
----------
category: str
Choices: 'neutral', 'explicit', 'chuck', 'all'
lang: str
Choices: 'en', 'de', 'es'
Returns
-------
joke: str
"""
+ if language in all_jokes:
+ jokes = all_jokes[language]
+ else:
+ raise LanguageNotFoundError('No such language %s' % language)
- if language == 'en':
- from .jokes_en import jokes
- elif language == 'de':
- from .jokes_de import jokes
- elif language == 'es':
- from .jokes_es import jokes
- try:
+ if category in jokes:
jokes = jokes[category]
+ return random.choice(jokes)
- except:
- return 'Could not get the joke. Choose another category.'
else:
- return random.choice(jokes)
+ raise CategoryNotFound('No such category %s' % category)
| Use dict not if/else, add exceptions | ## Code Before:
from __future__ import absolute_import
import random
import importlib
def get_joke(category='neutral', language='en'):
"""
Parameters
----------
category: str
Choices: 'neutral', 'explicit', 'chuck', 'all'
lang: str
Choices: 'en', 'de', 'es'
Returns
-------
joke: str
"""
if language == 'en':
from .jokes_en import jokes
elif language == 'de':
from .jokes_de import jokes
elif language == 'es':
from .jokes_es import jokes
try:
jokes = jokes[category]
except:
return 'Could not get the joke. Choose another category.'
else:
return random.choice(jokes)
## Instruction:
Use dict not if/else, add exceptions
## Code After:
from __future__ import absolute_import
import random
from .jokes_en import jokes as jokes_en
from .jokes_de import jokes as jokes_de
from .jokes_es import jokes as jokes_es
all_jokes = {
'en': jokes_en,
'de': jokes_de,
'es': jokes_es,
}
class LanguageNotFoundError(Exception):
pass
class CategoryNotFoundError(Exception):
pass
def get_joke(category='neutral', language='en'):
"""
Parameters
----------
category: str
Choices: 'neutral', 'explicit', 'chuck', 'all'
lang: str
Choices: 'en', 'de', 'es'
Returns
-------
joke: str
"""
if language in all_jokes:
jokes = all_jokes[language]
else:
raise LanguageNotFoundError('No such language %s' % language)
if category in jokes:
jokes = jokes[category]
return random.choice(jokes)
else:
raise CategoryNotFound('No such category %s' % category)
| // ... existing code ...
from __future__ import absolute_import
import random
from .jokes_en import jokes as jokes_en
from .jokes_de import jokes as jokes_de
from .jokes_es import jokes as jokes_es
all_jokes = {
'en': jokes_en,
'de': jokes_de,
'es': jokes_es,
}
class LanguageNotFoundError(Exception):
pass
class CategoryNotFoundError(Exception):
pass
def get_joke(category='neutral', language='en'):
// ... modified code ...
"""
if language in all_jokes:
jokes = all_jokes[language]
else:
raise LanguageNotFoundError('No such language %s' % language)
if category in jokes:
jokes = jokes[category]
return random.choice(jokes)
else:
raise CategoryNotFound('No such category %s' % category)
// ... rest of the code ... |
e85e94d901560cd176883b3522cf0a961759732c | db/Db.py | db/Db.py | import abc
import sqlite3
import Config
class Db(object):
__metaclass__ = abc.ABCMeta
def __init__(self):
self._connection = self.connect()
@abc.abstractmethod
def connect(self, config_file = None):
raise NotImplementedError("Called method is not implemented")
@abc.abstractmethod
def execute(self, query, params = None):
raise NotImplementedError("Called method is not implemented")
@abc.abstractmethod
def commit(self):
raise NotImplementedError("Called method is not implemented")
@abc.abstractmethod
def close(self):
raise NotImplementedError("Called method is not implemented")
class SQLiteDb(Db):
def connect(self, config_file):
conf = Config(config_file)
cfg = conf.sqlite_options()
sqlite3.connect(cfg.db_file)
def execute(self, query, params = None):
self._connection.execute(query, params)
def commit(self):
self._connection.commit()
def close(self):
self._connection.close()
| import abc
import sqlite3
from ebroker.Config import Config
def getDb(config_file = None):
return SQLiteDb(config_file)
class Db(object):
__metaclass__ = abc.ABCMeta
def __init__(self, config_file = None):
self._config_file = config_file
self._connection = None # make sure attribute _connection exists
@abc.abstractmethod
def connect(self):
raise NotImplementedError("Called method is not implemented")
@abc.abstractmethod
def execute(self, query, params = None):
raise NotImplementedError("Called method is not implemented")
@abc.abstractmethod
def commit(self):
raise NotImplementedError("Called method is not implemented")
@abc.abstractmethod
def close(self):
raise NotImplementedError("Called method is not implemented")
class SQLiteDb(Db):
def __init__(self, config_file = None):
super(SQLiteDb, self).__init__(config_file)
conf = Config(config_file)
cfg = conf.sqlite_options()
self._db_file = cfg.db_file
def connect(self):
self._connection = sqlite3.connect(self._db_file)
def execute(self, query, params = None):
if self._connection is None:
self.connect()
if params is None:
self._connection.execute(query)
else:
self._connection.execute(query, params)
def commit(self):
self._connection.commit()
def close(self):
self._connection.close()
def prepare(db = None):
_db = db
if _db is None:
_db = getDb()
_db.execute('''
CREATE TABLE requests(ticker int, price double, amount int, symbol varchar(10), amount_satisfied int)
''')
| Fix various small issues in DB support | Fix various small issues in DB support
| Python | mit | vjuranek/e-broker-client | import abc
import sqlite3
- import Config
+ from ebroker.Config import Config
+
+
+ def getDb(config_file = None):
+ return SQLiteDb(config_file)
+
class Db(object):
__metaclass__ = abc.ABCMeta
- def __init__(self):
- self._connection = self.connect()
+ def __init__(self, config_file = None):
+ self._config_file = config_file
+ self._connection = None # make sure attribute _connection exists
@abc.abstractmethod
- def connect(self, config_file = None):
+ def connect(self):
raise NotImplementedError("Called method is not implemented")
@abc.abstractmethod
def execute(self, query, params = None):
raise NotImplementedError("Called method is not implemented")
@abc.abstractmethod
def commit(self):
raise NotImplementedError("Called method is not implemented")
@abc.abstractmethod
def close(self):
raise NotImplementedError("Called method is not implemented")
class SQLiteDb(Db):
+
- def connect(self, config_file):
+ def __init__(self, config_file = None):
+ super(SQLiteDb, self).__init__(config_file)
conf = Config(config_file)
cfg = conf.sqlite_options()
- sqlite3.connect(cfg.db_file)
+ self._db_file = cfg.db_file
+
+ def connect(self):
+ self._connection = sqlite3.connect(self._db_file)
def execute(self, query, params = None):
+ if self._connection is None:
+ self.connect()
+ if params is None:
+ self._connection.execute(query)
+ else:
- self._connection.execute(query, params)
+ self._connection.execute(query, params)
def commit(self):
self._connection.commit()
def close(self):
self._connection.close()
+
+ def prepare(db = None):
+ _db = db
+ if _db is None:
+ _db = getDb()
+ _db.execute('''
+ CREATE TABLE requests(ticker int, price double, amount int, symbol varchar(10), amount_satisfied int)
+ ''')
+
+
+ | Fix various small issues in DB support | ## Code Before:
import abc
import sqlite3
import Config
class Db(object):
__metaclass__ = abc.ABCMeta
def __init__(self):
self._connection = self.connect()
@abc.abstractmethod
def connect(self, config_file = None):
raise NotImplementedError("Called method is not implemented")
@abc.abstractmethod
def execute(self, query, params = None):
raise NotImplementedError("Called method is not implemented")
@abc.abstractmethod
def commit(self):
raise NotImplementedError("Called method is not implemented")
@abc.abstractmethod
def close(self):
raise NotImplementedError("Called method is not implemented")
class SQLiteDb(Db):
def connect(self, config_file):
conf = Config(config_file)
cfg = conf.sqlite_options()
sqlite3.connect(cfg.db_file)
def execute(self, query, params = None):
self._connection.execute(query, params)
def commit(self):
self._connection.commit()
def close(self):
self._connection.close()
## Instruction:
Fix various small issues in DB support
## Code After:
import abc
import sqlite3
from ebroker.Config import Config
def getDb(config_file = None):
return SQLiteDb(config_file)
class Db(object):
__metaclass__ = abc.ABCMeta
def __init__(self, config_file = None):
self._config_file = config_file
self._connection = None # make sure attribute _connection exists
@abc.abstractmethod
def connect(self):
raise NotImplementedError("Called method is not implemented")
@abc.abstractmethod
def execute(self, query, params = None):
raise NotImplementedError("Called method is not implemented")
@abc.abstractmethod
def commit(self):
raise NotImplementedError("Called method is not implemented")
@abc.abstractmethod
def close(self):
raise NotImplementedError("Called method is not implemented")
class SQLiteDb(Db):
def __init__(self, config_file = None):
super(SQLiteDb, self).__init__(config_file)
conf = Config(config_file)
cfg = conf.sqlite_options()
self._db_file = cfg.db_file
def connect(self):
self._connection = sqlite3.connect(self._db_file)
def execute(self, query, params = None):
if self._connection is None:
self.connect()
if params is None:
self._connection.execute(query)
else:
self._connection.execute(query, params)
def commit(self):
self._connection.commit()
def close(self):
self._connection.close()
def prepare(db = None):
_db = db
if _db is None:
_db = getDb()
_db.execute('''
CREATE TABLE requests(ticker int, price double, amount int, symbol varchar(10), amount_satisfied int)
''')
| // ... existing code ...
import sqlite3
from ebroker.Config import Config
def getDb(config_file = None):
return SQLiteDb(config_file)
class Db(object):
// ... modified code ...
__metaclass__ = abc.ABCMeta
def __init__(self, config_file = None):
self._config_file = config_file
self._connection = None # make sure attribute _connection exists
@abc.abstractmethod
def connect(self):
raise NotImplementedError("Called method is not implemented")
...
class SQLiteDb(Db):
def __init__(self, config_file = None):
super(SQLiteDb, self).__init__(config_file)
conf = Config(config_file)
cfg = conf.sqlite_options()
self._db_file = cfg.db_file
def connect(self):
self._connection = sqlite3.connect(self._db_file)
def execute(self, query, params = None):
if self._connection is None:
self.connect()
if params is None:
self._connection.execute(query)
else:
self._connection.execute(query, params)
def commit(self):
...
def close(self):
self._connection.close()
def prepare(db = None):
_db = db
if _db is None:
_db = getDb()
_db.execute('''
CREATE TABLE requests(ticker int, price double, amount int, symbol varchar(10), amount_satisfied int)
''')
// ... rest of the code ... |
0ca07405b864f761ae1d7ed659cac67c799bf39a | src/core/queue.py | src/core/queue.py |
class ActionsQueue:
def __init__(self):
self.queue = []
# Normal buttons
def btnBrowse(self, val):
print(val)
def actionReset(self, val):
print(val)
def btnRedirect(self, val):
print(val)
# Radio buttons
def radioColor256(self, val):
print(val)
def radioColor16b(self, val):
print(val)
def radioModelLow(self, val):
print(val)
def radioModelFast(self, val):
print(val)
def radioModelHigh(self, val):
print(val)
def radioTexFast(self, val):
print(val)
def radioTexHigh(self, val):
print(val)
# Check boxes
def chkCursor(self, val):
print(val)
def chkDraw3D(self, val):
print(val)
def chkFlipVideo(self, val):
print(val)
def chkFullscreen(self, val):
print(val)
def chkJoystick(self, val):
print(val)
def chkMusic(self, val):
print(val)
def chkSound(self, val):
print(val)
# Direct3D dropdown selection
def comboD3D(self, val):
print(val)
|
class ActionsQueue:
def __init__(self):
self.queue = []
class Responses:
def __init__(self):
pass
# Normal buttons
def btnBrowse(self, val):
print(val)
def actionReset(self, val):
print(val)
def btnRedirect(self, val):
print(val)
# Radio buttons
def radioColor256(self, val):
print(val)
def radioColor16b(self, val):
print(val)
def radioModelLow(self, val):
print(val)
def radioModelFast(self, val):
print(val)
def radioModelHigh(self, val):
print(val)
def radioTexFast(self, val):
print(val)
def radioTexHigh(self, val):
print(val)
# Check boxes
def chkCursor(self, val):
print(val)
def chkDraw3D(self, val):
print(val)
def chkFlipVideo(self, val):
print(val)
def chkFullscreen(self, val):
print(val)
def chkJoystick(self, val):
print(val)
def chkMusic(self, val):
print(val)
def chkSound(self, val):
print(val)
# Direct3D dropdown selection
def comboD3D(self, val):
print(val)
| Move those methods to own class | Move those methods to own class [ci skip]
| Python | mit | le717/ICU |
class ActionsQueue:
def __init__(self):
self.queue = []
+
+
+ class Responses:
+
+ def __init__(self):
+ pass
# Normal buttons
def btnBrowse(self, val):
print(val)
def actionReset(self, val):
print(val)
def btnRedirect(self, val):
print(val)
# Radio buttons
def radioColor256(self, val):
print(val)
def radioColor16b(self, val):
print(val)
def radioModelLow(self, val):
print(val)
def radioModelFast(self, val):
print(val)
def radioModelHigh(self, val):
print(val)
def radioTexFast(self, val):
print(val)
def radioTexHigh(self, val):
print(val)
# Check boxes
def chkCursor(self, val):
print(val)
def chkDraw3D(self, val):
print(val)
def chkFlipVideo(self, val):
print(val)
def chkFullscreen(self, val):
print(val)
def chkJoystick(self, val):
print(val)
def chkMusic(self, val):
print(val)
def chkSound(self, val):
print(val)
# Direct3D dropdown selection
def comboD3D(self, val):
print(val)
| Move those methods to own class | ## Code Before:
class ActionsQueue:
def __init__(self):
self.queue = []
# Normal buttons
def btnBrowse(self, val):
print(val)
def actionReset(self, val):
print(val)
def btnRedirect(self, val):
print(val)
# Radio buttons
def radioColor256(self, val):
print(val)
def radioColor16b(self, val):
print(val)
def radioModelLow(self, val):
print(val)
def radioModelFast(self, val):
print(val)
def radioModelHigh(self, val):
print(val)
def radioTexFast(self, val):
print(val)
def radioTexHigh(self, val):
print(val)
# Check boxes
def chkCursor(self, val):
print(val)
def chkDraw3D(self, val):
print(val)
def chkFlipVideo(self, val):
print(val)
def chkFullscreen(self, val):
print(val)
def chkJoystick(self, val):
print(val)
def chkMusic(self, val):
print(val)
def chkSound(self, val):
print(val)
# Direct3D dropdown selection
def comboD3D(self, val):
print(val)
## Instruction:
Move those methods to own class
## Code After:
class ActionsQueue:
def __init__(self):
self.queue = []
class Responses:
def __init__(self):
pass
# Normal buttons
def btnBrowse(self, val):
print(val)
def actionReset(self, val):
print(val)
def btnRedirect(self, val):
print(val)
# Radio buttons
def radioColor256(self, val):
print(val)
def radioColor16b(self, val):
print(val)
def radioModelLow(self, val):
print(val)
def radioModelFast(self, val):
print(val)
def radioModelHigh(self, val):
print(val)
def radioTexFast(self, val):
print(val)
def radioTexHigh(self, val):
print(val)
# Check boxes
def chkCursor(self, val):
print(val)
def chkDraw3D(self, val):
print(val)
def chkFlipVideo(self, val):
print(val)
def chkFullscreen(self, val):
print(val)
def chkJoystick(self, val):
print(val)
def chkMusic(self, val):
print(val)
def chkSound(self, val):
print(val)
# Direct3D dropdown selection
def comboD3D(self, val):
print(val)
| ...
def __init__(self):
self.queue = []
class Responses:
def __init__(self):
pass
# Normal buttons
... |
c897942c8b1c3d9283ea6453bcc6616ca3d5108e | builds/python3.6_ci/src/lint_turtle_files.py | builds/python3.6_ci/src/lint_turtle_files.py |
print("Hello, I am turtle linter")
|
import logging
import os
import daiquiri
import rdflib
daiquiri.setup(level=logging.INFO)
logger = daiquiri.getLogger(__name__)
# This is a slightly cheaty way of tracking which paths (if any) failed --
# we append to this global list, and inspect it at the end of the script!
failures = []
def parse_turtle(path):
"""
Try to parse the Turtle at a given path. Raises a ValueError if it fails!
"""
logger.info("Parsing Turtle at path %s", path)
graph = rdflib.Graph()
try:
graph.parse(path, format='ttl')
except Exception as exc:
# Get the name of the exception class
# e.g. rdflib.plugins.parsers.notation3.BadSyntax
exc_name = f'{exc.__class__.__module__}.{exc.__class__.__name__}'
# Then try to log something useful
logger.error("Error parsing Turtle (%s)", exc_name)
logger.error(exc)
failures.append(path)
else:
logger.info("Successfully parsed Turtle!")
if __name__ == '__main__':
for root, _, filenames in os.walk('.'):
for f in filenames:
if not f.endswith('.ttl'):
continue
path = os.path.join(root, f)
if 'WIP' in path:
logger.info("Skipping path %s as WIP", path)
continue
parse_turtle(path)
| Write a proper Turtle linter | Write a proper Turtle linter
| Python | mit | wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api |
- print("Hello, I am turtle linter")
+ import logging
+ import os
+ import daiquiri
+ import rdflib
+
+ daiquiri.setup(level=logging.INFO)
+
+ logger = daiquiri.getLogger(__name__)
+
+ # This is a slightly cheaty way of tracking which paths (if any) failed --
+ # we append to this global list, and inspect it at the end of the script!
+ failures = []
+
+
+ def parse_turtle(path):
+ """
+ Try to parse the Turtle at a given path. Raises a ValueError if it fails!
+ """
+ logger.info("Parsing Turtle at path %s", path)
+ graph = rdflib.Graph()
+ try:
+ graph.parse(path, format='ttl')
+ except Exception as exc:
+ # Get the name of the exception class
+ # e.g. rdflib.plugins.parsers.notation3.BadSyntax
+ exc_name = f'{exc.__class__.__module__}.{exc.__class__.__name__}'
+
+ # Then try to log something useful
+ logger.error("Error parsing Turtle (%s)", exc_name)
+ logger.error(exc)
+
+ failures.append(path)
+ else:
+ logger.info("Successfully parsed Turtle!")
+
+
+ if __name__ == '__main__':
+ for root, _, filenames in os.walk('.'):
+ for f in filenames:
+ if not f.endswith('.ttl'):
+ continue
+ path = os.path.join(root, f)
+
+ if 'WIP' in path:
+ logger.info("Skipping path %s as WIP", path)
+ continue
+
+ parse_turtle(path)
+ | Write a proper Turtle linter | ## Code Before:
print("Hello, I am turtle linter")
## Instruction:
Write a proper Turtle linter
## Code After:
import logging
import os
import daiquiri
import rdflib
daiquiri.setup(level=logging.INFO)
logger = daiquiri.getLogger(__name__)
# This is a slightly cheaty way of tracking which paths (if any) failed --
# we append to this global list, and inspect it at the end of the script!
failures = []
def parse_turtle(path):
"""
Try to parse the Turtle at a given path. Raises a ValueError if it fails!
"""
logger.info("Parsing Turtle at path %s", path)
graph = rdflib.Graph()
try:
graph.parse(path, format='ttl')
except Exception as exc:
# Get the name of the exception class
# e.g. rdflib.plugins.parsers.notation3.BadSyntax
exc_name = f'{exc.__class__.__module__}.{exc.__class__.__name__}'
# Then try to log something useful
logger.error("Error parsing Turtle (%s)", exc_name)
logger.error(exc)
failures.append(path)
else:
logger.info("Successfully parsed Turtle!")
if __name__ == '__main__':
for root, _, filenames in os.walk('.'):
for f in filenames:
if not f.endswith('.ttl'):
continue
path = os.path.join(root, f)
if 'WIP' in path:
logger.info("Skipping path %s as WIP", path)
continue
parse_turtle(path)
| // ... existing code ...
import logging
import os
import daiquiri
import rdflib
daiquiri.setup(level=logging.INFO)
logger = daiquiri.getLogger(__name__)
# This is a slightly cheaty way of tracking which paths (if any) failed --
# we append to this global list, and inspect it at the end of the script!
failures = []
def parse_turtle(path):
"""
Try to parse the Turtle at a given path. Raises a ValueError if it fails!
"""
logger.info("Parsing Turtle at path %s", path)
graph = rdflib.Graph()
try:
graph.parse(path, format='ttl')
except Exception as exc:
# Get the name of the exception class
# e.g. rdflib.plugins.parsers.notation3.BadSyntax
exc_name = f'{exc.__class__.__module__}.{exc.__class__.__name__}'
# Then try to log something useful
logger.error("Error parsing Turtle (%s)", exc_name)
logger.error(exc)
failures.append(path)
else:
logger.info("Successfully parsed Turtle!")
if __name__ == '__main__':
for root, _, filenames in os.walk('.'):
for f in filenames:
if not f.endswith('.ttl'):
continue
path = os.path.join(root, f)
if 'WIP' in path:
logger.info("Skipping path %s as WIP", path)
continue
parse_turtle(path)
// ... rest of the code ... |
1ce899d118b3d46a816c0fc5f2f1a6f0ca9670ed | addons/resource/models/res_company.py | addons/resource/models/res_company.py |
from odoo import api, fields, models, _
class ResCompany(models.Model):
_inherit = 'res.company'
resource_calendar_ids = fields.One2many(
'resource.calendar', 'company_id', 'Working Hours')
resource_calendar_id = fields.Many2one(
'resource.calendar', 'Default Working Hours', ondelete='restrict')
@api.model
def _init_data_resource_calendar(self):
for company in self.search([('resource_calendar_id', '=', False)]):
company.resource_calendar_id = self.env['resource.calendar'].create({'name': _('Standard 40 hours/week')}).id
@api.model
def create(self, values):
if not values.get('resource_calendar_id'):
values['resource_calendar_id'] = self.env['resource.calendar'].sudo().create({'name': _('Standard 40 hours/week')}).id
company = super(ResCompany, self).create(values)
# calendar created from form view: no company_id set because record was still not created
if not company.resource_calendar_id.company_id:
company.resource_calendar_id.company_id = company.id
return company
|
from odoo import api, fields, models, _
class ResCompany(models.Model):
_inherit = 'res.company'
resource_calendar_ids = fields.One2many(
'resource.calendar', 'company_id', 'Working Hours')
resource_calendar_id = fields.Many2one(
'resource.calendar', 'Default Working Hours', ondelete='restrict')
@api.model
def _init_data_resource_calendar(self):
self.search([('resource_calendar_id', '=', False)])._create_resource_calendar()
def _create_resource_calendar(self):
for company in self:
company.resource_calendar_id = self.env['resource.calendar'].create({
'name': _('Standard 40 hours/week'),
'company_id': company.id
}).id
@api.model
def create(self, values):
company = super(ResCompany, self).create(values)
if not company.resource_calendar_id:
company.sudo()._create_resource_calendar()
# calendar created from form view: no company_id set because record was still not created
if not company.resource_calendar_id.company_id:
company.resource_calendar_id.company_id = company.id
return company
| Set company_id on a resource.calendar on company creation | [IMP] resource: Set company_id on a resource.calendar on company creation
Purpose
=======
Currently, when creating a company, the resource calendar is created if not specified.
This lead to duplicated data. In Manufacturing > Configuration > Working Time, two same working time demo data('Standard 40 Hours/Week')
Specification
=============
Company should be correctly set in the calendar.
| Python | agpl-3.0 | ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo |
from odoo import api, fields, models, _
class ResCompany(models.Model):
_inherit = 'res.company'
resource_calendar_ids = fields.One2many(
'resource.calendar', 'company_id', 'Working Hours')
resource_calendar_id = fields.Many2one(
'resource.calendar', 'Default Working Hours', ondelete='restrict')
@api.model
def _init_data_resource_calendar(self):
- for company in self.search([('resource_calendar_id', '=', False)]):
+ self.search([('resource_calendar_id', '=', False)])._create_resource_calendar()
+
+ def _create_resource_calendar(self):
+ for company in self:
- company.resource_calendar_id = self.env['resource.calendar'].create({'name': _('Standard 40 hours/week')}).id
+ company.resource_calendar_id = self.env['resource.calendar'].create({
+ 'name': _('Standard 40 hours/week'),
+ 'company_id': company.id
+ }).id
@api.model
def create(self, values):
- if not values.get('resource_calendar_id'):
- values['resource_calendar_id'] = self.env['resource.calendar'].sudo().create({'name': _('Standard 40 hours/week')}).id
company = super(ResCompany, self).create(values)
+ if not company.resource_calendar_id:
+ company.sudo()._create_resource_calendar()
# calendar created from form view: no company_id set because record was still not created
if not company.resource_calendar_id.company_id:
company.resource_calendar_id.company_id = company.id
return company
| Set company_id on a resource.calendar on company creation | ## Code Before:
from odoo import api, fields, models, _
class ResCompany(models.Model):
_inherit = 'res.company'
resource_calendar_ids = fields.One2many(
'resource.calendar', 'company_id', 'Working Hours')
resource_calendar_id = fields.Many2one(
'resource.calendar', 'Default Working Hours', ondelete='restrict')
@api.model
def _init_data_resource_calendar(self):
for company in self.search([('resource_calendar_id', '=', False)]):
company.resource_calendar_id = self.env['resource.calendar'].create({'name': _('Standard 40 hours/week')}).id
@api.model
def create(self, values):
if not values.get('resource_calendar_id'):
values['resource_calendar_id'] = self.env['resource.calendar'].sudo().create({'name': _('Standard 40 hours/week')}).id
company = super(ResCompany, self).create(values)
# calendar created from form view: no company_id set because record was still not created
if not company.resource_calendar_id.company_id:
company.resource_calendar_id.company_id = company.id
return company
## Instruction:
Set company_id on a resource.calendar on company creation
## Code After:
from odoo import api, fields, models, _
class ResCompany(models.Model):
_inherit = 'res.company'
resource_calendar_ids = fields.One2many(
'resource.calendar', 'company_id', 'Working Hours')
resource_calendar_id = fields.Many2one(
'resource.calendar', 'Default Working Hours', ondelete='restrict')
@api.model
def _init_data_resource_calendar(self):
self.search([('resource_calendar_id', '=', False)])._create_resource_calendar()
def _create_resource_calendar(self):
for company in self:
company.resource_calendar_id = self.env['resource.calendar'].create({
'name': _('Standard 40 hours/week'),
'company_id': company.id
}).id
@api.model
def create(self, values):
company = super(ResCompany, self).create(values)
if not company.resource_calendar_id:
company.sudo()._create_resource_calendar()
# calendar created from form view: no company_id set because record was still not created
if not company.resource_calendar_id.company_id:
company.resource_calendar_id.company_id = company.id
return company
| # ... existing code ...
@api.model
def _init_data_resource_calendar(self):
self.search([('resource_calendar_id', '=', False)])._create_resource_calendar()
def _create_resource_calendar(self):
for company in self:
company.resource_calendar_id = self.env['resource.calendar'].create({
'name': _('Standard 40 hours/week'),
'company_id': company.id
}).id
@api.model
def create(self, values):
company = super(ResCompany, self).create(values)
if not company.resource_calendar_id:
company.sudo()._create_resource_calendar()
# calendar created from form view: no company_id set because record was still not created
if not company.resource_calendar_id.company_id:
# ... rest of the code ... |
b860372a9e874e8bc06efc9711f7b58591300e81 | tohu/__init__.py | tohu/__init__.py | from distutils.version import StrictVersion
from platform import python_version
min_supported_python_version = '3.6'
if StrictVersion(python_version()) < StrictVersion(min_supported_python_version):
error_msg = (
"Tohu requires Python {min_supported_python_version} or greater to run "
"(currently running under Python {python_version()})"
)
raise RuntimeError(error_msg)
from . import v6
from .v6.base import *
from .v6.primitive_generators import *
from .v6.derived_generators import *
from .v6.generator_dispatch import *
from .v6.custom_generator import CustomGenerator
from .v6.logging import logger
from .v6.utils import print_generated_sequence, print_tohu_version
from .v6 import base
from .v6 import primitive_generators
from .v6 import derived_generators
from .v6 import generator_dispatch
from .v6 import custom_generator
from .v6 import set_special_methods
__all__ = base.__all__ \
+ primitive_generators.__all__ \
+ derived_generators.__all__ \
+ generator_dispatch.__all__ \
+ custom_generator.__all__ \
+ ['tohu_logger', 'print_generated_sequence', 'print_tohu_version']
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
tohu_logger = logger # alias | from distutils.version import LooseVersion
from platform import python_version
min_supported_python_version = '3.6'
if LooseVersion(python_version()) < LooseVersion(min_supported_python_version):
error_msg = (
"Tohu requires Python {min_supported_python_version} or greater to run "
"(currently running under Python {python_version()})"
)
raise RuntimeError(error_msg)
from . import v6
from .v6.base import *
from .v6.primitive_generators import *
from .v6.derived_generators import *
from .v6.generator_dispatch import *
from .v6.custom_generator import CustomGenerator
from .v6.logging import logger
from .v6.utils import print_generated_sequence, print_tohu_version
from .v6 import base
from .v6 import primitive_generators
from .v6 import derived_generators
from .v6 import generator_dispatch
from .v6 import custom_generator
from .v6 import set_special_methods
__all__ = base.__all__ \
+ primitive_generators.__all__ \
+ derived_generators.__all__ \
+ generator_dispatch.__all__ \
+ custom_generator.__all__ \
+ ['tohu_logger', 'print_generated_sequence', 'print_tohu_version']
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
tohu_logger = logger # alias | Use LooseVersion in version check (to avoid errors for e.g. '3.7.2+') | Use LooseVersion in version check (to avoid errors for e.g. '3.7.2+')
| Python | mit | maxalbert/tohu | - from distutils.version import StrictVersion
+ from distutils.version import LooseVersion
from platform import python_version
min_supported_python_version = '3.6'
- if StrictVersion(python_version()) < StrictVersion(min_supported_python_version):
+ if LooseVersion(python_version()) < LooseVersion(min_supported_python_version):
error_msg = (
"Tohu requires Python {min_supported_python_version} or greater to run "
"(currently running under Python {python_version()})"
)
raise RuntimeError(error_msg)
from . import v6
from .v6.base import *
from .v6.primitive_generators import *
from .v6.derived_generators import *
from .v6.generator_dispatch import *
from .v6.custom_generator import CustomGenerator
from .v6.logging import logger
from .v6.utils import print_generated_sequence, print_tohu_version
from .v6 import base
from .v6 import primitive_generators
from .v6 import derived_generators
from .v6 import generator_dispatch
from .v6 import custom_generator
from .v6 import set_special_methods
__all__ = base.__all__ \
+ primitive_generators.__all__ \
+ derived_generators.__all__ \
+ generator_dispatch.__all__ \
+ custom_generator.__all__ \
+ ['tohu_logger', 'print_generated_sequence', 'print_tohu_version']
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
tohu_logger = logger # alias | Use LooseVersion in version check (to avoid errors for e.g. '3.7.2+') | ## Code Before:
from distutils.version import StrictVersion
from platform import python_version
min_supported_python_version = '3.6'
if StrictVersion(python_version()) < StrictVersion(min_supported_python_version):
error_msg = (
"Tohu requires Python {min_supported_python_version} or greater to run "
"(currently running under Python {python_version()})"
)
raise RuntimeError(error_msg)
from . import v6
from .v6.base import *
from .v6.primitive_generators import *
from .v6.derived_generators import *
from .v6.generator_dispatch import *
from .v6.custom_generator import CustomGenerator
from .v6.logging import logger
from .v6.utils import print_generated_sequence, print_tohu_version
from .v6 import base
from .v6 import primitive_generators
from .v6 import derived_generators
from .v6 import generator_dispatch
from .v6 import custom_generator
from .v6 import set_special_methods
__all__ = base.__all__ \
+ primitive_generators.__all__ \
+ derived_generators.__all__ \
+ generator_dispatch.__all__ \
+ custom_generator.__all__ \
+ ['tohu_logger', 'print_generated_sequence', 'print_tohu_version']
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
tohu_logger = logger # alias
## Instruction:
Use LooseVersion in version check (to avoid errors for e.g. '3.7.2+')
## Code After:
from distutils.version import LooseVersion
from platform import python_version
min_supported_python_version = '3.6'
if LooseVersion(python_version()) < LooseVersion(min_supported_python_version):
error_msg = (
"Tohu requires Python {min_supported_python_version} or greater to run "
"(currently running under Python {python_version()})"
)
raise RuntimeError(error_msg)
from . import v6
from .v6.base import *
from .v6.primitive_generators import *
from .v6.derived_generators import *
from .v6.generator_dispatch import *
from .v6.custom_generator import CustomGenerator
from .v6.logging import logger
from .v6.utils import print_generated_sequence, print_tohu_version
from .v6 import base
from .v6 import primitive_generators
from .v6 import derived_generators
from .v6 import generator_dispatch
from .v6 import custom_generator
from .v6 import set_special_methods
__all__ = base.__all__ \
+ primitive_generators.__all__ \
+ derived_generators.__all__ \
+ generator_dispatch.__all__ \
+ custom_generator.__all__ \
+ ['tohu_logger', 'print_generated_sequence', 'print_tohu_version']
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
tohu_logger = logger # alias | ...
from distutils.version import LooseVersion
from platform import python_version
...
min_supported_python_version = '3.6'
if LooseVersion(python_version()) < LooseVersion(min_supported_python_version):
error_msg = (
"Tohu requires Python {min_supported_python_version} or greater to run "
... |
Subsets and Splits