commit
stringlengths
40
40
old_file
stringlengths
4
106
new_file
stringlengths
4
106
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
2.95k
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.31k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
diff
stringlengths
49
3.61k
b448d52e5a30346633dd20e52431af39eb6859ec
importer/importer/connections.py
importer/importer/connections.py
import aioes from .utils import wait_for_all_services from .settings import ELASTICSEARCH_ENDPOINTS async def connect_to_elasticsearch(): print("Connecting to Elasticsearch...") await wait_for_all_services(ELASTICSEARCH_ENDPOINTS, timeout=10) elastic = aioes.Elasticsearch(ELASTICSEARCH_ENDPOINTS) await elastic.cluster.health(wait_for_status='yellow', timeout='5s') return elastic
import aioes from .utils import wait_for_all_services from .settings import ELASTICSEARCH_ENDPOINTS async def connect_to_elasticsearch(): print("Connecting to Elasticsearch...") await wait_for_all_services(ELASTICSEARCH_ENDPOINTS, timeout=10) elastic = aioes.Elasticsearch(ELASTICSEARCH_ENDPOINTS) return elastic
Remove the pointless cluster health check
Remove the pointless cluster health check
Python
mit
despawnerer/theatrics,despawnerer/theatrics,despawnerer/theatrics
import aioes from .utils import wait_for_all_services from .settings import ELASTICSEARCH_ENDPOINTS async def connect_to_elasticsearch(): print("Connecting to Elasticsearch...") await wait_for_all_services(ELASTICSEARCH_ENDPOINTS, timeout=10) elastic = aioes.Elasticsearch(ELASTICSEARCH_ENDPOINTS) - await elastic.cluster.health(wait_for_status='yellow', timeout='5s') return elastic
Remove the pointless cluster health check
## Code Before: import aioes from .utils import wait_for_all_services from .settings import ELASTICSEARCH_ENDPOINTS async def connect_to_elasticsearch(): print("Connecting to Elasticsearch...") await wait_for_all_services(ELASTICSEARCH_ENDPOINTS, timeout=10) elastic = aioes.Elasticsearch(ELASTICSEARCH_ENDPOINTS) await elastic.cluster.health(wait_for_status='yellow', timeout='5s') return elastic ## Instruction: Remove the pointless cluster health check ## Code After: import aioes from .utils import wait_for_all_services from .settings import ELASTICSEARCH_ENDPOINTS async def connect_to_elasticsearch(): print("Connecting to Elasticsearch...") await wait_for_all_services(ELASTICSEARCH_ENDPOINTS, timeout=10) elastic = aioes.Elasticsearch(ELASTICSEARCH_ENDPOINTS) return elastic
import aioes from .utils import wait_for_all_services from .settings import ELASTICSEARCH_ENDPOINTS async def connect_to_elasticsearch(): print("Connecting to Elasticsearch...") await wait_for_all_services(ELASTICSEARCH_ENDPOINTS, timeout=10) elastic = aioes.Elasticsearch(ELASTICSEARCH_ENDPOINTS) - await elastic.cluster.health(wait_for_status='yellow', timeout='5s') return elastic
f5f4397d026678570ad271e84099d2bcec541c72
whacked4/whacked4/ui/dialogs/startdialog.py
whacked4/whacked4/ui/dialogs/startdialog.py
from whacked4 import config from whacked4.ui import windows class StartDialog(windows.StartDialogBase): """ This dialog is meant to be displayed on startup of the application. It allows the user to quickly access some common functions without having to dig down into a menu first. """ def __init__(self, parent): windows.StartDialogBase.__init__(self, parent) client_width = self.FileList.GetClientSizeTuple()[0] - 4 self.FileList.InsertColumn(0, 'Filename', width=client_width) # Populate the list of recently accessed Dehacked patches. recent_files = config.settings['recent_files'] for index, filename in enumerate(recent_files): self.FileList.InsertStringItem(index, filename) def open_file_list(self, event): """ Opens a Dehacked patch directly from the file list. """ self.Hide() filename = config.settings['recent_files'][event.GetIndex()] self.GetParent().open_file(filename) def new_file(self, event): self.Hide() self.GetParent().new_file() def open_file(self, event): self.Hide() self.GetParent().open_file_dialog() def cancel(self, event): self.Hide()
from whacked4 import config from whacked4.ui import windows class StartDialog(windows.StartDialogBase): """ This dialog is meant to be displayed on startup of the application. It allows the user to quickly access some common functions without having to dig down into a menu first. """ def __init__(self, parent): windows.StartDialogBase.__init__(self, parent) client_width = self.FileList.GetClientSizeTuple()[0] - 4 self.FileList.InsertColumn(0, 'Filename', width=client_width) # Populate the list of recently accessed Dehacked patches. config.settings.recent_files_clean() recent_files = config.settings['recent_files'] for index, filename in enumerate(recent_files): self.FileList.InsertStringItem(index, filename) def open_file_list(self, event): """ Opens a Dehacked patch directly from the file list. """ self.Hide() filename = config.settings['recent_files'][event.GetIndex()] self.GetParent().open_file(filename) def new_file(self, event): self.Hide() self.GetParent().new_file() def open_file(self, event): self.Hide() self.GetParent().open_file_dialog() def cancel(self, event): self.Hide()
Clean the recent files list before displaying it in the startup dialog.
Clean the recent files list before displaying it in the startup dialog.
Python
bsd-2-clause
GitExl/WhackEd4,GitExl/WhackEd4
from whacked4 import config from whacked4.ui import windows class StartDialog(windows.StartDialogBase): """ This dialog is meant to be displayed on startup of the application. It allows the user to quickly access some common functions without having to dig down into a menu first. """ def __init__(self, parent): windows.StartDialogBase.__init__(self, parent) client_width = self.FileList.GetClientSizeTuple()[0] - 4 self.FileList.InsertColumn(0, 'Filename', width=client_width) # Populate the list of recently accessed Dehacked patches. + config.settings.recent_files_clean() recent_files = config.settings['recent_files'] for index, filename in enumerate(recent_files): self.FileList.InsertStringItem(index, filename) def open_file_list(self, event): """ Opens a Dehacked patch directly from the file list. """ self.Hide() filename = config.settings['recent_files'][event.GetIndex()] self.GetParent().open_file(filename) def new_file(self, event): self.Hide() self.GetParent().new_file() def open_file(self, event): self.Hide() self.GetParent().open_file_dialog() def cancel(self, event): self.Hide()
Clean the recent files list before displaying it in the startup dialog.
## Code Before: from whacked4 import config from whacked4.ui import windows class StartDialog(windows.StartDialogBase): """ This dialog is meant to be displayed on startup of the application. It allows the user to quickly access some common functions without having to dig down into a menu first. """ def __init__(self, parent): windows.StartDialogBase.__init__(self, parent) client_width = self.FileList.GetClientSizeTuple()[0] - 4 self.FileList.InsertColumn(0, 'Filename', width=client_width) # Populate the list of recently accessed Dehacked patches. recent_files = config.settings['recent_files'] for index, filename in enumerate(recent_files): self.FileList.InsertStringItem(index, filename) def open_file_list(self, event): """ Opens a Dehacked patch directly from the file list. """ self.Hide() filename = config.settings['recent_files'][event.GetIndex()] self.GetParent().open_file(filename) def new_file(self, event): self.Hide() self.GetParent().new_file() def open_file(self, event): self.Hide() self.GetParent().open_file_dialog() def cancel(self, event): self.Hide() ## Instruction: Clean the recent files list before displaying it in the startup dialog. ## Code After: from whacked4 import config from whacked4.ui import windows class StartDialog(windows.StartDialogBase): """ This dialog is meant to be displayed on startup of the application. It allows the user to quickly access some common functions without having to dig down into a menu first. """ def __init__(self, parent): windows.StartDialogBase.__init__(self, parent) client_width = self.FileList.GetClientSizeTuple()[0] - 4 self.FileList.InsertColumn(0, 'Filename', width=client_width) # Populate the list of recently accessed Dehacked patches. config.settings.recent_files_clean() recent_files = config.settings['recent_files'] for index, filename in enumerate(recent_files): self.FileList.InsertStringItem(index, filename) def open_file_list(self, event): """ Opens a Dehacked patch directly from the file list. """ self.Hide() filename = config.settings['recent_files'][event.GetIndex()] self.GetParent().open_file(filename) def new_file(self, event): self.Hide() self.GetParent().new_file() def open_file(self, event): self.Hide() self.GetParent().open_file_dialog() def cancel(self, event): self.Hide()
from whacked4 import config from whacked4.ui import windows class StartDialog(windows.StartDialogBase): """ This dialog is meant to be displayed on startup of the application. It allows the user to quickly access some common functions without having to dig down into a menu first. """ def __init__(self, parent): windows.StartDialogBase.__init__(self, parent) client_width = self.FileList.GetClientSizeTuple()[0] - 4 self.FileList.InsertColumn(0, 'Filename', width=client_width) # Populate the list of recently accessed Dehacked patches. + config.settings.recent_files_clean() recent_files = config.settings['recent_files'] for index, filename in enumerate(recent_files): self.FileList.InsertStringItem(index, filename) def open_file_list(self, event): """ Opens a Dehacked patch directly from the file list. """ self.Hide() filename = config.settings['recent_files'][event.GetIndex()] self.GetParent().open_file(filename) def new_file(self, event): self.Hide() self.GetParent().new_file() def open_file(self, event): self.Hide() self.GetParent().open_file_dialog() def cancel(self, event): self.Hide()
033b17a8be5be32188ca9b5f286fe023fc07d34a
frappe/utils/pdf.py
frappe/utils/pdf.py
from __future__ import unicode_literals import pdfkit, os, frappe from frappe.utils import scrub_urls def get_pdf(html, options=None): if not options: options = {} options.update({ "print-media-type": None, "background": None, "images": None, 'margin-top': '15mm', 'margin-right': '15mm', 'margin-bottom': '15mm', 'margin-left': '15mm', 'encoding': "UTF-8", 'no-outline': None }) if not options.get("page-size"): options['page-size'] = frappe.db.get_single_value("Print Settings", "pdf_page_size") or "A4" html = scrub_urls(html) fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf") pdfkit.from_string(html, fname, options=options or {}) with open(fname, "rb") as fileobj: filedata = fileobj.read() os.remove(fname) return filedata
from __future__ import unicode_literals import pdfkit, os, frappe from frappe.utils import scrub_urls def get_pdf(html, options=None): if not options: options = {} options.update({ "print-media-type": None, "background": None, "images": None, # 'margin-top': '10mm', # 'margin-right': '1mm', # 'margin-bottom': '10mm', # 'margin-left': '1mm', 'encoding': "UTF-8", 'no-outline': None }) if not options.get("page-size"): options['page-size'] = frappe.db.get_single_value("Print Settings", "pdf_page_size") or "A4" html = scrub_urls(html) fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf") pdfkit.from_string(html, fname, options=options or {}) with open(fname, "rb") as fileobj: filedata = fileobj.read() os.remove(fname) return filedata
Remove margin constrains from PDF printing
Remove margin constrains from PDF printing
Python
mit
BhupeshGupta/frappe,BhupeshGupta/frappe,BhupeshGupta/frappe,BhupeshGupta/frappe
from __future__ import unicode_literals import pdfkit, os, frappe from frappe.utils import scrub_urls def get_pdf(html, options=None): if not options: options = {} options.update({ "print-media-type": None, "background": None, "images": None, - 'margin-top': '15mm', + # 'margin-top': '10mm', - 'margin-right': '15mm', + # 'margin-right': '1mm', - 'margin-bottom': '15mm', + # 'margin-bottom': '10mm', - 'margin-left': '15mm', + # 'margin-left': '1mm', 'encoding': "UTF-8", 'no-outline': None }) if not options.get("page-size"): options['page-size'] = frappe.db.get_single_value("Print Settings", "pdf_page_size") or "A4" html = scrub_urls(html) fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf") pdfkit.from_string(html, fname, options=options or {}) with open(fname, "rb") as fileobj: filedata = fileobj.read() os.remove(fname) return filedata
Remove margin constrains from PDF printing
## Code Before: from __future__ import unicode_literals import pdfkit, os, frappe from frappe.utils import scrub_urls def get_pdf(html, options=None): if not options: options = {} options.update({ "print-media-type": None, "background": None, "images": None, 'margin-top': '15mm', 'margin-right': '15mm', 'margin-bottom': '15mm', 'margin-left': '15mm', 'encoding': "UTF-8", 'no-outline': None }) if not options.get("page-size"): options['page-size'] = frappe.db.get_single_value("Print Settings", "pdf_page_size") or "A4" html = scrub_urls(html) fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf") pdfkit.from_string(html, fname, options=options or {}) with open(fname, "rb") as fileobj: filedata = fileobj.read() os.remove(fname) return filedata ## Instruction: Remove margin constrains from PDF printing ## Code After: from __future__ import unicode_literals import pdfkit, os, frappe from frappe.utils import scrub_urls def get_pdf(html, options=None): if not options: options = {} options.update({ "print-media-type": None, "background": None, "images": None, # 'margin-top': '10mm', # 'margin-right': '1mm', # 'margin-bottom': '10mm', # 'margin-left': '1mm', 'encoding': "UTF-8", 'no-outline': None }) if not options.get("page-size"): options['page-size'] = frappe.db.get_single_value("Print Settings", "pdf_page_size") or "A4" html = scrub_urls(html) fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf") pdfkit.from_string(html, fname, options=options or {}) with open(fname, "rb") as fileobj: filedata = fileobj.read() os.remove(fname) return filedata
from __future__ import unicode_literals import pdfkit, os, frappe from frappe.utils import scrub_urls def get_pdf(html, options=None): if not options: options = {} options.update({ "print-media-type": None, "background": None, "images": None, - 'margin-top': '15mm', ? ^ + # 'margin-top': '10mm', ? ++ ^ - 'margin-right': '15mm', ? - + # 'margin-right': '1mm', ? ++ - 'margin-bottom': '15mm', ? ^ + # 'margin-bottom': '10mm', ? ++ ^ - 'margin-left': '15mm', ? - + # 'margin-left': '1mm', ? ++ 'encoding': "UTF-8", 'no-outline': None }) if not options.get("page-size"): options['page-size'] = frappe.db.get_single_value("Print Settings", "pdf_page_size") or "A4" html = scrub_urls(html) fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf") pdfkit.from_string(html, fname, options=options or {}) with open(fname, "rb") as fileobj: filedata = fileobj.read() os.remove(fname) return filedata
ed34dac136af052c849b35adacc7c95b2d82e00a
tests/test_content_type.py
tests/test_content_type.py
import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) requestWithQueryParam = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert FormParser is negotiation.select_parser( requestWithQueryParam, parsers) requestWithoutQueryParam = Request( factory.post('/', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert None is negotiation.select_parser( requestWithoutQueryParam, parsers) def test_limited_overrides(): """ The content type shouldn't be overridden if the header is something other than 'text/plain', or missing entirely. """ from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) req = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/somethingelse')) assert negotiation.select_parser(req, parsers) is None
import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) requestWithQueryParam = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) parser = negotiation.select_parser(requestWithQueryParam, parsers) assert parser.media_type == 'application/x-www-form-urlencoded' requestWithoutQueryParam = Request( factory.post('/', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert None is negotiation.select_parser( requestWithoutQueryParam, parsers) def test_limited_overrides(): """ The content type shouldn't be overridden if the header is something other than 'text/plain', or missing entirely. """ from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) req = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/somethingelse')) assert negotiation.select_parser(req, parsers) is None
Check media_type instead of class type
Check media_type instead of class type The `parsers` list should contain instances, not classes.
Python
mit
hzdg/drf-url-content-type-override
import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) requestWithQueryParam = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) - assert FormParser is negotiation.select_parser( - requestWithQueryParam, parsers) + parser = negotiation.select_parser(requestWithQueryParam, parsers) + assert parser.media_type == 'application/x-www-form-urlencoded' requestWithoutQueryParam = Request( factory.post('/', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert None is negotiation.select_parser( requestWithoutQueryParam, parsers) def test_limited_overrides(): """ The content type shouldn't be overridden if the header is something other than 'text/plain', or missing entirely. """ from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) req = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/somethingelse')) assert negotiation.select_parser(req, parsers) is None
Check media_type instead of class type
## Code Before: import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) requestWithQueryParam = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert FormParser is negotiation.select_parser( requestWithQueryParam, parsers) requestWithoutQueryParam = Request( factory.post('/', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert None is negotiation.select_parser( requestWithoutQueryParam, parsers) def test_limited_overrides(): """ The content type shouldn't be overridden if the header is something other than 'text/plain', or missing entirely. """ from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) req = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/somethingelse')) assert negotiation.select_parser(req, parsers) is None ## Instruction: Check media_type instead of class type ## Code After: import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) requestWithQueryParam = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) parser = negotiation.select_parser(requestWithQueryParam, parsers) assert parser.media_type == 'application/x-www-form-urlencoded' requestWithoutQueryParam = Request( factory.post('/', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert None is negotiation.select_parser( requestWithoutQueryParam, parsers) def test_limited_overrides(): """ The content type shouldn't be overridden if the header is something other than 'text/plain', or missing entirely. """ from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) req = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/somethingelse')) assert negotiation.select_parser(req, parsers) is None
import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) requestWithQueryParam = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) - assert FormParser is negotiation.select_parser( - requestWithQueryParam, parsers) + parser = negotiation.select_parser(requestWithQueryParam, parsers) + assert parser.media_type == 'application/x-www-form-urlencoded' requestWithoutQueryParam = Request( factory.post('/', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert None is negotiation.select_parser( requestWithoutQueryParam, parsers) def test_limited_overrides(): """ The content type shouldn't be overridden if the header is something other than 'text/plain', or missing entirely. """ from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) req = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/somethingelse')) assert negotiation.select_parser(req, parsers) is None
f4383f964643c7fa1c4de050feaf7d134e34d814
example/people.py
example/people.py
from pupa.scrape import Scraper from pupa.scrape.helpers import Legislator, Organization class PersonScraper(Scraper): def get_people(self): # committee tech = Organization('Technology', classification='committee') tech.add_post('Chairman', 'chairman') tech.add_source('https://example.com') yield tech # subcommittee ecom = Organization('Subcommittee on E-Commerce', parent=tech, classification='committee') ecom.add_source('https://example.com') yield ecom p = Person('Paul Tagliamonte', district='6', chamber='upper') p.add_committee_membership(tech, role='chairman') p.add_source('https://example.com') yield p
from pupa.scrape import Scraper from pupa.scrape.helpers import Legislator, Organization class PersonScraper(Scraper): def get_people(self): # committee tech = Organization('Technology', classification='committee') tech.add_post('Chairman', 'chairman') tech.add_source('https://example.com') yield tech # subcommittee ecom = Organization('Subcommittee on E-Commerce', parent=tech, classification='committee') ecom.add_source('https://example.com') yield ecom p = Legislator('Paul Tagliamonte', '6') p.add_membership(tech, role='chairman') p.add_source('https://example.com') yield p
Make it so that the example runs without error
Make it so that the example runs without error
Python
bsd-3-clause
datamade/pupa,influence-usa/pupa,rshorey/pupa,datamade/pupa,opencivicdata/pupa,rshorey/pupa,mileswwatkins/pupa,mileswwatkins/pupa,opencivicdata/pupa,influence-usa/pupa
from pupa.scrape import Scraper from pupa.scrape.helpers import Legislator, Organization class PersonScraper(Scraper): def get_people(self): # committee tech = Organization('Technology', classification='committee') tech.add_post('Chairman', 'chairman') tech.add_source('https://example.com') yield tech # subcommittee ecom = Organization('Subcommittee on E-Commerce', parent=tech, classification='committee') ecom.add_source('https://example.com') yield ecom - p = Person('Paul Tagliamonte', district='6', chamber='upper') + p = Legislator('Paul Tagliamonte', '6') - p.add_committee_membership(tech, role='chairman') + p.add_membership(tech, role='chairman') p.add_source('https://example.com') yield p
Make it so that the example runs without error
## Code Before: from pupa.scrape import Scraper from pupa.scrape.helpers import Legislator, Organization class PersonScraper(Scraper): def get_people(self): # committee tech = Organization('Technology', classification='committee') tech.add_post('Chairman', 'chairman') tech.add_source('https://example.com') yield tech # subcommittee ecom = Organization('Subcommittee on E-Commerce', parent=tech, classification='committee') ecom.add_source('https://example.com') yield ecom p = Person('Paul Tagliamonte', district='6', chamber='upper') p.add_committee_membership(tech, role='chairman') p.add_source('https://example.com') yield p ## Instruction: Make it so that the example runs without error ## Code After: from pupa.scrape import Scraper from pupa.scrape.helpers import Legislator, Organization class PersonScraper(Scraper): def get_people(self): # committee tech = Organization('Technology', classification='committee') tech.add_post('Chairman', 'chairman') tech.add_source('https://example.com') yield tech # subcommittee ecom = Organization('Subcommittee on E-Commerce', parent=tech, classification='committee') ecom.add_source('https://example.com') yield ecom p = Legislator('Paul Tagliamonte', '6') p.add_membership(tech, role='chairman') p.add_source('https://example.com') yield p
from pupa.scrape import Scraper from pupa.scrape.helpers import Legislator, Organization class PersonScraper(Scraper): def get_people(self): # committee tech = Organization('Technology', classification='committee') tech.add_post('Chairman', 'chairman') tech.add_source('https://example.com') yield tech # subcommittee ecom = Organization('Subcommittee on E-Commerce', parent=tech, classification='committee') ecom.add_source('https://example.com') yield ecom - p = Person('Paul Tagliamonte', district='6', chamber='upper') + p = Legislator('Paul Tagliamonte', '6') - p.add_committee_membership(tech, role='chairman') ? ---------- + p.add_membership(tech, role='chairman') p.add_source('https://example.com') yield p
cf3596ee93eabf425c7d42c15fc07b11f7741158
humblemedia/causes/models.py
humblemedia/causes/models.py
from django.db import models class Cause(models.Model): title = models.CharField(max_length=64) description = models.TextField() creator = models.ForeignKey('auth.User', related_name='causes') target = models.PositiveIntegerField(null=True, blank=True) url = models.URLField(null=True, blank=True) is_verified = models.BooleanField(default=False) is_published = models.BooleanField(default=False) def __str__(self): return self.title
from django.db import models class Cause(models.Model): title = models.CharField(max_length=64) description = models.TextField() creator = models.ForeignKey('auth.User', related_name='causes') organization = models.ForeignKey('organizations.Organization', related_name='causes', null=True, blank=True) target = models.PositiveIntegerField(null=True, blank=True) url = models.URLField(null=True, blank=True) is_verified = models.BooleanField(default=False) is_published = models.BooleanField(default=False) def __str__(self): return self.title
Add organization to cause model
Add organization to cause model
Python
mit
vladimiroff/humble-media,vladimiroff/humble-media
from django.db import models class Cause(models.Model): title = models.CharField(max_length=64) description = models.TextField() creator = models.ForeignKey('auth.User', related_name='causes') + organization = models.ForeignKey('organizations.Organization', related_name='causes', null=True, blank=True) target = models.PositiveIntegerField(null=True, blank=True) url = models.URLField(null=True, blank=True) is_verified = models.BooleanField(default=False) is_published = models.BooleanField(default=False) def __str__(self): return self.title
Add organization to cause model
## Code Before: from django.db import models class Cause(models.Model): title = models.CharField(max_length=64) description = models.TextField() creator = models.ForeignKey('auth.User', related_name='causes') target = models.PositiveIntegerField(null=True, blank=True) url = models.URLField(null=True, blank=True) is_verified = models.BooleanField(default=False) is_published = models.BooleanField(default=False) def __str__(self): return self.title ## Instruction: Add organization to cause model ## Code After: from django.db import models class Cause(models.Model): title = models.CharField(max_length=64) description = models.TextField() creator = models.ForeignKey('auth.User', related_name='causes') organization = models.ForeignKey('organizations.Organization', related_name='causes', null=True, blank=True) target = models.PositiveIntegerField(null=True, blank=True) url = models.URLField(null=True, blank=True) is_verified = models.BooleanField(default=False) is_published = models.BooleanField(default=False) def __str__(self): return self.title
from django.db import models class Cause(models.Model): title = models.CharField(max_length=64) description = models.TextField() creator = models.ForeignKey('auth.User', related_name='causes') + organization = models.ForeignKey('organizations.Organization', related_name='causes', null=True, blank=True) target = models.PositiveIntegerField(null=True, blank=True) url = models.URLField(null=True, blank=True) is_verified = models.BooleanField(default=False) is_published = models.BooleanField(default=False) def __str__(self): return self.title
bcd7f8f3d7313538ab1c04da9c42e774350ccdfe
ui/widgets/histogram/TrackingHistogramWidget.py
ui/widgets/histogram/TrackingHistogramWidget.py
from PySide.QtGui import * from PySide.QtCore import * from HistogramWidget import HistogramWidget from TrackingNodeItem import TrackingNodeItem class TrackingHistogramWidget(HistogramWidget): """ TrackingHistogramWidget """ updatePosition = Signal(float) def __init__(self): super(TrackingHistogramWidget, self).__init__() self.nodeItem = None def update(self): super(TrackingHistogramWidget, self).update() if not self.nodeItem: return self.nodeItem.update() def setHistogram(self, histogram): super(TrackingHistogramWidget, self).setHistogram(histogram) if not self.nodeItem: self.nodeItem = TrackingNodeItem() self.scene().addItem(self.nodeItem) self.nodeItem.setHistogramItem(self._histogramItem) self.nodeItem.setPos(QPoint(0, 0)) self.nodeItem.setZValue(300) self.nodeItem.delegate = self def updatePos(self, position): self.updatePosition.emit(position)
from PySide.QtGui import * from PySide.QtCore import * from HistogramWidget import HistogramWidget from TrackingNodeItem import TrackingNodeItem from ui.widgets import Style class TrackingHistogramWidget(HistogramWidget): """ TrackingHistogramWidget """ updatePosition = Signal(float) def __init__(self): super(TrackingHistogramWidget, self).__init__() self.nodeItem = None Style.styleWidgetForTab(self) def update(self): super(TrackingHistogramWidget, self).update() if not self.nodeItem: return self.nodeItem.update() def setHistogram(self, histogram): super(TrackingHistogramWidget, self).setHistogram(histogram) if not self.nodeItem: self.nodeItem = TrackingNodeItem() self.scene().addItem(self.nodeItem) self.nodeItem.setHistogramItem(self._histogramItem) self.nodeItem.setPos(QPoint(0, 0)) self.nodeItem.setZValue(300) self.nodeItem.delegate = self def updatePos(self, position): self.updatePosition.emit(position)
Fix background color on OS X for histogram widget of ray.
Fix background color on OS X for histogram widget of ray.
Python
mit
berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop
from PySide.QtGui import * from PySide.QtCore import * from HistogramWidget import HistogramWidget from TrackingNodeItem import TrackingNodeItem + from ui.widgets import Style class TrackingHistogramWidget(HistogramWidget): """ TrackingHistogramWidget """ updatePosition = Signal(float) def __init__(self): super(TrackingHistogramWidget, self).__init__() self.nodeItem = None + Style.styleWidgetForTab(self) def update(self): super(TrackingHistogramWidget, self).update() if not self.nodeItem: return self.nodeItem.update() def setHistogram(self, histogram): super(TrackingHistogramWidget, self).setHistogram(histogram) if not self.nodeItem: self.nodeItem = TrackingNodeItem() self.scene().addItem(self.nodeItem) self.nodeItem.setHistogramItem(self._histogramItem) self.nodeItem.setPos(QPoint(0, 0)) self.nodeItem.setZValue(300) self.nodeItem.delegate = self def updatePos(self, position): self.updatePosition.emit(position)
Fix background color on OS X for histogram widget of ray.
## Code Before: from PySide.QtGui import * from PySide.QtCore import * from HistogramWidget import HistogramWidget from TrackingNodeItem import TrackingNodeItem class TrackingHistogramWidget(HistogramWidget): """ TrackingHistogramWidget """ updatePosition = Signal(float) def __init__(self): super(TrackingHistogramWidget, self).__init__() self.nodeItem = None def update(self): super(TrackingHistogramWidget, self).update() if not self.nodeItem: return self.nodeItem.update() def setHistogram(self, histogram): super(TrackingHistogramWidget, self).setHistogram(histogram) if not self.nodeItem: self.nodeItem = TrackingNodeItem() self.scene().addItem(self.nodeItem) self.nodeItem.setHistogramItem(self._histogramItem) self.nodeItem.setPos(QPoint(0, 0)) self.nodeItem.setZValue(300) self.nodeItem.delegate = self def updatePos(self, position): self.updatePosition.emit(position) ## Instruction: Fix background color on OS X for histogram widget of ray. ## Code After: from PySide.QtGui import * from PySide.QtCore import * from HistogramWidget import HistogramWidget from TrackingNodeItem import TrackingNodeItem from ui.widgets import Style class TrackingHistogramWidget(HistogramWidget): """ TrackingHistogramWidget """ updatePosition = Signal(float) def __init__(self): super(TrackingHistogramWidget, self).__init__() self.nodeItem = None Style.styleWidgetForTab(self) def update(self): super(TrackingHistogramWidget, self).update() if not self.nodeItem: return self.nodeItem.update() def setHistogram(self, histogram): super(TrackingHistogramWidget, self).setHistogram(histogram) if not self.nodeItem: self.nodeItem = TrackingNodeItem() self.scene().addItem(self.nodeItem) self.nodeItem.setHistogramItem(self._histogramItem) self.nodeItem.setPos(QPoint(0, 0)) self.nodeItem.setZValue(300) self.nodeItem.delegate = self def updatePos(self, position): self.updatePosition.emit(position)
from PySide.QtGui import * from PySide.QtCore import * from HistogramWidget import HistogramWidget from TrackingNodeItem import TrackingNodeItem + from ui.widgets import Style class TrackingHistogramWidget(HistogramWidget): """ TrackingHistogramWidget """ updatePosition = Signal(float) def __init__(self): super(TrackingHistogramWidget, self).__init__() self.nodeItem = None + Style.styleWidgetForTab(self) def update(self): super(TrackingHistogramWidget, self).update() if not self.nodeItem: return self.nodeItem.update() def setHistogram(self, histogram): super(TrackingHistogramWidget, self).setHistogram(histogram) if not self.nodeItem: self.nodeItem = TrackingNodeItem() self.scene().addItem(self.nodeItem) self.nodeItem.setHistogramItem(self._histogramItem) self.nodeItem.setPos(QPoint(0, 0)) self.nodeItem.setZValue(300) self.nodeItem.delegate = self def updatePos(self, position): self.updatePosition.emit(position)
c80fc3c31003e6ecec049ac2e1ca370e58ab2b3c
mediasync/processors/yuicompressor.py
mediasync/processors/yuicompressor.py
from django.conf import settings from mediasync import JS_MIMETYPES import os from subprocess import Popen, PIPE def _yui_path(settings): if not hasattr(settings, 'MEDIASYNC'): return None path = settings.MEDIASYNC.get('YUI_COMPRESSOR_PATH', None) if path: path = os.path.realpath(os.path.expanduser(path)) return path def css_minifier(filedata, content_type, remote_path, is_active): is_css = (content_type in JS_MIMETYPES or remote_path.lower().endswith('.css')) yui_path = _yui_path(settings) if is_css and yui_path and is_active: proc = Popen(['java', '-jar', yui_path, '--type', 'css'], stdout=PIPE, stderr=PIPE, stdin=PIPE) stdout, stderr = proc.communicate(input=filedata) return str(stdout) def js_minifier(filedata, content_type, remote_path, is_active): is_js = (content_type in JS_MIMETYPES or remote_path.lower().endswith('.js')) yui_path = _yui_path(settings) if is_js and yui_path and is_active: proc = Popen(['java', '-jar', yui_path, '--type', 'js'], stdout=PIPE, stderr=PIPE, stdin=PIPE) stdout, stderr = proc.communicate(input=filedata) return str(stdout)
from django.conf import settings from mediasync import CSS_MIMETYPES, JS_MIMETYPES import os from subprocess import Popen, PIPE def _yui_path(settings): if not hasattr(settings, 'MEDIASYNC'): return None path = settings.MEDIASYNC.get('YUI_COMPRESSOR_PATH', None) if path: path = os.path.realpath(os.path.expanduser(path)) return path def css_minifier(filedata, content_type, remote_path, is_active): is_css = (content_type in CSS_MIMETYPES or remote_path.lower().endswith('.css')) yui_path = _yui_path(settings) if is_css and yui_path and is_active: proc = Popen(['java', '-jar', yui_path, '--type', 'css'], stdout=PIPE, stderr=PIPE, stdin=PIPE) stdout, stderr = proc.communicate(input=filedata) return str(stdout) def js_minifier(filedata, content_type, remote_path, is_active): is_js = (content_type in JS_MIMETYPES or remote_path.lower().endswith('.js')) yui_path = _yui_path(settings) if is_js and yui_path and is_active: proc = Popen(['java', '-jar', yui_path, '--type', 'js'], stdout=PIPE, stderr=PIPE, stdin=PIPE) stdout, stderr = proc.communicate(input=filedata) return str(stdout)
Replace incorrect JS_MIMETYPES with CSS_MIMETYPES
Replace incorrect JS_MIMETYPES with CSS_MIMETYPES
Python
bsd-3-clause
sunlightlabs/django-mediasync,mntan/django-mediasync,mntan/django-mediasync,sunlightlabs/django-mediasync,sunlightlabs/django-mediasync,mntan/django-mediasync
from django.conf import settings - from mediasync import JS_MIMETYPES + from mediasync import CSS_MIMETYPES, JS_MIMETYPES import os from subprocess import Popen, PIPE def _yui_path(settings): if not hasattr(settings, 'MEDIASYNC'): return None path = settings.MEDIASYNC.get('YUI_COMPRESSOR_PATH', None) if path: path = os.path.realpath(os.path.expanduser(path)) return path def css_minifier(filedata, content_type, remote_path, is_active): - is_css = (content_type in JS_MIMETYPES or remote_path.lower().endswith('.css')) + is_css = (content_type in CSS_MIMETYPES or remote_path.lower().endswith('.css')) yui_path = _yui_path(settings) if is_css and yui_path and is_active: proc = Popen(['java', '-jar', yui_path, '--type', 'css'], stdout=PIPE, stderr=PIPE, stdin=PIPE) stdout, stderr = proc.communicate(input=filedata) return str(stdout) def js_minifier(filedata, content_type, remote_path, is_active): is_js = (content_type in JS_MIMETYPES or remote_path.lower().endswith('.js')) yui_path = _yui_path(settings) if is_js and yui_path and is_active: proc = Popen(['java', '-jar', yui_path, '--type', 'js'], stdout=PIPE, stderr=PIPE, stdin=PIPE) stdout, stderr = proc.communicate(input=filedata) return str(stdout)
Replace incorrect JS_MIMETYPES with CSS_MIMETYPES
## Code Before: from django.conf import settings from mediasync import JS_MIMETYPES import os from subprocess import Popen, PIPE def _yui_path(settings): if not hasattr(settings, 'MEDIASYNC'): return None path = settings.MEDIASYNC.get('YUI_COMPRESSOR_PATH', None) if path: path = os.path.realpath(os.path.expanduser(path)) return path def css_minifier(filedata, content_type, remote_path, is_active): is_css = (content_type in JS_MIMETYPES or remote_path.lower().endswith('.css')) yui_path = _yui_path(settings) if is_css and yui_path and is_active: proc = Popen(['java', '-jar', yui_path, '--type', 'css'], stdout=PIPE, stderr=PIPE, stdin=PIPE) stdout, stderr = proc.communicate(input=filedata) return str(stdout) def js_minifier(filedata, content_type, remote_path, is_active): is_js = (content_type in JS_MIMETYPES or remote_path.lower().endswith('.js')) yui_path = _yui_path(settings) if is_js and yui_path and is_active: proc = Popen(['java', '-jar', yui_path, '--type', 'js'], stdout=PIPE, stderr=PIPE, stdin=PIPE) stdout, stderr = proc.communicate(input=filedata) return str(stdout) ## Instruction: Replace incorrect JS_MIMETYPES with CSS_MIMETYPES ## Code After: from django.conf import settings from mediasync import CSS_MIMETYPES, JS_MIMETYPES import os from subprocess import Popen, PIPE def _yui_path(settings): if not hasattr(settings, 'MEDIASYNC'): return None path = settings.MEDIASYNC.get('YUI_COMPRESSOR_PATH', None) if path: path = os.path.realpath(os.path.expanduser(path)) return path def css_minifier(filedata, content_type, remote_path, is_active): is_css = (content_type in CSS_MIMETYPES or remote_path.lower().endswith('.css')) yui_path = _yui_path(settings) if is_css and yui_path and is_active: proc = Popen(['java', '-jar', yui_path, '--type', 'css'], stdout=PIPE, stderr=PIPE, stdin=PIPE) stdout, stderr = proc.communicate(input=filedata) return str(stdout) def js_minifier(filedata, content_type, remote_path, is_active): is_js = (content_type in JS_MIMETYPES or remote_path.lower().endswith('.js')) yui_path = _yui_path(settings) if is_js and yui_path and is_active: proc = Popen(['java', '-jar', yui_path, '--type', 'js'], stdout=PIPE, stderr=PIPE, stdin=PIPE) stdout, stderr = proc.communicate(input=filedata) return str(stdout)
from django.conf import settings - from mediasync import JS_MIMETYPES + from mediasync import CSS_MIMETYPES, JS_MIMETYPES ? +++++++++++++++ import os from subprocess import Popen, PIPE def _yui_path(settings): if not hasattr(settings, 'MEDIASYNC'): return None path = settings.MEDIASYNC.get('YUI_COMPRESSOR_PATH', None) if path: path = os.path.realpath(os.path.expanduser(path)) return path def css_minifier(filedata, content_type, remote_path, is_active): - is_css = (content_type in JS_MIMETYPES or remote_path.lower().endswith('.css')) ? ^ + is_css = (content_type in CSS_MIMETYPES or remote_path.lower().endswith('.css')) ? ^^ yui_path = _yui_path(settings) if is_css and yui_path and is_active: proc = Popen(['java', '-jar', yui_path, '--type', 'css'], stdout=PIPE, stderr=PIPE, stdin=PIPE) stdout, stderr = proc.communicate(input=filedata) return str(stdout) def js_minifier(filedata, content_type, remote_path, is_active): is_js = (content_type in JS_MIMETYPES or remote_path.lower().endswith('.js')) yui_path = _yui_path(settings) if is_js and yui_path and is_active: proc = Popen(['java', '-jar', yui_path, '--type', 'js'], stdout=PIPE, stderr=PIPE, stdin=PIPE) stdout, stderr = proc.communicate(input=filedata) return str(stdout)
6c61e1000f3f87501b6e45a2715bd26a3b83b407
collector/absolutefrequency.py
collector/absolutefrequency.py
from collector import ItemCollector class ItemNumericAbsoluteFrequencyCollector(ItemCollector): def __init__(self, previous_collector_set = None): ItemCollector.__init__(self, previous_collector_set) self.absolute_frequencies = {} def collect(self, item, collector_set=None): current_absolute_frequency = self.absolute_frequencies.get(item, 0) + 1 self.absolute_frequencies[item] = current_absolute_frequency def get_result(self, collector_set=None): return self.absolute_frequencies
import collections from collector import ItemCollector class ItemNumericAbsoluteFrequencyCollector(ItemCollector): def __init__(self, previous_collector_set = None): ItemCollector.__init__(self, previous_collector_set) self.absolute_frequencies = collections.defaultdict(int) def collect(self, item, collector_set=None): self.absolute_frequencies[item] += 1 def get_result(self, collector_set=None): return self.absolute_frequencies
Use defaultdict for absolute frequency collector
Use defaultdict for absolute frequency collector
Python
mit
davidfoerster/schema-matching
+ import collections from collector import ItemCollector class ItemNumericAbsoluteFrequencyCollector(ItemCollector): def __init__(self, previous_collector_set = None): ItemCollector.__init__(self, previous_collector_set) - self.absolute_frequencies = {} + self.absolute_frequencies = collections.defaultdict(int) def collect(self, item, collector_set=None): - current_absolute_frequency = self.absolute_frequencies.get(item, 0) + 1 - self.absolute_frequencies[item] = current_absolute_frequency + self.absolute_frequencies[item] += 1 + def get_result(self, collector_set=None): return self.absolute_frequencies
Use defaultdict for absolute frequency collector
## Code Before: from collector import ItemCollector class ItemNumericAbsoluteFrequencyCollector(ItemCollector): def __init__(self, previous_collector_set = None): ItemCollector.__init__(self, previous_collector_set) self.absolute_frequencies = {} def collect(self, item, collector_set=None): current_absolute_frequency = self.absolute_frequencies.get(item, 0) + 1 self.absolute_frequencies[item] = current_absolute_frequency def get_result(self, collector_set=None): return self.absolute_frequencies ## Instruction: Use defaultdict for absolute frequency collector ## Code After: import collections from collector import ItemCollector class ItemNumericAbsoluteFrequencyCollector(ItemCollector): def __init__(self, previous_collector_set = None): ItemCollector.__init__(self, previous_collector_set) self.absolute_frequencies = collections.defaultdict(int) def collect(self, item, collector_set=None): self.absolute_frequencies[item] += 1 def get_result(self, collector_set=None): return self.absolute_frequencies
+ import collections from collector import ItemCollector class ItemNumericAbsoluteFrequencyCollector(ItemCollector): def __init__(self, previous_collector_set = None): ItemCollector.__init__(self, previous_collector_set) - self.absolute_frequencies = {} + self.absolute_frequencies = collections.defaultdict(int) def collect(self, item, collector_set=None): - current_absolute_frequency = self.absolute_frequencies.get(item, 0) + 1 - self.absolute_frequencies[item] = current_absolute_frequency + self.absolute_frequencies[item] += 1 + def get_result(self, collector_set=None): return self.absolute_frequencies
d406aa60f31f5e318a46e84539546a4452574ce6
src/rtruffle/source_section.py
src/rtruffle/source_section.py
class SourceCoordinate(object): _immutable_fields_ = ['_start_line', '_start_column', '_char_idx'] def __init__(self, start_line, start_column, char_idx): self._start_line = start_line self._start_column = start_column self._char_idx = char_idx def get_start_line(self): return self._start_line def get_start_column(self): return self._start_column class SourceSection(object): _immutable_fields_ = ['_source', '_identifier', '_coord', '_char_length'] def __init__(self, source = None, identifier = None, coord = None, char_length = None, file = None, source_section = None): if source_section: self._source = source_section._source self._coord = source_section._coord self._char_length = source_section._char_length self._file = source_section._file else: self._source = source self._coord = coord self._char_length = char_length self._file = file self._identifier = identifier def __str__(self): return "%s:%d:%d" % (self._file, self._coord.get_start_line(), self._coord.get_start_column())
class SourceCoordinate(object): _immutable_fields_ = ['_start_line', '_start_column', '_char_idx'] def __init__(self, start_line, start_column, char_idx): self._start_line = start_line self._start_column = start_column self._char_idx = char_idx def get_start_line(self): return self._start_line def get_start_column(self): return self._start_column class SourceSection(object): _immutable_fields_ = ['_source', '_identifier', '_coord', '_char_length'] def __init__(self, source = None, identifier = None, coord = None, char_length = 0, file_name = None, source_section = None): if source_section: self._source = source_section._source self._coord = source_section._coord self._char_length = source_section._char_length self._file = source_section._file else: self._source = source self._coord = coord self._char_length = char_length self._file = file_name self._identifier = identifier def __str__(self): return "%s:%d:%d" % (self._file, self._coord.get_start_line(), self._coord.get_start_column())
Initialize char_length with a number
Initialize char_length with a number And make var name `file` less ambiguous by using `file_name` instead. Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
Python
mit
SOM-st/RPySOM,smarr/RTruffleSOM,SOM-st/RTruffleSOM,smarr/PySOM,SOM-st/PySOM,SOM-st/RPySOM,smarr/RTruffleSOM,SOM-st/RTruffleSOM,smarr/PySOM,SOM-st/PySOM
class SourceCoordinate(object): _immutable_fields_ = ['_start_line', '_start_column', '_char_idx'] def __init__(self, start_line, start_column, char_idx): self._start_line = start_line self._start_column = start_column self._char_idx = char_idx def get_start_line(self): return self._start_line def get_start_column(self): return self._start_column class SourceSection(object): _immutable_fields_ = ['_source', '_identifier', '_coord', '_char_length'] def __init__(self, source = None, identifier = None, coord = None, - char_length = None, file = None, source_section = None): + char_length = 0, file_name = None, source_section = None): if source_section: self._source = source_section._source self._coord = source_section._coord self._char_length = source_section._char_length self._file = source_section._file else: self._source = source self._coord = coord self._char_length = char_length - self._file = file + self._file = file_name self._identifier = identifier def __str__(self): return "%s:%d:%d" % (self._file, self._coord.get_start_line(), self._coord.get_start_column())
Initialize char_length with a number
## Code Before: class SourceCoordinate(object): _immutable_fields_ = ['_start_line', '_start_column', '_char_idx'] def __init__(self, start_line, start_column, char_idx): self._start_line = start_line self._start_column = start_column self._char_idx = char_idx def get_start_line(self): return self._start_line def get_start_column(self): return self._start_column class SourceSection(object): _immutable_fields_ = ['_source', '_identifier', '_coord', '_char_length'] def __init__(self, source = None, identifier = None, coord = None, char_length = None, file = None, source_section = None): if source_section: self._source = source_section._source self._coord = source_section._coord self._char_length = source_section._char_length self._file = source_section._file else: self._source = source self._coord = coord self._char_length = char_length self._file = file self._identifier = identifier def __str__(self): return "%s:%d:%d" % (self._file, self._coord.get_start_line(), self._coord.get_start_column()) ## Instruction: Initialize char_length with a number ## Code After: class SourceCoordinate(object): _immutable_fields_ = ['_start_line', '_start_column', '_char_idx'] def __init__(self, start_line, start_column, char_idx): self._start_line = start_line self._start_column = start_column self._char_idx = char_idx def get_start_line(self): return self._start_line def get_start_column(self): return self._start_column class SourceSection(object): _immutable_fields_ = ['_source', '_identifier', '_coord', '_char_length'] def __init__(self, source = None, identifier = None, coord = None, char_length = 0, file_name = None, source_section = None): if source_section: self._source = source_section._source self._coord = source_section._coord self._char_length = source_section._char_length self._file = source_section._file else: self._source = source self._coord = coord self._char_length = char_length self._file = file_name self._identifier = identifier def __str__(self): return "%s:%d:%d" % (self._file, self._coord.get_start_line(), self._coord.get_start_column())
class SourceCoordinate(object): _immutable_fields_ = ['_start_line', '_start_column', '_char_idx'] def __init__(self, start_line, start_column, char_idx): self._start_line = start_line self._start_column = start_column self._char_idx = char_idx def get_start_line(self): return self._start_line def get_start_column(self): return self._start_column class SourceSection(object): _immutable_fields_ = ['_source', '_identifier', '_coord', '_char_length'] def __init__(self, source = None, identifier = None, coord = None, - char_length = None, file = None, source_section = None): ? ^^^^ + char_length = 0, file_name = None, source_section = None): ? ^ +++++ if source_section: self._source = source_section._source self._coord = source_section._coord self._char_length = source_section._char_length self._file = source_section._file else: self._source = source self._coord = coord self._char_length = char_length - self._file = file + self._file = file_name ? +++++ self._identifier = identifier def __str__(self): return "%s:%d:%d" % (self._file, self._coord.get_start_line(), self._coord.get_start_column())
a2b9777cc7ec4d606d3a33400c4f242bc9177fab
awx/main/migrations/0004_rbac_migrations.py
awx/main/migrations/0004_rbac_migrations.py
from __future__ import unicode_literals from awx.main.migrations import _rbac as rbac from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0003_rbac_changes'), ] operations = [ migrations.RunPython(rbac.migrate_organization), migrations.RunPython(rbac.migrate_credential), migrations.RunPython(rbac.migrate_team), migrations.RunPython(rbac.migrate_inventory), ]
from __future__ import unicode_literals from awx.main.migrations import _rbac as rbac from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0003_rbac_changes'), ] operations = [ migrations.RunPython(rbac.migrate_users), migrations.RunPython(rbac.migrate_organization), migrations.RunPython(rbac.migrate_credential), migrations.RunPython(rbac.migrate_team), migrations.RunPython(rbac.migrate_inventory), migrations.RunPython(rbac.migrate_projects), ]
Add migrate_users and migrate_projects to our migration plan
Add migrate_users and migrate_projects to our migration plan
Python
apache-2.0
wwitzel3/awx,snahelou/awx,snahelou/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,wwitzel3/awx,snahelou/awx
from __future__ import unicode_literals from awx.main.migrations import _rbac as rbac from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0003_rbac_changes'), ] operations = [ + migrations.RunPython(rbac.migrate_users), migrations.RunPython(rbac.migrate_organization), migrations.RunPython(rbac.migrate_credential), migrations.RunPython(rbac.migrate_team), migrations.RunPython(rbac.migrate_inventory), + migrations.RunPython(rbac.migrate_projects), ]
Add migrate_users and migrate_projects to our migration plan
## Code Before: from __future__ import unicode_literals from awx.main.migrations import _rbac as rbac from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0003_rbac_changes'), ] operations = [ migrations.RunPython(rbac.migrate_organization), migrations.RunPython(rbac.migrate_credential), migrations.RunPython(rbac.migrate_team), migrations.RunPython(rbac.migrate_inventory), ] ## Instruction: Add migrate_users and migrate_projects to our migration plan ## Code After: from __future__ import unicode_literals from awx.main.migrations import _rbac as rbac from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0003_rbac_changes'), ] operations = [ migrations.RunPython(rbac.migrate_users), migrations.RunPython(rbac.migrate_organization), migrations.RunPython(rbac.migrate_credential), migrations.RunPython(rbac.migrate_team), migrations.RunPython(rbac.migrate_inventory), migrations.RunPython(rbac.migrate_projects), ]
from __future__ import unicode_literals from awx.main.migrations import _rbac as rbac from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0003_rbac_changes'), ] operations = [ + migrations.RunPython(rbac.migrate_users), migrations.RunPython(rbac.migrate_organization), migrations.RunPython(rbac.migrate_credential), migrations.RunPython(rbac.migrate_team), migrations.RunPython(rbac.migrate_inventory), + migrations.RunPython(rbac.migrate_projects), ]
4dd13a8b031a57f6290fb43dc6daa5082041658a
dashboard/consumers.py
dashboard/consumers.py
from channels import Group from channels.auth import channel_session_user, channel_session_user_from_http @channel_session_user_from_http def ws_connect(message): Group('btc-price').add(message.reply_channel) message.reply_channel.send({ 'accept': True }) @channel_session_user def ws_disconnect(message): Group('btc-price').discard(message.reply_channel)
import json from channels import Group from channels.auth import channel_session_user @channel_session_user def ws_connect(message): Group('btc-price').add(message.reply_channel) message.channel_session['coin-group'] = 'btc-price' message.reply_channel.send({ 'accept': True }) @channel_session_user def ws_receive(message): data = json.loads(message.content.get('text')) if data.get('coin') == 'litecoin': Group('ltc-price').add(message.reply_channel) Group('btc-price').discard(message.reply_channel) message.channel_session['coin-group'] = 'ltc-price' elif data.get('coin') == 'bitcoin': Group('btc-price').add(message.reply_channel) Group('ltc-price').discard(message.reply_channel) message.channel_session['coin-group'] = 'btc-price' @channel_session_user def ws_disconnect(message): user_group = message.channel_session['coin-group'] Group(user_group).discard(message.reply_channel)
Add ws_receive consumer with channel_session_user decorator
Add ws_receive consumer with channel_session_user decorator
Python
mit
alessandroHenrique/coinpricemonitor,alessandroHenrique/coinpricemonitor,alessandroHenrique/coinpricemonitor
+ import json + from channels import Group - from channels.auth import channel_session_user, channel_session_user_from_http + from channels.auth import channel_session_user - @channel_session_user_from_http + @channel_session_user def ws_connect(message): + Group('btc-price').add(message.reply_channel) - Group('btc-price').add(message.reply_channel) + message.channel_session['coin-group'] = 'btc-price' message.reply_channel.send({ 'accept': True }) @channel_session_user + def ws_receive(message): + data = json.loads(message.content.get('text')) + + if data.get('coin') == 'litecoin': + Group('ltc-price').add(message.reply_channel) + Group('btc-price').discard(message.reply_channel) + + message.channel_session['coin-group'] = 'ltc-price' + + elif data.get('coin') == 'bitcoin': + Group('btc-price').add(message.reply_channel) + Group('ltc-price').discard(message.reply_channel) + + message.channel_session['coin-group'] = 'btc-price' + + + @channel_session_user def ws_disconnect(message): - Group('btc-price').discard(message.reply_channel) + user_group = message.channel_session['coin-group'] + Group(user_group).discard(message.reply_channel) +
Add ws_receive consumer with channel_session_user decorator
## Code Before: from channels import Group from channels.auth import channel_session_user, channel_session_user_from_http @channel_session_user_from_http def ws_connect(message): Group('btc-price').add(message.reply_channel) message.reply_channel.send({ 'accept': True }) @channel_session_user def ws_disconnect(message): Group('btc-price').discard(message.reply_channel) ## Instruction: Add ws_receive consumer with channel_session_user decorator ## Code After: import json from channels import Group from channels.auth import channel_session_user @channel_session_user def ws_connect(message): Group('btc-price').add(message.reply_channel) message.channel_session['coin-group'] = 'btc-price' message.reply_channel.send({ 'accept': True }) @channel_session_user def ws_receive(message): data = json.loads(message.content.get('text')) if data.get('coin') == 'litecoin': Group('ltc-price').add(message.reply_channel) Group('btc-price').discard(message.reply_channel) message.channel_session['coin-group'] = 'ltc-price' elif data.get('coin') == 'bitcoin': Group('btc-price').add(message.reply_channel) Group('ltc-price').discard(message.reply_channel) message.channel_session['coin-group'] = 'btc-price' @channel_session_user def ws_disconnect(message): user_group = message.channel_session['coin-group'] Group(user_group).discard(message.reply_channel)
+ import json + from channels import Group - from channels.auth import channel_session_user, channel_session_user_from_http + from channels.auth import channel_session_user - @channel_session_user_from_http ? ---------- + @channel_session_user def ws_connect(message): + Group('btc-price').add(message.reply_channel) - Group('btc-price').add(message.reply_channel) + message.channel_session['coin-group'] = 'btc-price' message.reply_channel.send({ 'accept': True }) @channel_session_user + def ws_receive(message): + data = json.loads(message.content.get('text')) + + if data.get('coin') == 'litecoin': + Group('ltc-price').add(message.reply_channel) + Group('btc-price').discard(message.reply_channel) + + message.channel_session['coin-group'] = 'ltc-price' + + elif data.get('coin') == 'bitcoin': + Group('btc-price').add(message.reply_channel) + Group('ltc-price').discard(message.reply_channel) + + message.channel_session['coin-group'] = 'btc-price' + + + @channel_session_user def ws_disconnect(message): + user_group = message.channel_session['coin-group'] + - Group('btc-price').discard(message.reply_channel) ? ^^^^^ ----- + Group(user_group).discard(message.reply_channel) ? ^^^^^^^^^
a0ceb84519d1bf735979b3afdfdb8b17621d308b
froide/problem/admin.py
froide/problem/admin.py
from django.contrib import admin from django.utils.html import format_html from django.urls import reverse from django.utils.translation import gettext_lazy as _ from froide.helper.admin_utils import make_nullfilter from .models import ProblemReport class ProblemReportAdmin(admin.ModelAdmin): date_hierarchy = 'timestamp' raw_id_fields = ('message', 'user', 'moderator') list_filter = ( 'auto_submitted', 'resolved', 'kind', make_nullfilter('claimed', _('Claimed')), make_nullfilter('escalated', _('Escalated')), ) list_display = ( 'kind', 'timestamp', 'admin_link_message', 'auto_submitted', 'resolved', ) def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.select_related('message') return qs def admin_link_message(self, obj): return format_html('<a href="{}">{}</a>', reverse('admin:foirequest_foimessage_change', args=(obj.message_id,)), str(obj.message)) def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) if 'resolved' in form.changed_data and obj.resolved: sent = obj.resolve(request.user) if sent: self.message_user( request, _('User will be notified of resolution') ) admin.site.register(ProblemReport, ProblemReportAdmin)
from django.contrib import admin from django.utils.html import format_html from django.urls import reverse from django.utils.translation import gettext_lazy as _ from froide.helper.admin_utils import make_nullfilter from .models import ProblemReport class ProblemReportAdmin(admin.ModelAdmin): date_hierarchy = 'timestamp' raw_id_fields = ('message', 'user', 'moderator') list_filter = ( 'auto_submitted', 'resolved', 'kind', make_nullfilter('claimed', _('Claimed')), make_nullfilter('escalated', _('Escalated')), ) list_display = ( 'kind', 'timestamp', 'admin_link_message', 'auto_submitted', 'resolved', ) def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.select_related('message') return qs def admin_link_message(self, obj): return format_html('<a href="{}">{}</a>', reverse('admin:foirequest_foimessage_change', args=(obj.message_id,)), str(obj.message)) def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) if 'resolved' in form.changed_data and obj.resolved: sent = obj.resolve(request.user, resolution=obj.resolution) if sent: self.message_user( request, _('User will be notified of resolution') ) admin.site.register(ProblemReport, ProblemReportAdmin)
Fix overwriting resolution with empty text
Fix overwriting resolution with empty text
Python
mit
stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide
from django.contrib import admin from django.utils.html import format_html from django.urls import reverse from django.utils.translation import gettext_lazy as _ from froide.helper.admin_utils import make_nullfilter from .models import ProblemReport class ProblemReportAdmin(admin.ModelAdmin): date_hierarchy = 'timestamp' raw_id_fields = ('message', 'user', 'moderator') list_filter = ( 'auto_submitted', 'resolved', 'kind', make_nullfilter('claimed', _('Claimed')), make_nullfilter('escalated', _('Escalated')), ) list_display = ( 'kind', 'timestamp', 'admin_link_message', 'auto_submitted', 'resolved', ) def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.select_related('message') return qs def admin_link_message(self, obj): return format_html('<a href="{}">{}</a>', reverse('admin:foirequest_foimessage_change', args=(obj.message_id,)), str(obj.message)) def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) if 'resolved' in form.changed_data and obj.resolved: - sent = obj.resolve(request.user) + sent = obj.resolve(request.user, resolution=obj.resolution) if sent: self.message_user( request, _('User will be notified of resolution') ) admin.site.register(ProblemReport, ProblemReportAdmin)
Fix overwriting resolution with empty text
## Code Before: from django.contrib import admin from django.utils.html import format_html from django.urls import reverse from django.utils.translation import gettext_lazy as _ from froide.helper.admin_utils import make_nullfilter from .models import ProblemReport class ProblemReportAdmin(admin.ModelAdmin): date_hierarchy = 'timestamp' raw_id_fields = ('message', 'user', 'moderator') list_filter = ( 'auto_submitted', 'resolved', 'kind', make_nullfilter('claimed', _('Claimed')), make_nullfilter('escalated', _('Escalated')), ) list_display = ( 'kind', 'timestamp', 'admin_link_message', 'auto_submitted', 'resolved', ) def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.select_related('message') return qs def admin_link_message(self, obj): return format_html('<a href="{}">{}</a>', reverse('admin:foirequest_foimessage_change', args=(obj.message_id,)), str(obj.message)) def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) if 'resolved' in form.changed_data and obj.resolved: sent = obj.resolve(request.user) if sent: self.message_user( request, _('User will be notified of resolution') ) admin.site.register(ProblemReport, ProblemReportAdmin) ## Instruction: Fix overwriting resolution with empty text ## Code After: from django.contrib import admin from django.utils.html import format_html from django.urls import reverse from django.utils.translation import gettext_lazy as _ from froide.helper.admin_utils import make_nullfilter from .models import ProblemReport class ProblemReportAdmin(admin.ModelAdmin): date_hierarchy = 'timestamp' raw_id_fields = ('message', 'user', 'moderator') list_filter = ( 'auto_submitted', 'resolved', 'kind', make_nullfilter('claimed', _('Claimed')), make_nullfilter('escalated', _('Escalated')), ) list_display = ( 'kind', 'timestamp', 'admin_link_message', 'auto_submitted', 'resolved', ) def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.select_related('message') return qs def admin_link_message(self, obj): return format_html('<a href="{}">{}</a>', reverse('admin:foirequest_foimessage_change', args=(obj.message_id,)), str(obj.message)) def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) if 'resolved' in form.changed_data and obj.resolved: sent = obj.resolve(request.user, resolution=obj.resolution) if sent: self.message_user( request, _('User will be notified of resolution') ) admin.site.register(ProblemReport, ProblemReportAdmin)
from django.contrib import admin from django.utils.html import format_html from django.urls import reverse from django.utils.translation import gettext_lazy as _ from froide.helper.admin_utils import make_nullfilter from .models import ProblemReport class ProblemReportAdmin(admin.ModelAdmin): date_hierarchy = 'timestamp' raw_id_fields = ('message', 'user', 'moderator') list_filter = ( 'auto_submitted', 'resolved', 'kind', make_nullfilter('claimed', _('Claimed')), make_nullfilter('escalated', _('Escalated')), ) list_display = ( 'kind', 'timestamp', 'admin_link_message', 'auto_submitted', 'resolved', ) def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.select_related('message') return qs def admin_link_message(self, obj): return format_html('<a href="{}">{}</a>', reverse('admin:foirequest_foimessage_change', args=(obj.message_id,)), str(obj.message)) def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) if 'resolved' in form.changed_data and obj.resolved: - sent = obj.resolve(request.user) + sent = obj.resolve(request.user, resolution=obj.resolution) ? +++++++++++++++++++++++++++ if sent: self.message_user( request, _('User will be notified of resolution') ) admin.site.register(ProblemReport, ProblemReportAdmin)
ee5ab61090cef682f37631a8c3f5764bdda63772
xpserver_web/tests/unit/test_web.py
xpserver_web/tests/unit/test_web.py
from django.core.urlresolvers import resolve from xpserver_web.views import main def test_root_resolves_to_hello_world(): found = resolve('/') assert found.func == main
from django.core.urlresolvers import resolve from xpserver_web.views import main, register def test_root_resolves_to_main(): found = resolve('/') assert found.func == main def test_register_resolves_to_main(): found = resolve('/register/') assert found.func == register
Add unit test for register
Add unit test for register
Python
mit
xp2017-hackergarden/server,xp2017-hackergarden/server,xp2017-hackergarden/server,xp2017-hackergarden/server
from django.core.urlresolvers import resolve - from xpserver_web.views import main + from xpserver_web.views import main, register - def test_root_resolves_to_hello_world(): + def test_root_resolves_to_main(): found = resolve('/') assert found.func == main + def test_register_resolves_to_main(): + found = resolve('/register/') + assert found.func == register +
Add unit test for register
## Code Before: from django.core.urlresolvers import resolve from xpserver_web.views import main def test_root_resolves_to_hello_world(): found = resolve('/') assert found.func == main ## Instruction: Add unit test for register ## Code After: from django.core.urlresolvers import resolve from xpserver_web.views import main, register def test_root_resolves_to_main(): found = resolve('/') assert found.func == main def test_register_resolves_to_main(): found = resolve('/register/') assert found.func == register
from django.core.urlresolvers import resolve - from xpserver_web.views import main + from xpserver_web.views import main, register ? ++++++++++ - def test_root_resolves_to_hello_world(): ? ^^^^^^^^^^^ + def test_root_resolves_to_main(): ? ^^^^ found = resolve('/') assert found.func == main + + def test_register_resolves_to_main(): + found = resolve('/register/') + assert found.func == register
1a93c58e278712a2c52f36b098a570a7f48c7ef2
taOonja/game/views.py
taOonja/game/views.py
from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from game.models import * class LocationListView(ListView): template_name = 'game/location_list.html' context_object_name = 'location_list' def get_queryset(self): return Detail.objects.all() def get_context_data(self, **kwargs): context = super(LocationListView, self).get_context_data(**kwargs) return context class LocationDetailView(DetailView): model = Location context_object_name = 'location_detail' def get_context_data(self, **kwargs): context = super(LocationDetailView, self).get_context_data(**kwargs) context['detail_info'] = Detail.objects.all() return context
from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from game.models import Location class LocationListView(ListView): template_name = 'game/location_list.html' context_object_name = 'location_list' def get_queryset(self): return Location.objects.all() def get_context_data(self, **kwargs): context = super(LocationListView, self).get_context_data(**kwargs) return context class LocationDetailView(DetailView): model = Location context_object_name = 'location_detail' def get_context_data(self, **kwargs): l_pk = self.kwargs['pk'] Location.objects.filter(pk=l_pk).update(visited = True) context = super(LocationDetailView, self).get_context_data(**kwargs) return context
Change View According to model Changes
Change View According to model Changes
Python
mit
Javid-Izadfar/TaOonja,Javid-Izadfar/TaOonja,Javid-Izadfar/TaOonja
from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView - from game.models import * + from game.models import Location class LocationListView(ListView): template_name = 'game/location_list.html' context_object_name = 'location_list' def get_queryset(self): - return Detail.objects.all() + return Location.objects.all() def get_context_data(self, **kwargs): context = super(LocationListView, self).get_context_data(**kwargs) return context class LocationDetailView(DetailView): model = Location context_object_name = 'location_detail' - + def get_context_data(self, **kwargs): + l_pk = self.kwargs['pk'] + Location.objects.filter(pk=l_pk).update(visited = True) context = super(LocationDetailView, self).get_context_data(**kwargs) - context['detail_info'] = Detail.objects.all() return context
Change View According to model Changes
## Code Before: from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from game.models import * class LocationListView(ListView): template_name = 'game/location_list.html' context_object_name = 'location_list' def get_queryset(self): return Detail.objects.all() def get_context_data(self, **kwargs): context = super(LocationListView, self).get_context_data(**kwargs) return context class LocationDetailView(DetailView): model = Location context_object_name = 'location_detail' def get_context_data(self, **kwargs): context = super(LocationDetailView, self).get_context_data(**kwargs) context['detail_info'] = Detail.objects.all() return context ## Instruction: Change View According to model Changes ## Code After: from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from game.models import Location class LocationListView(ListView): template_name = 'game/location_list.html' context_object_name = 'location_list' def get_queryset(self): return Location.objects.all() def get_context_data(self, **kwargs): context = super(LocationListView, self).get_context_data(**kwargs) return context class LocationDetailView(DetailView): model = Location context_object_name = 'location_detail' def get_context_data(self, **kwargs): l_pk = self.kwargs['pk'] Location.objects.filter(pk=l_pk).update(visited = True) context = super(LocationDetailView, self).get_context_data(**kwargs) return context
from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView - from game.models import * ? ^ + from game.models import Location ? ^^^^^^^^ class LocationListView(ListView): template_name = 'game/location_list.html' context_object_name = 'location_list' def get_queryset(self): - return Detail.objects.all() ? ^^ - ^ + return Location.objects.all() ? ^^^^ ^^ def get_context_data(self, **kwargs): context = super(LocationListView, self).get_context_data(**kwargs) return context class LocationDetailView(DetailView): model = Location context_object_name = 'location_detail' - + def get_context_data(self, **kwargs): + l_pk = self.kwargs['pk'] + Location.objects.filter(pk=l_pk).update(visited = True) context = super(LocationDetailView, self).get_context_data(**kwargs) - context['detail_info'] = Detail.objects.all() return context
9b820aff6fc64ffa750dbf92a51d754f9c55ab79
froide/publicbody/search_indexes.py
froide/publicbody/search_indexes.py
from __future__ import print_function from django.conf import settings from haystack import indexes from celery_haystack.indexes import CelerySearchIndex from .models import PublicBody PUBLIC_BODY_BOOSTS = settings.FROIDE_CONFIG.get("public_body_boosts", {}) class PublicBodyIndex(CelerySearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name', boost=1.5) jurisdiction = indexes.CharField(model_attr='jurisdiction__name', default='') topic_auto = indexes.EdgeNgramField(model_attr='topic_name') topic_slug = indexes.CharField(model_attr='topic__slug') name_auto = indexes.EdgeNgramField(model_attr='name') url = indexes.CharField(model_attr='get_absolute_url') def get_model(self): return PublicBody def index_queryset(self, **kwargs): """Used when the entire index for model is updated.""" return self.get_model().objects.get_for_search_index() def prepare(self, obj): data = super(PublicBodyIndex, self).prepare(obj) if obj.classification in PUBLIC_BODY_BOOSTS: data['boost'] = PUBLIC_BODY_BOOSTS[obj.classification] print("Boosting %s at %f" % (obj, data['boost'])) return data
from __future__ import print_function from django.conf import settings from haystack import indexes from celery_haystack.indexes import CelerySearchIndex from .models import PublicBody PUBLIC_BODY_BOOSTS = settings.FROIDE_CONFIG.get("public_body_boosts", {}) class PublicBodyIndex(CelerySearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name', boost=1.5) jurisdiction = indexes.CharField(model_attr='jurisdiction__name', default='') topic_auto = indexes.EdgeNgramField(model_attr='topic__name', default='') topic_slug = indexes.CharField(model_attr='topic__slug', default='') name_auto = indexes.EdgeNgramField(model_attr='name') url = indexes.CharField(model_attr='get_absolute_url') def get_model(self): return PublicBody def index_queryset(self, **kwargs): """Used when the entire index for model is updated.""" return self.get_model().objects.get_for_search_index() def prepare(self, obj): data = super(PublicBodyIndex, self).prepare(obj) if obj.classification in PUBLIC_BODY_BOOSTS: data['boost'] = PUBLIC_BODY_BOOSTS[obj.classification] print("Boosting %s at %f" % (obj, data['boost'])) return data
Make topic_* field on public body search index optional
Make topic_* field on public body search index optional
Python
mit
okfse/froide,ryankanno/froide,fin/froide,catcosmo/froide,ryankanno/froide,stefanw/froide,okfse/froide,catcosmo/froide,okfse/froide,ryankanno/froide,stefanw/froide,ryankanno/froide,stefanw/froide,stefanw/froide,okfse/froide,okfse/froide,LilithWittmann/froide,catcosmo/froide,CodeforHawaii/froide,fin/froide,LilithWittmann/froide,catcosmo/froide,LilithWittmann/froide,CodeforHawaii/froide,LilithWittmann/froide,ryankanno/froide,catcosmo/froide,CodeforHawaii/froide,fin/froide,CodeforHawaii/froide,LilithWittmann/froide,CodeforHawaii/froide,stefanw/froide,fin/froide
from __future__ import print_function from django.conf import settings from haystack import indexes from celery_haystack.indexes import CelerySearchIndex from .models import PublicBody PUBLIC_BODY_BOOSTS = settings.FROIDE_CONFIG.get("public_body_boosts", {}) class PublicBodyIndex(CelerySearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name', boost=1.5) jurisdiction = indexes.CharField(model_attr='jurisdiction__name', default='') - topic_auto = indexes.EdgeNgramField(model_attr='topic_name') + topic_auto = indexes.EdgeNgramField(model_attr='topic__name', default='') - topic_slug = indexes.CharField(model_attr='topic__slug') + topic_slug = indexes.CharField(model_attr='topic__slug', default='') name_auto = indexes.EdgeNgramField(model_attr='name') url = indexes.CharField(model_attr='get_absolute_url') def get_model(self): return PublicBody def index_queryset(self, **kwargs): """Used when the entire index for model is updated.""" return self.get_model().objects.get_for_search_index() def prepare(self, obj): data = super(PublicBodyIndex, self).prepare(obj) if obj.classification in PUBLIC_BODY_BOOSTS: data['boost'] = PUBLIC_BODY_BOOSTS[obj.classification] print("Boosting %s at %f" % (obj, data['boost'])) return data
Make topic_* field on public body search index optional
## Code Before: from __future__ import print_function from django.conf import settings from haystack import indexes from celery_haystack.indexes import CelerySearchIndex from .models import PublicBody PUBLIC_BODY_BOOSTS = settings.FROIDE_CONFIG.get("public_body_boosts", {}) class PublicBodyIndex(CelerySearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name', boost=1.5) jurisdiction = indexes.CharField(model_attr='jurisdiction__name', default='') topic_auto = indexes.EdgeNgramField(model_attr='topic_name') topic_slug = indexes.CharField(model_attr='topic__slug') name_auto = indexes.EdgeNgramField(model_attr='name') url = indexes.CharField(model_attr='get_absolute_url') def get_model(self): return PublicBody def index_queryset(self, **kwargs): """Used when the entire index for model is updated.""" return self.get_model().objects.get_for_search_index() def prepare(self, obj): data = super(PublicBodyIndex, self).prepare(obj) if obj.classification in PUBLIC_BODY_BOOSTS: data['boost'] = PUBLIC_BODY_BOOSTS[obj.classification] print("Boosting %s at %f" % (obj, data['boost'])) return data ## Instruction: Make topic_* field on public body search index optional ## Code After: from __future__ import print_function from django.conf import settings from haystack import indexes from celery_haystack.indexes import CelerySearchIndex from .models import PublicBody PUBLIC_BODY_BOOSTS = settings.FROIDE_CONFIG.get("public_body_boosts", {}) class PublicBodyIndex(CelerySearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name', boost=1.5) jurisdiction = indexes.CharField(model_attr='jurisdiction__name', default='') topic_auto = indexes.EdgeNgramField(model_attr='topic__name', default='') topic_slug = indexes.CharField(model_attr='topic__slug', default='') name_auto = indexes.EdgeNgramField(model_attr='name') url = indexes.CharField(model_attr='get_absolute_url') def get_model(self): return PublicBody def index_queryset(self, **kwargs): """Used when the entire index for model is updated.""" return self.get_model().objects.get_for_search_index() def prepare(self, obj): data = super(PublicBodyIndex, self).prepare(obj) if obj.classification in PUBLIC_BODY_BOOSTS: data['boost'] = PUBLIC_BODY_BOOSTS[obj.classification] print("Boosting %s at %f" % (obj, data['boost'])) return data
from __future__ import print_function from django.conf import settings from haystack import indexes from celery_haystack.indexes import CelerySearchIndex from .models import PublicBody PUBLIC_BODY_BOOSTS = settings.FROIDE_CONFIG.get("public_body_boosts", {}) class PublicBodyIndex(CelerySearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name', boost=1.5) jurisdiction = indexes.CharField(model_attr='jurisdiction__name', default='') - topic_auto = indexes.EdgeNgramField(model_attr='topic_name') + topic_auto = indexes.EdgeNgramField(model_attr='topic__name', default='') ? + ++++++++++++ - topic_slug = indexes.CharField(model_attr='topic__slug') + topic_slug = indexes.CharField(model_attr='topic__slug', default='') ? ++++++++++++ name_auto = indexes.EdgeNgramField(model_attr='name') url = indexes.CharField(model_attr='get_absolute_url') def get_model(self): return PublicBody def index_queryset(self, **kwargs): """Used when the entire index for model is updated.""" return self.get_model().objects.get_for_search_index() def prepare(self, obj): data = super(PublicBodyIndex, self).prepare(obj) if obj.classification in PUBLIC_BODY_BOOSTS: data['boost'] = PUBLIC_BODY_BOOSTS[obj.classification] print("Boosting %s at %f" % (obj, data['boost'])) return data
8c18b43880368bba654e715c2da197f7a6d9e41a
tests/test_carddb.py
tests/test_carddb.py
from hearthstone.enums import CardType, GameTag, Rarity import utils CARDS = utils.fireplace.cards.db def test_all_tags_known(): """ Iterate through the card database and check that all specified GameTags are known in hearthstone.enums.GameTag """ unknown_tags = set() known_tags = list(GameTag) known_rarities = list(Rarity) # Check the db loaded correctly assert utils.fireplace.cards.db for card in CARDS.values(): card_tags = [int(e.attrib["enumID"]) for e in card.xml.findall("./Tag")] for tag in card_tags: # We have fake tags in fireplace.enums which are always negative if tag not in known_tags and tag > 0: unknown_tags.add(tag) # Test rarities as well (cf. TB_BlingBrawl_Blade1e in 10956...) assert card.rarity in known_rarities assert not unknown_tags def test_play_scripts(): for card in CARDS.values(): if card.scripts.activate: assert card.type == CardType.HERO_POWER elif card.scripts.play: assert card.type not in (CardType.HERO, CardType.HERO_POWER, CardType.ENCHANTMENT)
from hearthstone.enums import CardType, GameTag, Rarity import utils CARDS = utils.fireplace.cards.db def test_all_tags_known(): """ Iterate through the card database and check that all specified GameTags are known in hearthstone.enums.GameTag """ unknown_tags = set() known_tags = list(GameTag) known_rarities = list(Rarity) # Check the db loaded correctly assert utils.fireplace.cards.db for card in CARDS.values(): for tag in card.tags: # We have fake tags in fireplace.enums which are always negative if tag not in known_tags and tag > 0: unknown_tags.add(tag) # Test rarities as well (cf. TB_BlingBrawl_Blade1e in 10956...) assert card.rarity in known_rarities assert not unknown_tags def test_play_scripts(): for card in CARDS.values(): if card.scripts.activate: assert card.type == CardType.HERO_POWER elif card.scripts.play: assert card.type not in (CardType.HERO, CardType.HERO_POWER, CardType.ENCHANTMENT)
Simplify the CardDB test check for tags
Simplify the CardDB test check for tags
Python
agpl-3.0
smallnamespace/fireplace,NightKev/fireplace,smallnamespace/fireplace,beheh/fireplace,Ragowit/fireplace,Ragowit/fireplace,jleclanche/fireplace
from hearthstone.enums import CardType, GameTag, Rarity import utils CARDS = utils.fireplace.cards.db def test_all_tags_known(): """ Iterate through the card database and check that all specified GameTags are known in hearthstone.enums.GameTag """ unknown_tags = set() known_tags = list(GameTag) known_rarities = list(Rarity) # Check the db loaded correctly assert utils.fireplace.cards.db for card in CARDS.values(): - card_tags = [int(e.attrib["enumID"]) for e in card.xml.findall("./Tag")] - for tag in card_tags: + for tag in card.tags: # We have fake tags in fireplace.enums which are always negative if tag not in known_tags and tag > 0: unknown_tags.add(tag) # Test rarities as well (cf. TB_BlingBrawl_Blade1e in 10956...) assert card.rarity in known_rarities assert not unknown_tags def test_play_scripts(): for card in CARDS.values(): if card.scripts.activate: assert card.type == CardType.HERO_POWER elif card.scripts.play: assert card.type not in (CardType.HERO, CardType.HERO_POWER, CardType.ENCHANTMENT)
Simplify the CardDB test check for tags
## Code Before: from hearthstone.enums import CardType, GameTag, Rarity import utils CARDS = utils.fireplace.cards.db def test_all_tags_known(): """ Iterate through the card database and check that all specified GameTags are known in hearthstone.enums.GameTag """ unknown_tags = set() known_tags = list(GameTag) known_rarities = list(Rarity) # Check the db loaded correctly assert utils.fireplace.cards.db for card in CARDS.values(): card_tags = [int(e.attrib["enumID"]) for e in card.xml.findall("./Tag")] for tag in card_tags: # We have fake tags in fireplace.enums which are always negative if tag not in known_tags and tag > 0: unknown_tags.add(tag) # Test rarities as well (cf. TB_BlingBrawl_Blade1e in 10956...) assert card.rarity in known_rarities assert not unknown_tags def test_play_scripts(): for card in CARDS.values(): if card.scripts.activate: assert card.type == CardType.HERO_POWER elif card.scripts.play: assert card.type not in (CardType.HERO, CardType.HERO_POWER, CardType.ENCHANTMENT) ## Instruction: Simplify the CardDB test check for tags ## Code After: from hearthstone.enums import CardType, GameTag, Rarity import utils CARDS = utils.fireplace.cards.db def test_all_tags_known(): """ Iterate through the card database and check that all specified GameTags are known in hearthstone.enums.GameTag """ unknown_tags = set() known_tags = list(GameTag) known_rarities = list(Rarity) # Check the db loaded correctly assert utils.fireplace.cards.db for card in CARDS.values(): for tag in card.tags: # We have fake tags in fireplace.enums which are always negative if tag not in known_tags and tag > 0: unknown_tags.add(tag) # Test rarities as well (cf. TB_BlingBrawl_Blade1e in 10956...) assert card.rarity in known_rarities assert not unknown_tags def test_play_scripts(): for card in CARDS.values(): if card.scripts.activate: assert card.type == CardType.HERO_POWER elif card.scripts.play: assert card.type not in (CardType.HERO, CardType.HERO_POWER, CardType.ENCHANTMENT)
from hearthstone.enums import CardType, GameTag, Rarity import utils CARDS = utils.fireplace.cards.db def test_all_tags_known(): """ Iterate through the card database and check that all specified GameTags are known in hearthstone.enums.GameTag """ unknown_tags = set() known_tags = list(GameTag) known_rarities = list(Rarity) # Check the db loaded correctly assert utils.fireplace.cards.db for card in CARDS.values(): - card_tags = [int(e.attrib["enumID"]) for e in card.xml.findall("./Tag")] - for tag in card_tags: ? ^ + for tag in card.tags: ? ^ # We have fake tags in fireplace.enums which are always negative if tag not in known_tags and tag > 0: unknown_tags.add(tag) # Test rarities as well (cf. TB_BlingBrawl_Blade1e in 10956...) assert card.rarity in known_rarities assert not unknown_tags def test_play_scripts(): for card in CARDS.values(): if card.scripts.activate: assert card.type == CardType.HERO_POWER elif card.scripts.play: assert card.type not in (CardType.HERO, CardType.HERO_POWER, CardType.ENCHANTMENT)
31632158c7882e20122a91643aebfbba7ae602e7
tests/test_modules/git_test.py
tests/test_modules/git_test.py
from subprocess import call, check_output class TestGit: """ Test that the user has a modern version of git installed """
from subprocess import call, check_output class TestGit: """ Test that the user has a modern version of git installed """ def git_version(self): """ returns a tuple with execution of git --version """ exit_code = call(["git", "--version"]) output = check_output(["git", "--version"]).decode("utf-8").lstrip().rstrip() return (output, exit_code) def test_git_version(self): """ tests the output from git_version() """ assert self.git_version()[1] == 0 assert self.git_version()[0].index('git version') >= 0
Add tests for git installation
Add tests for git installation
Python
bsd-3-clause
DevBlend/zenias,DevBlend/zenias,DevBlend/DevBlend,DevBlend/zenias,DevBlend/DevBlend,DevBlend/DevBlend,DevBlend/DevBlend,byteknacker/fcc-python-vagrant,DevBlend/zenias,DevBlend/DevBlend,byteknacker/fcc-python-vagrant,DevBlend/zenias,DevBlend/DevBlend,DevBlend/zenias
from subprocess import call, check_output class TestGit: """ Test that the user has a modern version of git installed """ + + def git_version(self): + """ returns a tuple with execution of git --version """ + exit_code = call(["git", "--version"]) + output = check_output(["git", "--version"]).decode("utf-8").lstrip().rstrip() + return (output, exit_code) + + def test_git_version(self): + """ tests the output from git_version() """ + assert self.git_version()[1] == 0 + assert self.git_version()[0].index('git version') >= 0
Add tests for git installation
## Code Before: from subprocess import call, check_output class TestGit: """ Test that the user has a modern version of git installed """ ## Instruction: Add tests for git installation ## Code After: from subprocess import call, check_output class TestGit: """ Test that the user has a modern version of git installed """ def git_version(self): """ returns a tuple with execution of git --version """ exit_code = call(["git", "--version"]) output = check_output(["git", "--version"]).decode("utf-8").lstrip().rstrip() return (output, exit_code) def test_git_version(self): """ tests the output from git_version() """ assert self.git_version()[1] == 0 assert self.git_version()[0].index('git version') >= 0
from subprocess import call, check_output class TestGit: """ Test that the user has a modern version of git installed """ + + def git_version(self): + """ returns a tuple with execution of git --version """ + exit_code = call(["git", "--version"]) + output = check_output(["git", "--version"]).decode("utf-8").lstrip().rstrip() + return (output, exit_code) + + def test_git_version(self): + """ tests the output from git_version() """ + assert self.git_version()[1] == 0 + assert self.git_version()[0].index('git version') >= 0
49bed20629d4b2ef50026700b98694da4c2ce224
tasks.py
tasks.py
"""Useful task commands for development and maintenance.""" from invoke import run, task @task def clean(): """Clean the project directory of unwanted files and directories.""" run('rm -rf gmusicapi_scripts.egg-info') run('rm -rf .coverage') run('rm -rf .tox') run('rm -rf .cache') run('rm -rf build/') run('rm -rf dist/') run('rm -rf site/') run('find . -name *.pyc -delete') run('find . -name *.pyo -delete') run('find . -name __pycache__ -delete -depth') run('find . -name *~ -delete') @task(clean) def build(): """Build sdist and bdist_wheel distributions.""" run('python setup.py sdist bdist_wheel') @task(build) def deploy(): """Build and upload gmusicapi_scripts distributions.""" upload() @task def upload(): """Upload gmusicapi_scripts distributions using twine.""" run('twine upload dist/*')
"""Useful task commands for development and maintenance.""" from invoke import run, task @task def clean(): """Clean the project directory of unwanted files and directories.""" run('rm -rf gmusicapi_scripts.egg-info') run('rm -rf .coverage') run('rm -rf .tox') run('rm -rf .cache') run('rm -rf build/') run('rm -rf dist/') run('rm -rf site/') run('find . -name *.pyc -delete') run('find . -name *.pyo -delete') run('find . -name __pycache__ -delete -depth') run('find . -name *~ -delete') @task(clean) def build(): """Build sdist and bdist_wheel distributions.""" run('python setup.py sdist bdist_wheel') @task(build) def deploy(): """Build and upload gmusicapi_scripts distributions.""" upload() @task def docs(test=False): """"Build the gmusicapi_scripts docs.""" if test: run('mkdocs serve') else: run('mkdocs gh-deploy --clean') @task def upload(): """Upload gmusicapi_scripts distributions using twine.""" run('twine upload dist/*')
Add task for building docs
Add task for building docs
Python
mit
thebigmunch/gmusicapi-scripts
"""Useful task commands for development and maintenance.""" from invoke import run, task @task def clean(): """Clean the project directory of unwanted files and directories.""" run('rm -rf gmusicapi_scripts.egg-info') run('rm -rf .coverage') run('rm -rf .tox') run('rm -rf .cache') run('rm -rf build/') run('rm -rf dist/') run('rm -rf site/') run('find . -name *.pyc -delete') run('find . -name *.pyo -delete') run('find . -name __pycache__ -delete -depth') run('find . -name *~ -delete') @task(clean) def build(): """Build sdist and bdist_wheel distributions.""" run('python setup.py sdist bdist_wheel') @task(build) def deploy(): """Build and upload gmusicapi_scripts distributions.""" upload() @task + def docs(test=False): + """"Build the gmusicapi_scripts docs.""" + + if test: + run('mkdocs serve') + else: + run('mkdocs gh-deploy --clean') + + + @task def upload(): """Upload gmusicapi_scripts distributions using twine.""" run('twine upload dist/*')
Add task for building docs
## Code Before: """Useful task commands for development and maintenance.""" from invoke import run, task @task def clean(): """Clean the project directory of unwanted files and directories.""" run('rm -rf gmusicapi_scripts.egg-info') run('rm -rf .coverage') run('rm -rf .tox') run('rm -rf .cache') run('rm -rf build/') run('rm -rf dist/') run('rm -rf site/') run('find . -name *.pyc -delete') run('find . -name *.pyo -delete') run('find . -name __pycache__ -delete -depth') run('find . -name *~ -delete') @task(clean) def build(): """Build sdist and bdist_wheel distributions.""" run('python setup.py sdist bdist_wheel') @task(build) def deploy(): """Build and upload gmusicapi_scripts distributions.""" upload() @task def upload(): """Upload gmusicapi_scripts distributions using twine.""" run('twine upload dist/*') ## Instruction: Add task for building docs ## Code After: """Useful task commands for development and maintenance.""" from invoke import run, task @task def clean(): """Clean the project directory of unwanted files and directories.""" run('rm -rf gmusicapi_scripts.egg-info') run('rm -rf .coverage') run('rm -rf .tox') run('rm -rf .cache') run('rm -rf build/') run('rm -rf dist/') run('rm -rf site/') run('find . -name *.pyc -delete') run('find . -name *.pyo -delete') run('find . -name __pycache__ -delete -depth') run('find . -name *~ -delete') @task(clean) def build(): """Build sdist and bdist_wheel distributions.""" run('python setup.py sdist bdist_wheel') @task(build) def deploy(): """Build and upload gmusicapi_scripts distributions.""" upload() @task def docs(test=False): """"Build the gmusicapi_scripts docs.""" if test: run('mkdocs serve') else: run('mkdocs gh-deploy --clean') @task def upload(): """Upload gmusicapi_scripts distributions using twine.""" run('twine upload dist/*')
"""Useful task commands for development and maintenance.""" from invoke import run, task @task def clean(): """Clean the project directory of unwanted files and directories.""" run('rm -rf gmusicapi_scripts.egg-info') run('rm -rf .coverage') run('rm -rf .tox') run('rm -rf .cache') run('rm -rf build/') run('rm -rf dist/') run('rm -rf site/') run('find . -name *.pyc -delete') run('find . -name *.pyo -delete') run('find . -name __pycache__ -delete -depth') run('find . -name *~ -delete') @task(clean) def build(): """Build sdist and bdist_wheel distributions.""" run('python setup.py sdist bdist_wheel') @task(build) def deploy(): """Build and upload gmusicapi_scripts distributions.""" upload() @task + def docs(test=False): + """"Build the gmusicapi_scripts docs.""" + + if test: + run('mkdocs serve') + else: + run('mkdocs gh-deploy --clean') + + + @task def upload(): """Upload gmusicapi_scripts distributions using twine.""" run('twine upload dist/*')
e201f3179388414d0ac6fc9d3a641dda3a5930be
snafu/installations.py
snafu/installations.py
import contextlib import itertools import os import pathlib import re import subprocess import attr @attr.s class Installation: path = attr.ib(convert=pathlib.Path) @property def python(self): return self.path.joinpath('python.exe') @property def scripts_dir(self): return self.path.joinpath('Scripts') @property def pip(self): return self.scripts_dir.joinpath('pip.exe') def get_version_info(self): output = subprocess.check_output( [str(self.python), '--version'], encoding='ascii', ).strip() match = re.match(r'^Python (\d+)\.(\d+)\.(\d+)$', output) return match.groups() def find_script(self, name): names = itertools.chain([name], ( '{}{}'.format(name, ext) for ext in os.environ['PATHEXT'].split(';') )) for name in names: with contextlib.suppress(FileNotFoundError): return self.scripts_dir.joinpath(name).resolve() raise FileNotFoundError(name)
import contextlib import itertools import os import pathlib import re import subprocess import attr @attr.s class Installation: path = attr.ib(convert=pathlib.Path) @property def python(self): return self.path.joinpath('python.exe') @property def scripts_dir(self): return self.path.joinpath('Scripts') @property def pip(self): return self.scripts_dir.joinpath('pip.exe') def get_version_info(self): output = subprocess.check_output( [str(self.python), '--version'], encoding='ascii', ).strip() match = re.match(r'^Python (\d+)\.(\d+)\.(\d+)$', output) return tuple(int(x) for x in match.groups()) def find_script(self, name): names = itertools.chain([name], ( '{}{}'.format(name, ext) for ext in os.environ['PATHEXT'].split(';') )) for name in names: with contextlib.suppress(FileNotFoundError): return self.scripts_dir.joinpath(name).resolve() raise FileNotFoundError(name)
Fix installation version info type
Fix installation version info type
Python
isc
uranusjr/snafu,uranusjr/snafu
import contextlib import itertools import os import pathlib import re import subprocess import attr @attr.s class Installation: path = attr.ib(convert=pathlib.Path) @property def python(self): return self.path.joinpath('python.exe') @property def scripts_dir(self): return self.path.joinpath('Scripts') @property def pip(self): return self.scripts_dir.joinpath('pip.exe') def get_version_info(self): output = subprocess.check_output( [str(self.python), '--version'], encoding='ascii', ).strip() match = re.match(r'^Python (\d+)\.(\d+)\.(\d+)$', output) - return match.groups() + return tuple(int(x) for x in match.groups()) def find_script(self, name): names = itertools.chain([name], ( '{}{}'.format(name, ext) for ext in os.environ['PATHEXT'].split(';') )) for name in names: with contextlib.suppress(FileNotFoundError): return self.scripts_dir.joinpath(name).resolve() raise FileNotFoundError(name)
Fix installation version info type
## Code Before: import contextlib import itertools import os import pathlib import re import subprocess import attr @attr.s class Installation: path = attr.ib(convert=pathlib.Path) @property def python(self): return self.path.joinpath('python.exe') @property def scripts_dir(self): return self.path.joinpath('Scripts') @property def pip(self): return self.scripts_dir.joinpath('pip.exe') def get_version_info(self): output = subprocess.check_output( [str(self.python), '--version'], encoding='ascii', ).strip() match = re.match(r'^Python (\d+)\.(\d+)\.(\d+)$', output) return match.groups() def find_script(self, name): names = itertools.chain([name], ( '{}{}'.format(name, ext) for ext in os.environ['PATHEXT'].split(';') )) for name in names: with contextlib.suppress(FileNotFoundError): return self.scripts_dir.joinpath(name).resolve() raise FileNotFoundError(name) ## Instruction: Fix installation version info type ## Code After: import contextlib import itertools import os import pathlib import re import subprocess import attr @attr.s class Installation: path = attr.ib(convert=pathlib.Path) @property def python(self): return self.path.joinpath('python.exe') @property def scripts_dir(self): return self.path.joinpath('Scripts') @property def pip(self): return self.scripts_dir.joinpath('pip.exe') def get_version_info(self): output = subprocess.check_output( [str(self.python), '--version'], encoding='ascii', ).strip() match = re.match(r'^Python (\d+)\.(\d+)\.(\d+)$', output) return tuple(int(x) for x in match.groups()) def find_script(self, name): names = itertools.chain([name], ( '{}{}'.format(name, ext) for ext in os.environ['PATHEXT'].split(';') )) for name in names: with contextlib.suppress(FileNotFoundError): return self.scripts_dir.joinpath(name).resolve() raise FileNotFoundError(name)
import contextlib import itertools import os import pathlib import re import subprocess import attr @attr.s class Installation: path = attr.ib(convert=pathlib.Path) @property def python(self): return self.path.joinpath('python.exe') @property def scripts_dir(self): return self.path.joinpath('Scripts') @property def pip(self): return self.scripts_dir.joinpath('pip.exe') def get_version_info(self): output = subprocess.check_output( [str(self.python), '--version'], encoding='ascii', ).strip() match = re.match(r'^Python (\d+)\.(\d+)\.(\d+)$', output) - return match.groups() + return tuple(int(x) for x in match.groups()) def find_script(self, name): names = itertools.chain([name], ( '{}{}'.format(name, ext) for ext in os.environ['PATHEXT'].split(';') )) for name in names: with contextlib.suppress(FileNotFoundError): return self.scripts_dir.joinpath(name).resolve() raise FileNotFoundError(name)
bf6f77d90c3749983eb0b5358fb2f9fedb7d53da
app/main.py
app/main.py
import spark import motion from bot import process_command from config import config from flask import Flask from flask import request from flask import jsonify from threading import Thread import time import sys app = Flask(__name__) def on_motion_detected(): print("motion detected!") def run_motion_detection(): print("hello") motion.detector_on(on_motion_detected) def run_flask_server(): app.run(host='0.0.0.0', port=8181) @app.route("/", methods=["post"]) def index(): # Parse request webhook_req = request.get_json() message = spark.get_message(message_id=webhook_req['data']['id'], bearer=config["bearer"]) if message["personEmail"] != config["bot_email"]: res = process_command(message["command"]) if res["response_required"]: spark.send_message(message["roomId"], res["data"], config["bearer"]) return jsonify({}) if __name__ == "__main__": motion_thread = Thread(target = run_motion_detection) flask_thread = Thread(target = run_flask_server) motion_thread.daemon = True flask_thread.daemon = True motion_thread.start() flask_thread.start()
import spark import motion from bot import process_command from config import config from flask import Flask from flask import request from flask import jsonify from threading import Thread import time import sys app = Flask(__name__) def on_motion_detected(): print("motion detected!") def run_motion_detection(): print("hello") motion.detector_on(on_motion_detected) def run_flask_server(): app.run(host='0.0.0.0', port=8181) @app.route("/", methods=["post"]) def index(): # Parse request webhook_req = request.get_json() message = spark.get_message(message_id=webhook_req['data']['id'], bearer=config["bearer"]) if message["personEmail"] != config["bot_email"]: res = process_command(message["command"]) if res["response_required"]: spark.send_message(message["roomId"], res["data"], config["bearer"]) return jsonify({}) if __name__ == "__main__": motion_thread = Thread(target = run_motion_detection) motion_thread.daemon = True motion_thread.start() app.run(host='0.0.0.0', port=8080)
Use Python 3.6 compatible API for threading
Use Python 3.6 compatible API for threading
Python
mit
alwye/spark-pi,alwye/spark-pi
import spark import motion from bot import process_command from config import config from flask import Flask from flask import request from flask import jsonify from threading import Thread import time import sys app = Flask(__name__) def on_motion_detected(): print("motion detected!") def run_motion_detection(): print("hello") motion.detector_on(on_motion_detected) def run_flask_server(): app.run(host='0.0.0.0', port=8181) @app.route("/", methods=["post"]) def index(): # Parse request webhook_req = request.get_json() message = spark.get_message(message_id=webhook_req['data']['id'], bearer=config["bearer"]) if message["personEmail"] != config["bot_email"]: res = process_command(message["command"]) if res["response_required"]: spark.send_message(message["roomId"], res["data"], config["bearer"]) return jsonify({}) if __name__ == "__main__": motion_thread = Thread(target = run_motion_detection) - flask_thread = Thread(target = run_flask_server) motion_thread.daemon = True - flask_thread.daemon = True motion_thread.start() - flask_thread.start() + app.run(host='0.0.0.0', port=8080)
Use Python 3.6 compatible API for threading
## Code Before: import spark import motion from bot import process_command from config import config from flask import Flask from flask import request from flask import jsonify from threading import Thread import time import sys app = Flask(__name__) def on_motion_detected(): print("motion detected!") def run_motion_detection(): print("hello") motion.detector_on(on_motion_detected) def run_flask_server(): app.run(host='0.0.0.0', port=8181) @app.route("/", methods=["post"]) def index(): # Parse request webhook_req = request.get_json() message = spark.get_message(message_id=webhook_req['data']['id'], bearer=config["bearer"]) if message["personEmail"] != config["bot_email"]: res = process_command(message["command"]) if res["response_required"]: spark.send_message(message["roomId"], res["data"], config["bearer"]) return jsonify({}) if __name__ == "__main__": motion_thread = Thread(target = run_motion_detection) flask_thread = Thread(target = run_flask_server) motion_thread.daemon = True flask_thread.daemon = True motion_thread.start() flask_thread.start() ## Instruction: Use Python 3.6 compatible API for threading ## Code After: import spark import motion from bot import process_command from config import config from flask import Flask from flask import request from flask import jsonify from threading import Thread import time import sys app = Flask(__name__) def on_motion_detected(): print("motion detected!") def run_motion_detection(): print("hello") motion.detector_on(on_motion_detected) def run_flask_server(): app.run(host='0.0.0.0', port=8181) @app.route("/", methods=["post"]) def index(): # Parse request webhook_req = request.get_json() message = spark.get_message(message_id=webhook_req['data']['id'], bearer=config["bearer"]) if message["personEmail"] != config["bot_email"]: res = process_command(message["command"]) if res["response_required"]: spark.send_message(message["roomId"], res["data"], config["bearer"]) return jsonify({}) if __name__ == "__main__": motion_thread = Thread(target = run_motion_detection) motion_thread.daemon = True motion_thread.start() app.run(host='0.0.0.0', port=8080)
import spark import motion from bot import process_command from config import config from flask import Flask from flask import request from flask import jsonify from threading import Thread import time import sys app = Flask(__name__) def on_motion_detected(): print("motion detected!") def run_motion_detection(): print("hello") motion.detector_on(on_motion_detected) def run_flask_server(): app.run(host='0.0.0.0', port=8181) @app.route("/", methods=["post"]) def index(): # Parse request webhook_req = request.get_json() message = spark.get_message(message_id=webhook_req['data']['id'], bearer=config["bearer"]) if message["personEmail"] != config["bot_email"]: res = process_command(message["command"]) if res["response_required"]: spark.send_message(message["roomId"], res["data"], config["bearer"]) return jsonify({}) if __name__ == "__main__": motion_thread = Thread(target = run_motion_detection) - flask_thread = Thread(target = run_flask_server) motion_thread.daemon = True - flask_thread.daemon = True motion_thread.start() - flask_thread.start() + app.run(host='0.0.0.0', port=8080)
d981b34dc18236cf857d1249629b6437005e073f
openmc/capi/__init__.py
openmc/capi/__init__.py
from ctypes import CDLL import os import sys from warnings import warn import pkg_resources # Determine shared-library suffix if sys.platform == 'darwin': _suffix = 'dylib' else: _suffix = 'so' if os.environ.get('READTHEDOCS', None) != 'True': # Open shared library _filename = pkg_resources.resource_filename( __name__, 'libopenmc.{}'.format(_suffix)) _dll = CDLL(_filename) else: # For documentation builds, we don't actually have the shared library # available. Instead, we create a mock object so that when the modules # within the openmc.capi package try to configure arguments and return # values for symbols, no errors occur try: from unittest.mock import Mock except ImportError: from mock import Mock _dll = Mock() from .error import * from .core import * from .nuclide import * from .material import * from .cell import * from .filter import * from .tally import * from .settings import settings warn("The Python bindings to OpenMC's C API are still unstable " "and may change substantially in future releases.", FutureWarning)
from ctypes import CDLL import os import sys import pkg_resources # Determine shared-library suffix if sys.platform == 'darwin': _suffix = 'dylib' else: _suffix = 'so' if os.environ.get('READTHEDOCS', None) != 'True': # Open shared library _filename = pkg_resources.resource_filename( __name__, 'libopenmc.{}'.format(_suffix)) _dll = CDLL(_filename) else: # For documentation builds, we don't actually have the shared library # available. Instead, we create a mock object so that when the modules # within the openmc.capi package try to configure arguments and return # values for symbols, no errors occur from unittest.mock import Mock _dll = Mock() from .error import * from .core import * from .nuclide import * from .material import * from .cell import * from .filter import * from .tally import * from .settings import settings
Remove FutureWarning for capi import
Remove FutureWarning for capi import
Python
mit
mit-crpg/openmc,shikhar413/openmc,smharper/openmc,amandalund/openmc,amandalund/openmc,wbinventor/openmc,walshjon/openmc,amandalund/openmc,paulromano/openmc,mit-crpg/openmc,walshjon/openmc,paulromano/openmc,liangjg/openmc,mit-crpg/openmc,johnnyliu27/openmc,amandalund/openmc,walshjon/openmc,shikhar413/openmc,shikhar413/openmc,mit-crpg/openmc,smharper/openmc,johnnyliu27/openmc,paulromano/openmc,smharper/openmc,wbinventor/openmc,wbinventor/openmc,liangjg/openmc,johnnyliu27/openmc,shikhar413/openmc,paulromano/openmc,walshjon/openmc,johnnyliu27/openmc,liangjg/openmc,liangjg/openmc,wbinventor/openmc,smharper/openmc
from ctypes import CDLL import os import sys - from warnings import warn import pkg_resources # Determine shared-library suffix if sys.platform == 'darwin': _suffix = 'dylib' else: _suffix = 'so' if os.environ.get('READTHEDOCS', None) != 'True': # Open shared library _filename = pkg_resources.resource_filename( __name__, 'libopenmc.{}'.format(_suffix)) _dll = CDLL(_filename) else: # For documentation builds, we don't actually have the shared library # available. Instead, we create a mock object so that when the modules # within the openmc.capi package try to configure arguments and return # values for symbols, no errors occur - try: - from unittest.mock import Mock + from unittest.mock import Mock - except ImportError: - from mock import Mock _dll = Mock() from .error import * from .core import * from .nuclide import * from .material import * from .cell import * from .filter import * from .tally import * from .settings import settings - warn("The Python bindings to OpenMC's C API are still unstable " - "and may change substantially in future releases.", FutureWarning) -
Remove FutureWarning for capi import
## Code Before: from ctypes import CDLL import os import sys from warnings import warn import pkg_resources # Determine shared-library suffix if sys.platform == 'darwin': _suffix = 'dylib' else: _suffix = 'so' if os.environ.get('READTHEDOCS', None) != 'True': # Open shared library _filename = pkg_resources.resource_filename( __name__, 'libopenmc.{}'.format(_suffix)) _dll = CDLL(_filename) else: # For documentation builds, we don't actually have the shared library # available. Instead, we create a mock object so that when the modules # within the openmc.capi package try to configure arguments and return # values for symbols, no errors occur try: from unittest.mock import Mock except ImportError: from mock import Mock _dll = Mock() from .error import * from .core import * from .nuclide import * from .material import * from .cell import * from .filter import * from .tally import * from .settings import settings warn("The Python bindings to OpenMC's C API are still unstable " "and may change substantially in future releases.", FutureWarning) ## Instruction: Remove FutureWarning for capi import ## Code After: from ctypes import CDLL import os import sys import pkg_resources # Determine shared-library suffix if sys.platform == 'darwin': _suffix = 'dylib' else: _suffix = 'so' if os.environ.get('READTHEDOCS', None) != 'True': # Open shared library _filename = pkg_resources.resource_filename( __name__, 'libopenmc.{}'.format(_suffix)) _dll = CDLL(_filename) else: # For documentation builds, we don't actually have the shared library # available. Instead, we create a mock object so that when the modules # within the openmc.capi package try to configure arguments and return # values for symbols, no errors occur from unittest.mock import Mock _dll = Mock() from .error import * from .core import * from .nuclide import * from .material import * from .cell import * from .filter import * from .tally import * from .settings import settings
from ctypes import CDLL import os import sys - from warnings import warn import pkg_resources # Determine shared-library suffix if sys.platform == 'darwin': _suffix = 'dylib' else: _suffix = 'so' if os.environ.get('READTHEDOCS', None) != 'True': # Open shared library _filename = pkg_resources.resource_filename( __name__, 'libopenmc.{}'.format(_suffix)) _dll = CDLL(_filename) else: # For documentation builds, we don't actually have the shared library # available. Instead, we create a mock object so that when the modules # within the openmc.capi package try to configure arguments and return # values for symbols, no errors occur - try: - from unittest.mock import Mock ? ---- + from unittest.mock import Mock - except ImportError: - from mock import Mock _dll = Mock() from .error import * from .core import * from .nuclide import * from .material import * from .cell import * from .filter import * from .tally import * from .settings import settings - - warn("The Python bindings to OpenMC's C API are still unstable " - "and may change substantially in future releases.", FutureWarning)
3609df9044fd72008234bae9145487f315096fcd
hcalendar/__init__.py
hcalendar/__init__.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals """ python-hcalendar is a basic hCalendar parser """ __version_info__ = { 'major': 0, 'minor': 2, 'micro': 0, 'releaselevel': 'final', } def get_version(): """ Return the formatted version information """ vers = ["%(major)i.%(minor)i" % __version_info__, ] if __version_info__['micro']: vers.append(".%(micro)i" % __version_info__) if __version_info__['releaselevel'] != 'final': vers.append('%(releaselevel)s' % __version_info__) return ''.join(vers) __version__ = get_version() try: from .hcalendar import hCalendar except ImportError: pass __all__ = ['hCalendar']
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __version_info__ = { 'major': 0, 'minor': 2, 'micro': 0, 'releaselevel': 'final', } def get_version(): """ Return the formatted version information """ vers = ["%(major)i.%(minor)i" % __version_info__, ] if __version_info__['micro']: vers.append(".%(micro)i" % __version_info__) if __version_info__['releaselevel'] != 'final': vers.append('%(releaselevel)s' % __version_info__) return ''.join(vers) __version__ = get_version() try: from .hcalendar import hCalendar except ImportError: pass __all__ = ['hCalendar']
Fix hcalendar module __doc__ missing
Fix hcalendar module __doc__ missing
Python
mit
mback2k/python-hcalendar
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals - - """ - python-hcalendar is a basic hCalendar parser - """ __version_info__ = { 'major': 0, 'minor': 2, 'micro': 0, 'releaselevel': 'final', } def get_version(): """ Return the formatted version information """ vers = ["%(major)i.%(minor)i" % __version_info__, ] if __version_info__['micro']: vers.append(".%(micro)i" % __version_info__) if __version_info__['releaselevel'] != 'final': vers.append('%(releaselevel)s' % __version_info__) return ''.join(vers) __version__ = get_version() try: from .hcalendar import hCalendar except ImportError: pass __all__ = ['hCalendar']
Fix hcalendar module __doc__ missing
## Code Before: from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals """ python-hcalendar is a basic hCalendar parser """ __version_info__ = { 'major': 0, 'minor': 2, 'micro': 0, 'releaselevel': 'final', } def get_version(): """ Return the formatted version information """ vers = ["%(major)i.%(minor)i" % __version_info__, ] if __version_info__['micro']: vers.append(".%(micro)i" % __version_info__) if __version_info__['releaselevel'] != 'final': vers.append('%(releaselevel)s' % __version_info__) return ''.join(vers) __version__ = get_version() try: from .hcalendar import hCalendar except ImportError: pass __all__ = ['hCalendar'] ## Instruction: Fix hcalendar module __doc__ missing ## Code After: from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __version_info__ = { 'major': 0, 'minor': 2, 'micro': 0, 'releaselevel': 'final', } def get_version(): """ Return the formatted version information """ vers = ["%(major)i.%(minor)i" % __version_info__, ] if __version_info__['micro']: vers.append(".%(micro)i" % __version_info__) if __version_info__['releaselevel'] != 'final': vers.append('%(releaselevel)s' % __version_info__) return ''.join(vers) __version__ = get_version() try: from .hcalendar import hCalendar except ImportError: pass __all__ = ['hCalendar']
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals - - """ - python-hcalendar is a basic hCalendar parser - """ __version_info__ = { 'major': 0, 'minor': 2, 'micro': 0, 'releaselevel': 'final', } def get_version(): """ Return the formatted version information """ vers = ["%(major)i.%(minor)i" % __version_info__, ] if __version_info__['micro']: vers.append(".%(micro)i" % __version_info__) if __version_info__['releaselevel'] != 'final': vers.append('%(releaselevel)s' % __version_info__) return ''.join(vers) __version__ = get_version() try: from .hcalendar import hCalendar except ImportError: pass __all__ = ['hCalendar']
801c370ce88b3b2689da5890ebf09bae533089f4
tob-api/tob_api/hyperledger_indy.py
tob-api/tob_api/hyperledger_indy.py
import os import platform def config(): genesis_txn_path = "/opt/app-root/genesis" platform_name = platform.system() if platform_name == "Windows": genesis_txn_path = os.path.realpath("./app-root/genesis") return { "genesis_txn_path": genesis_txn_path, }
import os import platform import requests from pathlib import Path def getGenesisData(): """ Get a copy of the genesis transaction file from the web. """ genesisUrl = os.getenv('GENESIS_URL', 'http://138.197.170.136/genesis').lower() response = requests.get(genesisUrl) return response.text def checkGenesisFile(genesis_txn_path): """ Check on the genesis transaction file and create it is it does not exist. """ genesis_txn_file = Path(genesis_txn_path) if not genesis_txn_file.exists(): if not genesis_txn_file.parent.exists(): genesis_txn_file.parent.mkdir(parents = True) data = getGenesisData() with open(genesis_txn_path, 'x') as genesisFile: genesisFile.write(data) def config(): """ Get the hyperledger configuration settings for the environment. """ genesis_txn_path = "/opt/app-root/genesis" platform_name = platform.system() if platform_name == "Windows": genesis_txn_path = os.path.realpath("./app-root/genesis") checkGenesisFile(genesis_txn_path) return { "genesis_txn_path": genesis_txn_path, }
Add support for downloading the genesis transaction file.
Add support for downloading the genesis transaction file.
Python
apache-2.0
swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook
import os import platform + import requests + from pathlib import Path + + def getGenesisData(): + """ + Get a copy of the genesis transaction file from the web. + """ + genesisUrl = os.getenv('GENESIS_URL', 'http://138.197.170.136/genesis').lower() + response = requests.get(genesisUrl) + return response.text + + def checkGenesisFile(genesis_txn_path): + """ + Check on the genesis transaction file and create it is it does not exist. + """ + genesis_txn_file = Path(genesis_txn_path) + if not genesis_txn_file.exists(): + if not genesis_txn_file.parent.exists(): + genesis_txn_file.parent.mkdir(parents = True) + data = getGenesisData() + with open(genesis_txn_path, 'x') as genesisFile: + genesisFile.write(data) def config(): + """ + Get the hyperledger configuration settings for the environment. + """ genesis_txn_path = "/opt/app-root/genesis" platform_name = platform.system() if platform_name == "Windows": genesis_txn_path = os.path.realpath("./app-root/genesis") + checkGenesisFile(genesis_txn_path) + return { "genesis_txn_path": genesis_txn_path, }
Add support for downloading the genesis transaction file.
## Code Before: import os import platform def config(): genesis_txn_path = "/opt/app-root/genesis" platform_name = platform.system() if platform_name == "Windows": genesis_txn_path = os.path.realpath("./app-root/genesis") return { "genesis_txn_path": genesis_txn_path, } ## Instruction: Add support for downloading the genesis transaction file. ## Code After: import os import platform import requests from pathlib import Path def getGenesisData(): """ Get a copy of the genesis transaction file from the web. """ genesisUrl = os.getenv('GENESIS_URL', 'http://138.197.170.136/genesis').lower() response = requests.get(genesisUrl) return response.text def checkGenesisFile(genesis_txn_path): """ Check on the genesis transaction file and create it is it does not exist. """ genesis_txn_file = Path(genesis_txn_path) if not genesis_txn_file.exists(): if not genesis_txn_file.parent.exists(): genesis_txn_file.parent.mkdir(parents = True) data = getGenesisData() with open(genesis_txn_path, 'x') as genesisFile: genesisFile.write(data) def config(): """ Get the hyperledger configuration settings for the environment. """ genesis_txn_path = "/opt/app-root/genesis" platform_name = platform.system() if platform_name == "Windows": genesis_txn_path = os.path.realpath("./app-root/genesis") checkGenesisFile(genesis_txn_path) return { "genesis_txn_path": genesis_txn_path, }
import os import platform + import requests + from pathlib import Path + + def getGenesisData(): + """ + Get a copy of the genesis transaction file from the web. + """ + genesisUrl = os.getenv('GENESIS_URL', 'http://138.197.170.136/genesis').lower() + response = requests.get(genesisUrl) + return response.text + + def checkGenesisFile(genesis_txn_path): + """ + Check on the genesis transaction file and create it is it does not exist. + """ + genesis_txn_file = Path(genesis_txn_path) + if not genesis_txn_file.exists(): + if not genesis_txn_file.parent.exists(): + genesis_txn_file.parent.mkdir(parents = True) + data = getGenesisData() + with open(genesis_txn_path, 'x') as genesisFile: + genesisFile.write(data) def config(): + """ + Get the hyperledger configuration settings for the environment. + """ genesis_txn_path = "/opt/app-root/genesis" platform_name = platform.system() if platform_name == "Windows": genesis_txn_path = os.path.realpath("./app-root/genesis") + checkGenesisFile(genesis_txn_path) + return { "genesis_txn_path": genesis_txn_path, }
f3cdd03f1e02f7fd0614d4421b831794c01de66d
tests/web_api/case_with_reform/reforms.py
tests/web_api/case_with_reform/reforms.py
from openfisca_core.model_api import Variable, Reform, MONTH from openfisca_country_template.entities import Person class goes_to_school(Variable): value_type = bool default_value = True entity = Person label = "The person goes to school (only relevant for children)" definition_period = MONTH class add_variable_reform(Reform): def apply(self): self.add_variable(goes_to_school)
from openfisca_core.model_api import Variable, Reform, MONTH from openfisca_country_template.entities import Person def test_dynamic_variable(): class NewDynamicClass(Variable): value_type = bool default_value = True entity = Person label = "The person goes to school (only relevant for children)" definition_period = MONTH NewDynamicClass.__name__ = "goes_to_school" return NewDynamicClass class add_variable_reform(Reform): def apply(self): self.add_variable(test_dynamic_variable())
Update test reform to make it fail without a fix
Update test reform to make it fail without a fix
Python
agpl-3.0
openfisca/openfisca-core,openfisca/openfisca-core
from openfisca_core.model_api import Variable, Reform, MONTH from openfisca_country_template.entities import Person - class goes_to_school(Variable): + def test_dynamic_variable(): + class NewDynamicClass(Variable): - value_type = bool + value_type = bool - default_value = True + default_value = True - entity = Person + entity = Person - label = "The person goes to school (only relevant for children)" + label = "The person goes to school (only relevant for children)" - definition_period = MONTH + definition_period = MONTH + + NewDynamicClass.__name__ = "goes_to_school" + return NewDynamicClass class add_variable_reform(Reform): def apply(self): - self.add_variable(goes_to_school) + self.add_variable(test_dynamic_variable())
Update test reform to make it fail without a fix
## Code Before: from openfisca_core.model_api import Variable, Reform, MONTH from openfisca_country_template.entities import Person class goes_to_school(Variable): value_type = bool default_value = True entity = Person label = "The person goes to school (only relevant for children)" definition_period = MONTH class add_variable_reform(Reform): def apply(self): self.add_variable(goes_to_school) ## Instruction: Update test reform to make it fail without a fix ## Code After: from openfisca_core.model_api import Variable, Reform, MONTH from openfisca_country_template.entities import Person def test_dynamic_variable(): class NewDynamicClass(Variable): value_type = bool default_value = True entity = Person label = "The person goes to school (only relevant for children)" definition_period = MONTH NewDynamicClass.__name__ = "goes_to_school" return NewDynamicClass class add_variable_reform(Reform): def apply(self): self.add_variable(test_dynamic_variable())
from openfisca_core.model_api import Variable, Reform, MONTH from openfisca_country_template.entities import Person - class goes_to_school(Variable): + def test_dynamic_variable(): + class NewDynamicClass(Variable): - value_type = bool + value_type = bool ? ++++ - default_value = True + default_value = True ? ++++ - entity = Person + entity = Person ? ++++ - label = "The person goes to school (only relevant for children)" + label = "The person goes to school (only relevant for children)" ? ++++ - definition_period = MONTH + definition_period = MONTH ? ++++ + + NewDynamicClass.__name__ = "goes_to_school" + return NewDynamicClass class add_variable_reform(Reform): def apply(self): - self.add_variable(goes_to_school) + self.add_variable(test_dynamic_variable())
0f4fd0d49ba06963b0b97e032fd2e6eedf8e597a
cloacina/extract_from_b64.py
cloacina/extract_from_b64.py
from bs4 import BeautifulSoup import json import re def extract_from_b64(encoded_doc): #doc = base64.urlsafe_b64decode(encoded_doc) doc = encoded_doc.decode("base64") doc = re.sub("</p><p>", " ", doc) soup = BeautifulSoup(doc) news_source = soup.find("meta", {"name":"sourceName"})['content'] article_title = soup.find("title").text.strip() try: publication_date = soup.find("div", {"class":"PUB-DATE"}).text.strip() except AttributeError: publication_date = soup.find("div", {"class":"DATE"}).text.strip() article_body = soup.find("div", {"class":"BODY"}).text.strip() doc_id = soup.find("meta", {"name":"documentToken"})['content'] data = {"news_source" : news_source, "publication_date_raw" : publication_date, "article_title" : article_title, "article_body" : article_body, "doc_id" : doc_id} return data
from bs4 import BeautifulSoup import json import re def extract_from_b64(encoded_doc): #doc = base64.urlsafe_b64decode(encoded_doc) doc = encoded_doc.decode("base64") doc = re.sub("</p><p>", " ", doc) doc = re.sub('<div class="BODY-2">', " ", doc) soup = BeautifulSoup(doc) news_source = soup.find("meta", {"name":"sourceName"})['content'] article_title = soup.find("title").text.strip() try: publication_date = soup.find("div", {"class":"PUB-DATE"}).text.strip() except AttributeError: publication_date = soup.find("div", {"class":"DATE"}).text.strip() article_body = soup.find("div", {"class":"BODY"}).text.strip() doc_id = soup.find("meta", {"name":"documentToken"})['content'] data = {"news_source" : news_source, "publication_date_raw" : publication_date, "article_title" : article_title, "article_body" : article_body, "doc_id" : doc_id} return data
Fix missing space between lede and rest of article
Fix missing space between lede and rest of article
Python
mit
ahalterman/cloacina
from bs4 import BeautifulSoup import json import re def extract_from_b64(encoded_doc): #doc = base64.urlsafe_b64decode(encoded_doc) doc = encoded_doc.decode("base64") doc = re.sub("</p><p>", " ", doc) + doc = re.sub('<div class="BODY-2">', " ", doc) soup = BeautifulSoup(doc) news_source = soup.find("meta", {"name":"sourceName"})['content'] article_title = soup.find("title").text.strip() try: publication_date = soup.find("div", {"class":"PUB-DATE"}).text.strip() except AttributeError: publication_date = soup.find("div", {"class":"DATE"}).text.strip() article_body = soup.find("div", {"class":"BODY"}).text.strip() doc_id = soup.find("meta", {"name":"documentToken"})['content'] data = {"news_source" : news_source, "publication_date_raw" : publication_date, "article_title" : article_title, "article_body" : article_body, "doc_id" : doc_id} return data
Fix missing space between lede and rest of article
## Code Before: from bs4 import BeautifulSoup import json import re def extract_from_b64(encoded_doc): #doc = base64.urlsafe_b64decode(encoded_doc) doc = encoded_doc.decode("base64") doc = re.sub("</p><p>", " ", doc) soup = BeautifulSoup(doc) news_source = soup.find("meta", {"name":"sourceName"})['content'] article_title = soup.find("title").text.strip() try: publication_date = soup.find("div", {"class":"PUB-DATE"}).text.strip() except AttributeError: publication_date = soup.find("div", {"class":"DATE"}).text.strip() article_body = soup.find("div", {"class":"BODY"}).text.strip() doc_id = soup.find("meta", {"name":"documentToken"})['content'] data = {"news_source" : news_source, "publication_date_raw" : publication_date, "article_title" : article_title, "article_body" : article_body, "doc_id" : doc_id} return data ## Instruction: Fix missing space between lede and rest of article ## Code After: from bs4 import BeautifulSoup import json import re def extract_from_b64(encoded_doc): #doc = base64.urlsafe_b64decode(encoded_doc) doc = encoded_doc.decode("base64") doc = re.sub("</p><p>", " ", doc) doc = re.sub('<div class="BODY-2">', " ", doc) soup = BeautifulSoup(doc) news_source = soup.find("meta", {"name":"sourceName"})['content'] article_title = soup.find("title").text.strip() try: publication_date = soup.find("div", {"class":"PUB-DATE"}).text.strip() except AttributeError: publication_date = soup.find("div", {"class":"DATE"}).text.strip() article_body = soup.find("div", {"class":"BODY"}).text.strip() doc_id = soup.find("meta", {"name":"documentToken"})['content'] data = {"news_source" : news_source, "publication_date_raw" : publication_date, "article_title" : article_title, "article_body" : article_body, "doc_id" : doc_id} return data
from bs4 import BeautifulSoup import json import re def extract_from_b64(encoded_doc): #doc = base64.urlsafe_b64decode(encoded_doc) doc = encoded_doc.decode("base64") doc = re.sub("</p><p>", " ", doc) + doc = re.sub('<div class="BODY-2">', " ", doc) soup = BeautifulSoup(doc) news_source = soup.find("meta", {"name":"sourceName"})['content'] article_title = soup.find("title").text.strip() try: publication_date = soup.find("div", {"class":"PUB-DATE"}).text.strip() except AttributeError: publication_date = soup.find("div", {"class":"DATE"}).text.strip() article_body = soup.find("div", {"class":"BODY"}).text.strip() doc_id = soup.find("meta", {"name":"documentToken"})['content'] data = {"news_source" : news_source, "publication_date_raw" : publication_date, "article_title" : article_title, "article_body" : article_body, "doc_id" : doc_id} return data
ad7507f795f465425e72fb6821115e395046b84d
pyshtools/shio/yilm_index_vector.py
pyshtools/shio/yilm_index_vector.py
def YilmIndexVector(i, l, m): """ Compute the index of an 1D array of spherical harmonic coefficients corresponding to i, l, and m. Usage ----- index = YilmIndexVector (i, l, m) Returns ------- index : integer Index of an 1D array of spherical harmonic coefficients corresponding to i, l, and m. Parameters ---------- i : integer 1 corresponds to the cosine coefficient cilm[0,:,:], and 2 corresponds to the sine coefficient cilm[1,:,:]. l : integer The spherical harmonic degree. m : integer The angular order. Notes ----- YilmIndexVector will calculate the index of a 1D vector of spherical harmonic coefficients corresponding to degree l, angular order m and i (1 = cosine, 2 = sine). The index is given by l**2+(i-1)*l+m. """ return l**2 + (i - 1) * l + m
def YilmIndexVector(i, l, m): """ Compute the index of a 1D array of spherical harmonic coefficients corresponding to i, l, and m. Usage ----- index = YilmIndexVector (i, l, m) Returns ------- index : integer Index of a 1D array of spherical harmonic coefficients corresponding to i, l, and m. Parameters ---------- i : integer 1 corresponds to the cosine coefficient Ylm = cilm[0,:,:], and 2 corresponds to the sine coefficient Yl,-m = cilm[1,:,:]. l : integer The spherical harmonic degree. m : integer The angular order, which must be greater or equal to zero. Notes ----- YilmIndexVector will calculate the index of a 1D vector of spherical harmonic coefficients corresponding to degree l, (positive) angular order m and i (1 = cosine, 2 = sine). The index is given by l**2+(i-1)*l+m. """ if l < 0: raise ValueError('The spherical harmonic degree must be positive. ' 'Input value is {:s}'.format(repr(l))) if m < 0: raise ValueError('The angular order must be positive. ' 'Input value is {:s}'.format(repr(m))) if m >= l: raise ValueError('The angular order must be less than or equal to ' 'the spherical harmonic degree. Input degree is {:s}.' ' Input order is {:s}.'.format(repr(l), repr(m))) return l**2 + (i - 1) * l + m
Add error checks to YilmIndexVector (and update docs)
Add error checks to YilmIndexVector (and update docs)
Python
bsd-3-clause
SHTOOLS/SHTOOLS,MarkWieczorek/SHTOOLS,MarkWieczorek/SHTOOLS,SHTOOLS/SHTOOLS
def YilmIndexVector(i, l, m): """ - Compute the index of an 1D array of spherical harmonic coefficients + Compute the index of a 1D array of spherical harmonic coefficients corresponding to i, l, and m. Usage ----- index = YilmIndexVector (i, l, m) Returns ------- index : integer - Index of an 1D array of spherical harmonic coefficients corresponding + Index of a 1D array of spherical harmonic coefficients corresponding to i, l, and m. Parameters ---------- i : integer - 1 corresponds to the cosine coefficient cilm[0,:,:], and 2 corresponds + 1 corresponds to the cosine coefficient Ylm = cilm[0,:,:], and 2 - to the sine coefficient cilm[1,:,:]. + corresponds to the sine coefficient Yl,-m = cilm[1,:,:]. l : integer The spherical harmonic degree. m : integer - The angular order. + The angular order, which must be greater or equal to zero. Notes ----- YilmIndexVector will calculate the index of a 1D vector of spherical - harmonic coefficients corresponding to degree l, angular order m and i + harmonic coefficients corresponding to degree l, (positive) angular order - (1 = cosine, 2 = sine). The index is given by l**2+(i-1)*l+m. + m and i (1 = cosine, 2 = sine). The index is given by l**2+(i-1)*l+m. """ + if l < 0: + raise ValueError('The spherical harmonic degree must be positive. ' + 'Input value is {:s}'.format(repr(l))) + if m < 0: + raise ValueError('The angular order must be positive. ' + 'Input value is {:s}'.format(repr(m))) + if m >= l: + raise ValueError('The angular order must be less than or equal to ' + 'the spherical harmonic degree. Input degree is {:s}.' + ' Input order is {:s}.'.format(repr(l), repr(m))) return l**2 + (i - 1) * l + m
Add error checks to YilmIndexVector (and update docs)
## Code Before: def YilmIndexVector(i, l, m): """ Compute the index of an 1D array of spherical harmonic coefficients corresponding to i, l, and m. Usage ----- index = YilmIndexVector (i, l, m) Returns ------- index : integer Index of an 1D array of spherical harmonic coefficients corresponding to i, l, and m. Parameters ---------- i : integer 1 corresponds to the cosine coefficient cilm[0,:,:], and 2 corresponds to the sine coefficient cilm[1,:,:]. l : integer The spherical harmonic degree. m : integer The angular order. Notes ----- YilmIndexVector will calculate the index of a 1D vector of spherical harmonic coefficients corresponding to degree l, angular order m and i (1 = cosine, 2 = sine). The index is given by l**2+(i-1)*l+m. """ return l**2 + (i - 1) * l + m ## Instruction: Add error checks to YilmIndexVector (and update docs) ## Code After: def YilmIndexVector(i, l, m): """ Compute the index of a 1D array of spherical harmonic coefficients corresponding to i, l, and m. Usage ----- index = YilmIndexVector (i, l, m) Returns ------- index : integer Index of a 1D array of spherical harmonic coefficients corresponding to i, l, and m. Parameters ---------- i : integer 1 corresponds to the cosine coefficient Ylm = cilm[0,:,:], and 2 corresponds to the sine coefficient Yl,-m = cilm[1,:,:]. l : integer The spherical harmonic degree. m : integer The angular order, which must be greater or equal to zero. Notes ----- YilmIndexVector will calculate the index of a 1D vector of spherical harmonic coefficients corresponding to degree l, (positive) angular order m and i (1 = cosine, 2 = sine). The index is given by l**2+(i-1)*l+m. """ if l < 0: raise ValueError('The spherical harmonic degree must be positive. ' 'Input value is {:s}'.format(repr(l))) if m < 0: raise ValueError('The angular order must be positive. ' 'Input value is {:s}'.format(repr(m))) if m >= l: raise ValueError('The angular order must be less than or equal to ' 'the spherical harmonic degree. Input degree is {:s}.' ' Input order is {:s}.'.format(repr(l), repr(m))) return l**2 + (i - 1) * l + m
def YilmIndexVector(i, l, m): """ - Compute the index of an 1D array of spherical harmonic coefficients ? - + Compute the index of a 1D array of spherical harmonic coefficients corresponding to i, l, and m. Usage ----- index = YilmIndexVector (i, l, m) Returns ------- index : integer - Index of an 1D array of spherical harmonic coefficients corresponding ? - + Index of a 1D array of spherical harmonic coefficients corresponding to i, l, and m. Parameters ---------- i : integer - 1 corresponds to the cosine coefficient cilm[0,:,:], and 2 corresponds ? ------------ + 1 corresponds to the cosine coefficient Ylm = cilm[0,:,:], and 2 ? ++++++ - to the sine coefficient cilm[1,:,:]. + corresponds to the sine coefficient Yl,-m = cilm[1,:,:]. ? ++++++++++++ ++++++++ l : integer The spherical harmonic degree. m : integer - The angular order. + The angular order, which must be greater or equal to zero. Notes ----- YilmIndexVector will calculate the index of a 1D vector of spherical - harmonic coefficients corresponding to degree l, angular order m and i ? -------- + harmonic coefficients corresponding to degree l, (positive) angular order ? +++++++++++ - (1 = cosine, 2 = sine). The index is given by l**2+(i-1)*l+m. + m and i (1 = cosine, 2 = sine). The index is given by l**2+(i-1)*l+m. ? ++++++++ """ + if l < 0: + raise ValueError('The spherical harmonic degree must be positive. ' + 'Input value is {:s}'.format(repr(l))) + if m < 0: + raise ValueError('The angular order must be positive. ' + 'Input value is {:s}'.format(repr(m))) + if m >= l: + raise ValueError('The angular order must be less than or equal to ' + 'the spherical harmonic degree. Input degree is {:s}.' + ' Input order is {:s}.'.format(repr(l), repr(m))) return l**2 + (i - 1) * l + m
a75c51594e225fbada37f1be23cf2de581da29a4
keeper/tasks/dashboardbuild.py
keeper/tasks/dashboardbuild.py
from __future__ import annotations from typing import TYPE_CHECKING from celery.utils.log import get_task_logger from keeper.celery import celery_app from keeper.models import Product from keeper.services.dashboard import build_dashboard as build_dashboard_svc if TYPE_CHECKING: import celery.task __all__ = ["build_dashboard"] logger = get_task_logger(__name__) @celery_app.task(bind=True) def build_dashboard(self: celery.task.Task, product_id: str) -> None: """Build a product's dashboard as a Celery task. Parameters ---------- product_url : `str` URL of the product resource. """ logger.info( "Starting dashboard build product_id=%s retry=%d", product_id, self.request.retries, ) product = Product.query(id=product_id).one() build_dashboard_svc(product, logger) logger.info("Finished triggering dashboard build")
from __future__ import annotations from typing import TYPE_CHECKING from celery.utils.log import get_task_logger from keeper.celery import celery_app from keeper.models import Product from keeper.services.dashboard import build_dashboard as build_dashboard_svc if TYPE_CHECKING: import celery.task __all__ = ["build_dashboard"] logger = get_task_logger(__name__) @celery_app.task(bind=True) def build_dashboard(self: celery.task.Task, product_id: str) -> None: """Build a product's dashboard as a Celery task. Parameters ---------- product_url : `str` URL of the product resource. """ logger.info( "Starting dashboard build product_id=%s retry=%d", product_id, self.request.retries, ) product = Product.query.get(product_id) build_dashboard_svc(product, logger) logger.info("Finished triggering dashboard build")
Fix getting product in build_dashboard task
Fix getting product in build_dashboard task
Python
mit
lsst-sqre/ltd-keeper,lsst-sqre/ltd-keeper
from __future__ import annotations from typing import TYPE_CHECKING from celery.utils.log import get_task_logger from keeper.celery import celery_app from keeper.models import Product from keeper.services.dashboard import build_dashboard as build_dashboard_svc if TYPE_CHECKING: import celery.task __all__ = ["build_dashboard"] logger = get_task_logger(__name__) @celery_app.task(bind=True) def build_dashboard(self: celery.task.Task, product_id: str) -> None: """Build a product's dashboard as a Celery task. Parameters ---------- product_url : `str` URL of the product resource. """ logger.info( "Starting dashboard build product_id=%s retry=%d", product_id, self.request.retries, ) - product = Product.query(id=product_id).one() + product = Product.query.get(product_id) build_dashboard_svc(product, logger) logger.info("Finished triggering dashboard build")
Fix getting product in build_dashboard task
## Code Before: from __future__ import annotations from typing import TYPE_CHECKING from celery.utils.log import get_task_logger from keeper.celery import celery_app from keeper.models import Product from keeper.services.dashboard import build_dashboard as build_dashboard_svc if TYPE_CHECKING: import celery.task __all__ = ["build_dashboard"] logger = get_task_logger(__name__) @celery_app.task(bind=True) def build_dashboard(self: celery.task.Task, product_id: str) -> None: """Build a product's dashboard as a Celery task. Parameters ---------- product_url : `str` URL of the product resource. """ logger.info( "Starting dashboard build product_id=%s retry=%d", product_id, self.request.retries, ) product = Product.query(id=product_id).one() build_dashboard_svc(product, logger) logger.info("Finished triggering dashboard build") ## Instruction: Fix getting product in build_dashboard task ## Code After: from __future__ import annotations from typing import TYPE_CHECKING from celery.utils.log import get_task_logger from keeper.celery import celery_app from keeper.models import Product from keeper.services.dashboard import build_dashboard as build_dashboard_svc if TYPE_CHECKING: import celery.task __all__ = ["build_dashboard"] logger = get_task_logger(__name__) @celery_app.task(bind=True) def build_dashboard(self: celery.task.Task, product_id: str) -> None: """Build a product's dashboard as a Celery task. Parameters ---------- product_url : `str` URL of the product resource. """ logger.info( "Starting dashboard build product_id=%s retry=%d", product_id, self.request.retries, ) product = Product.query.get(product_id) build_dashboard_svc(product, logger) logger.info("Finished triggering dashboard build")
from __future__ import annotations from typing import TYPE_CHECKING from celery.utils.log import get_task_logger from keeper.celery import celery_app from keeper.models import Product from keeper.services.dashboard import build_dashboard as build_dashboard_svc if TYPE_CHECKING: import celery.task __all__ = ["build_dashboard"] logger = get_task_logger(__name__) @celery_app.task(bind=True) def build_dashboard(self: celery.task.Task, product_id: str) -> None: """Build a product's dashboard as a Celery task. Parameters ---------- product_url : `str` URL of the product resource. """ logger.info( "Starting dashboard build product_id=%s retry=%d", product_id, self.request.retries, ) - product = Product.query(id=product_id).one() ? --- ------ + product = Product.query.get(product_id) ? ++++ build_dashboard_svc(product, logger) logger.info("Finished triggering dashboard build")
405e34b7573e3af78051741feb32e7589e49dfb9
controllers/main.py
controllers/main.py
import logging import simplejson import os import base64 import openerp from ..helpers.zebra import zebra class PrintController(openerp.addons.web.http.Controller): _cp_path = '/printer_proxy' @openerp.addons.web.http.jsonrequest def output(self, request, format="epl2", **kwargs): '''Print the passed-in data. Corresponds to "printer_proxy.print"''' if format.lower() == "epl2": return self.output_epl2(request, **kwargs) return {'success': False, 'error': "Format '%s' not recognized" % format} def output_epl2(self, request, printer_name='zebra_python_unittest', data=[], raw=False, test=False): '''Print the passed-in EPL2 data.''' printer = zebra(printer_name) printer.setup(direct_thermal=True) for datum in data: if not raw: datum = base64.b64decode(datum) printer.output(datum) return {'success': True}
import logging import simplejson import os import base64 import openerp from ..helpers.zebra import zebra class PrintController(openerp.addons.web.http.Controller): _cp_path = '/printer_proxy' @openerp.addons.web.http.jsonrequest def output(self, request, format="epl2", **kwargs): '''Print the passed-in data. Corresponds to "printer_proxy.print"''' if format.lower() == "epl2": return self.output_epl2(request, **kwargs) return {'success': False, 'error': "Format '%s' not recognized" % format} def output_epl2(self, request, printer_name='zebra_python_unittest', data=[], raw=False, test=False): '''Print the passed-in EPL2 data.''' printer = zebra(printer_name) for datum in data: if not raw: datum = base64.b64decode(datum) printer.output(datum) return {'success': True}
Remove line that causes a form feed upon every call to PrintController.output_epl.
Remove line that causes a form feed upon every call to PrintController.output_epl.
Python
agpl-3.0
ryepdx/printer_proxy,ryepdx/printer_proxy
import logging import simplejson import os import base64 import openerp from ..helpers.zebra import zebra class PrintController(openerp.addons.web.http.Controller): _cp_path = '/printer_proxy' @openerp.addons.web.http.jsonrequest def output(self, request, format="epl2", **kwargs): '''Print the passed-in data. Corresponds to "printer_proxy.print"''' if format.lower() == "epl2": return self.output_epl2(request, **kwargs) return {'success': False, 'error': "Format '%s' not recognized" % format} def output_epl2(self, request, printer_name='zebra_python_unittest', data=[], raw=False, test=False): '''Print the passed-in EPL2 data.''' printer = zebra(printer_name) - printer.setup(direct_thermal=True) for datum in data: if not raw: datum = base64.b64decode(datum) printer.output(datum) return {'success': True}
Remove line that causes a form feed upon every call to PrintController.output_epl.
## Code Before: import logging import simplejson import os import base64 import openerp from ..helpers.zebra import zebra class PrintController(openerp.addons.web.http.Controller): _cp_path = '/printer_proxy' @openerp.addons.web.http.jsonrequest def output(self, request, format="epl2", **kwargs): '''Print the passed-in data. Corresponds to "printer_proxy.print"''' if format.lower() == "epl2": return self.output_epl2(request, **kwargs) return {'success': False, 'error': "Format '%s' not recognized" % format} def output_epl2(self, request, printer_name='zebra_python_unittest', data=[], raw=False, test=False): '''Print the passed-in EPL2 data.''' printer = zebra(printer_name) printer.setup(direct_thermal=True) for datum in data: if not raw: datum = base64.b64decode(datum) printer.output(datum) return {'success': True} ## Instruction: Remove line that causes a form feed upon every call to PrintController.output_epl. ## Code After: import logging import simplejson import os import base64 import openerp from ..helpers.zebra import zebra class PrintController(openerp.addons.web.http.Controller): _cp_path = '/printer_proxy' @openerp.addons.web.http.jsonrequest def output(self, request, format="epl2", **kwargs): '''Print the passed-in data. Corresponds to "printer_proxy.print"''' if format.lower() == "epl2": return self.output_epl2(request, **kwargs) return {'success': False, 'error': "Format '%s' not recognized" % format} def output_epl2(self, request, printer_name='zebra_python_unittest', data=[], raw=False, test=False): '''Print the passed-in EPL2 data.''' printer = zebra(printer_name) for datum in data: if not raw: datum = base64.b64decode(datum) printer.output(datum) return {'success': True}
import logging import simplejson import os import base64 import openerp from ..helpers.zebra import zebra class PrintController(openerp.addons.web.http.Controller): _cp_path = '/printer_proxy' @openerp.addons.web.http.jsonrequest def output(self, request, format="epl2", **kwargs): '''Print the passed-in data. Corresponds to "printer_proxy.print"''' if format.lower() == "epl2": return self.output_epl2(request, **kwargs) return {'success': False, 'error': "Format '%s' not recognized" % format} def output_epl2(self, request, printer_name='zebra_python_unittest', data=[], raw=False, test=False): '''Print the passed-in EPL2 data.''' printer = zebra(printer_name) - printer.setup(direct_thermal=True) for datum in data: if not raw: datum = base64.b64decode(datum) printer.output(datum) return {'success': True}
8798381c93c49d6f7a83320c3ae27c348e95b8ff
testhook/templatetags/testhook.py
testhook/templatetags/testhook.py
import sys from django.template import Library, TemplateSyntaxError from django.conf import settings from django.utils.safestring import mark_safe from django.utils.text import slugify if sys.version_info[0] == 2: str = basestring register = Library() @register.simple_tag def testhook(name, *args): if not getattr(settings, 'TESTHOOK_ENABLED', True): return u'' if not name: raise TemplateSyntaxError( 'Invalid testhook argument for name, expected non empty string' ) elif not isinstance(name, str): raise TemplateSyntaxError( 'Invalid testhook argument for name, expected string' ) # slugify the name by default name = slugify(name) if args: name = '{}-{}'.format(name, '-'.join(filter(None, args))) return mark_safe(u'data-testhook-id="{0}"'.format(name))
import sys from django.template import Library, TemplateSyntaxError from django.conf import settings from django.utils.safestring import mark_safe from django.utils.text import slugify if sys.version_info[0] == 2: str = basestring register = Library() @register.simple_tag def testhook(name, *args): if not getattr(settings, 'TESTHOOK_ENABLED', True): return u'' if not name or not isinstance(name, str): raise TemplateSyntaxError( 'Testhook takes at least one argument (string)' ) # slugify the name by default name = slugify(name) if args: name = '{}-{}'.format(name, '-'.join(filter(None, args))) return mark_safe(u'data-testhook-id="{0}"'.format(name))
Simplify exception handling of required argument
Simplify exception handling of required argument
Python
apache-2.0
jjanssen/django-testhook
import sys from django.template import Library, TemplateSyntaxError from django.conf import settings from django.utils.safestring import mark_safe from django.utils.text import slugify if sys.version_info[0] == 2: str = basestring register = Library() @register.simple_tag def testhook(name, *args): if not getattr(settings, 'TESTHOOK_ENABLED', True): return u'' - if not name: + if not name or not isinstance(name, str): raise TemplateSyntaxError( + 'Testhook takes at least one argument (string)' - 'Invalid testhook argument for name, expected non empty string' - ) - elif not isinstance(name, str): - raise TemplateSyntaxError( - 'Invalid testhook argument for name, expected string' ) # slugify the name by default name = slugify(name) if args: name = '{}-{}'.format(name, '-'.join(filter(None, args))) return mark_safe(u'data-testhook-id="{0}"'.format(name))
Simplify exception handling of required argument
## Code Before: import sys from django.template import Library, TemplateSyntaxError from django.conf import settings from django.utils.safestring import mark_safe from django.utils.text import slugify if sys.version_info[0] == 2: str = basestring register = Library() @register.simple_tag def testhook(name, *args): if not getattr(settings, 'TESTHOOK_ENABLED', True): return u'' if not name: raise TemplateSyntaxError( 'Invalid testhook argument for name, expected non empty string' ) elif not isinstance(name, str): raise TemplateSyntaxError( 'Invalid testhook argument for name, expected string' ) # slugify the name by default name = slugify(name) if args: name = '{}-{}'.format(name, '-'.join(filter(None, args))) return mark_safe(u'data-testhook-id="{0}"'.format(name)) ## Instruction: Simplify exception handling of required argument ## Code After: import sys from django.template import Library, TemplateSyntaxError from django.conf import settings from django.utils.safestring import mark_safe from django.utils.text import slugify if sys.version_info[0] == 2: str = basestring register = Library() @register.simple_tag def testhook(name, *args): if not getattr(settings, 'TESTHOOK_ENABLED', True): return u'' if not name or not isinstance(name, str): raise TemplateSyntaxError( 'Testhook takes at least one argument (string)' ) # slugify the name by default name = slugify(name) if args: name = '{}-{}'.format(name, '-'.join(filter(None, args))) return mark_safe(u'data-testhook-id="{0}"'.format(name))
import sys from django.template import Library, TemplateSyntaxError from django.conf import settings from django.utils.safestring import mark_safe from django.utils.text import slugify if sys.version_info[0] == 2: str = basestring register = Library() @register.simple_tag def testhook(name, *args): if not getattr(settings, 'TESTHOOK_ENABLED', True): return u'' - if not name: + if not name or not isinstance(name, str): raise TemplateSyntaxError( + 'Testhook takes at least one argument (string)' - 'Invalid testhook argument for name, expected non empty string' - ) - elif not isinstance(name, str): - raise TemplateSyntaxError( - 'Invalid testhook argument for name, expected string' ) # slugify the name by default name = slugify(name) if args: name = '{}-{}'.format(name, '-'.join(filter(None, args))) return mark_safe(u'data-testhook-id="{0}"'.format(name))
d07722c8e7cc2efa0551830ca424d2db2bf734f3
app/__init__.py
app/__init__.py
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.uploads import UploadSet, configure_uploads, IMAGES from config import config bootstrap = Bootstrap() db = SQLAlchemy() login_manager = LoginManager() login_manager.login_view = 'auth.login' ads = UploadSet('ads', IMAGES) def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) bootstrap.init_app(app) db.init_app(app) login_manager.init_app(app) configure_uploads(app, ads) from .aflafrettir import aflafrettir as afla_blueprint from .auth import auth as auth_blueprint from .admin import admin as admin_blueprint app.register_blueprint(afla_blueprint) app.register_blueprint(auth_blueprint, url_prefix='/auth') app.register_blueprint(admin_blueprint, url_prefix='/admin') return app
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.uploads import UploadSet, configure_uploads, IMAGES from helpers.text import slugify from config import config bootstrap = Bootstrap() db = SQLAlchemy() login_manager = LoginManager() login_manager.login_view = 'auth.login' ads = UploadSet('ads', IMAGES) def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) app.jinja_env.globals.update(slugify=slugify) bootstrap.init_app(app) db.init_app(app) login_manager.init_app(app) configure_uploads(app, ads) from .aflafrettir import aflafrettir as afla_blueprint from .auth import auth as auth_blueprint from .admin import admin as admin_blueprint app.register_blueprint(afla_blueprint) app.register_blueprint(auth_blueprint, url_prefix='/auth') app.register_blueprint(admin_blueprint, url_prefix='/admin') return app
Add slugify to the jinja2's globals scope
Add slugify to the jinja2's globals scope
Python
mit
finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.uploads import UploadSet, configure_uploads, IMAGES + + from helpers.text import slugify from config import config bootstrap = Bootstrap() db = SQLAlchemy() login_manager = LoginManager() login_manager.login_view = 'auth.login' ads = UploadSet('ads', IMAGES) def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) + app.jinja_env.globals.update(slugify=slugify) bootstrap.init_app(app) db.init_app(app) login_manager.init_app(app) configure_uploads(app, ads) from .aflafrettir import aflafrettir as afla_blueprint from .auth import auth as auth_blueprint from .admin import admin as admin_blueprint app.register_blueprint(afla_blueprint) app.register_blueprint(auth_blueprint, url_prefix='/auth') app.register_blueprint(admin_blueprint, url_prefix='/admin') return app
Add slugify to the jinja2's globals scope
## Code Before: from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.uploads import UploadSet, configure_uploads, IMAGES from config import config bootstrap = Bootstrap() db = SQLAlchemy() login_manager = LoginManager() login_manager.login_view = 'auth.login' ads = UploadSet('ads', IMAGES) def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) bootstrap.init_app(app) db.init_app(app) login_manager.init_app(app) configure_uploads(app, ads) from .aflafrettir import aflafrettir as afla_blueprint from .auth import auth as auth_blueprint from .admin import admin as admin_blueprint app.register_blueprint(afla_blueprint) app.register_blueprint(auth_blueprint, url_prefix='/auth') app.register_blueprint(admin_blueprint, url_prefix='/admin') return app ## Instruction: Add slugify to the jinja2's globals scope ## Code After: from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.uploads import UploadSet, configure_uploads, IMAGES from helpers.text import slugify from config import config bootstrap = Bootstrap() db = SQLAlchemy() login_manager = LoginManager() login_manager.login_view = 'auth.login' ads = UploadSet('ads', IMAGES) def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) app.jinja_env.globals.update(slugify=slugify) bootstrap.init_app(app) db.init_app(app) login_manager.init_app(app) configure_uploads(app, ads) from .aflafrettir import aflafrettir as afla_blueprint from .auth import auth as auth_blueprint from .admin import admin as admin_blueprint app.register_blueprint(afla_blueprint) app.register_blueprint(auth_blueprint, url_prefix='/auth') app.register_blueprint(admin_blueprint, url_prefix='/admin') return app
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.uploads import UploadSet, configure_uploads, IMAGES + + from helpers.text import slugify from config import config bootstrap = Bootstrap() db = SQLAlchemy() login_manager = LoginManager() login_manager.login_view = 'auth.login' ads = UploadSet('ads', IMAGES) def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) + app.jinja_env.globals.update(slugify=slugify) bootstrap.init_app(app) db.init_app(app) login_manager.init_app(app) configure_uploads(app, ads) from .aflafrettir import aflafrettir as afla_blueprint from .auth import auth as auth_blueprint from .admin import admin as admin_blueprint app.register_blueprint(afla_blueprint) app.register_blueprint(auth_blueprint, url_prefix='/auth') app.register_blueprint(admin_blueprint, url_prefix='/admin') return app
2c965c0a75be129f429e40ade34ef608f8ceea27
micropress/urls.py
micropress/urls.py
from django.conf.urls.defaults import * urlpatterns = patterns('micropress.views', (r'^$', 'article_list'), (r'^issue/(?P<issue>\d+)/$', 'issue_list'), (r'^article/(?P<slug>[-\w]+)/$', 'article_detail'), #(r'^new/$', 'article_create'), )
from django.conf.urls.defaults import * urlpatterns = patterns('micropress.views', (r'^$', 'article_list'), url(r'^issue/(?P<issue>\d+)/$', 'article_list', name='issue_list'), (r'^article/(?P<slug>[-\w]+)/$', 'article_detail'), #(r'^new/$', 'article_create'), )
Fix url spec for article list by issue.
Fix url spec for article list by issue.
Python
mit
jbradberry/django-micro-press,jbradberry/django-micro-press
from django.conf.urls.defaults import * urlpatterns = patterns('micropress.views', (r'^$', 'article_list'), - (r'^issue/(?P<issue>\d+)/$', 'issue_list'), + url(r'^issue/(?P<issue>\d+)/$', 'article_list', name='issue_list'), (r'^article/(?P<slug>[-\w]+)/$', 'article_detail'), #(r'^new/$', 'article_create'), )
Fix url spec for article list by issue.
## Code Before: from django.conf.urls.defaults import * urlpatterns = patterns('micropress.views', (r'^$', 'article_list'), (r'^issue/(?P<issue>\d+)/$', 'issue_list'), (r'^article/(?P<slug>[-\w]+)/$', 'article_detail'), #(r'^new/$', 'article_create'), ) ## Instruction: Fix url spec for article list by issue. ## Code After: from django.conf.urls.defaults import * urlpatterns = patterns('micropress.views', (r'^$', 'article_list'), url(r'^issue/(?P<issue>\d+)/$', 'article_list', name='issue_list'), (r'^article/(?P<slug>[-\w]+)/$', 'article_detail'), #(r'^new/$', 'article_create'), )
from django.conf.urls.defaults import * urlpatterns = patterns('micropress.views', (r'^$', 'article_list'), - (r'^issue/(?P<issue>\d+)/$', 'issue_list'), + url(r'^issue/(?P<issue>\d+)/$', 'article_list', name='issue_list'), ? +++ +++++++++++++++++++++ (r'^article/(?P<slug>[-\w]+)/$', 'article_detail'), #(r'^new/$', 'article_create'), )
830c73beafa359e01fb839901bcb91360c1de365
web/thesaurus_template_generators.py
web/thesaurus_template_generators.py
import json from web.MetaInfo import MetaInfo def generate_language_template(language_id, structure_id, version=None): meta_info = MetaInfo() if structure_id not in meta_info.data_structures: raise ValueError language_name = meta_info.languages.get( language_id, {'name': 'Human-Readable Language Name'} )['name'] meta = { 'language': language_id, 'language_name': language_name, 'structure': structure_id, } if version: meta['language_version'] = version concepts = { id: {'code': [""]} for category in meta_info.structure(structure_id).categories.values() for (id, name) in category.items() } return json.dumps({'meta': meta, 'concepts': concepts}, indent=2) def generate_meta_template(structure_id, structure_name): meta = { 'structure': structure_id, 'structure_name': structure_name, } categories = { 'First Category Name': { 'concept_id1': 'Name of Concept 1', 'concept_id2': 'Name of Concept 2' }, 'Second Category Name': { 'concept_id3': 'Name of Concept 3', 'concept_id4': 'Name of Concept 4' } } return json.dumps({'meta': meta, 'categories': categories})
"""Generator functions for thesaurus files""" import json from web.MetaInfo import MetaInfo def generate_language_template(language_id, structure_id, version=None): """Generate a template for the given language and structure""" meta_info = MetaInfo() if structure_id not in meta_info.data_structures: raise ValueError language_name = meta_info.languages.get( language_id, {'name': 'Human-Readable Language Name'} )['name'] meta = { 'language': language_id, 'language_name': language_name, 'structure': structure_id, } if version: meta['language_version'] = version concepts = { id: { 'name': name, 'code': [""], } for category in meta_info.structure(structure_id).categories.values() for (id, name) in category.items() } return json.dumps({'meta': meta, 'concepts': concepts}, indent=2) def generate_meta_template(structure_id, structure_name): """Generate a template for a `meta file`""" meta = { 'structure': structure_id, 'structure_name': structure_name, } categories = { 'First Category Name': { 'concept_id1': 'Name of Concept 1', 'concept_id2': 'Name of Concept 2' }, 'Second Category Name': { 'concept_id3': 'Name of Concept 3', 'concept_id4': 'Name of Concept 4' } } return json.dumps({'meta': meta, 'categories': categories})
Add name fields to generated templates
Add name fields to generated templates
Python
agpl-3.0
codethesaurus/codethesaur.us,codethesaurus/codethesaur.us
+ """Generator functions for thesaurus files""" import json from web.MetaInfo import MetaInfo def generate_language_template(language_id, structure_id, version=None): + """Generate a template for the given language and structure""" meta_info = MetaInfo() if structure_id not in meta_info.data_structures: raise ValueError language_name = meta_info.languages.get( language_id, {'name': 'Human-Readable Language Name'} )['name'] meta = { 'language': language_id, 'language_name': language_name, 'structure': structure_id, } if version: meta['language_version'] = version concepts = { + id: { + 'name': name, - id: {'code': [""]} + 'code': [""], + } for category in meta_info.structure(structure_id).categories.values() for (id, name) in category.items() } return json.dumps({'meta': meta, 'concepts': concepts}, indent=2) def generate_meta_template(structure_id, structure_name): + """Generate a template for a `meta file`""" meta = { 'structure': structure_id, 'structure_name': structure_name, } categories = { 'First Category Name': { 'concept_id1': 'Name of Concept 1', 'concept_id2': 'Name of Concept 2' }, 'Second Category Name': { 'concept_id3': 'Name of Concept 3', 'concept_id4': 'Name of Concept 4' } } return json.dumps({'meta': meta, 'categories': categories})
Add name fields to generated templates
## Code Before: import json from web.MetaInfo import MetaInfo def generate_language_template(language_id, structure_id, version=None): meta_info = MetaInfo() if structure_id not in meta_info.data_structures: raise ValueError language_name = meta_info.languages.get( language_id, {'name': 'Human-Readable Language Name'} )['name'] meta = { 'language': language_id, 'language_name': language_name, 'structure': structure_id, } if version: meta['language_version'] = version concepts = { id: {'code': [""]} for category in meta_info.structure(structure_id).categories.values() for (id, name) in category.items() } return json.dumps({'meta': meta, 'concepts': concepts}, indent=2) def generate_meta_template(structure_id, structure_name): meta = { 'structure': structure_id, 'structure_name': structure_name, } categories = { 'First Category Name': { 'concept_id1': 'Name of Concept 1', 'concept_id2': 'Name of Concept 2' }, 'Second Category Name': { 'concept_id3': 'Name of Concept 3', 'concept_id4': 'Name of Concept 4' } } return json.dumps({'meta': meta, 'categories': categories}) ## Instruction: Add name fields to generated templates ## Code After: """Generator functions for thesaurus files""" import json from web.MetaInfo import MetaInfo def generate_language_template(language_id, structure_id, version=None): """Generate a template for the given language and structure""" meta_info = MetaInfo() if structure_id not in meta_info.data_structures: raise ValueError language_name = meta_info.languages.get( language_id, {'name': 'Human-Readable Language Name'} )['name'] meta = { 'language': language_id, 'language_name': language_name, 'structure': structure_id, } if version: meta['language_version'] = version concepts = { id: { 'name': name, 'code': [""], } for category in meta_info.structure(structure_id).categories.values() for (id, name) in category.items() } return json.dumps({'meta': meta, 'concepts': concepts}, indent=2) def generate_meta_template(structure_id, structure_name): """Generate a template for a `meta file`""" meta = { 'structure': structure_id, 'structure_name': structure_name, } categories = { 'First Category Name': { 'concept_id1': 'Name of Concept 1', 'concept_id2': 'Name of Concept 2' }, 'Second Category Name': { 'concept_id3': 'Name of Concept 3', 'concept_id4': 'Name of Concept 4' } } return json.dumps({'meta': meta, 'categories': categories})
+ """Generator functions for thesaurus files""" import json from web.MetaInfo import MetaInfo def generate_language_template(language_id, structure_id, version=None): + """Generate a template for the given language and structure""" meta_info = MetaInfo() if structure_id not in meta_info.data_structures: raise ValueError language_name = meta_info.languages.get( language_id, {'name': 'Human-Readable Language Name'} )['name'] meta = { 'language': language_id, 'language_name': language_name, 'structure': structure_id, } if version: meta['language_version'] = version concepts = { + id: { + 'name': name, - id: {'code': [""]} ? --- ^ ^ + 'code': [""], ? ^^^ ^ + } for category in meta_info.structure(structure_id).categories.values() for (id, name) in category.items() } return json.dumps({'meta': meta, 'concepts': concepts}, indent=2) def generate_meta_template(structure_id, structure_name): + """Generate a template for a `meta file`""" meta = { 'structure': structure_id, 'structure_name': structure_name, } categories = { 'First Category Name': { 'concept_id1': 'Name of Concept 1', 'concept_id2': 'Name of Concept 2' }, 'Second Category Name': { 'concept_id3': 'Name of Concept 3', 'concept_id4': 'Name of Concept 4' } } return json.dumps({'meta': meta, 'categories': categories})
28a457926921ef5e7f57c086d6e6b77a0221348c
carnifex/utils.py
carnifex/utils.py
def attr_string(filterKeys=(), filterValues=(), **kwargs): return ', '.join([str(k)+'='+repr(v) for k, v in kwargs.iteritems() if k not in filterKeys and v not in filterValues])
def attr_string(filterKeys=(), filterValues=(), **kwargs): """Build a string consisting of 'key=value' substrings for each keyword argument in :kwargs: @param filterKeys: list of key names to ignore @param filterValues: list of values to ignore (e.g. None will ignore all key=value pairs that has that value. """ return ', '.join([str(k)+'='+repr(v) for k, v in kwargs.iteritems() if k not in filterKeys and v not in filterValues])
Add documentation and touch up formatting of attr_string util method
Add documentation and touch up formatting of attr_string util method
Python
mit
sporsh/carnifex
def attr_string(filterKeys=(), filterValues=(), **kwargs): - return ', '.join([str(k)+'='+repr(v) for k, v in kwargs.iteritems() if k not in filterKeys and v not in filterValues]) + """Build a string consisting of 'key=value' substrings for each keyword + argument in :kwargs: + @param filterKeys: list of key names to ignore + @param filterValues: list of values to ignore (e.g. None will ignore all + key=value pairs that has that value. + """ + return ', '.join([str(k)+'='+repr(v) for k, v in kwargs.iteritems() + if k not in filterKeys and v not in filterValues]) +
Add documentation and touch up formatting of attr_string util method
## Code Before: def attr_string(filterKeys=(), filterValues=(), **kwargs): return ', '.join([str(k)+'='+repr(v) for k, v in kwargs.iteritems() if k not in filterKeys and v not in filterValues]) ## Instruction: Add documentation and touch up formatting of attr_string util method ## Code After: def attr_string(filterKeys=(), filterValues=(), **kwargs): """Build a string consisting of 'key=value' substrings for each keyword argument in :kwargs: @param filterKeys: list of key names to ignore @param filterValues: list of values to ignore (e.g. None will ignore all key=value pairs that has that value. """ return ', '.join([str(k)+'='+repr(v) for k, v in kwargs.iteritems() if k not in filterKeys and v not in filterValues])
def attr_string(filterKeys=(), filterValues=(), **kwargs): - return ', '.join([str(k)+'='+repr(v) for k, v in kwargs.iteritems() if k not in filterKeys and v not in filterValues]) + """Build a string consisting of 'key=value' substrings for each keyword + argument in :kwargs: + + @param filterKeys: list of key names to ignore + @param filterValues: list of values to ignore (e.g. None will ignore all + key=value pairs that has that value. + """ + return ', '.join([str(k)+'='+repr(v) for k, v in kwargs.iteritems() + if k not in filterKeys and v not in filterValues])
925270e5dd8ffcc72b95bf431444bce480fa18bb
simphony/engine/__init__.py
simphony/engine/__init__.py
from ..extension import get_engine_manager from ..extension import create_wrapper __all__ = ['get_supported_engines', 'create_wrapper', 'get_supported_engine_names'] def get_supported_engine_names(): """Show a list of supported engine names. Returns ------- names: list a list of engine names """ return get_engine_manager().get_supported_engine_names() def get_supported_engines(): """Show a list of supported engines. Returns ------- metadata: list a list of engine metadata objects """ return get_engine_manager().get_supported_engines() def load_engine_extentions(): """ Discover and load engine extension modules. """ from stevedore import extension mgr = extension.ExtensionManager( namespace='simphony.engine', invoke_on_load=False) extensions = {} engine_manager = get_engine_manager() for ext in mgr.extensions: extensions[ext.name] = ext.plugin # Load engine metadata engine_manager.load_metadata(ext.plugin) return extensions # Populate the module namespace globals().update(load_engine_extentions()) # cleanup del load_engine_extentions
from ..extension import get_engine_manager __all__ = ['get_supported_engines', 'get_supported_engine_names'] def get_supported_engine_names(): """Show a list of supported engine names. Returns ------- names: list a list of engine names """ return get_engine_manager().get_supported_engine_names() def get_supported_engines(): """Show a list of supported engines. Returns ------- metadata: list a list of engine metadata objects """ return get_engine_manager().get_supported_engines() def load_engine_extentions(): """ Discover and load engine extension modules. """ from stevedore import extension mgr = extension.ExtensionManager( namespace='simphony.engine', invoke_on_load=False) extensions = {} engine_manager = get_engine_manager() for ext in mgr.extensions: extensions[ext.name] = ext.plugin # Load engine metadata engine_manager.load_metadata(ext.plugin) return extensions # Populate the module namespace globals().update(load_engine_extentions()) # cleanup del load_engine_extentions
Remove create_wrapper from the API
Remove create_wrapper from the API
Python
bsd-2-clause
simphony/simphony-common
from ..extension import get_engine_manager - from ..extension import create_wrapper - __all__ = ['get_supported_engines', 'create_wrapper', + __all__ = ['get_supported_engines', 'get_supported_engine_names'] def get_supported_engine_names(): """Show a list of supported engine names. Returns ------- names: list a list of engine names """ return get_engine_manager().get_supported_engine_names() def get_supported_engines(): """Show a list of supported engines. Returns ------- metadata: list a list of engine metadata objects """ return get_engine_manager().get_supported_engines() def load_engine_extentions(): """ Discover and load engine extension modules. """ from stevedore import extension mgr = extension.ExtensionManager( namespace='simphony.engine', invoke_on_load=False) extensions = {} engine_manager = get_engine_manager() for ext in mgr.extensions: extensions[ext.name] = ext.plugin # Load engine metadata engine_manager.load_metadata(ext.plugin) return extensions # Populate the module namespace globals().update(load_engine_extentions()) # cleanup del load_engine_extentions
Remove create_wrapper from the API
## Code Before: from ..extension import get_engine_manager from ..extension import create_wrapper __all__ = ['get_supported_engines', 'create_wrapper', 'get_supported_engine_names'] def get_supported_engine_names(): """Show a list of supported engine names. Returns ------- names: list a list of engine names """ return get_engine_manager().get_supported_engine_names() def get_supported_engines(): """Show a list of supported engines. Returns ------- metadata: list a list of engine metadata objects """ return get_engine_manager().get_supported_engines() def load_engine_extentions(): """ Discover and load engine extension modules. """ from stevedore import extension mgr = extension.ExtensionManager( namespace='simphony.engine', invoke_on_load=False) extensions = {} engine_manager = get_engine_manager() for ext in mgr.extensions: extensions[ext.name] = ext.plugin # Load engine metadata engine_manager.load_metadata(ext.plugin) return extensions # Populate the module namespace globals().update(load_engine_extentions()) # cleanup del load_engine_extentions ## Instruction: Remove create_wrapper from the API ## Code After: from ..extension import get_engine_manager __all__ = ['get_supported_engines', 'get_supported_engine_names'] def get_supported_engine_names(): """Show a list of supported engine names. Returns ------- names: list a list of engine names """ return get_engine_manager().get_supported_engine_names() def get_supported_engines(): """Show a list of supported engines. Returns ------- metadata: list a list of engine metadata objects """ return get_engine_manager().get_supported_engines() def load_engine_extentions(): """ Discover and load engine extension modules. """ from stevedore import extension mgr = extension.ExtensionManager( namespace='simphony.engine', invoke_on_load=False) extensions = {} engine_manager = get_engine_manager() for ext in mgr.extensions: extensions[ext.name] = ext.plugin # Load engine metadata engine_manager.load_metadata(ext.plugin) return extensions # Populate the module namespace globals().update(load_engine_extentions()) # cleanup del load_engine_extentions
from ..extension import get_engine_manager - from ..extension import create_wrapper - __all__ = ['get_supported_engines', 'create_wrapper', ? ------------------ + __all__ = ['get_supported_engines', 'get_supported_engine_names'] def get_supported_engine_names(): """Show a list of supported engine names. Returns ------- names: list a list of engine names """ return get_engine_manager().get_supported_engine_names() def get_supported_engines(): """Show a list of supported engines. Returns ------- metadata: list a list of engine metadata objects """ return get_engine_manager().get_supported_engines() def load_engine_extentions(): """ Discover and load engine extension modules. """ from stevedore import extension mgr = extension.ExtensionManager( namespace='simphony.engine', invoke_on_load=False) extensions = {} engine_manager = get_engine_manager() for ext in mgr.extensions: extensions[ext.name] = ext.plugin # Load engine metadata engine_manager.load_metadata(ext.plugin) return extensions # Populate the module namespace globals().update(load_engine_extentions()) # cleanup del load_engine_extentions
8d339d610b57b40534af2a8d7cdbdaec041a995a
test/TestNGrams.py
test/TestNGrams.py
import unittest import NGrams class TestNGrams(unittest.TestCase): def test_unigrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 1) self.assertEqual(ngram_list, [['this'], ['is'], ['a'], ['random'], ['piece'], ['of'], ['text']]) def test_bigrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 2) self.assertEqual(ngram_list, [['this', 'is'], ['is', 'a'], ['a', 'random'], ['random', 'piece'], ['piece', 'of'], ['of', 'text']]) def test_fourgrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 4) self.assertEqual(ngram_list, [['this', 'is', 'a', 'random'], ['is', 'a', 'random', 'piece'], ['a', 'random', 'piece', 'of'], ['random', 'piece', 'of', 'text']]) if __name__ == '__main__': unittest.main()
import unittest import sys sys.path.append('../src') import NGrams class TestNGrams(unittest.TestCase): def test_unigrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 1) self.assertEqual(ngram_list, [['this'], ['is'], ['a'], ['random'], ['piece'], ['of'], ['text']]) def test_bigrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 2) self.assertEqual(ngram_list, [['this', 'is'], ['is', 'a'], ['a', 'random'], ['random', 'piece'], ['piece', 'of'], ['of', 'text']]) def test_fourgrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 4) self.assertEqual(ngram_list, [['this', 'is', 'a', 'random'], ['is', 'a', 'random', 'piece'], ['a', 'random', 'piece', 'of'], ['random', 'piece', 'of', 'text']]) if __name__ == '__main__': unittest.main()
Add path in test to src
Add path in test to src
Python
bsd-2-clause
ambidextrousTx/RNLTK
import unittest + import sys + sys.path.append('../src') import NGrams class TestNGrams(unittest.TestCase): def test_unigrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 1) self.assertEqual(ngram_list, [['this'], ['is'], ['a'], ['random'], ['piece'], ['of'], ['text']]) def test_bigrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 2) self.assertEqual(ngram_list, [['this', 'is'], ['is', 'a'], ['a', 'random'], ['random', 'piece'], ['piece', 'of'], ['of', 'text']]) def test_fourgrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 4) self.assertEqual(ngram_list, [['this', 'is', 'a', 'random'], ['is', 'a', 'random', 'piece'], ['a', 'random', 'piece', 'of'], ['random', 'piece', 'of', 'text']]) if __name__ == '__main__': unittest.main()
Add path in test to src
## Code Before: import unittest import NGrams class TestNGrams(unittest.TestCase): def test_unigrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 1) self.assertEqual(ngram_list, [['this'], ['is'], ['a'], ['random'], ['piece'], ['of'], ['text']]) def test_bigrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 2) self.assertEqual(ngram_list, [['this', 'is'], ['is', 'a'], ['a', 'random'], ['random', 'piece'], ['piece', 'of'], ['of', 'text']]) def test_fourgrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 4) self.assertEqual(ngram_list, [['this', 'is', 'a', 'random'], ['is', 'a', 'random', 'piece'], ['a', 'random', 'piece', 'of'], ['random', 'piece', 'of', 'text']]) if __name__ == '__main__': unittest.main() ## Instruction: Add path in test to src ## Code After: import unittest import sys sys.path.append('../src') import NGrams class TestNGrams(unittest.TestCase): def test_unigrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 1) self.assertEqual(ngram_list, [['this'], ['is'], ['a'], ['random'], ['piece'], ['of'], ['text']]) def test_bigrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 2) self.assertEqual(ngram_list, [['this', 'is'], ['is', 'a'], ['a', 'random'], ['random', 'piece'], ['piece', 'of'], ['of', 'text']]) def test_fourgrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 4) self.assertEqual(ngram_list, [['this', 'is', 'a', 'random'], ['is', 'a', 'random', 'piece'], ['a', 'random', 'piece', 'of'], ['random', 'piece', 'of', 'text']]) if __name__ == '__main__': unittest.main()
import unittest + import sys + sys.path.append('../src') import NGrams class TestNGrams(unittest.TestCase): def test_unigrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 1) self.assertEqual(ngram_list, [['this'], ['is'], ['a'], ['random'], ['piece'], ['of'], ['text']]) def test_bigrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 2) self.assertEqual(ngram_list, [['this', 'is'], ['is', 'a'], ['a', 'random'], ['random', 'piece'], ['piece', 'of'], ['of', 'text']]) def test_fourgrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 4) self.assertEqual(ngram_list, [['this', 'is', 'a', 'random'], ['is', 'a', 'random', 'piece'], ['a', 'random', 'piece', 'of'], ['random', 'piece', 'of', 'text']]) if __name__ == '__main__': unittest.main()
364d83c8add1fdde679aa2823ae94ad7f264cb48
raco/relation_key.py
raco/relation_key.py
class RelationKey(object): def __init__(self, user='public', program='adhoc', relation=None): assert relation self.user = user self.program = program self.relation = relation def __repr__(self): return 'RelationKey(%s,%s,%s)' % (self.user, self.program, self.relation) def __str__(self): return '%s:%s:%s' % (self.user, self.program, self.relation) def __eq__(self, other): return self.user == other.user and self.program == other.program \ and self.relation == other.relation @classmethod def from_string(cls, s): """Create a RelationKey from a colon-delimited string.""" toks = s.split(':') assert len(toks) <= 3 args = {'relation' : toks[-1]} try: args['program'] = toks[-2] args['user'] = toks[-3] except IndexError: pass return cls(**args)
class RelationKey(object): def __init__(self, user='public', program='adhoc', relation=None): assert relation self.user = user self.program = program self.relation = relation def __repr__(self): return 'RelationKey(%s,%s,%s)' % (self.user, self.program, self.relation) def __str__(self): return '%s:%s:%s' % (self.user, self.program, self.relation) def __eq__(self, other): return self.__dict__ == other.__dict__ def __hash__(self): return hash(str(self)) @classmethod def from_string(cls, s): """Create a RelationKey from a colon-delimited string.""" toks = s.split(':') assert len(toks) <= 3 args = {'relation' : toks[-1]} try: args['program'] = toks[-2] args['user'] = toks[-3] except IndexError: pass return cls(**args)
Add hash function to RelationKey
Add hash function to RelationKey
Python
bsd-3-clause
uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco
class RelationKey(object): def __init__(self, user='public', program='adhoc', relation=None): assert relation self.user = user self.program = program self.relation = relation def __repr__(self): return 'RelationKey(%s,%s,%s)' % (self.user, self.program, self.relation) def __str__(self): return '%s:%s:%s' % (self.user, self.program, self.relation) def __eq__(self, other): - return self.user == other.user and self.program == other.program \ - and self.relation == other.relation + return self.__dict__ == other.__dict__ + + def __hash__(self): + return hash(str(self)) @classmethod def from_string(cls, s): """Create a RelationKey from a colon-delimited string.""" toks = s.split(':') assert len(toks) <= 3 args = {'relation' : toks[-1]} try: args['program'] = toks[-2] args['user'] = toks[-3] except IndexError: pass return cls(**args)
Add hash function to RelationKey
## Code Before: class RelationKey(object): def __init__(self, user='public', program='adhoc', relation=None): assert relation self.user = user self.program = program self.relation = relation def __repr__(self): return 'RelationKey(%s,%s,%s)' % (self.user, self.program, self.relation) def __str__(self): return '%s:%s:%s' % (self.user, self.program, self.relation) def __eq__(self, other): return self.user == other.user and self.program == other.program \ and self.relation == other.relation @classmethod def from_string(cls, s): """Create a RelationKey from a colon-delimited string.""" toks = s.split(':') assert len(toks) <= 3 args = {'relation' : toks[-1]} try: args['program'] = toks[-2] args['user'] = toks[-3] except IndexError: pass return cls(**args) ## Instruction: Add hash function to RelationKey ## Code After: class RelationKey(object): def __init__(self, user='public', program='adhoc', relation=None): assert relation self.user = user self.program = program self.relation = relation def __repr__(self): return 'RelationKey(%s,%s,%s)' % (self.user, self.program, self.relation) def __str__(self): return '%s:%s:%s' % (self.user, self.program, self.relation) def __eq__(self, other): return self.__dict__ == other.__dict__ def __hash__(self): return hash(str(self)) @classmethod def from_string(cls, s): """Create a RelationKey from a colon-delimited string.""" toks = s.split(':') assert len(toks) <= 3 args = {'relation' : toks[-1]} try: args['program'] = toks[-2] args['user'] = toks[-3] except IndexError: pass return cls(**args)
class RelationKey(object): def __init__(self, user='public', program='adhoc', relation=None): assert relation self.user = user self.program = program self.relation = relation def __repr__(self): return 'RelationKey(%s,%s,%s)' % (self.user, self.program, self.relation) def __str__(self): return '%s:%s:%s' % (self.user, self.program, self.relation) def __eq__(self, other): - return self.user == other.user and self.program == other.program \ - and self.relation == other.relation + return self.__dict__ == other.__dict__ + + def __hash__(self): + return hash(str(self)) @classmethod def from_string(cls, s): """Create a RelationKey from a colon-delimited string.""" toks = s.split(':') assert len(toks) <= 3 args = {'relation' : toks[-1]} try: args['program'] = toks[-2] args['user'] = toks[-3] except IndexError: pass return cls(**args)
37fa40a9b5260f8090adaa8c15d3767c0867574f
python/fusion_engine_client/messages/__init__.py
python/fusion_engine_client/messages/__init__.py
from .core import * from . import ros message_type_to_class = { # Navigation solution messages. PoseMessage.MESSAGE_TYPE: PoseMessage, PoseAuxMessage.MESSAGE_TYPE: PoseAuxMessage, GNSSInfoMessage.MESSAGE_TYPE: GNSSInfoMessage, GNSSSatelliteMessage.MESSAGE_TYPE: GNSSSatelliteMessage, # Sensor measurement messages. IMUMeasurement.MESSAGE_TYPE: IMUMeasurement, # ROS messages. ros.PoseMessage.MESSAGE_TYPE: ros.PoseMessage, ros.GPSFixMessage.MESSAGE_TYPE: ros.GPSFixMessage, ros.IMUMessage.MESSAGE_TYPE: ros.IMUMessage, # Command and control messages. CommandResponseMessage.MESSAGE_TYPE: CommandResponseMessage, MessageRequest.MESSAGE_TYPE: MessageRequest, ResetRequest.MESSAGE_TYPE: ResetRequest, VersionInfoMessage.MESSAGE_TYPE: VersionInfoMessage, EventNotificationMessage.MESSAGE_TYPE: EventNotificationMessage, }
from .core import * from . import ros message_type_to_class = { # Navigation solution messages. PoseMessage.MESSAGE_TYPE: PoseMessage, PoseAuxMessage.MESSAGE_TYPE: PoseAuxMessage, GNSSInfoMessage.MESSAGE_TYPE: GNSSInfoMessage, GNSSSatelliteMessage.MESSAGE_TYPE: GNSSSatelliteMessage, # Sensor measurement messages. IMUMeasurement.MESSAGE_TYPE: IMUMeasurement, # ROS messages. ros.PoseMessage.MESSAGE_TYPE: ros.PoseMessage, ros.GPSFixMessage.MESSAGE_TYPE: ros.GPSFixMessage, ros.IMUMessage.MESSAGE_TYPE: ros.IMUMessage, # Command and control messages. CommandResponseMessage.MESSAGE_TYPE: CommandResponseMessage, MessageRequest.MESSAGE_TYPE: MessageRequest, ResetRequest.MESSAGE_TYPE: ResetRequest, VersionInfoMessage.MESSAGE_TYPE: VersionInfoMessage, EventNotificationMessage.MESSAGE_TYPE: EventNotificationMessage, } messages_with_system_time = [t for t, c in message_type_to_class.items() if hasattr(c(), 'system_time_ns')]
Create a list of messages that contain system time.
Create a list of messages that contain system time.
Python
mit
PointOneNav/fusion-engine-client,PointOneNav/fusion-engine-client,PointOneNav/fusion-engine-client
from .core import * from . import ros message_type_to_class = { # Navigation solution messages. PoseMessage.MESSAGE_TYPE: PoseMessage, PoseAuxMessage.MESSAGE_TYPE: PoseAuxMessage, GNSSInfoMessage.MESSAGE_TYPE: GNSSInfoMessage, GNSSSatelliteMessage.MESSAGE_TYPE: GNSSSatelliteMessage, # Sensor measurement messages. IMUMeasurement.MESSAGE_TYPE: IMUMeasurement, # ROS messages. ros.PoseMessage.MESSAGE_TYPE: ros.PoseMessage, ros.GPSFixMessage.MESSAGE_TYPE: ros.GPSFixMessage, ros.IMUMessage.MESSAGE_TYPE: ros.IMUMessage, # Command and control messages. CommandResponseMessage.MESSAGE_TYPE: CommandResponseMessage, MessageRequest.MESSAGE_TYPE: MessageRequest, ResetRequest.MESSAGE_TYPE: ResetRequest, VersionInfoMessage.MESSAGE_TYPE: VersionInfoMessage, EventNotificationMessage.MESSAGE_TYPE: EventNotificationMessage, } + messages_with_system_time = [t for t, c in message_type_to_class.items() if hasattr(c(), 'system_time_ns')] +
Create a list of messages that contain system time.
## Code Before: from .core import * from . import ros message_type_to_class = { # Navigation solution messages. PoseMessage.MESSAGE_TYPE: PoseMessage, PoseAuxMessage.MESSAGE_TYPE: PoseAuxMessage, GNSSInfoMessage.MESSAGE_TYPE: GNSSInfoMessage, GNSSSatelliteMessage.MESSAGE_TYPE: GNSSSatelliteMessage, # Sensor measurement messages. IMUMeasurement.MESSAGE_TYPE: IMUMeasurement, # ROS messages. ros.PoseMessage.MESSAGE_TYPE: ros.PoseMessage, ros.GPSFixMessage.MESSAGE_TYPE: ros.GPSFixMessage, ros.IMUMessage.MESSAGE_TYPE: ros.IMUMessage, # Command and control messages. CommandResponseMessage.MESSAGE_TYPE: CommandResponseMessage, MessageRequest.MESSAGE_TYPE: MessageRequest, ResetRequest.MESSAGE_TYPE: ResetRequest, VersionInfoMessage.MESSAGE_TYPE: VersionInfoMessage, EventNotificationMessage.MESSAGE_TYPE: EventNotificationMessage, } ## Instruction: Create a list of messages that contain system time. ## Code After: from .core import * from . import ros message_type_to_class = { # Navigation solution messages. PoseMessage.MESSAGE_TYPE: PoseMessage, PoseAuxMessage.MESSAGE_TYPE: PoseAuxMessage, GNSSInfoMessage.MESSAGE_TYPE: GNSSInfoMessage, GNSSSatelliteMessage.MESSAGE_TYPE: GNSSSatelliteMessage, # Sensor measurement messages. IMUMeasurement.MESSAGE_TYPE: IMUMeasurement, # ROS messages. ros.PoseMessage.MESSAGE_TYPE: ros.PoseMessage, ros.GPSFixMessage.MESSAGE_TYPE: ros.GPSFixMessage, ros.IMUMessage.MESSAGE_TYPE: ros.IMUMessage, # Command and control messages. CommandResponseMessage.MESSAGE_TYPE: CommandResponseMessage, MessageRequest.MESSAGE_TYPE: MessageRequest, ResetRequest.MESSAGE_TYPE: ResetRequest, VersionInfoMessage.MESSAGE_TYPE: VersionInfoMessage, EventNotificationMessage.MESSAGE_TYPE: EventNotificationMessage, } messages_with_system_time = [t for t, c in message_type_to_class.items() if hasattr(c(), 'system_time_ns')]
from .core import * from . import ros message_type_to_class = { # Navigation solution messages. PoseMessage.MESSAGE_TYPE: PoseMessage, PoseAuxMessage.MESSAGE_TYPE: PoseAuxMessage, GNSSInfoMessage.MESSAGE_TYPE: GNSSInfoMessage, GNSSSatelliteMessage.MESSAGE_TYPE: GNSSSatelliteMessage, # Sensor measurement messages. IMUMeasurement.MESSAGE_TYPE: IMUMeasurement, # ROS messages. ros.PoseMessage.MESSAGE_TYPE: ros.PoseMessage, ros.GPSFixMessage.MESSAGE_TYPE: ros.GPSFixMessage, ros.IMUMessage.MESSAGE_TYPE: ros.IMUMessage, # Command and control messages. CommandResponseMessage.MESSAGE_TYPE: CommandResponseMessage, MessageRequest.MESSAGE_TYPE: MessageRequest, ResetRequest.MESSAGE_TYPE: ResetRequest, VersionInfoMessage.MESSAGE_TYPE: VersionInfoMessage, EventNotificationMessage.MESSAGE_TYPE: EventNotificationMessage, } + + messages_with_system_time = [t for t, c in message_type_to_class.items() if hasattr(c(), 'system_time_ns')]
0e8d4e6649b6a48ac7bd87746574119a5ce5fd1a
qiime_studio/api/v1.py
qiime_studio/api/v1.py
from flask import Blueprint, jsonify from .security import validate_request_authentication from qiime.sdk import PluginManager v1 = Blueprint('v1', __name__) v1.before_request(validate_request_authentication) @v1.route('/', methods=['GET', 'POST']) def root(): return jsonify(content="!") @v1.route('/plugins', methods=['GET']) def plugins(): pm = PluginManager() return jsonify(pm.plugins)
from flask import Blueprint, jsonify from .security import validate_request_authentication from qiime.sdk import PluginManager PLUGIN_MANAGER = PluginManager() v1 = Blueprint('v1', __name__) v1.before_request(validate_request_authentication) @v1.route('/', methods=['GET', 'POST']) def root(): return jsonify(content="!") @v1.route('/plugins', methods=['GET']) def api_plugins(): plugin_list = list(PLUGIN_MANAGER.plugins.keys()) return jsonify({"names": plugin_list}) @v1.route('/workflows/<plugin_name>', methods=['GET']) def api_workflows(plugin_name): plugin = PLUGIN_MANAGER.plugins[plugin_name] workflows_dict = {} for key, value in plugin.workflows.items(): workflows_dict[key] = {} workflows_dict[key]['info'] = "Produces: {}".format(list(value.signature.output_artifacts.values())) return jsonify({"workflows": workflows_dict})
Add plugin workflow fetching to API
Add plugin workflow fetching to API
Python
bsd-3-clause
jakereps/qiime-studio,qiime2/qiime-studio,qiime2/qiime-studio-frontend,jakereps/qiime-studio,jakereps/qiime-studio,qiime2/qiime-studio-frontend,jakereps/qiime-studio-frontend,qiime2/qiime-studio,jakereps/qiime-studio-frontend,qiime2/qiime-studio
from flask import Blueprint, jsonify from .security import validate_request_authentication from qiime.sdk import PluginManager + PLUGIN_MANAGER = PluginManager() v1 = Blueprint('v1', __name__) v1.before_request(validate_request_authentication) @v1.route('/', methods=['GET', 'POST']) def root(): return jsonify(content="!") + @v1.route('/plugins', methods=['GET']) - def plugins(): + def api_plugins(): - pm = PluginManager() + plugin_list = list(PLUGIN_MANAGER.plugins.keys()) - return jsonify(pm.plugins) + return jsonify({"names": plugin_list}) + + @v1.route('/workflows/<plugin_name>', methods=['GET']) + def api_workflows(plugin_name): + plugin = PLUGIN_MANAGER.plugins[plugin_name] + workflows_dict = {} + for key, value in plugin.workflows.items(): + workflows_dict[key] = {} + workflows_dict[key]['info'] = "Produces: {}".format(list(value.signature.output_artifacts.values())) + return jsonify({"workflows": workflows_dict}) +
Add plugin workflow fetching to API
## Code Before: from flask import Blueprint, jsonify from .security import validate_request_authentication from qiime.sdk import PluginManager v1 = Blueprint('v1', __name__) v1.before_request(validate_request_authentication) @v1.route('/', methods=['GET', 'POST']) def root(): return jsonify(content="!") @v1.route('/plugins', methods=['GET']) def plugins(): pm = PluginManager() return jsonify(pm.plugins) ## Instruction: Add plugin workflow fetching to API ## Code After: from flask import Blueprint, jsonify from .security import validate_request_authentication from qiime.sdk import PluginManager PLUGIN_MANAGER = PluginManager() v1 = Blueprint('v1', __name__) v1.before_request(validate_request_authentication) @v1.route('/', methods=['GET', 'POST']) def root(): return jsonify(content="!") @v1.route('/plugins', methods=['GET']) def api_plugins(): plugin_list = list(PLUGIN_MANAGER.plugins.keys()) return jsonify({"names": plugin_list}) @v1.route('/workflows/<plugin_name>', methods=['GET']) def api_workflows(plugin_name): plugin = PLUGIN_MANAGER.plugins[plugin_name] workflows_dict = {} for key, value in plugin.workflows.items(): workflows_dict[key] = {} workflows_dict[key]['info'] = "Produces: {}".format(list(value.signature.output_artifacts.values())) return jsonify({"workflows": workflows_dict})
from flask import Blueprint, jsonify from .security import validate_request_authentication from qiime.sdk import PluginManager + PLUGIN_MANAGER = PluginManager() v1 = Blueprint('v1', __name__) v1.before_request(validate_request_authentication) @v1.route('/', methods=['GET', 'POST']) def root(): return jsonify(content="!") + @v1.route('/plugins', methods=['GET']) - def plugins(): + def api_plugins(): ? ++++ - pm = PluginManager() + plugin_list = list(PLUGIN_MANAGER.plugins.keys()) - return jsonify(pm.plugins) ? ^ ^ + return jsonify({"names": plugin_list}) ? ^^^^ ^^^^^ +++ ++ + + + @v1.route('/workflows/<plugin_name>', methods=['GET']) + def api_workflows(plugin_name): + plugin = PLUGIN_MANAGER.plugins[plugin_name] + workflows_dict = {} + for key, value in plugin.workflows.items(): + workflows_dict[key] = {} + workflows_dict[key]['info'] = "Produces: {}".format(list(value.signature.output_artifacts.values())) + return jsonify({"workflows": workflows_dict})
2f8c3ab7ecd0606069d524192c551e7be77ca461
zhihudaily/views/with_image.py
zhihudaily/views/with_image.py
from __future__ import absolute_import, unicode_literals import datetime from flask import render_template, Blueprint from zhihudaily.utils import make_request from zhihudaily.cache import cache image_ui = Blueprint('image_ui', __name__, template_folder='templates') @image_ui.route('/withimage') @cache.cached(timeout=900) def with_image(): """The page for 图片 UI.""" r = make_request('http://news.at.zhihu.com/api/1.2/news/latest') (display_date, date, news_list) = get_news_info(r) news_list = handle_image(news_list) day_before = ( datetime.datetime.strptime(date, '%Y%m%d') - datetime.timedelta(1) ).strftime('%Y%m%d') return render_template('with_image.html', lists=news_list, display_date=display_date, day_before=day_before, is_today=True)
from __future__ import absolute_import, unicode_literals from flask import render_template, Blueprint, json from zhihudaily.cache import cache from zhihudaily.models import Zhihudaily from zhihudaily.utils import Date image_ui = Blueprint('image_ui', __name__, template_folder='templates') @image_ui.route('/withimage') @cache.cached(timeout=900) def with_image(): """The page for 图片 UI.""" day = Date() news = Zhihudaily.select().where(Zhihudaily.date == int(day.today)).get() return render_template('with_image.html', lists=json.loads(news.json_news), display_date=news.display_date, day_before=day.day_before, is_today=True)
Switch to use database for image ui
Switch to use database for image ui
Python
mit
lord63/zhihudaily,lord63/zhihudaily,lord63/zhihudaily
from __future__ import absolute_import, unicode_literals - import datetime - from flask import render_template, Blueprint + from flask import render_template, Blueprint, json - from zhihudaily.utils import make_request from zhihudaily.cache import cache + from zhihudaily.models import Zhihudaily + from zhihudaily.utils import Date image_ui = Blueprint('image_ui', __name__, template_folder='templates') @image_ui.route('/withimage') @cache.cached(timeout=900) def with_image(): """The page for 图片 UI.""" + day = Date() + news = Zhihudaily.select().where(Zhihudaily.date == int(day.today)).get() + - r = make_request('http://news.at.zhihu.com/api/1.2/news/latest') - (display_date, date, news_list) = get_news_info(r) - news_list = handle_image(news_list) - day_before = ( - datetime.datetime.strptime(date, '%Y%m%d') - datetime.timedelta(1) - ).strftime('%Y%m%d') - return render_template('with_image.html', lists=news_list, + return render_template('with_image.html', + lists=json.loads(news.json_news), - display_date=display_date, + display_date=news.display_date, - day_before=day_before, + day_before=day.day_before, is_today=True)
Switch to use database for image ui
## Code Before: from __future__ import absolute_import, unicode_literals import datetime from flask import render_template, Blueprint from zhihudaily.utils import make_request from zhihudaily.cache import cache image_ui = Blueprint('image_ui', __name__, template_folder='templates') @image_ui.route('/withimage') @cache.cached(timeout=900) def with_image(): """The page for 图片 UI.""" r = make_request('http://news.at.zhihu.com/api/1.2/news/latest') (display_date, date, news_list) = get_news_info(r) news_list = handle_image(news_list) day_before = ( datetime.datetime.strptime(date, '%Y%m%d') - datetime.timedelta(1) ).strftime('%Y%m%d') return render_template('with_image.html', lists=news_list, display_date=display_date, day_before=day_before, is_today=True) ## Instruction: Switch to use database for image ui ## Code After: from __future__ import absolute_import, unicode_literals from flask import render_template, Blueprint, json from zhihudaily.cache import cache from zhihudaily.models import Zhihudaily from zhihudaily.utils import Date image_ui = Blueprint('image_ui', __name__, template_folder='templates') @image_ui.route('/withimage') @cache.cached(timeout=900) def with_image(): """The page for 图片 UI.""" day = Date() news = Zhihudaily.select().where(Zhihudaily.date == int(day.today)).get() return render_template('with_image.html', lists=json.loads(news.json_news), display_date=news.display_date, day_before=day.day_before, is_today=True)
from __future__ import absolute_import, unicode_literals - import datetime - from flask import render_template, Blueprint + from flask import render_template, Blueprint, json ? ++++++ - from zhihudaily.utils import make_request from zhihudaily.cache import cache + from zhihudaily.models import Zhihudaily + from zhihudaily.utils import Date image_ui = Blueprint('image_ui', __name__, template_folder='templates') @image_ui.route('/withimage') @cache.cached(timeout=900) def with_image(): """The page for 图片 UI.""" + day = Date() + news = Zhihudaily.select().where(Zhihudaily.date == int(day.today)).get() + - r = make_request('http://news.at.zhihu.com/api/1.2/news/latest') - (display_date, date, news_list) = get_news_info(r) - news_list = handle_image(news_list) - day_before = ( - datetime.datetime.strptime(date, '%Y%m%d') - datetime.timedelta(1) - ).strftime('%Y%m%d') - return render_template('with_image.html', lists=news_list, ? ----------------- + return render_template('with_image.html', + lists=json.loads(news.json_news), - display_date=display_date, + display_date=news.display_date, ? +++++ - day_before=day_before, + day_before=day.day_before, ? ++++ is_today=True)
bc0022c32ef912eba9cc3d9683c1649443d6aa35
pyfibot/modules/module_btc.py
pyfibot/modules/module_btc.py
from __future__ import unicode_literals, print_function, division def command_btc(bot, user, channel, args): """Display current BTC exchange rates from mtgox. Usage: btc [whitespace separated list of currency codes]""" currencies = ["EUR"] if args: currencies = args.split(" ") rates = [] for currency in currencies: rate = gen_string(bot, currency) if rate: rates.append(rate) if rates: return bot.say(channel, "1 BTC = %s" % " | ".join(rates)) def gen_string(bot, currency): r = bot.get_url("http://data.mtgox.com/api/1/BTC%s/ticker" % currency) if r.json()['result'] != 'success': return None data = r.json()['return'] avg = data['avg']['display_short'] low = data['low']['display_short'] high = data['high']['display_short'] vol = data['vol']['display_short'] return "%s avg:%s low:%s high:%s vol:%s" % (currency.upper(), avg, low, high, vol)
from __future__ import unicode_literals, print_function, division def command_btc(bot, user, channel, args): """Display current BTC exchange rates from mtgox. Usage: btc [whitespace separated list of currency codes]""" currencies = ["EUR"] if args: currencies = args.split(" ") return bot.say(channel, get_coin_value(bot, "BTC", currencies)) def command_ltc(bot, user, channel, args): """Display current LTC exchange rates from mtgox. Usage: ltc [whitespace separated list of currency codes]""" currencies = ["EUR"] if args: currencies = args.split(" ") return bot.say(channel, get_coin_value(bot, "LTC", currencies)) def get_coin_value(bot, coin, currencies): rates = [] for currency in currencies: rate = gen_string(bot, coin, currency) if rate: rates.append(rate) if rates: return "1 %s = %s" % (coin, " | ".join(rates)) else: return None def gen_string(bot, coin="BTC", currency="EUR"): r = bot.get_url("http://data.mtgox.com/api/1/%s%s/ticker" % (coin, currency)) if r.json()['result'] != 'success': return None data = r.json()['return'] avg = data['avg']['display_short'] low = data['low']['display_short'] high = data['high']['display_short'] vol = data['vol']['display_short'] return "%s avg:%s low:%s high:%s vol:%s" % (currency.upper(), avg, low, high, vol)
Add support for LTC in mtgox
Add support for LTC in mtgox
Python
bsd-3-clause
rnyberg/pyfibot,EArmour/pyfibot,EArmour/pyfibot,aapa/pyfibot,lepinkainen/pyfibot,huqa/pyfibot,rnyberg/pyfibot,huqa/pyfibot,aapa/pyfibot,lepinkainen/pyfibot
from __future__ import unicode_literals, print_function, division def command_btc(bot, user, channel, args): """Display current BTC exchange rates from mtgox. Usage: btc [whitespace separated list of currency codes]""" currencies = ["EUR"] if args: currencies = args.split(" ") + return bot.say(channel, get_coin_value(bot, "BTC", currencies)) + + + def command_ltc(bot, user, channel, args): + """Display current LTC exchange rates from mtgox. Usage: ltc [whitespace separated list of currency codes]""" + currencies = ["EUR"] + + if args: + currencies = args.split(" ") + + return bot.say(channel, get_coin_value(bot, "LTC", currencies)) + + + def get_coin_value(bot, coin, currencies): + rates = [] for currency in currencies: - rate = gen_string(bot, currency) + rate = gen_string(bot, coin, currency) if rate: rates.append(rate) if rates: - return bot.say(channel, "1 BTC = %s" % " | ".join(rates)) + return "1 %s = %s" % (coin, " | ".join(rates)) + else: + return None - def gen_string(bot, currency): + def gen_string(bot, coin="BTC", currency="EUR"): - r = bot.get_url("http://data.mtgox.com/api/1/BTC%s/ticker" % currency) + r = bot.get_url("http://data.mtgox.com/api/1/%s%s/ticker" % (coin, currency)) if r.json()['result'] != 'success': return None data = r.json()['return'] avg = data['avg']['display_short'] low = data['low']['display_short'] high = data['high']['display_short'] vol = data['vol']['display_short'] return "%s avg:%s low:%s high:%s vol:%s" % (currency.upper(), avg, low, high, vol)
Add support for LTC in mtgox
## Code Before: from __future__ import unicode_literals, print_function, division def command_btc(bot, user, channel, args): """Display current BTC exchange rates from mtgox. Usage: btc [whitespace separated list of currency codes]""" currencies = ["EUR"] if args: currencies = args.split(" ") rates = [] for currency in currencies: rate = gen_string(bot, currency) if rate: rates.append(rate) if rates: return bot.say(channel, "1 BTC = %s" % " | ".join(rates)) def gen_string(bot, currency): r = bot.get_url("http://data.mtgox.com/api/1/BTC%s/ticker" % currency) if r.json()['result'] != 'success': return None data = r.json()['return'] avg = data['avg']['display_short'] low = data['low']['display_short'] high = data['high']['display_short'] vol = data['vol']['display_short'] return "%s avg:%s low:%s high:%s vol:%s" % (currency.upper(), avg, low, high, vol) ## Instruction: Add support for LTC in mtgox ## Code After: from __future__ import unicode_literals, print_function, division def command_btc(bot, user, channel, args): """Display current BTC exchange rates from mtgox. Usage: btc [whitespace separated list of currency codes]""" currencies = ["EUR"] if args: currencies = args.split(" ") return bot.say(channel, get_coin_value(bot, "BTC", currencies)) def command_ltc(bot, user, channel, args): """Display current LTC exchange rates from mtgox. Usage: ltc [whitespace separated list of currency codes]""" currencies = ["EUR"] if args: currencies = args.split(" ") return bot.say(channel, get_coin_value(bot, "LTC", currencies)) def get_coin_value(bot, coin, currencies): rates = [] for currency in currencies: rate = gen_string(bot, coin, currency) if rate: rates.append(rate) if rates: return "1 %s = %s" % (coin, " | ".join(rates)) else: return None def gen_string(bot, coin="BTC", currency="EUR"): r = bot.get_url("http://data.mtgox.com/api/1/%s%s/ticker" % (coin, currency)) if r.json()['result'] != 'success': return None data = r.json()['return'] avg = data['avg']['display_short'] low = data['low']['display_short'] high = data['high']['display_short'] vol = data['vol']['display_short'] return "%s avg:%s low:%s high:%s vol:%s" % (currency.upper(), avg, low, high, vol)
from __future__ import unicode_literals, print_function, division def command_btc(bot, user, channel, args): """Display current BTC exchange rates from mtgox. Usage: btc [whitespace separated list of currency codes]""" currencies = ["EUR"] if args: currencies = args.split(" ") + return bot.say(channel, get_coin_value(bot, "BTC", currencies)) + + + def command_ltc(bot, user, channel, args): + """Display current LTC exchange rates from mtgox. Usage: ltc [whitespace separated list of currency codes]""" + currencies = ["EUR"] + + if args: + currencies = args.split(" ") + + return bot.say(channel, get_coin_value(bot, "LTC", currencies)) + + + def get_coin_value(bot, coin, currencies): + rates = [] for currency in currencies: - rate = gen_string(bot, currency) + rate = gen_string(bot, coin, currency) ? ++++++ if rate: rates.append(rate) if rates: - return bot.say(channel, "1 BTC = %s" % " | ".join(rates)) ? ----------------- ^^^ + return "1 %s = %s" % (coin, " | ".join(rates)) ? ^^ +++++++ + else: + return None - def gen_string(bot, currency): + def gen_string(bot, coin="BTC", currency="EUR"): ? ++++++++++++ ++++++ - r = bot.get_url("http://data.mtgox.com/api/1/BTC%s/ticker" % currency) ? ^^^ + r = bot.get_url("http://data.mtgox.com/api/1/%s%s/ticker" % (coin, currency)) ? ^^ +++++++ + if r.json()['result'] != 'success': return None data = r.json()['return'] avg = data['avg']['display_short'] low = data['low']['display_short'] high = data['high']['display_short'] vol = data['vol']['display_short'] return "%s avg:%s low:%s high:%s vol:%s" % (currency.upper(), avg, low, high, vol)
7da1482f93090bcafc420e96aa07515be61c8c50
linter.py
linter.py
"""This module exports the RubyLint plugin class.""" from SublimeLinter.lint import RubyLinter class RubyLint(RubyLinter): """Provides an interface to ruby-lint.""" syntax = ('ruby', 'ruby on rails', 'rspec') cmd = 'ruby-lint@ruby' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 2.0.0' regex = ( r'^.+?: (?:(?P<warning>warning)|(?P<error>error)): ' r'line (?P<line>\d+), column (?P<col>\d+): ' r'(?P<message>.+)' ) tempfile_suffix = 'rb' config_file = ('--config', 'ruby-lint.yml')
"""This module exports the RubyLint plugin class.""" from SublimeLinter.lint import RubyLinter class RubyLint(RubyLinter): """Provides an interface to ruby-lint.""" syntax = ('ruby', 'ruby on rails', 'rspec') cmd = 'ruby -S ruby-lint' version_args = '-S ruby-lint --version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 2.0.0' regex = ( r'^.+?: (?:(?P<warning>warning)|(?P<error>error)): ' r'line (?P<line>\d+), column (?P<col>\d+): ' r'(?P<message>.+)' ) tempfile_suffix = 'rb' config_file = ('--config', 'ruby-lint.yml')
Use 'ruby -S' to find ruby-lint executable
Use 'ruby -S' to find ruby-lint executable
Python
mit
jawshooah/SublimeLinter-contrib-ruby-lint
"""This module exports the RubyLint plugin class.""" from SublimeLinter.lint import RubyLinter class RubyLint(RubyLinter): """Provides an interface to ruby-lint.""" syntax = ('ruby', 'ruby on rails', 'rspec') - cmd = 'ruby-lint@ruby' + cmd = 'ruby -S ruby-lint' - version_args = '--version' + version_args = '-S ruby-lint --version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 2.0.0' regex = ( r'^.+?: (?:(?P<warning>warning)|(?P<error>error)): ' r'line (?P<line>\d+), column (?P<col>\d+): ' r'(?P<message>.+)' ) tempfile_suffix = 'rb' config_file = ('--config', 'ruby-lint.yml')
Use 'ruby -S' to find ruby-lint executable
## Code Before: """This module exports the RubyLint plugin class.""" from SublimeLinter.lint import RubyLinter class RubyLint(RubyLinter): """Provides an interface to ruby-lint.""" syntax = ('ruby', 'ruby on rails', 'rspec') cmd = 'ruby-lint@ruby' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 2.0.0' regex = ( r'^.+?: (?:(?P<warning>warning)|(?P<error>error)): ' r'line (?P<line>\d+), column (?P<col>\d+): ' r'(?P<message>.+)' ) tempfile_suffix = 'rb' config_file = ('--config', 'ruby-lint.yml') ## Instruction: Use 'ruby -S' to find ruby-lint executable ## Code After: """This module exports the RubyLint plugin class.""" from SublimeLinter.lint import RubyLinter class RubyLint(RubyLinter): """Provides an interface to ruby-lint.""" syntax = ('ruby', 'ruby on rails', 'rspec') cmd = 'ruby -S ruby-lint' version_args = '-S ruby-lint --version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 2.0.0' regex = ( r'^.+?: (?:(?P<warning>warning)|(?P<error>error)): ' r'line (?P<line>\d+), column (?P<col>\d+): ' r'(?P<message>.+)' ) tempfile_suffix = 'rb' config_file = ('--config', 'ruby-lint.yml')
"""This module exports the RubyLint plugin class.""" from SublimeLinter.lint import RubyLinter class RubyLint(RubyLinter): """Provides an interface to ruby-lint.""" syntax = ('ruby', 'ruby on rails', 'rspec') - cmd = 'ruby-lint@ruby' ? ----- + cmd = 'ruby -S ruby-lint' ? ++++++++ - version_args = '--version' + version_args = '-S ruby-lint --version' ? +++++++++++++ version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 2.0.0' regex = ( r'^.+?: (?:(?P<warning>warning)|(?P<error>error)): ' r'line (?P<line>\d+), column (?P<col>\d+): ' r'(?P<message>.+)' ) tempfile_suffix = 'rb' config_file = ('--config', 'ruby-lint.yml')
29b26aa8b44ea5820cfcd20e324d2c3631338228
portal/models/research_protocol.py
portal/models/research_protocol.py
"""Research Protocol module""" from datetime import datetime from ..database import db from ..date_tools import FHIR_datetime class ResearchProtocol(db.Model): """ResearchProtocol model for tracking QB versions""" __tablename__ = 'research_protocols' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text, nullable=False, unique=True) created_at = db.Column(db.DateTime, nullable=False) def __init__(self, name): self.name = name self.created_at = datetime.utcnow() @classmethod def from_json(cls, data): if 'name' not in data: raise ValueError("missing required name field") rp = ResearchProtocol.query.filter_by(name=data['name']).first() if not rp: rp = cls(data['name']) return rp def as_json(self): d = {} d['id'] = self.id d['resourceType'] = 'ResearchProtocol' d['name'] = self.name d['created_at'] = FHIR_datetime.as_fhir(self.created_at) return d
"""Research Protocol module""" from datetime import datetime from ..database import db from ..date_tools import FHIR_datetime class ResearchProtocol(db.Model): """ResearchProtocol model for tracking QB versions""" __tablename__ = 'research_protocols' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text, nullable=False, unique=True) created_at = db.Column(db.DateTime, nullable=False) def __init__(self, name): self.name = name self.created_at = datetime.utcnow() @classmethod def from_json(cls, data): if 'name' not in data: raise ValueError("missing required name field") instance = cls(data['name']) return instance.update_from_json(data) def update_from_json(self, data): self.name = data['name'] if 'created_at' in data: self.created_at = data['created_at'] return self def as_json(self): d = {} d['id'] = self.id d['resourceType'] = 'ResearchProtocol' d['name'] = self.name d['created_at'] = FHIR_datetime.as_fhir(self.created_at) return d
Implement common pattern from_json calls update_from_json
Implement common pattern from_json calls update_from_json
Python
bsd-3-clause
uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal
"""Research Protocol module""" from datetime import datetime from ..database import db from ..date_tools import FHIR_datetime class ResearchProtocol(db.Model): """ResearchProtocol model for tracking QB versions""" __tablename__ = 'research_protocols' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text, nullable=False, unique=True) created_at = db.Column(db.DateTime, nullable=False) def __init__(self, name): self.name = name self.created_at = datetime.utcnow() @classmethod def from_json(cls, data): if 'name' not in data: raise ValueError("missing required name field") - rp = ResearchProtocol.query.filter_by(name=data['name']).first() - if not rp: - rp = cls(data['name']) + instance = cls(data['name']) + return instance.update_from_json(data) + + def update_from_json(self, data): + self.name = data['name'] + if 'created_at' in data: + self.created_at = data['created_at'] - return rp + return self def as_json(self): d = {} d['id'] = self.id d['resourceType'] = 'ResearchProtocol' d['name'] = self.name d['created_at'] = FHIR_datetime.as_fhir(self.created_at) return d
Implement common pattern from_json calls update_from_json
## Code Before: """Research Protocol module""" from datetime import datetime from ..database import db from ..date_tools import FHIR_datetime class ResearchProtocol(db.Model): """ResearchProtocol model for tracking QB versions""" __tablename__ = 'research_protocols' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text, nullable=False, unique=True) created_at = db.Column(db.DateTime, nullable=False) def __init__(self, name): self.name = name self.created_at = datetime.utcnow() @classmethod def from_json(cls, data): if 'name' not in data: raise ValueError("missing required name field") rp = ResearchProtocol.query.filter_by(name=data['name']).first() if not rp: rp = cls(data['name']) return rp def as_json(self): d = {} d['id'] = self.id d['resourceType'] = 'ResearchProtocol' d['name'] = self.name d['created_at'] = FHIR_datetime.as_fhir(self.created_at) return d ## Instruction: Implement common pattern from_json calls update_from_json ## Code After: """Research Protocol module""" from datetime import datetime from ..database import db from ..date_tools import FHIR_datetime class ResearchProtocol(db.Model): """ResearchProtocol model for tracking QB versions""" __tablename__ = 'research_protocols' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text, nullable=False, unique=True) created_at = db.Column(db.DateTime, nullable=False) def __init__(self, name): self.name = name self.created_at = datetime.utcnow() @classmethod def from_json(cls, data): if 'name' not in data: raise ValueError("missing required name field") instance = cls(data['name']) return instance.update_from_json(data) def update_from_json(self, data): self.name = data['name'] if 'created_at' in data: self.created_at = data['created_at'] return self def as_json(self): d = {} d['id'] = self.id d['resourceType'] = 'ResearchProtocol' d['name'] = self.name d['created_at'] = FHIR_datetime.as_fhir(self.created_at) return d
"""Research Protocol module""" from datetime import datetime from ..database import db from ..date_tools import FHIR_datetime class ResearchProtocol(db.Model): """ResearchProtocol model for tracking QB versions""" __tablename__ = 'research_protocols' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text, nullable=False, unique=True) created_at = db.Column(db.DateTime, nullable=False) def __init__(self, name): self.name = name self.created_at = datetime.utcnow() @classmethod def from_json(cls, data): if 'name' not in data: raise ValueError("missing required name field") - rp = ResearchProtocol.query.filter_by(name=data['name']).first() - if not rp: - rp = cls(data['name']) ? ^^^^^^ + instance = cls(data['name']) ? ^^^^^^^^ + return instance.update_from_json(data) + + def update_from_json(self, data): + self.name = data['name'] + if 'created_at' in data: + self.created_at = data['created_at'] - return rp ? ^^ + return self ? ^^^^ def as_json(self): d = {} d['id'] = self.id d['resourceType'] = 'ResearchProtocol' d['name'] = self.name d['created_at'] = FHIR_datetime.as_fhir(self.created_at) return d
be7fded7f6c9fbc5d370849cc22113c30ab20fe7
astrobin_apps_premium/templatetags/astrobin_apps_premium_tags.py
astrobin_apps_premium/templatetags/astrobin_apps_premium_tags.py
import urllib # Django from django.conf import settings from django.db.models import Q from django.template import Library, Node # Third party from subscription.models import Subscription, UserSubscription # This app from astrobin_apps_premium.utils import premium_get_valid_usersubscription register = Library() @register.inclusion_tag('astrobin_apps_premium/inclusion_tags/premium_badge.html') def premium_badge(user, size = 'large'): return { 'user': user, 'size': size, } @register.filter def is_premium(user): print "ciao" return 'AstroBin Premium' in premium_get_valid_usersubscription(user).subscription.name @register.filter def is_lite(user): return 'AstroBin Lite' in premium_get_valid_usersubscription(user).subscription.name @register.filter def is_free(user): return not (is_lite(user) or is_premium(user))
import urllib # Django from django.conf import settings from django.db.models import Q from django.template import Library, Node # Third party from subscription.models import Subscription, UserSubscription # This app from astrobin_apps_premium.utils import premium_get_valid_usersubscription register = Library() @register.inclusion_tag('astrobin_apps_premium/inclusion_tags/premium_badge.html') def premium_badge(user, size = 'large'): return { 'user': user, 'size': size, } @register.filter def is_premium(user): return 'AstroBin Premium' in premium_get_valid_usersubscription(user).subscription.name @register.filter def is_lite(user): return 'AstroBin Lite' in premium_get_valid_usersubscription(user).subscription.name @register.filter def is_free(user): return not (is_lite(user) or is_premium(user))
Remove stray debug log message
Remove stray debug log message
Python
agpl-3.0
astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin
import urllib # Django from django.conf import settings from django.db.models import Q from django.template import Library, Node # Third party from subscription.models import Subscription, UserSubscription # This app from astrobin_apps_premium.utils import premium_get_valid_usersubscription register = Library() @register.inclusion_tag('astrobin_apps_premium/inclusion_tags/premium_badge.html') def premium_badge(user, size = 'large'): return { 'user': user, 'size': size, } @register.filter def is_premium(user): - print "ciao" return 'AstroBin Premium' in premium_get_valid_usersubscription(user).subscription.name @register.filter def is_lite(user): return 'AstroBin Lite' in premium_get_valid_usersubscription(user).subscription.name @register.filter def is_free(user): return not (is_lite(user) or is_premium(user))
Remove stray debug log message
## Code Before: import urllib # Django from django.conf import settings from django.db.models import Q from django.template import Library, Node # Third party from subscription.models import Subscription, UserSubscription # This app from astrobin_apps_premium.utils import premium_get_valid_usersubscription register = Library() @register.inclusion_tag('astrobin_apps_premium/inclusion_tags/premium_badge.html') def premium_badge(user, size = 'large'): return { 'user': user, 'size': size, } @register.filter def is_premium(user): print "ciao" return 'AstroBin Premium' in premium_get_valid_usersubscription(user).subscription.name @register.filter def is_lite(user): return 'AstroBin Lite' in premium_get_valid_usersubscription(user).subscription.name @register.filter def is_free(user): return not (is_lite(user) or is_premium(user)) ## Instruction: Remove stray debug log message ## Code After: import urllib # Django from django.conf import settings from django.db.models import Q from django.template import Library, Node # Third party from subscription.models import Subscription, UserSubscription # This app from astrobin_apps_premium.utils import premium_get_valid_usersubscription register = Library() @register.inclusion_tag('astrobin_apps_premium/inclusion_tags/premium_badge.html') def premium_badge(user, size = 'large'): return { 'user': user, 'size': size, } @register.filter def is_premium(user): return 'AstroBin Premium' in premium_get_valid_usersubscription(user).subscription.name @register.filter def is_lite(user): return 'AstroBin Lite' in premium_get_valid_usersubscription(user).subscription.name @register.filter def is_free(user): return not (is_lite(user) or is_premium(user))
import urllib # Django from django.conf import settings from django.db.models import Q from django.template import Library, Node # Third party from subscription.models import Subscription, UserSubscription # This app from astrobin_apps_premium.utils import premium_get_valid_usersubscription register = Library() @register.inclusion_tag('astrobin_apps_premium/inclusion_tags/premium_badge.html') def premium_badge(user, size = 'large'): return { 'user': user, 'size': size, } @register.filter def is_premium(user): - print "ciao" return 'AstroBin Premium' in premium_get_valid_usersubscription(user).subscription.name @register.filter def is_lite(user): return 'AstroBin Lite' in premium_get_valid_usersubscription(user).subscription.name @register.filter def is_free(user): return not (is_lite(user) or is_premium(user))
01d95de1a2fc9bc7283f72e4225d49a5d65af15b
poyo/patterns.py
poyo/patterns.py
INDENT = r"(?P<indent>^ *)" VARIABLE = r"(?P<variable>.+):" VALUE = r"(?P<value>(?:(?P<q2>['\"]).*?(?P=q2))|[^#]+?)" NEWLINE = r"$\n" BLANK = r" +" INLINE_COMMENT = r"(?: +#.*)?" COMMENT = r"^ *#.*" + NEWLINE BLANK_LINE = r"^[ \t]*" + NEWLINE DASHES = r"^---" + NEWLINE SECTION = INDENT + VARIABLE + INLINE_COMMENT + NEWLINE SIMPLE = INDENT + VARIABLE + BLANK + VALUE + INLINE_COMMENT + NEWLINE NULL = r"\b(null|Null|NULL|~)\b" TRUE = r"\b(true|True|TRUE)\b" FALSE = r"\b(false|False|FALSE)\b" INT = r"[-+]?[0-9]+" FLOAT = r"([-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?)" STR = r"(?P<quotes>['\"]?).*(?P=quotes)"
INDENT = r"(?P<indent>^ *)" VARIABLE = r"(?P<variable>.+):" VALUE = r"(?P<value>(?:(?P<q2>['\"]).*?(?P=q2))|[^#]+?)" NEWLINE = r"$\n" BLANK = r" +" INLINE_COMMENT = r"(?: +#.*)?" COMMENT = r"^ *#.*" + NEWLINE BLANK_LINE = r"^[ \t]*" + NEWLINE DASHES = r"^---" + NEWLINE SECTION = INDENT + VARIABLE + INLINE_COMMENT + NEWLINE SIMPLE = INDENT + VARIABLE + BLANK + VALUE + INLINE_COMMENT + NEWLINE LISTITEM = BLANK + r"-" + BLANK + VALUE + INLINE_COMMENT + NEWLINE LIST = SECTION + r"(?P<items>(?:(?P=indent)" + LISTITEM + r")+)" NULL = r"\b(null|Null|NULL|~)\b" TRUE = r"\b(true|True|TRUE)\b" FALSE = r"\b(false|False|FALSE)\b" INT = r"[-+]?[0-9]+" FLOAT = r"([-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?)" STR = r"(?P<quotes>['\"]?).*(?P=quotes)"
Implement regex pattern for list values
Implement regex pattern for list values
Python
mit
hackebrot/poyo
INDENT = r"(?P<indent>^ *)" VARIABLE = r"(?P<variable>.+):" VALUE = r"(?P<value>(?:(?P<q2>['\"]).*?(?P=q2))|[^#]+?)" NEWLINE = r"$\n" BLANK = r" +" INLINE_COMMENT = r"(?: +#.*)?" COMMENT = r"^ *#.*" + NEWLINE BLANK_LINE = r"^[ \t]*" + NEWLINE DASHES = r"^---" + NEWLINE SECTION = INDENT + VARIABLE + INLINE_COMMENT + NEWLINE SIMPLE = INDENT + VARIABLE + BLANK + VALUE + INLINE_COMMENT + NEWLINE + LISTITEM = BLANK + r"-" + BLANK + VALUE + INLINE_COMMENT + NEWLINE + LIST = SECTION + r"(?P<items>(?:(?P=indent)" + LISTITEM + r")+)" + NULL = r"\b(null|Null|NULL|~)\b" TRUE = r"\b(true|True|TRUE)\b" FALSE = r"\b(false|False|FALSE)\b" INT = r"[-+]?[0-9]+" FLOAT = r"([-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?)" STR = r"(?P<quotes>['\"]?).*(?P=quotes)"
Implement regex pattern for list values
## Code Before: INDENT = r"(?P<indent>^ *)" VARIABLE = r"(?P<variable>.+):" VALUE = r"(?P<value>(?:(?P<q2>['\"]).*?(?P=q2))|[^#]+?)" NEWLINE = r"$\n" BLANK = r" +" INLINE_COMMENT = r"(?: +#.*)?" COMMENT = r"^ *#.*" + NEWLINE BLANK_LINE = r"^[ \t]*" + NEWLINE DASHES = r"^---" + NEWLINE SECTION = INDENT + VARIABLE + INLINE_COMMENT + NEWLINE SIMPLE = INDENT + VARIABLE + BLANK + VALUE + INLINE_COMMENT + NEWLINE NULL = r"\b(null|Null|NULL|~)\b" TRUE = r"\b(true|True|TRUE)\b" FALSE = r"\b(false|False|FALSE)\b" INT = r"[-+]?[0-9]+" FLOAT = r"([-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?)" STR = r"(?P<quotes>['\"]?).*(?P=quotes)" ## Instruction: Implement regex pattern for list values ## Code After: INDENT = r"(?P<indent>^ *)" VARIABLE = r"(?P<variable>.+):" VALUE = r"(?P<value>(?:(?P<q2>['\"]).*?(?P=q2))|[^#]+?)" NEWLINE = r"$\n" BLANK = r" +" INLINE_COMMENT = r"(?: +#.*)?" COMMENT = r"^ *#.*" + NEWLINE BLANK_LINE = r"^[ \t]*" + NEWLINE DASHES = r"^---" + NEWLINE SECTION = INDENT + VARIABLE + INLINE_COMMENT + NEWLINE SIMPLE = INDENT + VARIABLE + BLANK + VALUE + INLINE_COMMENT + NEWLINE LISTITEM = BLANK + r"-" + BLANK + VALUE + INLINE_COMMENT + NEWLINE LIST = SECTION + r"(?P<items>(?:(?P=indent)" + LISTITEM + r")+)" NULL = r"\b(null|Null|NULL|~)\b" TRUE = r"\b(true|True|TRUE)\b" FALSE = r"\b(false|False|FALSE)\b" INT = r"[-+]?[0-9]+" FLOAT = r"([-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?)" STR = r"(?P<quotes>['\"]?).*(?P=quotes)"
INDENT = r"(?P<indent>^ *)" VARIABLE = r"(?P<variable>.+):" VALUE = r"(?P<value>(?:(?P<q2>['\"]).*?(?P=q2))|[^#]+?)" NEWLINE = r"$\n" BLANK = r" +" INLINE_COMMENT = r"(?: +#.*)?" COMMENT = r"^ *#.*" + NEWLINE BLANK_LINE = r"^[ \t]*" + NEWLINE DASHES = r"^---" + NEWLINE SECTION = INDENT + VARIABLE + INLINE_COMMENT + NEWLINE SIMPLE = INDENT + VARIABLE + BLANK + VALUE + INLINE_COMMENT + NEWLINE + LISTITEM = BLANK + r"-" + BLANK + VALUE + INLINE_COMMENT + NEWLINE + LIST = SECTION + r"(?P<items>(?:(?P=indent)" + LISTITEM + r")+)" + NULL = r"\b(null|Null|NULL|~)\b" TRUE = r"\b(true|True|TRUE)\b" FALSE = r"\b(false|False|FALSE)\b" INT = r"[-+]?[0-9]+" FLOAT = r"([-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?)" STR = r"(?P<quotes>['\"]?).*(?P=quotes)"
4166bf21aa8ff9264724ef8101231557f40b80ef
production.py
production.py
from flask import Flask, render_template, jsonify, make_response, request, current_app from gevent import monkey from gevent import wsgi import app monkey.patch_all() app = Flask(__name__) server = wsgi.WSGIServer(('203.29.62.211', 5050), app) server.serve_forever()
from flask import Flask, render_template, jsonify, make_response, request, current_app from gevent import monkey from gevent import wsgi import app monkey.patch_all() app = Flask(__name__) server = wsgi.WSGIServer(('203.29.62.211', 5050), app) server.serve_forever() @app.route('/') def index(): return render_template('index.html')
Add one route so that our monitoring system stops thinking this system is down
Add one route so that our monitoring system stops thinking this system is down
Python
apache-2.0
ishgroup/lightbook,ishgroup/lightbook,ishgroup/lightbook
from flask import Flask, render_template, jsonify, make_response, request, current_app from gevent import monkey from gevent import wsgi import app monkey.patch_all() app = Flask(__name__) server = wsgi.WSGIServer(('203.29.62.211', 5050), app) server.serve_forever() + + @app.route('/') + def index(): + return render_template('index.html')
Add one route so that our monitoring system stops thinking this system is down
## Code Before: from flask import Flask, render_template, jsonify, make_response, request, current_app from gevent import monkey from gevent import wsgi import app monkey.patch_all() app = Flask(__name__) server = wsgi.WSGIServer(('203.29.62.211', 5050), app) server.serve_forever() ## Instruction: Add one route so that our monitoring system stops thinking this system is down ## Code After: from flask import Flask, render_template, jsonify, make_response, request, current_app from gevent import monkey from gevent import wsgi import app monkey.patch_all() app = Flask(__name__) server = wsgi.WSGIServer(('203.29.62.211', 5050), app) server.serve_forever() @app.route('/') def index(): return render_template('index.html')
from flask import Flask, render_template, jsonify, make_response, request, current_app from gevent import monkey from gevent import wsgi import app monkey.patch_all() app = Flask(__name__) server = wsgi.WSGIServer(('203.29.62.211', 5050), app) server.serve_forever() + + @app.route('/') + def index(): + return render_template('index.html')
e19487f21d2de5edeaa2edbb295c43d140797310
tapioca_harvest/tapioca_harvest.py
tapioca_harvest/tapioca_harvest.py
from tapioca import ( TapiocaAdapter, generate_wrapper_from_adapter, JSONAdapterMixin) from requests.auth import HTTPBasicAuth from .resource_mapping import RESOURCE_MAPPING class HarvestClientAdapter(JSONAdapterMixin, TapiocaAdapter): resource_mapping = RESOURCE_MAPPING api_root = 'https://api.harvestapp.com/v2/' def get_request_kwargs(self, api_params, *args, **kwargs): params = super(HarvestClientAdapter, self).get_request_kwargs( api_params, *args, **kwargs) headers = { 'Authorization': 'Bearer %s' % params.get('token', ''), 'Harvest-Account-Id': params.get('account_id', ''), 'User-Agent': params.get('user_agent', '') } params['headers'] = params.get('headers', headers) params['headers']['Accept'] = 'application/json' return params def get_iterator_list(self, response_data): return response_data def get_iterator_next_request_kwargs(self, iterator_request_kwargs, response_data, response): pass def response_to_native(self, response): if response.content.strip(): return super(HarvestClientAdapter, self).response_to_native(response) Harvest = generate_wrapper_from_adapter(HarvestClientAdapter)
from tapioca import ( TapiocaAdapter, generate_wrapper_from_adapter, JSONAdapterMixin) from requests.auth import HTTPBasicAuth from .resource_mapping import RESOURCE_MAPPING class HarvestClientAdapter(JSONAdapterMixin, TapiocaAdapter): resource_mapping = RESOURCE_MAPPING api_root = 'https://api.harvestapp.com/v2/' def get_request_kwargs(self, api_params, *args, **kwargs): params = super(HarvestClientAdapter, self).get_request_kwargs( api_params, *args, **kwargs) params.setdefault('headers', {}).update({ 'Authorization': 'Bearer %s' % api_params.get('token', ''), 'Harvest-Account-Id': api_params.get('account_id', ''), 'User-Agent': api_params.get('user_agent', '') }) return params def get_iterator_list(self, response_data): return response_data def get_iterator_next_request_kwargs(self, iterator_request_kwargs, response_data, response): pass def response_to_native(self, response): if response.content.strip(): return super(HarvestClientAdapter, self).response_to_native(response) Harvest = generate_wrapper_from_adapter(HarvestClientAdapter)
Correct header params on adapter
Correct header params on adapter
Python
mit
vintasoftware/tapioca-harvest
from tapioca import ( TapiocaAdapter, generate_wrapper_from_adapter, JSONAdapterMixin) from requests.auth import HTTPBasicAuth from .resource_mapping import RESOURCE_MAPPING class HarvestClientAdapter(JSONAdapterMixin, TapiocaAdapter): resource_mapping = RESOURCE_MAPPING api_root = 'https://api.harvestapp.com/v2/' def get_request_kwargs(self, api_params, *args, **kwargs): params = super(HarvestClientAdapter, self).get_request_kwargs( api_params, *args, **kwargs) - headers = { + params.setdefault('headers', {}).update({ - 'Authorization': 'Bearer %s' % params.get('token', ''), + 'Authorization': 'Bearer %s' % api_params.get('token', ''), - 'Harvest-Account-Id': params.get('account_id', ''), + 'Harvest-Account-Id': api_params.get('account_id', ''), - 'User-Agent': params.get('user_agent', '') + 'User-Agent': api_params.get('user_agent', '') - } + }) - - params['headers'] = params.get('headers', headers) - params['headers']['Accept'] = 'application/json' return params def get_iterator_list(self, response_data): return response_data def get_iterator_next_request_kwargs(self, iterator_request_kwargs, response_data, response): pass def response_to_native(self, response): if response.content.strip(): return super(HarvestClientAdapter, self).response_to_native(response) Harvest = generate_wrapper_from_adapter(HarvestClientAdapter)
Correct header params on adapter
## Code Before: from tapioca import ( TapiocaAdapter, generate_wrapper_from_adapter, JSONAdapterMixin) from requests.auth import HTTPBasicAuth from .resource_mapping import RESOURCE_MAPPING class HarvestClientAdapter(JSONAdapterMixin, TapiocaAdapter): resource_mapping = RESOURCE_MAPPING api_root = 'https://api.harvestapp.com/v2/' def get_request_kwargs(self, api_params, *args, **kwargs): params = super(HarvestClientAdapter, self).get_request_kwargs( api_params, *args, **kwargs) headers = { 'Authorization': 'Bearer %s' % params.get('token', ''), 'Harvest-Account-Id': params.get('account_id', ''), 'User-Agent': params.get('user_agent', '') } params['headers'] = params.get('headers', headers) params['headers']['Accept'] = 'application/json' return params def get_iterator_list(self, response_data): return response_data def get_iterator_next_request_kwargs(self, iterator_request_kwargs, response_data, response): pass def response_to_native(self, response): if response.content.strip(): return super(HarvestClientAdapter, self).response_to_native(response) Harvest = generate_wrapper_from_adapter(HarvestClientAdapter) ## Instruction: Correct header params on adapter ## Code After: from tapioca import ( TapiocaAdapter, generate_wrapper_from_adapter, JSONAdapterMixin) from requests.auth import HTTPBasicAuth from .resource_mapping import RESOURCE_MAPPING class HarvestClientAdapter(JSONAdapterMixin, TapiocaAdapter): resource_mapping = RESOURCE_MAPPING api_root = 'https://api.harvestapp.com/v2/' def get_request_kwargs(self, api_params, *args, **kwargs): params = super(HarvestClientAdapter, self).get_request_kwargs( api_params, *args, **kwargs) params.setdefault('headers', {}).update({ 'Authorization': 'Bearer %s' % api_params.get('token', ''), 'Harvest-Account-Id': api_params.get('account_id', ''), 'User-Agent': api_params.get('user_agent', '') }) return params def get_iterator_list(self, response_data): return response_data def get_iterator_next_request_kwargs(self, iterator_request_kwargs, response_data, response): pass def response_to_native(self, response): if response.content.strip(): return super(HarvestClientAdapter, self).response_to_native(response) Harvest = generate_wrapper_from_adapter(HarvestClientAdapter)
from tapioca import ( TapiocaAdapter, generate_wrapper_from_adapter, JSONAdapterMixin) from requests.auth import HTTPBasicAuth from .resource_mapping import RESOURCE_MAPPING class HarvestClientAdapter(JSONAdapterMixin, TapiocaAdapter): resource_mapping = RESOURCE_MAPPING api_root = 'https://api.harvestapp.com/v2/' def get_request_kwargs(self, api_params, *args, **kwargs): params = super(HarvestClientAdapter, self).get_request_kwargs( api_params, *args, **kwargs) - headers = { + params.setdefault('headers', {}).update({ - 'Authorization': 'Bearer %s' % params.get('token', ''), + 'Authorization': 'Bearer %s' % api_params.get('token', ''), ? ++++ - 'Harvest-Account-Id': params.get('account_id', ''), + 'Harvest-Account-Id': api_params.get('account_id', ''), ? ++++ - 'User-Agent': params.get('user_agent', '') + 'User-Agent': api_params.get('user_agent', '') ? ++++ - } + }) ? + - - params['headers'] = params.get('headers', headers) - params['headers']['Accept'] = 'application/json' return params def get_iterator_list(self, response_data): return response_data def get_iterator_next_request_kwargs(self, iterator_request_kwargs, response_data, response): pass def response_to_native(self, response): if response.content.strip(): return super(HarvestClientAdapter, self).response_to_native(response) Harvest = generate_wrapper_from_adapter(HarvestClientAdapter)
e65ed7382c691d8ee19a22659ddb6deaa064e85b
kmip/__init__.py
kmip/__init__.py
import os import re # Dynamically set __version__ version_path = os.path.join(os.path.dirname( os.path.realpath(__file__)), 'version.py') with open(version_path, 'r') as version_file: mo = re.search(r"^.*= '(\d\.\d\.\d)'$", version_file.read(), re.MULTILINE) __version__ = mo.group(1) __all__ = ['core', 'demos', 'services']
import os import re from kmip.core import enums # Dynamically set __version__ version_path = os.path.join(os.path.dirname( os.path.realpath(__file__)), 'version.py') with open(version_path, 'r') as version_file: mo = re.search(r"^.*= '(\d\.\d\.\d)'$", version_file.read(), re.MULTILINE) __version__ = mo.group(1) __all__ = [ 'core', 'demos', 'enums', 'services' ]
Update the kmip package to allow importing enums globally
Update the kmip package to allow importing enums globally This change updates the root-level kmip package, allowing users to now import enums directly from the kmip package: from kmip import enums Enumerations are used throughout the codebase and user applications and this will simplify usage and help obfuscate internal package details that may change in the future.
Python
apache-2.0
OpenKMIP/PyKMIP,OpenKMIP/PyKMIP
import os import re + + from kmip.core import enums # Dynamically set __version__ version_path = os.path.join(os.path.dirname( os.path.realpath(__file__)), 'version.py') with open(version_path, 'r') as version_file: mo = re.search(r"^.*= '(\d\.\d\.\d)'$", version_file.read(), re.MULTILINE) __version__ = mo.group(1) - __all__ = ['core', 'demos', 'services'] + __all__ = [ + 'core', + 'demos', + 'enums', + 'services' + ]
Update the kmip package to allow importing enums globally
## Code Before: import os import re # Dynamically set __version__ version_path = os.path.join(os.path.dirname( os.path.realpath(__file__)), 'version.py') with open(version_path, 'r') as version_file: mo = re.search(r"^.*= '(\d\.\d\.\d)'$", version_file.read(), re.MULTILINE) __version__ = mo.group(1) __all__ = ['core', 'demos', 'services'] ## Instruction: Update the kmip package to allow importing enums globally ## Code After: import os import re from kmip.core import enums # Dynamically set __version__ version_path = os.path.join(os.path.dirname( os.path.realpath(__file__)), 'version.py') with open(version_path, 'r') as version_file: mo = re.search(r"^.*= '(\d\.\d\.\d)'$", version_file.read(), re.MULTILINE) __version__ = mo.group(1) __all__ = [ 'core', 'demos', 'enums', 'services' ]
import os import re + + from kmip.core import enums # Dynamically set __version__ version_path = os.path.join(os.path.dirname( os.path.realpath(__file__)), 'version.py') with open(version_path, 'r') as version_file: mo = re.search(r"^.*= '(\d\.\d\.\d)'$", version_file.read(), re.MULTILINE) __version__ = mo.group(1) - __all__ = ['core', 'demos', 'services'] + __all__ = [ + 'core', + 'demos', + 'enums', + 'services' + ]
24f0402e27ce7e51f370e82aa74c783438875d02
oslo_db/tests/sqlalchemy/__init__.py
oslo_db/tests/sqlalchemy/__init__.py
from oslo_db.sqlalchemy import test_base load_tests = test_base.optimize_db_test_loader(__file__)
from oslo_db.sqlalchemy import test_fixtures load_tests = test_fixtures.optimize_package_test_loader(__file__)
Remove deprecation warning when loading tests/sqlalchemy
Remove deprecation warning when loading tests/sqlalchemy /home/sam/Work/ironic/.tox/py27/local/lib/python2.7/site-packages/oslo_db/tests/sqlalchemy/__init__.py:20: DeprecationWarning: Function 'oslo_db.sqlalchemy.test_base.optimize_db_test_loader()' has moved to 'oslo_db.sqlalchemy.test_fixtures.optimize_package_test_loader()' Change-Id: I7fb4e776cedb8adcf97c9a43210049c60f796873
Python
apache-2.0
openstack/oslo.db,openstack/oslo.db
- from oslo_db.sqlalchemy import test_base + from oslo_db.sqlalchemy import test_fixtures - load_tests = test_base.optimize_db_test_loader(__file__) + load_tests = test_fixtures.optimize_package_test_loader(__file__)
Remove deprecation warning when loading tests/sqlalchemy
## Code Before: from oslo_db.sqlalchemy import test_base load_tests = test_base.optimize_db_test_loader(__file__) ## Instruction: Remove deprecation warning when loading tests/sqlalchemy ## Code After: from oslo_db.sqlalchemy import test_fixtures load_tests = test_fixtures.optimize_package_test_loader(__file__)
- from oslo_db.sqlalchemy import test_base ? ^^ - + from oslo_db.sqlalchemy import test_fixtures ? ^^^^^^^ - load_tests = test_base.optimize_db_test_loader(__file__) ? ^^ - ^^ + load_tests = test_fixtures.optimize_package_test_loader(__file__) ? ^^^^^^^ ^^^^^^^
28da05d860147b5e0df37d998f437af6a5d4d178
airflow/hooks/postgres_hook.py
airflow/hooks/postgres_hook.py
import psycopg2 from airflow.hooks.dbapi_hook import DbApiHook class PostgresHook(DbApiHook): ''' Interact with Postgres. You can specify ssl parameters in the extra field of your connection as ``{"sslmode": "require", "sslcert": "/path/to/cert.pem", etc}``. ''' conn_name_attr = 'postgres_conn_id' default_conn_name = 'postgres_default' supports_autocommit = True def get_conn(self): conn = self.get_connection(self.postgres_conn_id) conn_args = dict( host=conn.host, user=conn.login, password=conn.password, dbname=conn.schema, port=conn.port) # check for ssl parameters in conn.extra for arg_name, arg_val in conn.extra_dejson.items(): if arg_name in ['sslmode', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl']: conn_args[arg_name] = arg_val return psycopg2.connect(**conn_args)
import psycopg2 from airflow.hooks.dbapi_hook import DbApiHook class PostgresHook(DbApiHook): ''' Interact with Postgres. You can specify ssl parameters in the extra field of your connection as ``{"sslmode": "require", "sslcert": "/path/to/cert.pem", etc}``. ''' conn_name_attr = 'postgres_conn_id' default_conn_name = 'postgres_default' supports_autocommit = False def get_conn(self): conn = self.get_connection(self.postgres_conn_id) conn_args = dict( host=conn.host, user=conn.login, password=conn.password, dbname=conn.schema, port=conn.port) # check for ssl parameters in conn.extra for arg_name, arg_val in conn.extra_dejson.items(): if arg_name in ['sslmode', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl']: conn_args[arg_name] = arg_val psycopg2_conn = psycopg2.connect(**conn_args) if psycopg2_conn.server_version < 70400: self.supports_autocommit = True return psycopg2_conn
Set Postgres autocommit as supported only if server version is < 7.4
Set Postgres autocommit as supported only if server version is < 7.4 The server-side autocommit setting was removed here http://www.postgresql.org/docs/7.4/static/release-7-4.html Resolves: #690
Python
apache-2.0
vijaysbhat/incubator-airflow,dgies/incubator-airflow,owlabs/incubator-airflow,Acehaidrey/incubator-airflow,gtoonstra/airflow,hamedhsn/incubator-airflow,apache/airflow,N3da/incubator-airflow,mrkm4ntr/incubator-airflow,RealImpactAnalytics/airflow,r39132/airflow,janczak10/incubator-airflow,cfei18/incubator-airflow,CloverHealth/airflow,jhsenjaliya/incubator-airflow,Acehaidrey/incubator-airflow,DEVELByte/incubator-airflow,andrewmchen/incubator-airflow,cfei18/incubator-airflow,wileeam/airflow,mtdewulf/incubator-airflow,DEVELByte/incubator-airflow,nathanielvarona/airflow,MortalViews/incubator-airflow,nathanielvarona/airflow,forevernull/incubator-airflow,zodiac/incubator-airflow,nathanielvarona/airflow,gtoonstra/airflow,sid88in/incubator-airflow,dud225/incubator-airflow,danielvdende/incubator-airflow,jwi078/incubator-airflow,aminghadersohi/airflow,ty707/airflow,preete-dixit-ck/incubator-airflow,mrkm4ntr/incubator-airflow,kerzhner/airflow,caseyching/incubator-airflow,mattuuh7/incubator-airflow,dmitry-r/incubator-airflow,r39132/airflow,biln/airflow,AllisonWang/incubator-airflow,andrewmchen/incubator-airflow,aminghadersohi/airflow,holygits/incubator-airflow,adrpar/incubator-airflow,yati-sagade/incubator-airflow,adrpar/incubator-airflow,brandsoulmates/incubator-airflow,jfantom/incubator-airflow,skudriashev/incubator-airflow,adamhaney/airflow,sid88in/incubator-airflow,juvoinc/airflow,asnir/airflow,akosel/incubator-airflow,jgao54/airflow,adamhaney/airflow,malmiron/incubator-airflow,cfei18/incubator-airflow,wolfier/incubator-airflow,ledsusop/airflow,mattuuh7/incubator-airflow,dhuang/incubator-airflow,jbhsieh/incubator-airflow,jhsenjaliya/incubator-airflow,gilt/incubator-airflow,cfei18/incubator-airflow,mrares/incubator-airflow,Fokko/incubator-airflow,adamhaney/airflow,biln/airflow,kerzhner/airflow,yiqingj/airflow,spektom/incubator-airflow,subodhchhabra/airflow,zoyahav/incubator-airflow,plypaul/airflow,dud225/incubator-airflow,jgao54/airflow,jbhsieh/incubator-airflow,ledsusop/airflow,holygits/incubator-airflow,vineet-rh/incubator-airflow,cjqian/incubator-airflow,mrkm4ntr/incubator-airflow,stverhae/incubator-airflow,mistercrunch/airflow,caseyching/incubator-airflow,wndhydrnt/airflow,janczak10/incubator-airflow,mtdewulf/incubator-airflow,RealImpactAnalytics/airflow,wooga/airflow,stverhae/incubator-airflow,cfei18/incubator-airflow,cademarkegard/airflow,wolfier/incubator-airflow,fenglu-g/incubator-airflow,ronfung/incubator-airflow,holygits/incubator-airflow,AllisonWang/incubator-airflow,wxiang7/airflow,juvoinc/airflow,jwi078/incubator-airflow,mylons/incubator-airflow,mylons/incubator-airflow,wooga/airflow,easytaxibr/airflow,dgies/incubator-airflow,AllisonWang/incubator-airflow,Tagar/incubator-airflow,vijaysbhat/incubator-airflow,asnir/airflow,ledsusop/airflow,asnir/airflow,aminghadersohi/airflow,sdiazb/airflow,jesusfcr/airflow,NielsZeilemaker/incubator-airflow,malmiron/incubator-airflow,wileeam/airflow,kerzhner/airflow,jfantom/incubator-airflow,NielsZeilemaker/incubator-airflow,bolkedebruin/airflow,RealImpactAnalytics/airflow,mtdewulf/incubator-airflow,criccomini/airflow,Tagar/incubator-airflow,mrares/incubator-airflow,jbhsieh/incubator-airflow,janczak10/incubator-airflow,akosel/incubator-airflow,airbnb/airflow,lxneng/incubator-airflow,cjqian/incubator-airflow,janczak10/incubator-airflow,hgrif/incubator-airflow,brandsoulmates/incubator-airflow,jfantom/incubator-airflow,MetrodataTeam/incubator-airflow,modsy/incubator-airflow,stverhae/incubator-airflow,stverhae/incubator-airflow,sekikn/incubator-airflow,KL-WLCR/incubator-airflow,Acehaidrey/incubator-airflow,biln/airflow,dud225/incubator-airflow,danielvdende/incubator-airflow,cjqian/incubator-airflow,jbhsieh/incubator-airflow,cademarkegard/airflow,mtagle/airflow,fenglu-g/incubator-airflow,akosel/incubator-airflow,saguziel/incubator-airflow,MortalViews/incubator-airflow,subodhchhabra/airflow,gritlogic/incubator-airflow,wxiang7/airflow,mattuuh7/incubator-airflow,spektom/incubator-airflow,jesusfcr/airflow,sergiohgz/incubator-airflow,caseyching/incubator-airflow,mylons/incubator-airflow,NielsZeilemaker/incubator-airflow,sdiazb/airflow,artwr/airflow,alexvanboxel/airflow,Twistbioscience/incubator-airflow,CloverHealth/airflow,yk5/incubator-airflow,hgrif/incubator-airflow,wolfier/incubator-airflow,preete-dixit-ck/incubator-airflow,d-lee/airflow,rishibarve/incubator-airflow,Acehaidrey/incubator-airflow,yiqingj/airflow,cjqian/incubator-airflow,gilt/incubator-airflow,adrpar/incubator-airflow,yiqingj/airflow,danielvdende/incubator-airflow,sergiohgz/incubator-airflow,sekikn/incubator-airflow,gtoonstra/airflow,jwi078/incubator-airflow,zoyahav/incubator-airflow,adrpar/incubator-airflow,preete-dixit-ck/incubator-airflow,sid88in/incubator-airflow,apache/airflow,Acehaidrey/incubator-airflow,owlabs/incubator-airflow,zodiac/incubator-airflow,danielvdende/incubator-airflow,mattuuh7/incubator-airflow,skudriashev/incubator-airflow,preete-dixit-ck/incubator-airflow,mtdewulf/incubator-airflow,mistercrunch/airflow,mistercrunch/airflow,Fokko/incubator-airflow,sdiazb/airflow,danielvdende/incubator-airflow,OpringaoDoTurno/airflow,kerzhner/airflow,skudriashev/incubator-airflow,fenglu-g/incubator-airflow,jgao54/airflow,wileeam/airflow,DEVELByte/incubator-airflow,lyft/incubator-airflow,malmiron/incubator-airflow,malmiron/incubator-airflow,MortalViews/incubator-airflow,zack3241/incubator-airflow,dmitry-r/incubator-airflow,dgies/incubator-airflow,OpringaoDoTurno/airflow,edgarRd/incubator-airflow,juvoinc/airflow,yiqingj/airflow,ProstoMaxim/incubator-airflow,lyft/incubator-airflow,wileeam/airflow,hgrif/incubator-airflow,jlowin/airflow,apache/airflow,easytaxibr/airflow,mistercrunch/airflow,gritlogic/incubator-airflow,dgies/incubator-airflow,dhuang/incubator-airflow,DinoCow/airflow,zoyahav/incubator-airflow,d-lee/airflow,owlabs/incubator-airflow,ty707/airflow,btallman/incubator-airflow,jiwang576/incubator-airflow,AllisonWang/incubator-airflow,sekikn/incubator-airflow,easytaxibr/airflow,hamedhsn/incubator-airflow,jesusfcr/airflow,saguziel/incubator-airflow,ledsusop/airflow,wndhydrnt/airflow,btallman/incubator-airflow,ProstoMaxim/incubator-airflow,ProstoMaxim/incubator-airflow,andyxhadji/incubator-airflow,btallman/incubator-airflow,ronfung/incubator-airflow,nathanielvarona/airflow,andyxhadji/incubator-airflow,edgarRd/incubator-airflow,plypaul/airflow,airbnb/airflow,jesusfcr/airflow,wooga/airflow,apache/airflow,wooga/airflow,yk5/incubator-airflow,apache/airflow,subodhchhabra/airflow,mtagle/airflow,DinoCow/airflow,Acehaidrey/incubator-airflow,lxneng/incubator-airflow,gritlogic/incubator-airflow,alexvanboxel/airflow,zack3241/incubator-airflow,apache/incubator-airflow,jgao54/airflow,mrkm4ntr/incubator-airflow,gilt/incubator-airflow,brandsoulmates/incubator-airflow,criccomini/airflow,mtagle/airflow,modsy/incubator-airflow,artwr/airflow,mylons/incubator-airflow,yk5/incubator-airflow,apache/incubator-airflow,forevernull/incubator-airflow,cademarkegard/airflow,MortalViews/incubator-airflow,cademarkegard/airflow,ronfung/incubator-airflow,forevernull/incubator-airflow,ty707/airflow,KL-WLCR/incubator-airflow,lyft/incubator-airflow,cfei18/incubator-airflow,DinoCow/airflow,spektom/incubator-airflow,danielvdende/incubator-airflow,yati-sagade/incubator-airflow,Twistbioscience/incubator-airflow,mrares/incubator-airflow,jhsenjaliya/incubator-airflow,btallman/incubator-airflow,zoyahav/incubator-airflow,CloverHealth/airflow,biln/airflow,r39132/airflow,plypaul/airflow,hgrif/incubator-airflow,MetrodataTeam/incubator-airflow,hamedhsn/incubator-airflow,sekikn/incubator-airflow,Twistbioscience/incubator-airflow,dmitry-r/incubator-airflow,vineet-rh/incubator-airflow,yk5/incubator-airflow,wndhydrnt/airflow,mrares/incubator-airflow,dmitry-r/incubator-airflow,Fokko/incubator-airflow,ProstoMaxim/incubator-airflow,jfantom/incubator-airflow,apache/incubator-airflow,sergiohgz/incubator-airflow,gtoonstra/airflow,modsy/incubator-airflow,airbnb/airflow,edgarRd/incubator-airflow,zack3241/incubator-airflow,vineet-rh/incubator-airflow,yati-sagade/incubator-airflow,airbnb/airflow,jiwang576/incubator-airflow,jlowin/airflow,aminghadersohi/airflow,wolfier/incubator-airflow,d-lee/airflow,MetrodataTeam/incubator-airflow,criccomini/airflow,zack3241/incubator-airflow,asnir/airflow,apache/incubator-airflow,wxiang7/airflow,rishibarve/incubator-airflow,alexvanboxel/airflow,OpringaoDoTurno/airflow,juvoinc/airflow,bolkedebruin/airflow,jiwang576/incubator-airflow,Fokko/incubator-airflow,artwr/airflow,CloverHealth/airflow,lxneng/incubator-airflow,plypaul/airflow,mtagle/airflow,wndhydrnt/airflow,sergiohgz/incubator-airflow,N3da/incubator-airflow,MetrodataTeam/incubator-airflow,saguziel/incubator-airflow,jlowin/airflow,fenglu-g/incubator-airflow,Tagar/incubator-airflow,spektom/incubator-airflow,holygits/incubator-airflow,vijaysbhat/incubator-airflow,skudriashev/incubator-airflow,hamedhsn/incubator-airflow,DinoCow/airflow,artwr/airflow,rishibarve/incubator-airflow,wxiang7/airflow,nathanielvarona/airflow,jiwang576/incubator-airflow,sdiazb/airflow,lyft/incubator-airflow,ronfung/incubator-airflow,r39132/airflow,KL-WLCR/incubator-airflow,criccomini/airflow,N3da/incubator-airflow,jwi078/incubator-airflow,caseyching/incubator-airflow,saguziel/incubator-airflow,modsy/incubator-airflow,zodiac/incubator-airflow,RealImpactAnalytics/airflow,Tagar/incubator-airflow,jlowin/airflow,nathanielvarona/airflow,apache/airflow,bolkedebruin/airflow,brandsoulmates/incubator-airflow,rishibarve/incubator-airflow,subodhchhabra/airflow,NielsZeilemaker/incubator-airflow,easytaxibr/airflow,Twistbioscience/incubator-airflow,bolkedebruin/airflow,forevernull/incubator-airflow,adamhaney/airflow,vineet-rh/incubator-airflow,ty707/airflow,yati-sagade/incubator-airflow,andyxhadji/incubator-airflow,andrewmchen/incubator-airflow,akosel/incubator-airflow,andrewmchen/incubator-airflow,dhuang/incubator-airflow,N3da/incubator-airflow,owlabs/incubator-airflow,andyxhadji/incubator-airflow,d-lee/airflow,DEVELByte/incubator-airflow,dud225/incubator-airflow,dhuang/incubator-airflow,sid88in/incubator-airflow,vijaysbhat/incubator-airflow,alexvanboxel/airflow,gritlogic/incubator-airflow,gilt/incubator-airflow,lxneng/incubator-airflow,edgarRd/incubator-airflow,KL-WLCR/incubator-airflow,jhsenjaliya/incubator-airflow,zodiac/incubator-airflow,bolkedebruin/airflow,OpringaoDoTurno/airflow
import psycopg2 from airflow.hooks.dbapi_hook import DbApiHook class PostgresHook(DbApiHook): ''' Interact with Postgres. You can specify ssl parameters in the extra field of your connection as ``{"sslmode": "require", "sslcert": "/path/to/cert.pem", etc}``. ''' conn_name_attr = 'postgres_conn_id' default_conn_name = 'postgres_default' - supports_autocommit = True + supports_autocommit = False def get_conn(self): conn = self.get_connection(self.postgres_conn_id) conn_args = dict( host=conn.host, user=conn.login, password=conn.password, dbname=conn.schema, port=conn.port) # check for ssl parameters in conn.extra for arg_name, arg_val in conn.extra_dejson.items(): if arg_name in ['sslmode', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl']: conn_args[arg_name] = arg_val - return psycopg2.connect(**conn_args) + psycopg2_conn = psycopg2.connect(**conn_args) + if psycopg2_conn.server_version < 70400: + self.supports_autocommit = True + return psycopg2_conn
Set Postgres autocommit as supported only if server version is < 7.4
## Code Before: import psycopg2 from airflow.hooks.dbapi_hook import DbApiHook class PostgresHook(DbApiHook): ''' Interact with Postgres. You can specify ssl parameters in the extra field of your connection as ``{"sslmode": "require", "sslcert": "/path/to/cert.pem", etc}``. ''' conn_name_attr = 'postgres_conn_id' default_conn_name = 'postgres_default' supports_autocommit = True def get_conn(self): conn = self.get_connection(self.postgres_conn_id) conn_args = dict( host=conn.host, user=conn.login, password=conn.password, dbname=conn.schema, port=conn.port) # check for ssl parameters in conn.extra for arg_name, arg_val in conn.extra_dejson.items(): if arg_name in ['sslmode', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl']: conn_args[arg_name] = arg_val return psycopg2.connect(**conn_args) ## Instruction: Set Postgres autocommit as supported only if server version is < 7.4 ## Code After: import psycopg2 from airflow.hooks.dbapi_hook import DbApiHook class PostgresHook(DbApiHook): ''' Interact with Postgres. You can specify ssl parameters in the extra field of your connection as ``{"sslmode": "require", "sslcert": "/path/to/cert.pem", etc}``. ''' conn_name_attr = 'postgres_conn_id' default_conn_name = 'postgres_default' supports_autocommit = False def get_conn(self): conn = self.get_connection(self.postgres_conn_id) conn_args = dict( host=conn.host, user=conn.login, password=conn.password, dbname=conn.schema, port=conn.port) # check for ssl parameters in conn.extra for arg_name, arg_val in conn.extra_dejson.items(): if arg_name in ['sslmode', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl']: conn_args[arg_name] = arg_val psycopg2_conn = psycopg2.connect(**conn_args) if psycopg2_conn.server_version < 70400: self.supports_autocommit = True return psycopg2_conn
import psycopg2 from airflow.hooks.dbapi_hook import DbApiHook class PostgresHook(DbApiHook): ''' Interact with Postgres. You can specify ssl parameters in the extra field of your connection as ``{"sslmode": "require", "sslcert": "/path/to/cert.pem", etc}``. ''' conn_name_attr = 'postgres_conn_id' default_conn_name = 'postgres_default' - supports_autocommit = True ? ^^^ + supports_autocommit = False ? ^^^^ def get_conn(self): conn = self.get_connection(self.postgres_conn_id) conn_args = dict( host=conn.host, user=conn.login, password=conn.password, dbname=conn.schema, port=conn.port) # check for ssl parameters in conn.extra for arg_name, arg_val in conn.extra_dejson.items(): if arg_name in ['sslmode', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl']: conn_args[arg_name] = arg_val - return psycopg2.connect(**conn_args) ? ^^^^^ + psycopg2_conn = psycopg2.connect(**conn_args) ? ^^^^^^^^^^^ +++ + if psycopg2_conn.server_version < 70400: + self.supports_autocommit = True + return psycopg2_conn
49ce9aa1bdd3479c31b8aa2e606b1768a444aea2
irrigator_pro/farms/templatetags/today_filters.py
irrigator_pro/farms/templatetags/today_filters.py
from django import template from datetime import date, datetime, timedelta register = template.Library() @register.filter(expects_localtime=True) def is_today(value): if isinstance(value, datetime): value = value.date() return value == date.today() @register.filter(expects_localtime=True) def is_past(value): if isinstance(value, datetime): value = value.date() return value < date.today() @register.filter(expects_localtime=True) def is_future(value): if isinstance(value, datetime): value = value.date() return value > date.today() @register.filter(expects_localtime=True) def compare_today(value): if isinstance(value, datetime): value = value.date() return value - date.today()
from django import template from datetime import date, datetime, timedelta register = template.Library() @register.filter(expects_localtime=True) def is_today(value): if isinstance(value, datetime): value = value.date() return value == date.today() @register.filter(expects_localtime=True) def is_past(value): if isinstance(value, datetime): value = value.date() return value < date.today() @register.filter(expects_localtime=True) def is_future(value): if isinstance(value, datetime): value = value.date() return value > date.today() @register.filter(expects_localtime=True) def compare_today(value): if isinstance(value, datetime): value = value.date() return value - date.today() @register.filter(expects_locattime=True) def today_in_season(season): start_date = season.season_start_date end_date = season.season_end_date return (start_date <= date.today() <= end_date)
Add new filter to determine if today is within the time period for a season.
Add new filter to determine if today is within the time period for a season.
Python
mit
warnes/irrigatorpro,warnes/irrigatorpro,warnes/irrigatorpro,warnes/irrigatorpro
from django import template from datetime import date, datetime, timedelta register = template.Library() @register.filter(expects_localtime=True) def is_today(value): if isinstance(value, datetime): value = value.date() return value == date.today() @register.filter(expects_localtime=True) def is_past(value): if isinstance(value, datetime): value = value.date() return value < date.today() @register.filter(expects_localtime=True) def is_future(value): if isinstance(value, datetime): value = value.date() return value > date.today() @register.filter(expects_localtime=True) def compare_today(value): if isinstance(value, datetime): value = value.date() return value - date.today() + @register.filter(expects_locattime=True) + def today_in_season(season): + start_date = season.season_start_date + end_date = season.season_end_date + return (start_date <= date.today() <= end_date) + +
Add new filter to determine if today is within the time period for a season.
## Code Before: from django import template from datetime import date, datetime, timedelta register = template.Library() @register.filter(expects_localtime=True) def is_today(value): if isinstance(value, datetime): value = value.date() return value == date.today() @register.filter(expects_localtime=True) def is_past(value): if isinstance(value, datetime): value = value.date() return value < date.today() @register.filter(expects_localtime=True) def is_future(value): if isinstance(value, datetime): value = value.date() return value > date.today() @register.filter(expects_localtime=True) def compare_today(value): if isinstance(value, datetime): value = value.date() return value - date.today() ## Instruction: Add new filter to determine if today is within the time period for a season. ## Code After: from django import template from datetime import date, datetime, timedelta register = template.Library() @register.filter(expects_localtime=True) def is_today(value): if isinstance(value, datetime): value = value.date() return value == date.today() @register.filter(expects_localtime=True) def is_past(value): if isinstance(value, datetime): value = value.date() return value < date.today() @register.filter(expects_localtime=True) def is_future(value): if isinstance(value, datetime): value = value.date() return value > date.today() @register.filter(expects_localtime=True) def compare_today(value): if isinstance(value, datetime): value = value.date() return value - date.today() @register.filter(expects_locattime=True) def today_in_season(season): start_date = season.season_start_date end_date = season.season_end_date return (start_date <= date.today() <= end_date)
from django import template from datetime import date, datetime, timedelta register = template.Library() @register.filter(expects_localtime=True) def is_today(value): if isinstance(value, datetime): value = value.date() return value == date.today() @register.filter(expects_localtime=True) def is_past(value): if isinstance(value, datetime): value = value.date() return value < date.today() @register.filter(expects_localtime=True) def is_future(value): if isinstance(value, datetime): value = value.date() return value > date.today() @register.filter(expects_localtime=True) def compare_today(value): if isinstance(value, datetime): value = value.date() return value - date.today() + + @register.filter(expects_locattime=True) + def today_in_season(season): + start_date = season.season_start_date + end_date = season.season_end_date + return (start_date <= date.today() <= end_date) +
4d40e9db4bd6b58787557e8d5547f69eb67c9b96
tests/changes/api/test_author_build_index.py
tests/changes/api/test_author_build_index.py
from uuid import uuid4 from changes.config import db from changes.models import Author from changes.testutils import APITestCase class AuthorBuildListTest(APITestCase): def test_simple(self): fake_author_id = uuid4() self.create_build(self.project) path = '/api/0/authors/{0}/builds/'.format(fake_author_id.hex) resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert len(data) == 0 author = Author(email='foo@example.com', name='Foo Bar') db.session.add(author) build = self.create_build(self.project, author=author) path = '/api/0/authors/{0}/builds/'.format(author.id.hex) resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert len(data) == 1 assert data[0]['id'] == build.id.hex
from uuid import uuid4 from changes.config import db from changes.models import Author from changes.testutils import APITestCase class AuthorBuildListTest(APITestCase): def test_simple(self): fake_author_id = uuid4() self.create_build(self.project) path = '/api/0/authors/{0}/builds/'.format(fake_author_id.hex) resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert len(data) == 0 author = Author(email=self.default_user.email, name='Foo Bar') db.session.add(author) build = self.create_build(self.project, author=author) path = '/api/0/authors/{0}/builds/'.format(author.id.hex) resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert len(data) == 1 assert data[0]['id'] == build.id.hex self.login(self.default_user) path = '/api/0/authors/me/builds/' resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert len(data) == 1 assert data[0]['id'] == build.id.hex
Add additional coverage to author build list
Add additional coverage to author build list
Python
apache-2.0
wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes
from uuid import uuid4 from changes.config import db from changes.models import Author from changes.testutils import APITestCase class AuthorBuildListTest(APITestCase): def test_simple(self): fake_author_id = uuid4() self.create_build(self.project) path = '/api/0/authors/{0}/builds/'.format(fake_author_id.hex) resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert len(data) == 0 - author = Author(email='foo@example.com', name='Foo Bar') + author = Author(email=self.default_user.email, name='Foo Bar') db.session.add(author) build = self.create_build(self.project, author=author) path = '/api/0/authors/{0}/builds/'.format(author.id.hex) resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert len(data) == 1 assert data[0]['id'] == build.id.hex + self.login(self.default_user) + + path = '/api/0/authors/me/builds/' + + resp = self.client.get(path) + assert resp.status_code == 200 + data = self.unserialize(resp) + assert len(data) == 1 + assert data[0]['id'] == build.id.hex +
Add additional coverage to author build list
## Code Before: from uuid import uuid4 from changes.config import db from changes.models import Author from changes.testutils import APITestCase class AuthorBuildListTest(APITestCase): def test_simple(self): fake_author_id = uuid4() self.create_build(self.project) path = '/api/0/authors/{0}/builds/'.format(fake_author_id.hex) resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert len(data) == 0 author = Author(email='foo@example.com', name='Foo Bar') db.session.add(author) build = self.create_build(self.project, author=author) path = '/api/0/authors/{0}/builds/'.format(author.id.hex) resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert len(data) == 1 assert data[0]['id'] == build.id.hex ## Instruction: Add additional coverage to author build list ## Code After: from uuid import uuid4 from changes.config import db from changes.models import Author from changes.testutils import APITestCase class AuthorBuildListTest(APITestCase): def test_simple(self): fake_author_id = uuid4() self.create_build(self.project) path = '/api/0/authors/{0}/builds/'.format(fake_author_id.hex) resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert len(data) == 0 author = Author(email=self.default_user.email, name='Foo Bar') db.session.add(author) build = self.create_build(self.project, author=author) path = '/api/0/authors/{0}/builds/'.format(author.id.hex) resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert len(data) == 1 assert data[0]['id'] == build.id.hex self.login(self.default_user) path = '/api/0/authors/me/builds/' resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert len(data) == 1 assert data[0]['id'] == build.id.hex
from uuid import uuid4 from changes.config import db from changes.models import Author from changes.testutils import APITestCase class AuthorBuildListTest(APITestCase): def test_simple(self): fake_author_id = uuid4() self.create_build(self.project) path = '/api/0/authors/{0}/builds/'.format(fake_author_id.hex) resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert len(data) == 0 - author = Author(email='foo@example.com', name='Foo Bar') ? ^ ^^^ ^ ^ ------ + author = Author(email=self.default_user.email, name='Foo Bar') ? ^^^ ^^ ^ ++++++++++ ^^ db.session.add(author) build = self.create_build(self.project, author=author) path = '/api/0/authors/{0}/builds/'.format(author.id.hex) resp = self.client.get(path) assert resp.status_code == 200 data = self.unserialize(resp) assert len(data) == 1 assert data[0]['id'] == build.id.hex + + self.login(self.default_user) + + path = '/api/0/authors/me/builds/' + + resp = self.client.get(path) + assert resp.status_code == 200 + data = self.unserialize(resp) + assert len(data) == 1 + assert data[0]['id'] == build.id.hex
a51d280ca7c7f487e6743e4f377f70641a8b4edd
turbustat/statistics/statistics_list.py
turbustat/statistics/statistics_list.py
''' Returns a list of all available distance metrics ''' statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer", "Skewness", "Kurtosis", "VCS_Small_Scale", "VCS_Break", "VCS_Large_Scale", "PDF_Hellinger", "PDF_KS", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"] twoD_statistics_list = \ ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "Tsallis", "Skewness", "Kurtosis", "PDF_Hellinger", "PDF_KS", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"]
''' Returns a list of all available distance metrics ''' statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer", "Skewness", "Kurtosis", "VCS_Small_Scale", "VCS_Break", "VCS_Large_Scale", "PDF_Hellinger", "PDF_KS", "PDF_Lognormal", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"] twoD_statistics_list = \ ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "Tsallis", "Skewness", "Kurtosis", "PDF_Hellinger", "PDF_KS", "PDF_Lognormal", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"] threeD_statistics_list = \ ["VCS", "VCA", "PCA", "SCF", "Cramer", "VCS_Small_Scale", "VCS_Large_Scale", "VCS_Break", "PDF_Hellinger", "PDF_KS", "PDF_Lognormal", "Dendrogram_Hist", "Dendrogram_Num"]
Update the stats lists and add a 3D only version
Update the stats lists and add a 3D only version
Python
mit
Astroua/TurbuStat,e-koch/TurbuStat
''' Returns a list of all available distance metrics ''' statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer", "Skewness", "Kurtosis", "VCS_Small_Scale", "VCS_Break", - "VCS_Large_Scale", "PDF_Hellinger", "PDF_KS", # "PDF_AD", + "VCS_Large_Scale", "PDF_Hellinger", "PDF_KS", + "PDF_Lognormal", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"] twoD_statistics_list = \ ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "Tsallis", "Skewness", "Kurtosis", - "PDF_Hellinger", "PDF_KS", # "PDF_AD", + "PDF_Hellinger", "PDF_KS", + "PDF_Lognormal", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"] + threeD_statistics_list = \ + ["VCS", "VCA", "PCA", "SCF", "Cramer", "VCS_Small_Scale", + "VCS_Large_Scale", "VCS_Break", "PDF_Hellinger", "PDF_KS", + "PDF_Lognormal", "Dendrogram_Hist", "Dendrogram_Num"] +
Update the stats lists and add a 3D only version
## Code Before: ''' Returns a list of all available distance metrics ''' statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer", "Skewness", "Kurtosis", "VCS_Small_Scale", "VCS_Break", "VCS_Large_Scale", "PDF_Hellinger", "PDF_KS", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"] twoD_statistics_list = \ ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "Tsallis", "Skewness", "Kurtosis", "PDF_Hellinger", "PDF_KS", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"] ## Instruction: Update the stats lists and add a 3D only version ## Code After: ''' Returns a list of all available distance metrics ''' statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer", "Skewness", "Kurtosis", "VCS_Small_Scale", "VCS_Break", "VCS_Large_Scale", "PDF_Hellinger", "PDF_KS", "PDF_Lognormal", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"] twoD_statistics_list = \ ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "Tsallis", "Skewness", "Kurtosis", "PDF_Hellinger", "PDF_KS", "PDF_Lognormal", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"] threeD_statistics_list = \ ["VCS", "VCA", "PCA", "SCF", "Cramer", "VCS_Small_Scale", "VCS_Large_Scale", "VCS_Break", "PDF_Hellinger", "PDF_KS", "PDF_Lognormal", "Dendrogram_Hist", "Dendrogram_Num"]
''' Returns a list of all available distance metrics ''' statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer", "Skewness", "Kurtosis", "VCS_Small_Scale", "VCS_Break", - "VCS_Large_Scale", "PDF_Hellinger", "PDF_KS", # "PDF_AD", ? ------------- + "VCS_Large_Scale", "PDF_Hellinger", "PDF_KS", + "PDF_Lognormal", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"] twoD_statistics_list = \ ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "Tsallis", "Skewness", "Kurtosis", - "PDF_Hellinger", "PDF_KS", # "PDF_AD", ? ------------- + "PDF_Hellinger", "PDF_KS", + "PDF_Lognormal", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"] + + threeD_statistics_list = \ + ["VCS", "VCA", "PCA", "SCF", "Cramer", "VCS_Small_Scale", + "VCS_Large_Scale", "VCS_Break", "PDF_Hellinger", "PDF_KS", + "PDF_Lognormal", "Dendrogram_Hist", "Dendrogram_Num"]
128a0ae97e86d6dec6c149a7d3f8bccd7f8c499d
agents/DiffAgentBase.py
agents/DiffAgentBase.py
class DiffAgentBase(object): diff = [] noise_reduction = [] latest_observation = 0 current_prediction = [] name = '' behaviour = None working_behaviour_size = 2 def __init__(self, experience, knowledge, space): self.space = space self.experience = experience self.knowledge = knowledge self.prediction() def reset_behaviour(self): total_score = 0 count = 0 if len(self.knowledge.behaviour) > 0: for b, score in self.knowledge.behaviour.iteritems(): total_score += score average_score = total_score / len(self.knowledge.behaviour) new_behaviour = {} for b, score in self.knowledge.behaviour.iteritems(): count += 1; if score >= average_score or count <= self.working_behaviour_size: new_behaviour[b] = score self.behaviour = new_behaviour.iteritems() # self.behaviour = self.knowledge.behaviour.iteritems() def sleep(self): self.behaviour = None
class DiffAgentBase(object): diff = [] noise_reduction = [] latest_observation = 0 current_prediction = [] name = '' behaviour = None working_behaviour_size = 2 def __init__(self, experience, knowledge, space): self.space = space self.experience = experience self.knowledge = knowledge self.prediction() def reset_behaviour(self): total_score = 0 count = 0 if len(self.knowledge.behaviour) > 0: for b, score in self.knowledge.behaviour.iteritems(): total_score += score average_score = total_score / len(self.knowledge.behaviour) new_behaviour = {} for b, score in self.knowledge.behaviour.iteritems(): count += 1; if score >= average_score or count <= self.working_behaviour_size: new_behaviour[b] = score else: break self.behaviour = new_behaviour.iteritems() # self.behaviour = self.knowledge.behaviour.iteritems() def sleep(self): self.behaviour = None
Break when done copying the working behaviour
Break when done copying the working behaviour
Python
apache-2.0
sergiuionescu/gym-agents
class DiffAgentBase(object): diff = [] noise_reduction = [] latest_observation = 0 current_prediction = [] name = '' behaviour = None working_behaviour_size = 2 def __init__(self, experience, knowledge, space): self.space = space self.experience = experience self.knowledge = knowledge self.prediction() def reset_behaviour(self): total_score = 0 count = 0 if len(self.knowledge.behaviour) > 0: for b, score in self.knowledge.behaviour.iteritems(): total_score += score average_score = total_score / len(self.knowledge.behaviour) new_behaviour = {} for b, score in self.knowledge.behaviour.iteritems(): count += 1; if score >= average_score or count <= self.working_behaviour_size: new_behaviour[b] = score + else: + break self.behaviour = new_behaviour.iteritems() # self.behaviour = self.knowledge.behaviour.iteritems() def sleep(self): self.behaviour = None
Break when done copying the working behaviour
## Code Before: class DiffAgentBase(object): diff = [] noise_reduction = [] latest_observation = 0 current_prediction = [] name = '' behaviour = None working_behaviour_size = 2 def __init__(self, experience, knowledge, space): self.space = space self.experience = experience self.knowledge = knowledge self.prediction() def reset_behaviour(self): total_score = 0 count = 0 if len(self.knowledge.behaviour) > 0: for b, score in self.knowledge.behaviour.iteritems(): total_score += score average_score = total_score / len(self.knowledge.behaviour) new_behaviour = {} for b, score in self.knowledge.behaviour.iteritems(): count += 1; if score >= average_score or count <= self.working_behaviour_size: new_behaviour[b] = score self.behaviour = new_behaviour.iteritems() # self.behaviour = self.knowledge.behaviour.iteritems() def sleep(self): self.behaviour = None ## Instruction: Break when done copying the working behaviour ## Code After: class DiffAgentBase(object): diff = [] noise_reduction = [] latest_observation = 0 current_prediction = [] name = '' behaviour = None working_behaviour_size = 2 def __init__(self, experience, knowledge, space): self.space = space self.experience = experience self.knowledge = knowledge self.prediction() def reset_behaviour(self): total_score = 0 count = 0 if len(self.knowledge.behaviour) > 0: for b, score in self.knowledge.behaviour.iteritems(): total_score += score average_score = total_score / len(self.knowledge.behaviour) new_behaviour = {} for b, score in self.knowledge.behaviour.iteritems(): count += 1; if score >= average_score or count <= self.working_behaviour_size: new_behaviour[b] = score else: break self.behaviour = new_behaviour.iteritems() # self.behaviour = self.knowledge.behaviour.iteritems() def sleep(self): self.behaviour = None
class DiffAgentBase(object): diff = [] noise_reduction = [] latest_observation = 0 current_prediction = [] name = '' behaviour = None working_behaviour_size = 2 def __init__(self, experience, knowledge, space): self.space = space self.experience = experience self.knowledge = knowledge self.prediction() def reset_behaviour(self): total_score = 0 count = 0 if len(self.knowledge.behaviour) > 0: for b, score in self.knowledge.behaviour.iteritems(): total_score += score average_score = total_score / len(self.knowledge.behaviour) new_behaviour = {} for b, score in self.knowledge.behaviour.iteritems(): count += 1; if score >= average_score or count <= self.working_behaviour_size: new_behaviour[b] = score + else: + break self.behaviour = new_behaviour.iteritems() # self.behaviour = self.knowledge.behaviour.iteritems() def sleep(self): self.behaviour = None
63946ef78a842b82064b560dd0f73c9a5fe7ac82
puzzle/urls.py
puzzle/urls.py
from django.conf.urls import include, url from django.contrib.auth import views as auth_views from puzzle import views from puzzle.feeds import PuzzleFeed urlpatterns = [ #pylint: disable=invalid-name url(r'^$', views.latest, name='latest'), url(r'^login/$', auth_views.login, {'template_name': 'puzzle/login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': 'latest'}, name='logout'), url(r'^create/$', views.create, name='create'), url(r'^save/$', views.save, name='save'), url(r'^rss/$', PuzzleFeed(), name='rss'), url(r'^archive/$', views.users, name='users'), url(r'^profile/$', views.profile, name='profile'), url(r'^puzzle/(?P<number>\d+)/$', views.puzzle_redirect), url(r'^setter/(?P<author>\w+)/(?P<number>\d+)/', include([ url(r'^$', views.puzzle, name='puzzle'), url(r'^solution/$', views.solution, name='solution'), url(r'^edit/$', views.edit, name='edit'), ])), ]
from django.conf.urls import include, url from django.contrib.auth import views as auth_views from puzzle import views from puzzle.feeds import PuzzleFeed urlpatterns = [ #pylint: disable=invalid-name url(r'^$', views.latest, name='latest'), url(r'^login/$', auth_views.LoginView.as_view(template_name='puzzle/login.html'), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(next_page='latest'), name='logout'), url(r'^create/$', views.create, name='create'), url(r'^save/$', views.save, name='save'), url(r'^rss/$', PuzzleFeed(), name='rss'), url(r'^archive/$', views.users, name='users'), url(r'^profile/$', views.profile, name='profile'), url(r'^puzzle/(?P<number>\d+)/$', views.puzzle_redirect), url(r'^setter/(?P<author>\w+)/(?P<number>\d+)/', include([ url(r'^$', views.puzzle, name='puzzle'), url(r'^solution/$', views.solution, name='solution'), url(r'^edit/$', views.edit, name='edit'), ])), ]
Replace deprecated login/logout function-based views
Replace deprecated login/logout function-based views
Python
mit
jomoore/threepins,jomoore/threepins,jomoore/threepins
from django.conf.urls import include, url from django.contrib.auth import views as auth_views from puzzle import views from puzzle.feeds import PuzzleFeed urlpatterns = [ #pylint: disable=invalid-name url(r'^$', views.latest, name='latest'), - url(r'^login/$', auth_views.login, {'template_name': 'puzzle/login.html'}, name='login'), + url(r'^login/$', auth_views.LoginView.as_view(template_name='puzzle/login.html'), name='login'), - url(r'^logout/$', auth_views.logout, {'next_page': 'latest'}, name='logout'), + url(r'^logout/$', auth_views.LogoutView.as_view(next_page='latest'), name='logout'), url(r'^create/$', views.create, name='create'), url(r'^save/$', views.save, name='save'), url(r'^rss/$', PuzzleFeed(), name='rss'), url(r'^archive/$', views.users, name='users'), url(r'^profile/$', views.profile, name='profile'), url(r'^puzzle/(?P<number>\d+)/$', views.puzzle_redirect), url(r'^setter/(?P<author>\w+)/(?P<number>\d+)/', include([ url(r'^$', views.puzzle, name='puzzle'), url(r'^solution/$', views.solution, name='solution'), url(r'^edit/$', views.edit, name='edit'), ])), ]
Replace deprecated login/logout function-based views
## Code Before: from django.conf.urls import include, url from django.contrib.auth import views as auth_views from puzzle import views from puzzle.feeds import PuzzleFeed urlpatterns = [ #pylint: disable=invalid-name url(r'^$', views.latest, name='latest'), url(r'^login/$', auth_views.login, {'template_name': 'puzzle/login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': 'latest'}, name='logout'), url(r'^create/$', views.create, name='create'), url(r'^save/$', views.save, name='save'), url(r'^rss/$', PuzzleFeed(), name='rss'), url(r'^archive/$', views.users, name='users'), url(r'^profile/$', views.profile, name='profile'), url(r'^puzzle/(?P<number>\d+)/$', views.puzzle_redirect), url(r'^setter/(?P<author>\w+)/(?P<number>\d+)/', include([ url(r'^$', views.puzzle, name='puzzle'), url(r'^solution/$', views.solution, name='solution'), url(r'^edit/$', views.edit, name='edit'), ])), ] ## Instruction: Replace deprecated login/logout function-based views ## Code After: from django.conf.urls import include, url from django.contrib.auth import views as auth_views from puzzle import views from puzzle.feeds import PuzzleFeed urlpatterns = [ #pylint: disable=invalid-name url(r'^$', views.latest, name='latest'), url(r'^login/$', auth_views.LoginView.as_view(template_name='puzzle/login.html'), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(next_page='latest'), name='logout'), url(r'^create/$', views.create, name='create'), url(r'^save/$', views.save, name='save'), url(r'^rss/$', PuzzleFeed(), name='rss'), url(r'^archive/$', views.users, name='users'), url(r'^profile/$', views.profile, name='profile'), url(r'^puzzle/(?P<number>\d+)/$', views.puzzle_redirect), url(r'^setter/(?P<author>\w+)/(?P<number>\d+)/', include([ url(r'^$', views.puzzle, name='puzzle'), url(r'^solution/$', views.solution, name='solution'), url(r'^edit/$', views.edit, name='edit'), ])), ]
from django.conf.urls import include, url from django.contrib.auth import views as auth_views from puzzle import views from puzzle.feeds import PuzzleFeed urlpatterns = [ #pylint: disable=invalid-name url(r'^$', views.latest, name='latest'), - url(r'^login/$', auth_views.login, {'template_name': 'puzzle/login.html'}, name='login'), ? ^ ^^^^ ^^^ ^ + url(r'^login/$', auth_views.LoginView.as_view(template_name='puzzle/login.html'), name='login'), ? ^ ^^^^^^^^^^^^^ ^ ^ - url(r'^logout/$', auth_views.logout, {'next_page': 'latest'}, name='logout'), ? ^ ^^^^ ^^^ ^ + url(r'^logout/$', auth_views.LogoutView.as_view(next_page='latest'), name='logout'), ? ^ ^^^^^^^^^^^^^ ^ ^ url(r'^create/$', views.create, name='create'), url(r'^save/$', views.save, name='save'), url(r'^rss/$', PuzzleFeed(), name='rss'), url(r'^archive/$', views.users, name='users'), url(r'^profile/$', views.profile, name='profile'), url(r'^puzzle/(?P<number>\d+)/$', views.puzzle_redirect), url(r'^setter/(?P<author>\w+)/(?P<number>\d+)/', include([ url(r'^$', views.puzzle, name='puzzle'), url(r'^solution/$', views.solution, name='solution'), url(r'^edit/$', views.edit, name='edit'), ])), ]
f8f0335a1a790b1ef8163a2be968b29769be80a2
arim/models.py
arim/models.py
from django.db import models class Lease(models.Model): class Meta: db_table = 'autoreg' mac = models.CharField(max_length=17, db_index=True) ip = models.IntegerField(primary_key=True) date = models.IntegerField()
from django.db import models from ipaddr import IPv4Address class Lease(models.Model): class Meta: db_table = 'autoreg' mac = models.CharField(max_length=17, db_index=True) ip = models.IntegerField(primary_key=True) date = models.IntegerField() def __str__(self): return unicode(self).encode('ascii', 'replace') def __unicode__(self): return unicode(IPv4Address(self.ip)) + u' = ' + unicode(self.mac) def __repr__(self): return u'<Lease: ' + unicode(self) + u'>'
Add __str__, __unicode__, and __repr__
Add __str__, __unicode__, and __repr__
Python
bsd-3-clause
drkitty/arim,OSU-Net/arim,OSU-Net/arim,drkitty/arim,drkitty/arim,OSU-Net/arim
from django.db import models + from ipaddr import IPv4Address class Lease(models.Model): class Meta: db_table = 'autoreg' mac = models.CharField(max_length=17, db_index=True) ip = models.IntegerField(primary_key=True) date = models.IntegerField() + def __str__(self): + return unicode(self).encode('ascii', 'replace') + + def __unicode__(self): + return unicode(IPv4Address(self.ip)) + u' = ' + unicode(self.mac) + + def __repr__(self): + return u'<Lease: ' + unicode(self) + u'>' +
Add __str__, __unicode__, and __repr__
## Code Before: from django.db import models class Lease(models.Model): class Meta: db_table = 'autoreg' mac = models.CharField(max_length=17, db_index=True) ip = models.IntegerField(primary_key=True) date = models.IntegerField() ## Instruction: Add __str__, __unicode__, and __repr__ ## Code After: from django.db import models from ipaddr import IPv4Address class Lease(models.Model): class Meta: db_table = 'autoreg' mac = models.CharField(max_length=17, db_index=True) ip = models.IntegerField(primary_key=True) date = models.IntegerField() def __str__(self): return unicode(self).encode('ascii', 'replace') def __unicode__(self): return unicode(IPv4Address(self.ip)) + u' = ' + unicode(self.mac) def __repr__(self): return u'<Lease: ' + unicode(self) + u'>'
from django.db import models + from ipaddr import IPv4Address class Lease(models.Model): class Meta: db_table = 'autoreg' mac = models.CharField(max_length=17, db_index=True) ip = models.IntegerField(primary_key=True) date = models.IntegerField() + + def __str__(self): + return unicode(self).encode('ascii', 'replace') + + def __unicode__(self): + return unicode(IPv4Address(self.ip)) + u' = ' + unicode(self.mac) + + def __repr__(self): + return u'<Lease: ' + unicode(self) + u'>'
7c1612d954c38ea86d2dff91537a4103f15cc0cb
statsmodels/tsa/api.py
statsmodels/tsa/api.py
from .ar_model import AR from .arima_model import ARMA, ARIMA import vector_ar as var from .vector_ar.var_model import VAR from .vector_ar.svar_model import SVAR from .vector_ar.dynamic import DynamicVAR import filters import tsatools from .tsatools import (add_trend, detrend, lagmat, lagmat2ds, add_lag) import interp import stattools from .stattools import (adfuller, acovf, q_stat, acf, pacf_yw, pacf_ols, pacf, ccovf, ccf, periodogram, grangercausalitytests) from .base import datetools
from .ar_model import AR from .arima_model import ARMA, ARIMA import vector_ar as var from .vector_ar.var_model import VAR from .vector_ar.svar_model import SVAR from .vector_ar.dynamic import DynamicVAR import filters import tsatools from .tsatools import (add_trend, detrend, lagmat, lagmat2ds, add_lag) import interp import stattools from .stattools import * from .base import datetools
Use import * since __all__ is defined.
REF: Use import * since __all__ is defined.
Python
bsd-3-clause
josef-pkt/statsmodels,bert9bert/statsmodels,ChadFulton/statsmodels,statsmodels/statsmodels,musically-ut/statsmodels,wwf5067/statsmodels,DonBeo/statsmodels,huongttlan/statsmodels,astocko/statsmodels,jstoxrocky/statsmodels,bashtage/statsmodels,wkfwkf/statsmodels,Averroes/statsmodels,bashtage/statsmodels,nvoron23/statsmodels,huongttlan/statsmodels,bert9bert/statsmodels,yl565/statsmodels,waynenilsen/statsmodels,josef-pkt/statsmodels,DonBeo/statsmodels,nguyentu1602/statsmodels,wdurhamh/statsmodels,bert9bert/statsmodels,kiyoto/statsmodels,bzero/statsmodels,bashtage/statsmodels,wwf5067/statsmodels,alekz112/statsmodels,rgommers/statsmodels,statsmodels/statsmodels,saketkc/statsmodels,YihaoLu/statsmodels,wkfwkf/statsmodels,wkfwkf/statsmodels,huongttlan/statsmodels,yl565/statsmodels,wzbozon/statsmodels,josef-pkt/statsmodels,bert9bert/statsmodels,phobson/statsmodels,bashtage/statsmodels,phobson/statsmodels,jseabold/statsmodels,wzbozon/statsmodels,bzero/statsmodels,detrout/debian-statsmodels,waynenilsen/statsmodels,rgommers/statsmodels,yl565/statsmodels,cbmoore/statsmodels,Averroes/statsmodels,cbmoore/statsmodels,saketkc/statsmodels,saketkc/statsmodels,alekz112/statsmodels,huongttlan/statsmodels,astocko/statsmodels,josef-pkt/statsmodels,gef756/statsmodels,waynenilsen/statsmodels,bsipocz/statsmodels,phobson/statsmodels,detrout/debian-statsmodels,edhuckle/statsmodels,adammenges/statsmodels,nvoron23/statsmodels,waynenilsen/statsmodels,nvoron23/statsmodels,phobson/statsmodels,jstoxrocky/statsmodels,edhuckle/statsmodels,rgommers/statsmodels,cbmoore/statsmodels,jseabold/statsmodels,ChadFulton/statsmodels,ChadFulton/statsmodels,bsipocz/statsmodels,detrout/debian-statsmodels,edhuckle/statsmodels,cbmoore/statsmodels,nguyentu1602/statsmodels,DonBeo/statsmodels,detrout/debian-statsmodels,bert9bert/statsmodels,bsipocz/statsmodels,gef756/statsmodels,statsmodels/statsmodels,yl565/statsmodels,nguyentu1602/statsmodels,DonBeo/statsmodels,kiyoto/statsmodels,wdurhamh/statsmodels,statsmodels/statsmodels,josef-pkt/statsmodels,astocko/statsmodels,saketkc/statsmodels,hlin117/statsmodels,hainm/statsmodels,bzero/statsmodels,wwf5067/statsmodels,wzbozon/statsmodels,phobson/statsmodels,statsmodels/statsmodels,bashtage/statsmodels,statsmodels/statsmodels,rgommers/statsmodels,Averroes/statsmodels,alekz112/statsmodels,Averroes/statsmodels,kiyoto/statsmodels,adammenges/statsmodels,wzbozon/statsmodels,gef756/statsmodels,jstoxrocky/statsmodels,edhuckle/statsmodels,wwf5067/statsmodels,hlin117/statsmodels,wkfwkf/statsmodels,hlin117/statsmodels,adammenges/statsmodels,DonBeo/statsmodels,nvoron23/statsmodels,bzero/statsmodels,nvoron23/statsmodels,kiyoto/statsmodels,wkfwkf/statsmodels,musically-ut/statsmodels,gef756/statsmodels,rgommers/statsmodels,musically-ut/statsmodels,jseabold/statsmodels,cbmoore/statsmodels,nguyentu1602/statsmodels,YihaoLu/statsmodels,hainm/statsmodels,hlin117/statsmodels,ChadFulton/statsmodels,bzero/statsmodels,josef-pkt/statsmodels,astocko/statsmodels,alekz112/statsmodels,YihaoLu/statsmodels,wdurhamh/statsmodels,wdurhamh/statsmodels,kiyoto/statsmodels,musically-ut/statsmodels,ChadFulton/statsmodels,gef756/statsmodels,jstoxrocky/statsmodels,YihaoLu/statsmodels,hainm/statsmodels,bsipocz/statsmodels,hainm/statsmodels,ChadFulton/statsmodels,jseabold/statsmodels,jseabold/statsmodels,wdurhamh/statsmodels,YihaoLu/statsmodels,saketkc/statsmodels,bashtage/statsmodels,yl565/statsmodels,adammenges/statsmodels,edhuckle/statsmodels,wzbozon/statsmodels
from .ar_model import AR from .arima_model import ARMA, ARIMA import vector_ar as var from .vector_ar.var_model import VAR from .vector_ar.svar_model import SVAR from .vector_ar.dynamic import DynamicVAR import filters import tsatools from .tsatools import (add_trend, detrend, lagmat, lagmat2ds, add_lag) import interp import stattools + from .stattools import * - from .stattools import (adfuller, acovf, q_stat, acf, pacf_yw, pacf_ols, pacf, - ccovf, ccf, periodogram, grangercausalitytests) from .base import datetools
Use import * since __all__ is defined.
## Code Before: from .ar_model import AR from .arima_model import ARMA, ARIMA import vector_ar as var from .vector_ar.var_model import VAR from .vector_ar.svar_model import SVAR from .vector_ar.dynamic import DynamicVAR import filters import tsatools from .tsatools import (add_trend, detrend, lagmat, lagmat2ds, add_lag) import interp import stattools from .stattools import (adfuller, acovf, q_stat, acf, pacf_yw, pacf_ols, pacf, ccovf, ccf, periodogram, grangercausalitytests) from .base import datetools ## Instruction: Use import * since __all__ is defined. ## Code After: from .ar_model import AR from .arima_model import ARMA, ARIMA import vector_ar as var from .vector_ar.var_model import VAR from .vector_ar.svar_model import SVAR from .vector_ar.dynamic import DynamicVAR import filters import tsatools from .tsatools import (add_trend, detrend, lagmat, lagmat2ds, add_lag) import interp import stattools from .stattools import * from .base import datetools
from .ar_model import AR from .arima_model import ARMA, ARIMA import vector_ar as var from .vector_ar.var_model import VAR from .vector_ar.svar_model import SVAR from .vector_ar.dynamic import DynamicVAR import filters import tsatools from .tsatools import (add_trend, detrend, lagmat, lagmat2ds, add_lag) import interp import stattools + from .stattools import * - from .stattools import (adfuller, acovf, q_stat, acf, pacf_yw, pacf_ols, pacf, - ccovf, ccf, periodogram, grangercausalitytests) from .base import datetools
48075a16190bbcc3d260dfa242a5553b129de8a8
tests/test_see.py
tests/test_see.py
from __future__ import print_function, unicode_literals try: import unittest2 as unittest except ImportError: import unittest import see class TestSee(unittest.TestCase): def test_line_width(self): # Arrange default_width = 1 max_width = 1 # Act width = see.line_width(default_width, max_width) # Assert self.assertIsInstance(width, int) self.assertEqual(width, 1) def test_regex_filter(self): # Arrange names = ["george", "helen"] pat = "or*" # Act out = see.regex_filter(names, pat) # Assert self.assertIsInstance(out, tuple) self.assertEqual(out, ("george",)) def test_fn_filter(self): # Arrange names = ["george", "helen"] pat = "*or*" # Act out = see.fn_filter(names, pat) # Assert self.assertIsInstance(out, tuple) self.assertEqual(out, ("george",)) def test_see_with_no_args(self): # Act out = see.see() # Assert self.assertIsInstance(out, see._SeeOutput) if __name__ == '__main__': unittest.main() # End of file
from __future__ import print_function, unicode_literals try: import unittest2 as unittest except ImportError: import unittest import os import sys sys.path.insert(0, os.path.dirname(__file__)) import see class TestSee(unittest.TestCase): def test_line_width(self): # Arrange default_width = 1 max_width = 1 # Act width = see.line_width(default_width, max_width) # Assert self.assertIsInstance(width, int) self.assertEqual(width, 1) def test_regex_filter(self): # Arrange names = ["george", "helen"] pat = "or*" # Act out = see.regex_filter(names, pat) # Assert self.assertIsInstance(out, tuple) self.assertEqual(out, ("george",)) def test_fn_filter(self): # Arrange names = ["george", "helen"] pat = "*or*" # Act out = see.fn_filter(names, pat) # Assert self.assertIsInstance(out, tuple) self.assertEqual(out, ("george",)) def test_see_with_no_args(self): # Act out = see.see() # Assert self.assertIsInstance(out, see._SeeOutput) if __name__ == '__main__': unittest.main() # End of file
Update tests to import see
Update tests to import see
Python
bsd-3-clause
araile/see
from __future__ import print_function, unicode_literals try: import unittest2 as unittest except ImportError: import unittest + + import os + import sys + + sys.path.insert(0, os.path.dirname(__file__)) import see class TestSee(unittest.TestCase): def test_line_width(self): # Arrange default_width = 1 max_width = 1 # Act width = see.line_width(default_width, max_width) # Assert self.assertIsInstance(width, int) self.assertEqual(width, 1) def test_regex_filter(self): # Arrange names = ["george", "helen"] pat = "or*" # Act out = see.regex_filter(names, pat) # Assert self.assertIsInstance(out, tuple) self.assertEqual(out, ("george",)) def test_fn_filter(self): # Arrange names = ["george", "helen"] pat = "*or*" # Act out = see.fn_filter(names, pat) # Assert self.assertIsInstance(out, tuple) self.assertEqual(out, ("george",)) def test_see_with_no_args(self): # Act out = see.see() # Assert self.assertIsInstance(out, see._SeeOutput) if __name__ == '__main__': unittest.main() # End of file
Update tests to import see
## Code Before: from __future__ import print_function, unicode_literals try: import unittest2 as unittest except ImportError: import unittest import see class TestSee(unittest.TestCase): def test_line_width(self): # Arrange default_width = 1 max_width = 1 # Act width = see.line_width(default_width, max_width) # Assert self.assertIsInstance(width, int) self.assertEqual(width, 1) def test_regex_filter(self): # Arrange names = ["george", "helen"] pat = "or*" # Act out = see.regex_filter(names, pat) # Assert self.assertIsInstance(out, tuple) self.assertEqual(out, ("george",)) def test_fn_filter(self): # Arrange names = ["george", "helen"] pat = "*or*" # Act out = see.fn_filter(names, pat) # Assert self.assertIsInstance(out, tuple) self.assertEqual(out, ("george",)) def test_see_with_no_args(self): # Act out = see.see() # Assert self.assertIsInstance(out, see._SeeOutput) if __name__ == '__main__': unittest.main() # End of file ## Instruction: Update tests to import see ## Code After: from __future__ import print_function, unicode_literals try: import unittest2 as unittest except ImportError: import unittest import os import sys sys.path.insert(0, os.path.dirname(__file__)) import see class TestSee(unittest.TestCase): def test_line_width(self): # Arrange default_width = 1 max_width = 1 # Act width = see.line_width(default_width, max_width) # Assert self.assertIsInstance(width, int) self.assertEqual(width, 1) def test_regex_filter(self): # Arrange names = ["george", "helen"] pat = "or*" # Act out = see.regex_filter(names, pat) # Assert self.assertIsInstance(out, tuple) self.assertEqual(out, ("george",)) def test_fn_filter(self): # Arrange names = ["george", "helen"] pat = "*or*" # Act out = see.fn_filter(names, pat) # Assert self.assertIsInstance(out, tuple) self.assertEqual(out, ("george",)) def test_see_with_no_args(self): # Act out = see.see() # Assert self.assertIsInstance(out, see._SeeOutput) if __name__ == '__main__': unittest.main() # End of file
from __future__ import print_function, unicode_literals try: import unittest2 as unittest except ImportError: import unittest + + import os + import sys + + sys.path.insert(0, os.path.dirname(__file__)) import see class TestSee(unittest.TestCase): def test_line_width(self): # Arrange default_width = 1 max_width = 1 # Act width = see.line_width(default_width, max_width) # Assert self.assertIsInstance(width, int) self.assertEqual(width, 1) def test_regex_filter(self): # Arrange names = ["george", "helen"] pat = "or*" # Act out = see.regex_filter(names, pat) # Assert self.assertIsInstance(out, tuple) self.assertEqual(out, ("george",)) def test_fn_filter(self): # Arrange names = ["george", "helen"] pat = "*or*" # Act out = see.fn_filter(names, pat) # Assert self.assertIsInstance(out, tuple) self.assertEqual(out, ("george",)) def test_see_with_no_args(self): # Act out = see.see() # Assert self.assertIsInstance(out, see._SeeOutput) if __name__ == '__main__': unittest.main() # End of file
79e23159c308a69896c464eda13c043dbbc8086e
thezombies/management/commands/validate_all_data_catalogs.py
thezombies/management/commands/validate_all_data_catalogs.py
from django.core.management.base import NoArgsCommand from thezombies.tasks.main import validate_data_catalogs class Command(NoArgsCommand): """Validate all of the agency data catalogs""" def handle_noargs(self): validator_group = validate_data_catalogs.delay() self.stdout.write(u"\nSpawned data catalog task group: {0}\n".format(validator_group.id))
from django.core.management.base import NoArgsCommand from thezombies.tasks.main import validate_data_catalogs class Command(NoArgsCommand): """Validate all of the agency data catalogs""" def handle_noargs(self, **options): validator_group = validate_data_catalogs.delay() self.stdout.write(u"\nSpawned data catalog task group: {0}\n".format(validator_group.id))
Fix options on NoArgsCommand. Huh.
Fix options on NoArgsCommand. Huh.
Python
bsd-3-clause
sunlightlabs/thezombies,sunlightlabs/thezombies,sunlightlabs/thezombies,sunlightlabs/thezombies
from django.core.management.base import NoArgsCommand from thezombies.tasks.main import validate_data_catalogs class Command(NoArgsCommand): """Validate all of the agency data catalogs""" - def handle_noargs(self): + def handle_noargs(self, **options): validator_group = validate_data_catalogs.delay() self.stdout.write(u"\nSpawned data catalog task group: {0}\n".format(validator_group.id))
Fix options on NoArgsCommand. Huh.
## Code Before: from django.core.management.base import NoArgsCommand from thezombies.tasks.main import validate_data_catalogs class Command(NoArgsCommand): """Validate all of the agency data catalogs""" def handle_noargs(self): validator_group = validate_data_catalogs.delay() self.stdout.write(u"\nSpawned data catalog task group: {0}\n".format(validator_group.id)) ## Instruction: Fix options on NoArgsCommand. Huh. ## Code After: from django.core.management.base import NoArgsCommand from thezombies.tasks.main import validate_data_catalogs class Command(NoArgsCommand): """Validate all of the agency data catalogs""" def handle_noargs(self, **options): validator_group = validate_data_catalogs.delay() self.stdout.write(u"\nSpawned data catalog task group: {0}\n".format(validator_group.id))
from django.core.management.base import NoArgsCommand from thezombies.tasks.main import validate_data_catalogs class Command(NoArgsCommand): """Validate all of the agency data catalogs""" - def handle_noargs(self): + def handle_noargs(self, **options): ? +++++++++++ validator_group = validate_data_catalogs.delay() self.stdout.write(u"\nSpawned data catalog task group: {0}\n".format(validator_group.id))
8a7fd251454026baf3cf7a0a1aa0300a0f3772bc
pycanvas/assignment.py
pycanvas/assignment.py
from canvas_object import CanvasObject from util import combine_kwargs class Assignment(CanvasObject): def __str__(self): # pragma: no cover return "{} ({})".format(self.name, self.id) def delete(self): """ Delete this assignment. :calls: `DELETE /api/v1/courses/:course_id/assignments/:id \ <https://canvas.instructure.com/doc/api/assignments.html#method.assignments.destroy>`_ :rtype: :class:`pycanvas.assignment.Assignment` """ response = self._requester.request( 'DELETE', 'courses/%s/assignments/%s' % (self.course_id, self.id), ) return Assignment(self._requester, response.json()) def edit(self, **kwargs): """ Modify this assignment. :calls: `PUT /api/v1/courses/:course_id/assignments/:id \ <https://canvas.instructure.com/doc/api/assignments.html#method.assignments_api.update>`_ :rtype: :class:`pycanvas.assignment.Assignment` """ response = self._requester.request( 'PUT', 'courses/%s/assignments/%s' % (self.course_id, self.id), **combine_kwargs(**kwargs) ) if 'name' in response.json(): super(Assignment, self).set_attributes(response.json()) return Assignment(self._requester, response.json())
from canvas_object import CanvasObject from util import combine_kwargs class Assignment(CanvasObject): def __str__(self): return "{} ({})".format(self.name, self.id) def delete(self): """ Delete this assignment. :calls: `DELETE /api/v1/courses/:course_id/assignments/:id \ <https://canvas.instructure.com/doc/api/assignments.html#method.assignments.destroy>`_ :rtype: :class:`pycanvas.assignment.Assignment` """ response = self._requester.request( 'DELETE', 'courses/%s/assignments/%s' % (self.course_id, self.id), ) return Assignment(self._requester, response.json()) def edit(self, **kwargs): """ Modify this assignment. :calls: `PUT /api/v1/courses/:course_id/assignments/:id \ <https://canvas.instructure.com/doc/api/assignments.html#method.assignments_api.update>`_ :rtype: :class:`pycanvas.assignment.Assignment` """ response = self._requester.request( 'PUT', 'courses/%s/assignments/%s' % (self.course_id, self.id), **combine_kwargs(**kwargs) ) if 'name' in response.json(): super(Assignment, self).set_attributes(response.json()) return Assignment(self._requester, response.json())
Remove no-cover from __str__ method
Remove no-cover from __str__ method
Python
mit
ucfopen/canvasapi,ucfopen/canvasapi,ucfopen/canvasapi
from canvas_object import CanvasObject from util import combine_kwargs class Assignment(CanvasObject): - def __str__(self): # pragma: no cover + def __str__(self): return "{} ({})".format(self.name, self.id) def delete(self): """ Delete this assignment. :calls: `DELETE /api/v1/courses/:course_id/assignments/:id \ <https://canvas.instructure.com/doc/api/assignments.html#method.assignments.destroy>`_ :rtype: :class:`pycanvas.assignment.Assignment` """ response = self._requester.request( 'DELETE', 'courses/%s/assignments/%s' % (self.course_id, self.id), ) return Assignment(self._requester, response.json()) def edit(self, **kwargs): """ Modify this assignment. :calls: `PUT /api/v1/courses/:course_id/assignments/:id \ <https://canvas.instructure.com/doc/api/assignments.html#method.assignments_api.update>`_ :rtype: :class:`pycanvas.assignment.Assignment` """ response = self._requester.request( 'PUT', 'courses/%s/assignments/%s' % (self.course_id, self.id), **combine_kwargs(**kwargs) ) if 'name' in response.json(): super(Assignment, self).set_attributes(response.json()) return Assignment(self._requester, response.json())
Remove no-cover from __str__ method
## Code Before: from canvas_object import CanvasObject from util import combine_kwargs class Assignment(CanvasObject): def __str__(self): # pragma: no cover return "{} ({})".format(self.name, self.id) def delete(self): """ Delete this assignment. :calls: `DELETE /api/v1/courses/:course_id/assignments/:id \ <https://canvas.instructure.com/doc/api/assignments.html#method.assignments.destroy>`_ :rtype: :class:`pycanvas.assignment.Assignment` """ response = self._requester.request( 'DELETE', 'courses/%s/assignments/%s' % (self.course_id, self.id), ) return Assignment(self._requester, response.json()) def edit(self, **kwargs): """ Modify this assignment. :calls: `PUT /api/v1/courses/:course_id/assignments/:id \ <https://canvas.instructure.com/doc/api/assignments.html#method.assignments_api.update>`_ :rtype: :class:`pycanvas.assignment.Assignment` """ response = self._requester.request( 'PUT', 'courses/%s/assignments/%s' % (self.course_id, self.id), **combine_kwargs(**kwargs) ) if 'name' in response.json(): super(Assignment, self).set_attributes(response.json()) return Assignment(self._requester, response.json()) ## Instruction: Remove no-cover from __str__ method ## Code After: from canvas_object import CanvasObject from util import combine_kwargs class Assignment(CanvasObject): def __str__(self): return "{} ({})".format(self.name, self.id) def delete(self): """ Delete this assignment. :calls: `DELETE /api/v1/courses/:course_id/assignments/:id \ <https://canvas.instructure.com/doc/api/assignments.html#method.assignments.destroy>`_ :rtype: :class:`pycanvas.assignment.Assignment` """ response = self._requester.request( 'DELETE', 'courses/%s/assignments/%s' % (self.course_id, self.id), ) return Assignment(self._requester, response.json()) def edit(self, **kwargs): """ Modify this assignment. :calls: `PUT /api/v1/courses/:course_id/assignments/:id \ <https://canvas.instructure.com/doc/api/assignments.html#method.assignments_api.update>`_ :rtype: :class:`pycanvas.assignment.Assignment` """ response = self._requester.request( 'PUT', 'courses/%s/assignments/%s' % (self.course_id, self.id), **combine_kwargs(**kwargs) ) if 'name' in response.json(): super(Assignment, self).set_attributes(response.json()) return Assignment(self._requester, response.json())
from canvas_object import CanvasObject from util import combine_kwargs class Assignment(CanvasObject): - def __str__(self): # pragma: no cover + def __str__(self): return "{} ({})".format(self.name, self.id) def delete(self): """ Delete this assignment. :calls: `DELETE /api/v1/courses/:course_id/assignments/:id \ <https://canvas.instructure.com/doc/api/assignments.html#method.assignments.destroy>`_ :rtype: :class:`pycanvas.assignment.Assignment` """ response = self._requester.request( 'DELETE', 'courses/%s/assignments/%s' % (self.course_id, self.id), ) return Assignment(self._requester, response.json()) def edit(self, **kwargs): """ Modify this assignment. :calls: `PUT /api/v1/courses/:course_id/assignments/:id \ <https://canvas.instructure.com/doc/api/assignments.html#method.assignments_api.update>`_ :rtype: :class:`pycanvas.assignment.Assignment` """ response = self._requester.request( 'PUT', 'courses/%s/assignments/%s' % (self.course_id, self.id), **combine_kwargs(**kwargs) ) if 'name' in response.json(): super(Assignment, self).set_attributes(response.json()) return Assignment(self._requester, response.json())
6e526a173de970f2cc8f7cd62823a257786e348e
category/urls.py
category/urls.py
from django.conf.urls import patterns, url from .views import CategoriesList, GalleryDetail, StoryDetail urlpatterns = patterns('category.views', url(r'^gallery/categories/(?P<slug>.+)/$', GalleryDetail.as_view(), name='gallery-detail'), url(r'^stories/categories/(?P<slug>.+)/$', StoryDetail.as_view(), name='story-detail'), url(r'^categories/$', CategoriesList.as_view(), name='category-list'), url(r'^gallery/$', 'gallery_home_page', name='gallery-home-page') )
from django.conf.urls import patterns, url from .views import CategoriesList, GalleryDetail, StoryDetail urlpatterns = patterns('category.views', url(r'^categories/$', CategoriesList.as_view(), name='category-list'), url(r'^categories/(?P<slug>.+)/$', StoryDetail.as_view(), name='category-detail'), url(r'^stories/categories/(?P<slug>.+)/$', StoryDetail.as_view(), name='story-detail'), url(r'^gallery/categories/(?P<slug>.+)/$', GalleryDetail.as_view(), name='gallery-detail'), url(r'^gallery/$', 'gallery_home_page', name='gallery-home-page') )
Add the missing category-detail urlconf to not to break bookmarked users
Add the missing category-detail urlconf to not to break bookmarked users
Python
bsd-3-clause
PARINetwork/pari,PARINetwork/pari,PARINetwork/pari,PARINetwork/pari
from django.conf.urls import patterns, url from .views import CategoriesList, GalleryDetail, StoryDetail urlpatterns = patterns('category.views', + url(r'^categories/$', CategoriesList.as_view(), name='category-list'), + url(r'^categories/(?P<slug>.+)/$', StoryDetail.as_view(), name='category-detail'), + url(r'^stories/categories/(?P<slug>.+)/$', StoryDetail.as_view(), name='story-detail'), url(r'^gallery/categories/(?P<slug>.+)/$', GalleryDetail.as_view(), name='gallery-detail'), + - url(r'^stories/categories/(?P<slug>.+)/$', StoryDetail.as_view(), name='story-detail'), - url(r'^categories/$', CategoriesList.as_view(), name='category-list'), url(r'^gallery/$', 'gallery_home_page', name='gallery-home-page') )
Add the missing category-detail urlconf to not to break bookmarked users
## Code Before: from django.conf.urls import patterns, url from .views import CategoriesList, GalleryDetail, StoryDetail urlpatterns = patterns('category.views', url(r'^gallery/categories/(?P<slug>.+)/$', GalleryDetail.as_view(), name='gallery-detail'), url(r'^stories/categories/(?P<slug>.+)/$', StoryDetail.as_view(), name='story-detail'), url(r'^categories/$', CategoriesList.as_view(), name='category-list'), url(r'^gallery/$', 'gallery_home_page', name='gallery-home-page') ) ## Instruction: Add the missing category-detail urlconf to not to break bookmarked users ## Code After: from django.conf.urls import patterns, url from .views import CategoriesList, GalleryDetail, StoryDetail urlpatterns = patterns('category.views', url(r'^categories/$', CategoriesList.as_view(), name='category-list'), url(r'^categories/(?P<slug>.+)/$', StoryDetail.as_view(), name='category-detail'), url(r'^stories/categories/(?P<slug>.+)/$', StoryDetail.as_view(), name='story-detail'), url(r'^gallery/categories/(?P<slug>.+)/$', GalleryDetail.as_view(), name='gallery-detail'), url(r'^gallery/$', 'gallery_home_page', name='gallery-home-page') )
from django.conf.urls import patterns, url from .views import CategoriesList, GalleryDetail, StoryDetail urlpatterns = patterns('category.views', + url(r'^categories/$', CategoriesList.as_view(), name='category-list'), + url(r'^categories/(?P<slug>.+)/$', StoryDetail.as_view(), name='category-detail'), + url(r'^stories/categories/(?P<slug>.+)/$', StoryDetail.as_view(), name='story-detail'), url(r'^gallery/categories/(?P<slug>.+)/$', GalleryDetail.as_view(), name='gallery-detail'), + - url(r'^stories/categories/(?P<slug>.+)/$', StoryDetail.as_view(), name='story-detail'), - url(r'^categories/$', CategoriesList.as_view(), name='category-list'), url(r'^gallery/$', 'gallery_home_page', name='gallery-home-page') )
f5cab8249d5e162285e5fc94ded8bf7ced292986
test/test_ev3_key.py
test/test_ev3_key.py
from ev3.ev3dev import Key import unittest from util import get_input import time class TestTone(unittest.TestCase): def test_tone(self): d = Key() get_input('Test keyboard. Hold Up key') print(d.up) get_input('Test keyboard. Release Up key') print(d.up) get_input('Test keyboard. Hold Down key') print(d.down) get_input('Test keyboard. Release Down key') print(d.down) get_input('Test keyboard. Hold Left key') print(d.left) get_input('Test keyboard. Release Left key') print(d.left) get_input('Test keyboard. Hold Right key') print(d.right) get_input('Test keyboard. Release Right key') print(d.right) get_input('Test keyboard. Hold Backspace key') print(d.backspace) get_input('Test keyboard. Release Backspace key') print(d.backspace) get_input('Test keyboard. Hold Enter key') print(d.enter) get_input('Test keyboard. Release Enter key') print(d.enter) if __name__ == '__main__': unittest.main()
from ev3.ev3dev import Key import unittest from util import get_input class TestKey(unittest.TestCase): def test_key(self): d = Key() get_input('Test keyboard. Hold Up key') print(d.up) get_input('Test keyboard. Release Up key') print(d.up) get_input('Test keyboard. Hold Down key') print(d.down) get_input('Test keyboard. Release Down key') print(d.down) get_input('Test keyboard. Hold Left key') print(d.left) get_input('Test keyboard. Release Left key') print(d.left) get_input('Test keyboard. Hold Right key') print(d.right) get_input('Test keyboard. Release Right key') print(d.right) get_input('Test keyboard. Hold Backspace key') print(d.backspace) get_input('Test keyboard. Release Backspace key') print(d.backspace) get_input('Test keyboard. Hold Enter key') print(d.enter) get_input('Test keyboard. Release Enter key') print(d.enter) if __name__ == '__main__': unittest.main()
Change dname of key test
Change dname of key test
Python
apache-2.0
topikachu/python-ev3,MaxNoe/python-ev3,evz/python-ev3,topikachu/python-ev3,MaxNoe/python-ev3,evz/python-ev3
from ev3.ev3dev import Key import unittest from util import get_input - import time - class TestTone(unittest.TestCase): + class TestKey(unittest.TestCase): - def test_tone(self): + def test_key(self): d = Key() get_input('Test keyboard. Hold Up key') print(d.up) get_input('Test keyboard. Release Up key') print(d.up) get_input('Test keyboard. Hold Down key') print(d.down) get_input('Test keyboard. Release Down key') print(d.down) get_input('Test keyboard. Hold Left key') print(d.left) get_input('Test keyboard. Release Left key') print(d.left) get_input('Test keyboard. Hold Right key') print(d.right) get_input('Test keyboard. Release Right key') print(d.right) get_input('Test keyboard. Hold Backspace key') print(d.backspace) get_input('Test keyboard. Release Backspace key') print(d.backspace) get_input('Test keyboard. Hold Enter key') print(d.enter) get_input('Test keyboard. Release Enter key') print(d.enter) if __name__ == '__main__': unittest.main()
Change dname of key test
## Code Before: from ev3.ev3dev import Key import unittest from util import get_input import time class TestTone(unittest.TestCase): def test_tone(self): d = Key() get_input('Test keyboard. Hold Up key') print(d.up) get_input('Test keyboard. Release Up key') print(d.up) get_input('Test keyboard. Hold Down key') print(d.down) get_input('Test keyboard. Release Down key') print(d.down) get_input('Test keyboard. Hold Left key') print(d.left) get_input('Test keyboard. Release Left key') print(d.left) get_input('Test keyboard. Hold Right key') print(d.right) get_input('Test keyboard. Release Right key') print(d.right) get_input('Test keyboard. Hold Backspace key') print(d.backspace) get_input('Test keyboard. Release Backspace key') print(d.backspace) get_input('Test keyboard. Hold Enter key') print(d.enter) get_input('Test keyboard. Release Enter key') print(d.enter) if __name__ == '__main__': unittest.main() ## Instruction: Change dname of key test ## Code After: from ev3.ev3dev import Key import unittest from util import get_input class TestKey(unittest.TestCase): def test_key(self): d = Key() get_input('Test keyboard. Hold Up key') print(d.up) get_input('Test keyboard. Release Up key') print(d.up) get_input('Test keyboard. Hold Down key') print(d.down) get_input('Test keyboard. Release Down key') print(d.down) get_input('Test keyboard. Hold Left key') print(d.left) get_input('Test keyboard. Release Left key') print(d.left) get_input('Test keyboard. Hold Right key') print(d.right) get_input('Test keyboard. Release Right key') print(d.right) get_input('Test keyboard. Hold Backspace key') print(d.backspace) get_input('Test keyboard. Release Backspace key') print(d.backspace) get_input('Test keyboard. Hold Enter key') print(d.enter) get_input('Test keyboard. Release Enter key') print(d.enter) if __name__ == '__main__': unittest.main()
from ev3.ev3dev import Key import unittest from util import get_input - import time - class TestTone(unittest.TestCase): ? ^^^ + class TestKey(unittest.TestCase): ? ^ + - def test_tone(self): ? ^^^ + def test_key(self): ? ^ + d = Key() get_input('Test keyboard. Hold Up key') print(d.up) get_input('Test keyboard. Release Up key') print(d.up) get_input('Test keyboard. Hold Down key') print(d.down) get_input('Test keyboard. Release Down key') print(d.down) get_input('Test keyboard. Hold Left key') print(d.left) get_input('Test keyboard. Release Left key') print(d.left) get_input('Test keyboard. Hold Right key') print(d.right) get_input('Test keyboard. Release Right key') print(d.right) get_input('Test keyboard. Hold Backspace key') print(d.backspace) get_input('Test keyboard. Release Backspace key') print(d.backspace) get_input('Test keyboard. Hold Enter key') print(d.enter) get_input('Test keyboard. Release Enter key') print(d.enter) if __name__ == '__main__': unittest.main()
cb97f453284658da56d12ab696ef6b7d7991c727
dipy/io/tests/test_csareader.py
dipy/io/tests/test_csareader.py
import os from os.path import join as pjoin import numpy as np import dipy.io.csareader as csa from nose.tools import assert_true, assert_false, \ assert_equal, assert_raises from numpy.testing import assert_array_equal, assert_array_almost_equal from dipy.testing import parametric data_path = pjoin(os.path.dirname(__file__), 'data') CSA2_B0 = open(pjoin(data_path, 'csa2_b0.bin')).read() CSA2_B1000 = open(pjoin(data_path, 'csa2_b1000.bin')).read() @parametric def test_csa(): csa_info = csa.read(CSA2_B0) yield assert_equal(csa_info['type'], 2) yield assert_equal(csa_info['n_tags'], 83) tags = csa_info['tags'] yield assert_equal(len(tags), 83) print csa_info
import os from os.path import join as pjoin import numpy as np import dipy.io.csareader as csa from nose.tools import assert_true, assert_false, \ assert_equal, assert_raises from numpy.testing import assert_array_equal, assert_array_almost_equal from dipy.testing import parametric data_path = pjoin(os.path.dirname(__file__), 'data') CSA2_B0 = open(pjoin(data_path, 'csa2_b0.bin')).read() CSA2_B1000 = open(pjoin(data_path, 'csa2_b1000.bin')).read() @parametric def test_csa(): csa_info = csa.read(CSA2_B0) yield assert_equal(csa_info['type'], 2) yield assert_equal(csa_info['n_tags'], 83) tags = csa_info['tags'] yield assert_equal(len(tags), 83) yield assert_equal(tags['NumberOfImagesInMosaic']['value'], '48')
TEST - add test for value
TEST - add test for value
Python
bsd-3-clause
jyeatman/dipy,beni55/dipy,samuelstjean/dipy,FrancoisRheaultUS/dipy,demianw/dipy,demianw/dipy,nilgoyyou/dipy,jyeatman/dipy,Messaoud-Boudjada/dipy,maurozucchelli/dipy,Messaoud-Boudjada/dipy,StongeEtienne/dipy,villalonreina/dipy,JohnGriffiths/dipy,rfdougherty/dipy,villalonreina/dipy,sinkpoint/dipy,JohnGriffiths/dipy,FrancoisRheaultUS/dipy,maurozucchelli/dipy,oesteban/dipy,sinkpoint/dipy,samuelstjean/dipy,samuelstjean/dipy,StongeEtienne/dipy,mdesco/dipy,rfdougherty/dipy,oesteban/dipy,matthieudumont/dipy,matthieudumont/dipy,beni55/dipy,maurozucchelli/dipy,mdesco/dipy,nilgoyyou/dipy
import os from os.path import join as pjoin import numpy as np import dipy.io.csareader as csa from nose.tools import assert_true, assert_false, \ assert_equal, assert_raises from numpy.testing import assert_array_equal, assert_array_almost_equal from dipy.testing import parametric data_path = pjoin(os.path.dirname(__file__), 'data') CSA2_B0 = open(pjoin(data_path, 'csa2_b0.bin')).read() CSA2_B1000 = open(pjoin(data_path, 'csa2_b1000.bin')).read() @parametric def test_csa(): csa_info = csa.read(CSA2_B0) yield assert_equal(csa_info['type'], 2) yield assert_equal(csa_info['n_tags'], 83) tags = csa_info['tags'] yield assert_equal(len(tags), 83) - print csa_info + yield assert_equal(tags['NumberOfImagesInMosaic']['value'], + '48')
TEST - add test for value
## Code Before: import os from os.path import join as pjoin import numpy as np import dipy.io.csareader as csa from nose.tools import assert_true, assert_false, \ assert_equal, assert_raises from numpy.testing import assert_array_equal, assert_array_almost_equal from dipy.testing import parametric data_path = pjoin(os.path.dirname(__file__), 'data') CSA2_B0 = open(pjoin(data_path, 'csa2_b0.bin')).read() CSA2_B1000 = open(pjoin(data_path, 'csa2_b1000.bin')).read() @parametric def test_csa(): csa_info = csa.read(CSA2_B0) yield assert_equal(csa_info['type'], 2) yield assert_equal(csa_info['n_tags'], 83) tags = csa_info['tags'] yield assert_equal(len(tags), 83) print csa_info ## Instruction: TEST - add test for value ## Code After: import os from os.path import join as pjoin import numpy as np import dipy.io.csareader as csa from nose.tools import assert_true, assert_false, \ assert_equal, assert_raises from numpy.testing import assert_array_equal, assert_array_almost_equal from dipy.testing import parametric data_path = pjoin(os.path.dirname(__file__), 'data') CSA2_B0 = open(pjoin(data_path, 'csa2_b0.bin')).read() CSA2_B1000 = open(pjoin(data_path, 'csa2_b1000.bin')).read() @parametric def test_csa(): csa_info = csa.read(CSA2_B0) yield assert_equal(csa_info['type'], 2) yield assert_equal(csa_info['n_tags'], 83) tags = csa_info['tags'] yield assert_equal(len(tags), 83) yield assert_equal(tags['NumberOfImagesInMosaic']['value'], '48')
import os from os.path import join as pjoin import numpy as np import dipy.io.csareader as csa from nose.tools import assert_true, assert_false, \ assert_equal, assert_raises from numpy.testing import assert_array_equal, assert_array_almost_equal from dipy.testing import parametric data_path = pjoin(os.path.dirname(__file__), 'data') CSA2_B0 = open(pjoin(data_path, 'csa2_b0.bin')).read() CSA2_B1000 = open(pjoin(data_path, 'csa2_b1000.bin')).read() @parametric def test_csa(): csa_info = csa.read(CSA2_B0) yield assert_equal(csa_info['type'], 2) yield assert_equal(csa_info['n_tags'], 83) tags = csa_info['tags'] yield assert_equal(len(tags), 83) - print csa_info + yield assert_equal(tags['NumberOfImagesInMosaic']['value'], + '48')
149ca57fabad4430b22af08c88d8df6fbcc6dfc2
statictemplate/tests.py
statictemplate/tests.py
from StringIO import StringIO from django.conf import settings from django.core.management import call_command from django.template.base import TemplateDoesNotExist from django.template.loader import BaseLoader from statictemplate.management.commands.statictemplate import make_static import unittest class TestLoader(BaseLoader): is_usable = True templates = { 'simple': '{% extends "base" %}{% block content %}simple{% endblock %}', 'base': '{% block head %}head{% endblock %}{% block content %}content{% endblock %}', } def load_template_source(self, template_name, template_dirs=None): found = self.templates.get(template_name, None) if not found: # pragma: no cover raise TemplateDoesNotExist(template_name) return found, template_name class StaticTemplateTests(unittest.TestCase): def setUp(self): settings.TEMPLATE_LOADERS = ['statictemplate.tests.TestLoader'] def test_python_api(self): output = make_static('simple') self.assertEqual(output, 'headsimple') def test_call_command(self): sio = StringIO() call_command('statictemplate', 'simple', stdout=sio) self.assertEqual(sio.getvalue().strip(), 'headsimple')
from StringIO import StringIO from django.conf import settings from django.http import HttpResponseRedirect from django.core.management import call_command from django.template.base import TemplateDoesNotExist from django.template.loader import BaseLoader from statictemplate.management.commands.statictemplate import make_static import unittest class TestLoader(BaseLoader): is_usable = True templates = { 'simple': '{% extends "base" %}{% block content %}simple{% endblock %}', 'base': '{% block head %}head{% endblock %}{% block content %}content{% endblock %}', } def load_template_source(self, template_name, template_dirs=None): found = self.templates.get(template_name, None) if not found: # pragma: no cover raise TemplateDoesNotExist(template_name) return found, template_name class MeddlingMiddleware(object): def process_request(self, request): return HttpResponseRedirect('/foobarbaz') class StaticTemplateTests(unittest.TestCase): def setUp(self): settings.TEMPLATE_LOADERS = ['statictemplate.tests.TestLoader'] def test_python_api(self): output = make_static('simple') self.assertEqual(output, 'headsimple') def test_call_command(self): sio = StringIO() call_command('statictemplate', 'simple', stdout=sio) self.assertEqual(sio.getvalue().strip(), 'headsimple') def test_meddling_middleware(self): middleware = ( 'statictemplate.tests.MeddlingMiddleware', ) settings.MIDDLEWARE_CLASSES = middleware output = make_static('simple') self.assertEqual(output, 'headsimple') self.assertEqual(settings.MIDDLEWARE_CLASSES, middleware)
Add test for meddling middleware
Add test for meddling middleware
Python
bsd-3-clause
bdon/django-statictemplate,ojii/django-statictemplate,yakky/django-statictemplate
from StringIO import StringIO from django.conf import settings + from django.http import HttpResponseRedirect from django.core.management import call_command from django.template.base import TemplateDoesNotExist from django.template.loader import BaseLoader from statictemplate.management.commands.statictemplate import make_static import unittest class TestLoader(BaseLoader): is_usable = True templates = { 'simple': '{% extends "base" %}{% block content %}simple{% endblock %}', 'base': '{% block head %}head{% endblock %}{% block content %}content{% endblock %}', } def load_template_source(self, template_name, template_dirs=None): found = self.templates.get(template_name, None) if not found: # pragma: no cover raise TemplateDoesNotExist(template_name) return found, template_name + class MeddlingMiddleware(object): + def process_request(self, request): + return HttpResponseRedirect('/foobarbaz') + + class StaticTemplateTests(unittest.TestCase): def setUp(self): settings.TEMPLATE_LOADERS = ['statictemplate.tests.TestLoader'] def test_python_api(self): output = make_static('simple') self.assertEqual(output, 'headsimple') def test_call_command(self): sio = StringIO() call_command('statictemplate', 'simple', stdout=sio) self.assertEqual(sio.getvalue().strip(), 'headsimple') + def test_meddling_middleware(self): + middleware = ( + 'statictemplate.tests.MeddlingMiddleware', + ) + settings.MIDDLEWARE_CLASSES = middleware + output = make_static('simple') + self.assertEqual(output, 'headsimple') + self.assertEqual(settings.MIDDLEWARE_CLASSES, middleware) +
Add test for meddling middleware
## Code Before: from StringIO import StringIO from django.conf import settings from django.core.management import call_command from django.template.base import TemplateDoesNotExist from django.template.loader import BaseLoader from statictemplate.management.commands.statictemplate import make_static import unittest class TestLoader(BaseLoader): is_usable = True templates = { 'simple': '{% extends "base" %}{% block content %}simple{% endblock %}', 'base': '{% block head %}head{% endblock %}{% block content %}content{% endblock %}', } def load_template_source(self, template_name, template_dirs=None): found = self.templates.get(template_name, None) if not found: # pragma: no cover raise TemplateDoesNotExist(template_name) return found, template_name class StaticTemplateTests(unittest.TestCase): def setUp(self): settings.TEMPLATE_LOADERS = ['statictemplate.tests.TestLoader'] def test_python_api(self): output = make_static('simple') self.assertEqual(output, 'headsimple') def test_call_command(self): sio = StringIO() call_command('statictemplate', 'simple', stdout=sio) self.assertEqual(sio.getvalue().strip(), 'headsimple') ## Instruction: Add test for meddling middleware ## Code After: from StringIO import StringIO from django.conf import settings from django.http import HttpResponseRedirect from django.core.management import call_command from django.template.base import TemplateDoesNotExist from django.template.loader import BaseLoader from statictemplate.management.commands.statictemplate import make_static import unittest class TestLoader(BaseLoader): is_usable = True templates = { 'simple': '{% extends "base" %}{% block content %}simple{% endblock %}', 'base': '{% block head %}head{% endblock %}{% block content %}content{% endblock %}', } def load_template_source(self, template_name, template_dirs=None): found = self.templates.get(template_name, None) if not found: # pragma: no cover raise TemplateDoesNotExist(template_name) return found, template_name class MeddlingMiddleware(object): def process_request(self, request): return HttpResponseRedirect('/foobarbaz') class StaticTemplateTests(unittest.TestCase): def setUp(self): settings.TEMPLATE_LOADERS = ['statictemplate.tests.TestLoader'] def test_python_api(self): output = make_static('simple') self.assertEqual(output, 'headsimple') def test_call_command(self): sio = StringIO() call_command('statictemplate', 'simple', stdout=sio) self.assertEqual(sio.getvalue().strip(), 'headsimple') def test_meddling_middleware(self): middleware = ( 'statictemplate.tests.MeddlingMiddleware', ) settings.MIDDLEWARE_CLASSES = middleware output = make_static('simple') self.assertEqual(output, 'headsimple') self.assertEqual(settings.MIDDLEWARE_CLASSES, middleware)
from StringIO import StringIO from django.conf import settings + from django.http import HttpResponseRedirect from django.core.management import call_command from django.template.base import TemplateDoesNotExist from django.template.loader import BaseLoader from statictemplate.management.commands.statictemplate import make_static import unittest class TestLoader(BaseLoader): is_usable = True templates = { 'simple': '{% extends "base" %}{% block content %}simple{% endblock %}', 'base': '{% block head %}head{% endblock %}{% block content %}content{% endblock %}', } def load_template_source(self, template_name, template_dirs=None): found = self.templates.get(template_name, None) if not found: # pragma: no cover raise TemplateDoesNotExist(template_name) return found, template_name + class MeddlingMiddleware(object): + def process_request(self, request): + return HttpResponseRedirect('/foobarbaz') + + class StaticTemplateTests(unittest.TestCase): def setUp(self): settings.TEMPLATE_LOADERS = ['statictemplate.tests.TestLoader'] def test_python_api(self): output = make_static('simple') self.assertEqual(output, 'headsimple') def test_call_command(self): sio = StringIO() call_command('statictemplate', 'simple', stdout=sio) self.assertEqual(sio.getvalue().strip(), 'headsimple') + + def test_meddling_middleware(self): + middleware = ( + 'statictemplate.tests.MeddlingMiddleware', + ) + settings.MIDDLEWARE_CLASSES = middleware + output = make_static('simple') + self.assertEqual(output, 'headsimple') + self.assertEqual(settings.MIDDLEWARE_CLASSES, middleware)
fdf33278f66028a932dbecb999f66445ab0a3cd1
shuup/admin/modules/product_types/views/edit.py
shuup/admin/modules/product_types/views/edit.py
from __future__ import unicode_literals from django import forms from shuup.admin.utils.views import CreateOrUpdateView from shuup.core.models import ProductType from shuup.utils.multilanguage_model_form import MultiLanguageModelForm class ProductTypeForm(MultiLanguageModelForm): class Meta: model = ProductType exclude = () # All the fields! widgets = { "attributes": forms.CheckboxSelectMultiple } class ProductTypeEditView(CreateOrUpdateView): model = ProductType form_class = ProductTypeForm template_name = "shuup/admin/product_types/edit.jinja" context_object_name = "product_type"
from __future__ import unicode_literals from shuup.admin.forms.fields import Select2MultipleField from shuup.admin.utils.views import CreateOrUpdateView from shuup.core.models import Attribute, ProductType from shuup.utils.multilanguage_model_form import MultiLanguageModelForm class ProductTypeForm(MultiLanguageModelForm): attributes = Select2MultipleField(model=Attribute, required=False) class Meta: model = ProductType exclude = () def __init__(self, **kwargs): super(ProductTypeForm, self).__init__(**kwargs) if self.instance.pk: choices = [(a.pk, a.name) for a in self.instance.attributes.all()] self.fields["attributes"].widget.choices = choices self.fields["attributes"].initial = [pk for pk, name in choices] def clean_attributes(self): attributes = [int(a_id) for a_id in self.cleaned_data.get("attributes", [])] return Attribute.objects.filter(pk__in=attributes).all() def save(self, commit=True): obj = super(ProductTypeForm, self).save(commit=commit) obj.attributes.clear() obj.attributes = self.cleaned_data["attributes"] return self.instance class ProductTypeEditView(CreateOrUpdateView): model = ProductType form_class = ProductTypeForm template_name = "shuup/admin/product_types/edit.jinja" context_object_name = "product_type"
Use Select2 in attribute selection
Use Select2 in attribute selection With large amounts of attributes product type creation was really slow Refs SH-73
Python
agpl-3.0
shawnadelic/shuup,suutari-ai/shoop,shoopio/shoop,suutari-ai/shoop,shawnadelic/shuup,hrayr-artunyan/shuup,suutari/shoop,suutari/shoop,hrayr-artunyan/shuup,suutari/shoop,suutari-ai/shoop,hrayr-artunyan/shuup,shoopio/shoop,shawnadelic/shuup,shoopio/shoop
from __future__ import unicode_literals + from shuup.admin.forms.fields import Select2MultipleField - from django import forms - from shuup.admin.utils.views import CreateOrUpdateView - from shuup.core.models import ProductType + from shuup.core.models import Attribute, ProductType from shuup.utils.multilanguage_model_form import MultiLanguageModelForm class ProductTypeForm(MultiLanguageModelForm): + attributes = Select2MultipleField(model=Attribute, required=False) + class Meta: model = ProductType - exclude = () # All the fields! - widgets = { - "attributes": forms.CheckboxSelectMultiple - } + exclude = () + + def __init__(self, **kwargs): + super(ProductTypeForm, self).__init__(**kwargs) + if self.instance.pk: + choices = [(a.pk, a.name) for a in self.instance.attributes.all()] + self.fields["attributes"].widget.choices = choices + self.fields["attributes"].initial = [pk for pk, name in choices] + + def clean_attributes(self): + attributes = [int(a_id) for a_id in self.cleaned_data.get("attributes", [])] + return Attribute.objects.filter(pk__in=attributes).all() + + def save(self, commit=True): + obj = super(ProductTypeForm, self).save(commit=commit) + obj.attributes.clear() + obj.attributes = self.cleaned_data["attributes"] + return self.instance class ProductTypeEditView(CreateOrUpdateView): model = ProductType form_class = ProductTypeForm template_name = "shuup/admin/product_types/edit.jinja" context_object_name = "product_type"
Use Select2 in attribute selection
## Code Before: from __future__ import unicode_literals from django import forms from shuup.admin.utils.views import CreateOrUpdateView from shuup.core.models import ProductType from shuup.utils.multilanguage_model_form import MultiLanguageModelForm class ProductTypeForm(MultiLanguageModelForm): class Meta: model = ProductType exclude = () # All the fields! widgets = { "attributes": forms.CheckboxSelectMultiple } class ProductTypeEditView(CreateOrUpdateView): model = ProductType form_class = ProductTypeForm template_name = "shuup/admin/product_types/edit.jinja" context_object_name = "product_type" ## Instruction: Use Select2 in attribute selection ## Code After: from __future__ import unicode_literals from shuup.admin.forms.fields import Select2MultipleField from shuup.admin.utils.views import CreateOrUpdateView from shuup.core.models import Attribute, ProductType from shuup.utils.multilanguage_model_form import MultiLanguageModelForm class ProductTypeForm(MultiLanguageModelForm): attributes = Select2MultipleField(model=Attribute, required=False) class Meta: model = ProductType exclude = () def __init__(self, **kwargs): super(ProductTypeForm, self).__init__(**kwargs) if self.instance.pk: choices = [(a.pk, a.name) for a in self.instance.attributes.all()] self.fields["attributes"].widget.choices = choices self.fields["attributes"].initial = [pk for pk, name in choices] def clean_attributes(self): attributes = [int(a_id) for a_id in self.cleaned_data.get("attributes", [])] return Attribute.objects.filter(pk__in=attributes).all() def save(self, commit=True): obj = super(ProductTypeForm, self).save(commit=commit) obj.attributes.clear() obj.attributes = self.cleaned_data["attributes"] return self.instance class ProductTypeEditView(CreateOrUpdateView): model = ProductType form_class = ProductTypeForm template_name = "shuup/admin/product_types/edit.jinja" context_object_name = "product_type"
from __future__ import unicode_literals + from shuup.admin.forms.fields import Select2MultipleField - from django import forms - from shuup.admin.utils.views import CreateOrUpdateView - from shuup.core.models import ProductType + from shuup.core.models import Attribute, ProductType ? +++++++++++ from shuup.utils.multilanguage_model_form import MultiLanguageModelForm class ProductTypeForm(MultiLanguageModelForm): + attributes = Select2MultipleField(model=Attribute, required=False) + class Meta: model = ProductType - exclude = () # All the fields! - widgets = { - "attributes": forms.CheckboxSelectMultiple - } + exclude = () + + def __init__(self, **kwargs): + super(ProductTypeForm, self).__init__(**kwargs) + if self.instance.pk: + choices = [(a.pk, a.name) for a in self.instance.attributes.all()] + self.fields["attributes"].widget.choices = choices + self.fields["attributes"].initial = [pk for pk, name in choices] + + def clean_attributes(self): + attributes = [int(a_id) for a_id in self.cleaned_data.get("attributes", [])] + return Attribute.objects.filter(pk__in=attributes).all() + + def save(self, commit=True): + obj = super(ProductTypeForm, self).save(commit=commit) + obj.attributes.clear() + obj.attributes = self.cleaned_data["attributes"] + return self.instance class ProductTypeEditView(CreateOrUpdateView): model = ProductType form_class = ProductTypeForm template_name = "shuup/admin/product_types/edit.jinja" context_object_name = "product_type"
d8295756e73cb096acd5e3ef7e2b076b8b871c31
apps/domain/src/main/routes/general/routes.py
apps/domain/src/main/routes/general/routes.py
from .blueprint import root_blueprint as root_route from ...core.node import node # syft absolute from syft.core.common.message import SignedImmediateSyftMessageWithReply from syft.core.common.message import SignedImmediateSyftMessageWithoutReply from syft.core.common.serde.deserialize import _deserialize from flask import request, Response import json @root_route.route("/pysyft", methods=["POST"]) def root_route(): json_msg = request.get_json() obj_msg = _deserialize(blob=json_msg, from_json=True) if isinstance(obj_msg, SignedImmediateSyftMessageWithReply): reply = node.recv_immediate_msg_with_reply(msg=obj_msg) return reply.json() elif isinstance(obj_msg, SignedImmediateSyftMessageWithoutReply): node.recv_immediate_msg_without_reply(msg=obj_msg) else: node.recv_eventual_msg_without_reply(msg=obj_msg) return ""
from .blueprint import root_blueprint as root_route from ...core.node import node # syft absolute from syft.core.common.message import SignedImmediateSyftMessageWithReply from syft.core.common.message import SignedImmediateSyftMessageWithoutReply from syft.core.common.serde.deserialize import _deserialize from flask import request, Response import json @root_route.route("/pysyft", methods=["POST"]) def root_route(): data = request.get_data() obj_msg = _deserialize(blob=data, from_bytes=True) if isinstance(obj_msg, SignedImmediateSyftMessageWithReply): reply = node.recv_immediate_msg_with_reply(msg=obj_msg) r = Response(response=reply.serialize(to_bytes=True), status=200) r.headers["Content-Type"] = "application/octet-stream" return r elif isinstance(obj_msg, SignedImmediateSyftMessageWithoutReply): node.recv_immediate_msg_without_reply(msg=obj_msg) else: node.recv_eventual_msg_without_reply(msg=obj_msg) return ""
Update /users/login endpoint to return serialized metadata
Update /users/login endpoint to return serialized metadata
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
from .blueprint import root_blueprint as root_route from ...core.node import node # syft absolute from syft.core.common.message import SignedImmediateSyftMessageWithReply from syft.core.common.message import SignedImmediateSyftMessageWithoutReply from syft.core.common.serde.deserialize import _deserialize from flask import request, Response import json @root_route.route("/pysyft", methods=["POST"]) def root_route(): - json_msg = request.get_json() + data = request.get_data() - obj_msg = _deserialize(blob=json_msg, from_json=True) + obj_msg = _deserialize(blob=data, from_bytes=True) if isinstance(obj_msg, SignedImmediateSyftMessageWithReply): reply = node.recv_immediate_msg_with_reply(msg=obj_msg) - return reply.json() + r = Response(response=reply.serialize(to_bytes=True), status=200) + r.headers["Content-Type"] = "application/octet-stream" + return r elif isinstance(obj_msg, SignedImmediateSyftMessageWithoutReply): node.recv_immediate_msg_without_reply(msg=obj_msg) else: node.recv_eventual_msg_without_reply(msg=obj_msg) return ""
Update /users/login endpoint to return serialized metadata
## Code Before: from .blueprint import root_blueprint as root_route from ...core.node import node # syft absolute from syft.core.common.message import SignedImmediateSyftMessageWithReply from syft.core.common.message import SignedImmediateSyftMessageWithoutReply from syft.core.common.serde.deserialize import _deserialize from flask import request, Response import json @root_route.route("/pysyft", methods=["POST"]) def root_route(): json_msg = request.get_json() obj_msg = _deserialize(blob=json_msg, from_json=True) if isinstance(obj_msg, SignedImmediateSyftMessageWithReply): reply = node.recv_immediate_msg_with_reply(msg=obj_msg) return reply.json() elif isinstance(obj_msg, SignedImmediateSyftMessageWithoutReply): node.recv_immediate_msg_without_reply(msg=obj_msg) else: node.recv_eventual_msg_without_reply(msg=obj_msg) return "" ## Instruction: Update /users/login endpoint to return serialized metadata ## Code After: from .blueprint import root_blueprint as root_route from ...core.node import node # syft absolute from syft.core.common.message import SignedImmediateSyftMessageWithReply from syft.core.common.message import SignedImmediateSyftMessageWithoutReply from syft.core.common.serde.deserialize import _deserialize from flask import request, Response import json @root_route.route("/pysyft", methods=["POST"]) def root_route(): data = request.get_data() obj_msg = _deserialize(blob=data, from_bytes=True) if isinstance(obj_msg, SignedImmediateSyftMessageWithReply): reply = node.recv_immediate_msg_with_reply(msg=obj_msg) r = Response(response=reply.serialize(to_bytes=True), status=200) r.headers["Content-Type"] = "application/octet-stream" return r elif isinstance(obj_msg, SignedImmediateSyftMessageWithoutReply): node.recv_immediate_msg_without_reply(msg=obj_msg) else: node.recv_eventual_msg_without_reply(msg=obj_msg) return ""
from .blueprint import root_blueprint as root_route from ...core.node import node # syft absolute from syft.core.common.message import SignedImmediateSyftMessageWithReply from syft.core.common.message import SignedImmediateSyftMessageWithoutReply from syft.core.common.serde.deserialize import _deserialize from flask import request, Response import json @root_route.route("/pysyft", methods=["POST"]) def root_route(): - json_msg = request.get_json() + data = request.get_data() - obj_msg = _deserialize(blob=json_msg, from_json=True) ? ^^^^^^^^ ^ -- + obj_msg = _deserialize(blob=data, from_bytes=True) ? ^^^^ ^^^^ if isinstance(obj_msg, SignedImmediateSyftMessageWithReply): reply = node.recv_immediate_msg_with_reply(msg=obj_msg) - return reply.json() + r = Response(response=reply.serialize(to_bytes=True), status=200) + r.headers["Content-Type"] = "application/octet-stream" + return r elif isinstance(obj_msg, SignedImmediateSyftMessageWithoutReply): node.recv_immediate_msg_without_reply(msg=obj_msg) else: node.recv_eventual_msg_without_reply(msg=obj_msg) return ""
a9accd5460157e323e8514178d3e7bc9d2fa8667
dn1/kolona_vozil_test.py
dn1/kolona_vozil_test.py
__author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>' import unittest from jadrolinija import KolonaVozil class KolonaVozilTest(unittest.TestCase): def test_init(self): kv = KolonaVozil(2000) self.assertEqual(kv.max_dolzina, 2000) self.assertEqual(kv.zasedenost, 0) if __name__ == '__main__': unittest.main()
__author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>' import unittest from jadrolinija import KolonaVozil, Vozilo class KolonaVozilTest(unittest.TestCase): def test_init(self): kv = KolonaVozil(2000) self.assertEqual(kv.max_dolzina, 2000) self.assertEqual(kv.zasedenost, 0) def test_vkrcaj(self): kv = KolonaVozil(1000) vozilo1 = Vozilo('NM DK-34J', 425) kv.vkrcaj(vozilo1) self.assertEqual(kv.zasedenost, 425) vozilo2 = Vozilo('LJ N6-03K', 445) kv.vkrcaj(vozilo2) self.assertEqual(kv.zasedenost, 425 + 10 + 445) vozilo3 = Vozilo('KP JB-P20', 385) with self.assertRaisesRegexp(ValueError, 'ni dovolj prostora'): kv.vkrcaj(vozilo3) def test_izkrcaj(self): kv = KolonaVozil(1000) vozilo1 = Vozilo('NM DK-34J', 425) kv.vkrcaj(vozilo1) vozilo2 = Vozilo('LJ N6-03K', 445) kv.vkrcaj(vozilo2) self.assertIs(kv.izkrcaj(), vozilo1) self.assertEqual(kv.zasedenost, 425 + 10 + 445) with self.assertRaisesRegexp(ValueError, 'ni dovolj prostora'): kv.vkrcaj(vozilo1) self.assertIs(kv.izkrcaj(), vozilo2) self.assertEqual(kv.zasedenost, 0) with self.assertRaisesRegexp(ValueError, 'kolona je prazna'): kv.izkrcaj() if __name__ == '__main__': unittest.main()
Update unittests for Task 4
Update unittests for Task 4
Python
mit
nbasic/racunalnistvo-1
__author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>' import unittest - from jadrolinija import KolonaVozil + from jadrolinija import KolonaVozil, Vozilo class KolonaVozilTest(unittest.TestCase): def test_init(self): kv = KolonaVozil(2000) self.assertEqual(kv.max_dolzina, 2000) self.assertEqual(kv.zasedenost, 0) + def test_vkrcaj(self): + kv = KolonaVozil(1000) + + vozilo1 = Vozilo('NM DK-34J', 425) + kv.vkrcaj(vozilo1) + self.assertEqual(kv.zasedenost, 425) + + vozilo2 = Vozilo('LJ N6-03K', 445) + kv.vkrcaj(vozilo2) + self.assertEqual(kv.zasedenost, 425 + 10 + 445) + + vozilo3 = Vozilo('KP JB-P20', 385) + with self.assertRaisesRegexp(ValueError, 'ni dovolj prostora'): + kv.vkrcaj(vozilo3) + + def test_izkrcaj(self): + kv = KolonaVozil(1000) + + vozilo1 = Vozilo('NM DK-34J', 425) + kv.vkrcaj(vozilo1) + vozilo2 = Vozilo('LJ N6-03K', 445) + kv.vkrcaj(vozilo2) + + self.assertIs(kv.izkrcaj(), vozilo1) + self.assertEqual(kv.zasedenost, 425 + 10 + 445) + + with self.assertRaisesRegexp(ValueError, 'ni dovolj prostora'): + kv.vkrcaj(vozilo1) + + self.assertIs(kv.izkrcaj(), vozilo2) + self.assertEqual(kv.zasedenost, 0) + + with self.assertRaisesRegexp(ValueError, 'kolona je prazna'): + kv.izkrcaj() + + if __name__ == '__main__': unittest.main()
Update unittests for Task 4
## Code Before: __author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>' import unittest from jadrolinija import KolonaVozil class KolonaVozilTest(unittest.TestCase): def test_init(self): kv = KolonaVozil(2000) self.assertEqual(kv.max_dolzina, 2000) self.assertEqual(kv.zasedenost, 0) if __name__ == '__main__': unittest.main() ## Instruction: Update unittests for Task 4 ## Code After: __author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>' import unittest from jadrolinija import KolonaVozil, Vozilo class KolonaVozilTest(unittest.TestCase): def test_init(self): kv = KolonaVozil(2000) self.assertEqual(kv.max_dolzina, 2000) self.assertEqual(kv.zasedenost, 0) def test_vkrcaj(self): kv = KolonaVozil(1000) vozilo1 = Vozilo('NM DK-34J', 425) kv.vkrcaj(vozilo1) self.assertEqual(kv.zasedenost, 425) vozilo2 = Vozilo('LJ N6-03K', 445) kv.vkrcaj(vozilo2) self.assertEqual(kv.zasedenost, 425 + 10 + 445) vozilo3 = Vozilo('KP JB-P20', 385) with self.assertRaisesRegexp(ValueError, 'ni dovolj prostora'): kv.vkrcaj(vozilo3) def test_izkrcaj(self): kv = KolonaVozil(1000) vozilo1 = Vozilo('NM DK-34J', 425) kv.vkrcaj(vozilo1) vozilo2 = Vozilo('LJ N6-03K', 445) kv.vkrcaj(vozilo2) self.assertIs(kv.izkrcaj(), vozilo1) self.assertEqual(kv.zasedenost, 425 + 10 + 445) with self.assertRaisesRegexp(ValueError, 'ni dovolj prostora'): kv.vkrcaj(vozilo1) self.assertIs(kv.izkrcaj(), vozilo2) self.assertEqual(kv.zasedenost, 0) with self.assertRaisesRegexp(ValueError, 'kolona je prazna'): kv.izkrcaj() if __name__ == '__main__': unittest.main()
__author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>' import unittest - from jadrolinija import KolonaVozil + from jadrolinija import KolonaVozil, Vozilo ? ++++++++ class KolonaVozilTest(unittest.TestCase): def test_init(self): kv = KolonaVozil(2000) self.assertEqual(kv.max_dolzina, 2000) self.assertEqual(kv.zasedenost, 0) + def test_vkrcaj(self): + kv = KolonaVozil(1000) + + vozilo1 = Vozilo('NM DK-34J', 425) + kv.vkrcaj(vozilo1) + self.assertEqual(kv.zasedenost, 425) + + vozilo2 = Vozilo('LJ N6-03K', 445) + kv.vkrcaj(vozilo2) + self.assertEqual(kv.zasedenost, 425 + 10 + 445) + + vozilo3 = Vozilo('KP JB-P20', 385) + with self.assertRaisesRegexp(ValueError, 'ni dovolj prostora'): + kv.vkrcaj(vozilo3) + + def test_izkrcaj(self): + kv = KolonaVozil(1000) + + vozilo1 = Vozilo('NM DK-34J', 425) + kv.vkrcaj(vozilo1) + vozilo2 = Vozilo('LJ N6-03K', 445) + kv.vkrcaj(vozilo2) + + self.assertIs(kv.izkrcaj(), vozilo1) + self.assertEqual(kv.zasedenost, 425 + 10 + 445) + + with self.assertRaisesRegexp(ValueError, 'ni dovolj prostora'): + kv.vkrcaj(vozilo1) + + self.assertIs(kv.izkrcaj(), vozilo2) + self.assertEqual(kv.zasedenost, 0) + + with self.assertRaisesRegexp(ValueError, 'kolona je prazna'): + kv.izkrcaj() + + if __name__ == '__main__': unittest.main()
acd376d854693cacf8ca20a9971dcd2653a22429
rlpy/Agents/__init__.py
rlpy/Agents/__init__.py
from .TDControlAgent import Q_Learning, SARSA # for compatibility of old scripts Q_LEARNING = Q_Learning from .Greedy_GQ import Greedy_GQ from .LSPI import LSPI from .LSPI_SARSA import LSPI_SARSA from .NaturalActorCritic import NaturalActorCritic
from .TDControlAgent import Q_Learning, SARSA # for compatibility of old scripts Q_LEARNING = Q_Learning from .Greedy_GQ import Greedy_GQ from .LSPI import LSPI from .LSPI_SARSA import LSPI_SARSA from .NaturalActorCritic import NaturalActorCritic from .PosteriorSampling import PosteriorSampling from .UCRL import UCRL
Add new agents to init file
Add new agents to init file
Python
bsd-3-clause
imanolarrieta/RL,imanolarrieta/RL,imanolarrieta/RL
from .TDControlAgent import Q_Learning, SARSA # for compatibility of old scripts Q_LEARNING = Q_Learning from .Greedy_GQ import Greedy_GQ from .LSPI import LSPI from .LSPI_SARSA import LSPI_SARSA from .NaturalActorCritic import NaturalActorCritic + from .PosteriorSampling import PosteriorSampling + from .UCRL import UCRL
Add new agents to init file
## Code Before: from .TDControlAgent import Q_Learning, SARSA # for compatibility of old scripts Q_LEARNING = Q_Learning from .Greedy_GQ import Greedy_GQ from .LSPI import LSPI from .LSPI_SARSA import LSPI_SARSA from .NaturalActorCritic import NaturalActorCritic ## Instruction: Add new agents to init file ## Code After: from .TDControlAgent import Q_Learning, SARSA # for compatibility of old scripts Q_LEARNING = Q_Learning from .Greedy_GQ import Greedy_GQ from .LSPI import LSPI from .LSPI_SARSA import LSPI_SARSA from .NaturalActorCritic import NaturalActorCritic from .PosteriorSampling import PosteriorSampling from .UCRL import UCRL
from .TDControlAgent import Q_Learning, SARSA # for compatibility of old scripts Q_LEARNING = Q_Learning from .Greedy_GQ import Greedy_GQ from .LSPI import LSPI from .LSPI_SARSA import LSPI_SARSA from .NaturalActorCritic import NaturalActorCritic + from .PosteriorSampling import PosteriorSampling + from .UCRL import UCRL
2b3c0b50e5f67ca673f5305ccf0219a4bca6bb7b
luigi/tasks/rgd/__init__.py
luigi/tasks/rgd/__init__.py
import luigi from tasks.config import rgd from databases.rgd import helpers from .organism import RgdOrganism class Rgd(luigi.WrapperTask): def requires(self): for organism in helpers.gene_files(rgd().host): yield RgdOrganism(organism=organism)
import luigi from databases.rgd import helpers from .organism import RgdOrganism class Rgd(luigi.WrapperTask): def requires(self): for organism in helpers.known_organisms(): yield RgdOrganism(organism=organism)
Correct method to detect known organisms
Correct method to detect known organisms
Python
apache-2.0
RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline
import luigi - - from tasks.config import rgd from databases.rgd import helpers from .organism import RgdOrganism class Rgd(luigi.WrapperTask): def requires(self): - for organism in helpers.gene_files(rgd().host): + for organism in helpers.known_organisms(): yield RgdOrganism(organism=organism)
Correct method to detect known organisms
## Code Before: import luigi from tasks.config import rgd from databases.rgd import helpers from .organism import RgdOrganism class Rgd(luigi.WrapperTask): def requires(self): for organism in helpers.gene_files(rgd().host): yield RgdOrganism(organism=organism) ## Instruction: Correct method to detect known organisms ## Code After: import luigi from databases.rgd import helpers from .organism import RgdOrganism class Rgd(luigi.WrapperTask): def requires(self): for organism in helpers.known_organisms(): yield RgdOrganism(organism=organism)
import luigi - - from tasks.config import rgd from databases.rgd import helpers from .organism import RgdOrganism class Rgd(luigi.WrapperTask): def requires(self): - for organism in helpers.gene_files(rgd().host): + for organism in helpers.known_organisms(): yield RgdOrganism(organism=organism)
e0f6dba294e062d0a93b7cdf8a6c8fc1557671a2
cmsplugin_simple_markdown/models.py
cmsplugin_simple_markdown/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ from cms.models.pluginmodel import CMSPlugin class SimpleMarkdownPlugin(CMSPlugin): markdown_text = models.TextField(verbose_name=_('text')) def __unicode__(self): return self.markdown_text
import threading from django.db import models from django.utils.translation import ugettext_lazy as _ from cms.models.pluginmodel import CMSPlugin from cmsplugin_simple_markdown import utils localdata = threading.local() localdata.TEMPLATE_CHOICES = utils.autodiscover_templates() TEMPLATE_CHOICES = localdata.TEMPLATE_CHOICES class SimpleMarkdownPlugin(CMSPlugin): markdown_text = models.TextField(verbose_name=_('text')) template = models.CharField( verbose_name=_('template'), choices=TEMPLATE_CHOICES, max_length=255, default='cmsplugin_simple_markdown/simple_markdown.html', editable=len(TEMPLATE_CHOICES) > 1 ) def __unicode__(self): return self.markdown_text
Add template field to SimpleMarkdownPlugin model
Add template field to SimpleMarkdownPlugin model
Python
bsd-3-clause
Alir3z4/cmsplugin-simple-markdown,Alir3z4/cmsplugin-simple-markdown
+ import threading from django.db import models from django.utils.translation import ugettext_lazy as _ from cms.models.pluginmodel import CMSPlugin + from cmsplugin_simple_markdown import utils + + + localdata = threading.local() + localdata.TEMPLATE_CHOICES = utils.autodiscover_templates() + TEMPLATE_CHOICES = localdata.TEMPLATE_CHOICES class SimpleMarkdownPlugin(CMSPlugin): markdown_text = models.TextField(verbose_name=_('text')) + template = models.CharField( + verbose_name=_('template'), + choices=TEMPLATE_CHOICES, + max_length=255, + default='cmsplugin_simple_markdown/simple_markdown.html', + editable=len(TEMPLATE_CHOICES) > 1 + ) def __unicode__(self): return self.markdown_text
Add template field to SimpleMarkdownPlugin model
## Code Before: from django.db import models from django.utils.translation import ugettext_lazy as _ from cms.models.pluginmodel import CMSPlugin class SimpleMarkdownPlugin(CMSPlugin): markdown_text = models.TextField(verbose_name=_('text')) def __unicode__(self): return self.markdown_text ## Instruction: Add template field to SimpleMarkdownPlugin model ## Code After: import threading from django.db import models from django.utils.translation import ugettext_lazy as _ from cms.models.pluginmodel import CMSPlugin from cmsplugin_simple_markdown import utils localdata = threading.local() localdata.TEMPLATE_CHOICES = utils.autodiscover_templates() TEMPLATE_CHOICES = localdata.TEMPLATE_CHOICES class SimpleMarkdownPlugin(CMSPlugin): markdown_text = models.TextField(verbose_name=_('text')) template = models.CharField( verbose_name=_('template'), choices=TEMPLATE_CHOICES, max_length=255, default='cmsplugin_simple_markdown/simple_markdown.html', editable=len(TEMPLATE_CHOICES) > 1 ) def __unicode__(self): return self.markdown_text
+ import threading from django.db import models from django.utils.translation import ugettext_lazy as _ from cms.models.pluginmodel import CMSPlugin + from cmsplugin_simple_markdown import utils + + + localdata = threading.local() + localdata.TEMPLATE_CHOICES = utils.autodiscover_templates() + TEMPLATE_CHOICES = localdata.TEMPLATE_CHOICES class SimpleMarkdownPlugin(CMSPlugin): markdown_text = models.TextField(verbose_name=_('text')) + template = models.CharField( + verbose_name=_('template'), + choices=TEMPLATE_CHOICES, + max_length=255, + default='cmsplugin_simple_markdown/simple_markdown.html', + editable=len(TEMPLATE_CHOICES) > 1 + ) def __unicode__(self): return self.markdown_text
bfd8d1126e771702dfe4869923927b8f4fb81ef1
openstack/tests/functional/network/v2/test_extension.py
openstack/tests/functional/network/v2/test_extension.py
import six from openstack.tests.functional import base class TestExtension(base.BaseFunctionalTest): def test_list_and_find(self): extensions = list(self.conn.network.extensions()) self.assertGreater(len(extensions), 0) for ext in extensions: self.assertIsInstance(ext.name, six.string_types) self.assertIsInstance(ext.namespace, six.string_types) self.assertIsInstance(ext.alias, six.string_types)
import six from openstack.tests.functional import base class TestExtension(base.BaseFunctionalTest): def test_list_and_find(self): extensions = list(self.conn.network.extensions()) self.assertGreater(len(extensions), 0) for ext in extensions: self.assertIsInstance(ext.name, six.string_types) self.assertIsInstance(ext.alias, six.string_types)
Remove namespace from network ext test
Remove namespace from network ext test Change-Id: Id9b97d67ac6745fe962a76ccd9c0e4f7cbed4a89
Python
apache-2.0
mtougeron/python-openstacksdk,briancurtin/python-openstacksdk,stackforge/python-openstacksdk,stackforge/python-openstacksdk,dudymas/python-openstacksdk,dtroyer/python-openstacksdk,dtroyer/python-openstacksdk,mtougeron/python-openstacksdk,briancurtin/python-openstacksdk,openstack/python-openstacksdk,openstack/python-openstacksdk,dudymas/python-openstacksdk
import six from openstack.tests.functional import base class TestExtension(base.BaseFunctionalTest): def test_list_and_find(self): extensions = list(self.conn.network.extensions()) self.assertGreater(len(extensions), 0) for ext in extensions: self.assertIsInstance(ext.name, six.string_types) - self.assertIsInstance(ext.namespace, six.string_types) self.assertIsInstance(ext.alias, six.string_types)
Remove namespace from network ext test
## Code Before: import six from openstack.tests.functional import base class TestExtension(base.BaseFunctionalTest): def test_list_and_find(self): extensions = list(self.conn.network.extensions()) self.assertGreater(len(extensions), 0) for ext in extensions: self.assertIsInstance(ext.name, six.string_types) self.assertIsInstance(ext.namespace, six.string_types) self.assertIsInstance(ext.alias, six.string_types) ## Instruction: Remove namespace from network ext test ## Code After: import six from openstack.tests.functional import base class TestExtension(base.BaseFunctionalTest): def test_list_and_find(self): extensions = list(self.conn.network.extensions()) self.assertGreater(len(extensions), 0) for ext in extensions: self.assertIsInstance(ext.name, six.string_types) self.assertIsInstance(ext.alias, six.string_types)
import six from openstack.tests.functional import base class TestExtension(base.BaseFunctionalTest): def test_list_and_find(self): extensions = list(self.conn.network.extensions()) self.assertGreater(len(extensions), 0) for ext in extensions: self.assertIsInstance(ext.name, six.string_types) - self.assertIsInstance(ext.namespace, six.string_types) self.assertIsInstance(ext.alias, six.string_types)
fbd7da82e8231c025eaaf9dd60f94d104583c02c
crmapp/accounts/urls.py
crmapp/accounts/urls.py
from django.conf.urls import patterns, url account_urls = patterns('', url(r'^$', 'crmapp.accounts.views.account_detail', name='account_detail' ), )
from django.conf.urls import patterns, url account_urls = patterns('', url(r'^$', 'crmapp.accounts.views.account_detail', name='account_detail' ), url(r'^edit/$', 'crmapp.accounts.views.account_cru', name='account_update' ), )
Create the Account Detail Page - Part II > Edit Account - Create URL Conf
Create the Account Detail Page - Part II > Edit Account - Create URL Conf
Python
mit
tabdon/crmeasyapp,tabdon/crmeasyapp,deenaariff/Django
from django.conf.urls import patterns, url account_urls = patterns('', url(r'^$', 'crmapp.accounts.views.account_detail', name='account_detail' ), + url(r'^edit/$', + 'crmapp.accounts.views.account_cru', name='account_update' + ), )
Create the Account Detail Page - Part II > Edit Account - Create URL Conf
## Code Before: from django.conf.urls import patterns, url account_urls = patterns('', url(r'^$', 'crmapp.accounts.views.account_detail', name='account_detail' ), ) ## Instruction: Create the Account Detail Page - Part II > Edit Account - Create URL Conf ## Code After: from django.conf.urls import patterns, url account_urls = patterns('', url(r'^$', 'crmapp.accounts.views.account_detail', name='account_detail' ), url(r'^edit/$', 'crmapp.accounts.views.account_cru', name='account_update' ), )
from django.conf.urls import patterns, url account_urls = patterns('', url(r'^$', 'crmapp.accounts.views.account_detail', name='account_detail' ), + url(r'^edit/$', + 'crmapp.accounts.views.account_cru', name='account_update' + ), )
8f330d4d07ed548a9cab348895124f5f5d92a6e8
dask_ndmeasure/_test_utils.py
dask_ndmeasure/_test_utils.py
from __future__ import absolute_import import dask.array.utils def _assert_eq_nan(a, b, **kwargs): a = a.copy() b = b.copy() a_nan = (a != a) b_nan = (b != b) a[a_nan] = 0 b[b_nan] = 0 dask.array.utils.assert_eq(a_nan, b_nan, **kwargs) dask.array.utils.assert_eq(a, b, **kwargs)
from __future__ import absolute_import import dask.array.utils def _assert_eq_nan(a, b, **kwargs): a = a.copy() b = b.copy() a = a[...] b = b[...] a_nan = (a != a) b_nan = (b != b) a[a_nan] = 0 b[b_nan] = 0 dask.array.utils.assert_eq(a_nan, b_nan, **kwargs) dask.array.utils.assert_eq(a, b, **kwargs)
Handle scalar values in _assert_eq_nan
Handle scalar values in _assert_eq_nan Add some special handling in `_assert_eq_nan` to handle having scalar values passed in. Basically ensure that everything provided is an array. This is a no-op for arrays, but converts scalars into 0-D arrays. By doing this, we are able to use the same `nan` handling code. Also convert the 0-D arrays back to scalars. This means a 0-D array will be treated as a scalar in the end. However Dask doesn't really have a way to differentiate the two. So this is fine.
Python
bsd-3-clause
dask-image/dask-ndmeasure
from __future__ import absolute_import import dask.array.utils def _assert_eq_nan(a, b, **kwargs): a = a.copy() b = b.copy() + a = a[...] + b = b[...] + a_nan = (a != a) b_nan = (b != b) a[a_nan] = 0 b[b_nan] = 0 dask.array.utils.assert_eq(a_nan, b_nan, **kwargs) dask.array.utils.assert_eq(a, b, **kwargs)
Handle scalar values in _assert_eq_nan
## Code Before: from __future__ import absolute_import import dask.array.utils def _assert_eq_nan(a, b, **kwargs): a = a.copy() b = b.copy() a_nan = (a != a) b_nan = (b != b) a[a_nan] = 0 b[b_nan] = 0 dask.array.utils.assert_eq(a_nan, b_nan, **kwargs) dask.array.utils.assert_eq(a, b, **kwargs) ## Instruction: Handle scalar values in _assert_eq_nan ## Code After: from __future__ import absolute_import import dask.array.utils def _assert_eq_nan(a, b, **kwargs): a = a.copy() b = b.copy() a = a[...] b = b[...] a_nan = (a != a) b_nan = (b != b) a[a_nan] = 0 b[b_nan] = 0 dask.array.utils.assert_eq(a_nan, b_nan, **kwargs) dask.array.utils.assert_eq(a, b, **kwargs)
from __future__ import absolute_import import dask.array.utils def _assert_eq_nan(a, b, **kwargs): a = a.copy() b = b.copy() + a = a[...] + b = b[...] + a_nan = (a != a) b_nan = (b != b) a[a_nan] = 0 b[b_nan] = 0 dask.array.utils.assert_eq(a_nan, b_nan, **kwargs) dask.array.utils.assert_eq(a, b, **kwargs)
06db6c3823ae480d0180b747ac475f149b2f8976
try_telethon.py
try_telethon.py
import traceback from telethon.interactive_telegram_client import (InteractiveTelegramClient, print_title) def load_settings(path='api/settings'): """Loads the user settings located under `api/`""" result = {} with open(path, 'r', encoding='utf-8') as file: for line in file: value_pair = line.split('=') left = value_pair[0].strip() right = value_pair[1].strip() if right.isnumeric(): result[left] = int(right) else: result[left] = right return result if __name__ == '__main__': # Load the settings and initialize the client settings = load_settings() client = InteractiveTelegramClient( session_user_id=settings.get('session_name', 'anonymous'), user_phone=str(settings['user_phone']), api_id=settings['api_id'], api_hash=settings['api_hash']) print('Initialization done!') try: client.run() except Exception as e: print('Unexpected error ({}): {} at\n{}'.format( type(e), e, traceback.format_exc())) finally: print_title('Exit') print('Thanks for trying the interactive example! Exiting...') client.disconnect()
import traceback from telethon.interactive_telegram_client import (InteractiveTelegramClient, print_title) def load_settings(path='api/settings'): """Loads the user settings located under `api/`""" result = {} with open(path, 'r', encoding='utf-8') as file: for line in file: value_pair = line.split('=') left = value_pair[0].strip() right = value_pair[1].strip() if right.isnumeric(): result[left] = int(right) else: result[left] = right return result if __name__ == '__main__': # Load the settings and initialize the client settings = load_settings() client = InteractiveTelegramClient( session_user_id=str(settings.get('session_name', 'anonymous')), user_phone=str(settings['user_phone']), api_id=settings['api_id'], api_hash=str(settings['api_hash'])) print('Initialization done!') try: client.run() except Exception as e: print('Unexpected error ({}): {} at\n{}'.format( type(e), e, traceback.format_exc())) finally: print_title('Exit') print('Thanks for trying the interactive example! Exiting...') client.disconnect()
Allow integer-only session name and hash for the example
Allow integer-only session name and hash for the example
Python
mit
expectocode/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,andr-04/Telethon,LonamiWebs/Telethon,kyasabu/Telethon
import traceback from telethon.interactive_telegram_client import (InteractiveTelegramClient, print_title) def load_settings(path='api/settings'): """Loads the user settings located under `api/`""" result = {} with open(path, 'r', encoding='utf-8') as file: for line in file: value_pair = line.split('=') left = value_pair[0].strip() right = value_pair[1].strip() if right.isnumeric(): result[left] = int(right) else: result[left] = right return result if __name__ == '__main__': # Load the settings and initialize the client settings = load_settings() client = InteractiveTelegramClient( - session_user_id=settings.get('session_name', 'anonymous'), + session_user_id=str(settings.get('session_name', 'anonymous')), user_phone=str(settings['user_phone']), api_id=settings['api_id'], - api_hash=settings['api_hash']) + api_hash=str(settings['api_hash'])) print('Initialization done!') try: client.run() except Exception as e: print('Unexpected error ({}): {} at\n{}'.format( type(e), e, traceback.format_exc())) finally: print_title('Exit') print('Thanks for trying the interactive example! Exiting...') client.disconnect()
Allow integer-only session name and hash for the example
## Code Before: import traceback from telethon.interactive_telegram_client import (InteractiveTelegramClient, print_title) def load_settings(path='api/settings'): """Loads the user settings located under `api/`""" result = {} with open(path, 'r', encoding='utf-8') as file: for line in file: value_pair = line.split('=') left = value_pair[0].strip() right = value_pair[1].strip() if right.isnumeric(): result[left] = int(right) else: result[left] = right return result if __name__ == '__main__': # Load the settings and initialize the client settings = load_settings() client = InteractiveTelegramClient( session_user_id=settings.get('session_name', 'anonymous'), user_phone=str(settings['user_phone']), api_id=settings['api_id'], api_hash=settings['api_hash']) print('Initialization done!') try: client.run() except Exception as e: print('Unexpected error ({}): {} at\n{}'.format( type(e), e, traceback.format_exc())) finally: print_title('Exit') print('Thanks for trying the interactive example! Exiting...') client.disconnect() ## Instruction: Allow integer-only session name and hash for the example ## Code After: import traceback from telethon.interactive_telegram_client import (InteractiveTelegramClient, print_title) def load_settings(path='api/settings'): """Loads the user settings located under `api/`""" result = {} with open(path, 'r', encoding='utf-8') as file: for line in file: value_pair = line.split('=') left = value_pair[0].strip() right = value_pair[1].strip() if right.isnumeric(): result[left] = int(right) else: result[left] = right return result if __name__ == '__main__': # Load the settings and initialize the client settings = load_settings() client = InteractiveTelegramClient( session_user_id=str(settings.get('session_name', 'anonymous')), user_phone=str(settings['user_phone']), api_id=settings['api_id'], api_hash=str(settings['api_hash'])) print('Initialization done!') try: client.run() except Exception as e: print('Unexpected error ({}): {} at\n{}'.format( type(e), e, traceback.format_exc())) finally: print_title('Exit') print('Thanks for trying the interactive example! Exiting...') client.disconnect()
import traceback from telethon.interactive_telegram_client import (InteractiveTelegramClient, print_title) def load_settings(path='api/settings'): """Loads the user settings located under `api/`""" result = {} with open(path, 'r', encoding='utf-8') as file: for line in file: value_pair = line.split('=') left = value_pair[0].strip() right = value_pair[1].strip() if right.isnumeric(): result[left] = int(right) else: result[left] = right return result if __name__ == '__main__': # Load the settings and initialize the client settings = load_settings() client = InteractiveTelegramClient( - session_user_id=settings.get('session_name', 'anonymous'), + session_user_id=str(settings.get('session_name', 'anonymous')), ? ++++ + user_phone=str(settings['user_phone']), api_id=settings['api_id'], - api_hash=settings['api_hash']) + api_hash=str(settings['api_hash'])) ? ++++ + print('Initialization done!') try: client.run() except Exception as e: print('Unexpected error ({}): {} at\n{}'.format( type(e), e, traceback.format_exc())) finally: print_title('Exit') print('Thanks for trying the interactive example! Exiting...') client.disconnect()
cd342448675f3174bf74118de0447c1b0f169f3e
python/volumeBars.py
python/volumeBars.py
from rgbmatrix import RGBMatrix from random import randint import numpy import math import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width barWidth = width / 16 pi = numpy.pi barHeights = numpy.empty([16]) for i in range(16): barHeights[i] = i * pi / 16 while True: nextFrame = ledMatrix.CreateFrameCanvas() heights = numpy.sin(barHeights) barHeights += pi / 16 for x in range(width): barHeight = int(heights[int(x / barWidth)] * height) for y in range(height): if height - y <= barHeight: if y < 2: nextFrame.SetPixel(x, y, 255, 0, 0) elif y < 6: nextFrame.SetPixel(x, y, 200, 200, 0) else: nextFrame.SetPixel(x, y, 0, 200, 0) ledMatrix.SwapOnVSync(nextFrame) time.sleep(0.2)
from rgbmatrix import RGBMatrix from random import randint import numpy import math import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width barWidth = width / 16 pi = numpy.pi barHeights = numpy.empty([16]) for i in range(16): barHeights[i] = i * pi / 16 while True: nextFrame = ledMatrix.CreateFrameCanvas() heights = numpy.empty([16]) for i in range(len(barHeights)): heights[i] = (math.sin(randint(-3, 3) * x) + math.cos(randint(-3, 3) * x) + math.cos(randint(-3, 3) * x)) / 3 barHeights += pi / 16 for x in range(width): barHeight = int(heights[int(x / barWidth)] * height) for y in range(height): if height - y <= barHeight: if y < 2: nextFrame.SetPixel(x, y, 255, 0, 0) elif y < 6: nextFrame.SetPixel(x, y, 200, 200, 0) else: nextFrame.SetPixel(x, y, 0, 200, 0) ledMatrix.SwapOnVSync(nextFrame) time.sleep(0.2)
Create a more random function
Create a more random function
Python
mit
DarkAce65/rpi-led-matrix,DarkAce65/rpi-led-matrix
from rgbmatrix import RGBMatrix from random import randint import numpy import math import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width barWidth = width / 16 pi = numpy.pi barHeights = numpy.empty([16]) for i in range(16): barHeights[i] = i * pi / 16 while True: nextFrame = ledMatrix.CreateFrameCanvas() - heights = numpy.sin(barHeights) + heights = numpy.empty([16]) + for i in range(len(barHeights)): + heights[i] = (math.sin(randint(-3, 3) * x) + math.cos(randint(-3, 3) * x) + math.cos(randint(-3, 3) * x)) / 3 + barHeights += pi / 16 for x in range(width): barHeight = int(heights[int(x / barWidth)] * height) for y in range(height): if height - y <= barHeight: if y < 2: nextFrame.SetPixel(x, y, 255, 0, 0) elif y < 6: nextFrame.SetPixel(x, y, 200, 200, 0) else: nextFrame.SetPixel(x, y, 0, 200, 0) + ledMatrix.SwapOnVSync(nextFrame) time.sleep(0.2)
Create a more random function
## Code Before: from rgbmatrix import RGBMatrix from random import randint import numpy import math import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width barWidth = width / 16 pi = numpy.pi barHeights = numpy.empty([16]) for i in range(16): barHeights[i] = i * pi / 16 while True: nextFrame = ledMatrix.CreateFrameCanvas() heights = numpy.sin(barHeights) barHeights += pi / 16 for x in range(width): barHeight = int(heights[int(x / barWidth)] * height) for y in range(height): if height - y <= barHeight: if y < 2: nextFrame.SetPixel(x, y, 255, 0, 0) elif y < 6: nextFrame.SetPixel(x, y, 200, 200, 0) else: nextFrame.SetPixel(x, y, 0, 200, 0) ledMatrix.SwapOnVSync(nextFrame) time.sleep(0.2) ## Instruction: Create a more random function ## Code After: from rgbmatrix import RGBMatrix from random import randint import numpy import math import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width barWidth = width / 16 pi = numpy.pi barHeights = numpy.empty([16]) for i in range(16): barHeights[i] = i * pi / 16 while True: nextFrame = ledMatrix.CreateFrameCanvas() heights = numpy.empty([16]) for i in range(len(barHeights)): heights[i] = (math.sin(randint(-3, 3) * x) + math.cos(randint(-3, 3) * x) + math.cos(randint(-3, 3) * x)) / 3 barHeights += pi / 16 for x in range(width): barHeight = int(heights[int(x / barWidth)] * height) for y in range(height): if height - y <= barHeight: if y < 2: nextFrame.SetPixel(x, y, 255, 0, 0) elif y < 6: nextFrame.SetPixel(x, y, 200, 200, 0) else: nextFrame.SetPixel(x, y, 0, 200, 0) ledMatrix.SwapOnVSync(nextFrame) time.sleep(0.2)
from rgbmatrix import RGBMatrix from random import randint import numpy import math import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width barWidth = width / 16 pi = numpy.pi barHeights = numpy.empty([16]) for i in range(16): barHeights[i] = i * pi / 16 while True: nextFrame = ledMatrix.CreateFrameCanvas() - heights = numpy.sin(barHeights) + heights = numpy.empty([16]) + for i in range(len(barHeights)): + heights[i] = (math.sin(randint(-3, 3) * x) + math.cos(randint(-3, 3) * x) + math.cos(randint(-3, 3) * x)) / 3 + barHeights += pi / 16 for x in range(width): barHeight = int(heights[int(x / barWidth)] * height) for y in range(height): if height - y <= barHeight: if y < 2: nextFrame.SetPixel(x, y, 255, 0, 0) elif y < 6: nextFrame.SetPixel(x, y, 200, 200, 0) else: nextFrame.SetPixel(x, y, 0, 200, 0) + ledMatrix.SwapOnVSync(nextFrame) time.sleep(0.2)
96a313eef46c31af3308805f10ffa63e330cc817
02/test_move.py
02/test_move.py
from move import load_moves, encode_moves, normalize_index, move import unittest class TestMove(unittest.TestCase): def setUp(self): self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD'] def test_load_moves(self): assert load_moves('example.txt') == self.moves def test_encode_moves(self): assert encode_moves(self.moves) == '1985' def test_normalize_index(self): assert normalize_index(3) == 2 assert normalize_index(2) == 2 assert normalize_index(1) == 1 assert normalize_index(0) == 0 assert normalize_index(-1) == 0 assert normalize_index(2, 1) == 0 assert normalize_index(5, 2) == 1 assert normalize_index(-1, 4) == 0 def test_move(self): assert move(5, 'U') == 2 assert move(8, 'D') == 8 assert move(7, 'L') == 7 assert move(7, 'D') == 7 assert move(2, 'R') == 3 assert move(1, 'L') == 1 def test_alternate_move(self): assert alternate_move(5, 'U') == 5 assert alternate_move(5, 'L') == 5 assert alternate_move(7, 'D') == 'B' assert alternate_move('D', 'D') == 'D'
from move import load_moves, encode_moves, normalize_index, move import unittest class TestMove(unittest.TestCase): def setUp(self): self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD'] def test_load_moves(self): assert load_moves('example.txt') == self.moves def test_encode_moves(self): assert encode_moves(self.moves) == '1985' def test_normalize_index(self): assert normalize_index(3) == 2 assert normalize_index(2) == 2 assert normalize_index(1) == 1 assert normalize_index(0) == 0 assert normalize_index(-1) == 0 def test_move(self): assert move(5, 'U') == 2 assert move(8, 'D') == 8 assert move(7, 'L') == 7 assert move(7, 'D') == 7 assert move(2, 'R') == 3 assert move(1, 'L') == 1 def test_alternate_move(self): assert alternate_move(5, 'U') == 5 assert alternate_move(5, 'L') == 5 assert alternate_move(7, 'D') == 'B' assert alternate_move('D', 'D') == 'D'
Remove test of two-argument normalize function.
Remove test of two-argument normalize function.
Python
mit
machinelearningdeveloper/aoc_2016
from move import load_moves, encode_moves, normalize_index, move import unittest class TestMove(unittest.TestCase): def setUp(self): self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD'] def test_load_moves(self): assert load_moves('example.txt') == self.moves def test_encode_moves(self): assert encode_moves(self.moves) == '1985' def test_normalize_index(self): assert normalize_index(3) == 2 assert normalize_index(2) == 2 assert normalize_index(1) == 1 assert normalize_index(0) == 0 assert normalize_index(-1) == 0 - assert normalize_index(2, 1) == 0 - assert normalize_index(5, 2) == 1 - assert normalize_index(-1, 4) == 0 def test_move(self): assert move(5, 'U') == 2 assert move(8, 'D') == 8 assert move(7, 'L') == 7 assert move(7, 'D') == 7 assert move(2, 'R') == 3 assert move(1, 'L') == 1 def test_alternate_move(self): assert alternate_move(5, 'U') == 5 assert alternate_move(5, 'L') == 5 assert alternate_move(7, 'D') == 'B' assert alternate_move('D', 'D') == 'D'
Remove test of two-argument normalize function.
## Code Before: from move import load_moves, encode_moves, normalize_index, move import unittest class TestMove(unittest.TestCase): def setUp(self): self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD'] def test_load_moves(self): assert load_moves('example.txt') == self.moves def test_encode_moves(self): assert encode_moves(self.moves) == '1985' def test_normalize_index(self): assert normalize_index(3) == 2 assert normalize_index(2) == 2 assert normalize_index(1) == 1 assert normalize_index(0) == 0 assert normalize_index(-1) == 0 assert normalize_index(2, 1) == 0 assert normalize_index(5, 2) == 1 assert normalize_index(-1, 4) == 0 def test_move(self): assert move(5, 'U') == 2 assert move(8, 'D') == 8 assert move(7, 'L') == 7 assert move(7, 'D') == 7 assert move(2, 'R') == 3 assert move(1, 'L') == 1 def test_alternate_move(self): assert alternate_move(5, 'U') == 5 assert alternate_move(5, 'L') == 5 assert alternate_move(7, 'D') == 'B' assert alternate_move('D', 'D') == 'D' ## Instruction: Remove test of two-argument normalize function. ## Code After: from move import load_moves, encode_moves, normalize_index, move import unittest class TestMove(unittest.TestCase): def setUp(self): self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD'] def test_load_moves(self): assert load_moves('example.txt') == self.moves def test_encode_moves(self): assert encode_moves(self.moves) == '1985' def test_normalize_index(self): assert normalize_index(3) == 2 assert normalize_index(2) == 2 assert normalize_index(1) == 1 assert normalize_index(0) == 0 assert normalize_index(-1) == 0 def test_move(self): assert move(5, 'U') == 2 assert move(8, 'D') == 8 assert move(7, 'L') == 7 assert move(7, 'D') == 7 assert move(2, 'R') == 3 assert move(1, 'L') == 1 def test_alternate_move(self): assert alternate_move(5, 'U') == 5 assert alternate_move(5, 'L') == 5 assert alternate_move(7, 'D') == 'B' assert alternate_move('D', 'D') == 'D'
from move import load_moves, encode_moves, normalize_index, move import unittest class TestMove(unittest.TestCase): def setUp(self): self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD'] def test_load_moves(self): assert load_moves('example.txt') == self.moves def test_encode_moves(self): assert encode_moves(self.moves) == '1985' def test_normalize_index(self): assert normalize_index(3) == 2 assert normalize_index(2) == 2 assert normalize_index(1) == 1 assert normalize_index(0) == 0 assert normalize_index(-1) == 0 - assert normalize_index(2, 1) == 0 - assert normalize_index(5, 2) == 1 - assert normalize_index(-1, 4) == 0 def test_move(self): assert move(5, 'U') == 2 assert move(8, 'D') == 8 assert move(7, 'L') == 7 assert move(7, 'D') == 7 assert move(2, 'R') == 3 assert move(1, 'L') == 1 def test_alternate_move(self): assert alternate_move(5, 'U') == 5 assert alternate_move(5, 'L') == 5 assert alternate_move(7, 'D') == 'B' assert alternate_move('D', 'D') == 'D'
90ade823700da61824c113759f847bf08823c148
nova/objects/__init__.py
nova/objects/__init__.py
def register_all(): # NOTE(danms): You must make sure your object gets imported in this # function in order for it to be registered by services that may # need to receive it via RPC. __import__('nova.objects.dns_domain') __import__('nova.objects.instance') __import__('nova.objects.instance_info_cache') __import__('nova.objects.security_group') __import__('nova.objects.migration') __import__('nova.objects.quotas') __import__('nova.objects.virtual_interface') __import__('nova.objects.network') __import__('nova.objects.block_device') __import__('nova.objects.fixed_ip') __import__('nova.objects.floating_ip')
def register_all(): # NOTE(danms): You must make sure your object gets imported in this # function in order for it to be registered by services that may # need to receive it via RPC. __import__('nova.objects.dns_domain') __import__('nova.objects.instance') __import__('nova.objects.instance_info_cache') __import__('nova.objects.security_group') __import__('nova.objects.migration') __import__('nova.objects.quotas') __import__('nova.objects.virtual_interface') __import__('nova.objects.network') __import__('nova.objects.block_device') __import__('nova.objects.fixed_ip') __import__('nova.objects.floating_ip') __import__('nova.objects.security_group_rule')
Add security_group_rule to objects registry
Add security_group_rule to objects registry This adds the security_group_rule module to the objects registry, which allows a service to make sure that all of its objects are registered before any could be received over RPC. We don't really have a test for any of these because of the nature of how they're imported. Refactoring this later could provide some incremental steps to making this more testable. Change-Id: Ie96021f3cdeac6addab21c42a14cd8f136eb0b27 Closes-Bug: #1264816
Python
apache-2.0
citrix-openstack-build/oslo.versionedobjects,openstack/oslo.versionedobjects
def register_all(): # NOTE(danms): You must make sure your object gets imported in this # function in order for it to be registered by services that may # need to receive it via RPC. __import__('nova.objects.dns_domain') __import__('nova.objects.instance') __import__('nova.objects.instance_info_cache') __import__('nova.objects.security_group') __import__('nova.objects.migration') __import__('nova.objects.quotas') __import__('nova.objects.virtual_interface') __import__('nova.objects.network') __import__('nova.objects.block_device') __import__('nova.objects.fixed_ip') __import__('nova.objects.floating_ip') + __import__('nova.objects.security_group_rule')
Add security_group_rule to objects registry
## Code Before: def register_all(): # NOTE(danms): You must make sure your object gets imported in this # function in order for it to be registered by services that may # need to receive it via RPC. __import__('nova.objects.dns_domain') __import__('nova.objects.instance') __import__('nova.objects.instance_info_cache') __import__('nova.objects.security_group') __import__('nova.objects.migration') __import__('nova.objects.quotas') __import__('nova.objects.virtual_interface') __import__('nova.objects.network') __import__('nova.objects.block_device') __import__('nova.objects.fixed_ip') __import__('nova.objects.floating_ip') ## Instruction: Add security_group_rule to objects registry ## Code After: def register_all(): # NOTE(danms): You must make sure your object gets imported in this # function in order for it to be registered by services that may # need to receive it via RPC. __import__('nova.objects.dns_domain') __import__('nova.objects.instance') __import__('nova.objects.instance_info_cache') __import__('nova.objects.security_group') __import__('nova.objects.migration') __import__('nova.objects.quotas') __import__('nova.objects.virtual_interface') __import__('nova.objects.network') __import__('nova.objects.block_device') __import__('nova.objects.fixed_ip') __import__('nova.objects.floating_ip') __import__('nova.objects.security_group_rule')
def register_all(): # NOTE(danms): You must make sure your object gets imported in this # function in order for it to be registered by services that may # need to receive it via RPC. __import__('nova.objects.dns_domain') __import__('nova.objects.instance') __import__('nova.objects.instance_info_cache') __import__('nova.objects.security_group') __import__('nova.objects.migration') __import__('nova.objects.quotas') __import__('nova.objects.virtual_interface') __import__('nova.objects.network') __import__('nova.objects.block_device') __import__('nova.objects.fixed_ip') __import__('nova.objects.floating_ip') + __import__('nova.objects.security_group_rule')
8e2fe6bd486e7c105ef7cd6f061b41efd3e42b08
tasks/base.py
tasks/base.py
import os import invoke invoke.run = os.system class BaseTest(object): def download_mspec(self): if not os.path.isdir("../mspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/mspec") def download_rubyspec(self): if not os.path.isdir("../rubyspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/spec rubyspec")
import os import invoke if os.environ.get('TRAVIS_OS_NAME') == 'osx': invoke.run = os.system class BaseTest(object): def download_mspec(self): if not os.path.isdir("../mspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/mspec") def download_rubyspec(self): if not os.path.isdir("../rubyspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/spec rubyspec")
Use dirty macOS workaround only on OSX on Travis
Use dirty macOS workaround only on OSX on Travis
Python
bsd-3-clause
topazproject/topaz,topazproject/topaz,topazproject/topaz,topazproject/topaz
import os import invoke - + if os.environ.get('TRAVIS_OS_NAME') == 'osx': - invoke.run = os.system + invoke.run = os.system class BaseTest(object): def download_mspec(self): if not os.path.isdir("../mspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/mspec") def download_rubyspec(self): if not os.path.isdir("../rubyspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/spec rubyspec")
Use dirty macOS workaround only on OSX on Travis
## Code Before: import os import invoke invoke.run = os.system class BaseTest(object): def download_mspec(self): if not os.path.isdir("../mspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/mspec") def download_rubyspec(self): if not os.path.isdir("../rubyspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/spec rubyspec") ## Instruction: Use dirty macOS workaround only on OSX on Travis ## Code After: import os import invoke if os.environ.get('TRAVIS_OS_NAME') == 'osx': invoke.run = os.system class BaseTest(object): def download_mspec(self): if not os.path.isdir("../mspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/mspec") def download_rubyspec(self): if not os.path.isdir("../rubyspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/spec rubyspec")
import os import invoke - + if os.environ.get('TRAVIS_OS_NAME') == 'osx': - invoke.run = os.system + invoke.run = os.system ? ++++ class BaseTest(object): def download_mspec(self): if not os.path.isdir("../mspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/mspec") def download_rubyspec(self): if not os.path.isdir("../rubyspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/spec rubyspec")
7bed531fcbc63de25572a6b02fb8b19bd066fa50
test_pearhash.py
test_pearhash.py
import unittest from pearhash import PearsonHasher class TestPearsonHasher(unittest.TestCase): def test_table_is_a_permutation_of_range_256(self): hasher = PearsonHasher(2) self.assertEqual(set(hasher.table), set(range(256)))
import unittest from pearhash import PearsonHasher class TestPearsonHasher(unittest.TestCase): def test_table_is_a_permutation_of_range_256(self): hasher = PearsonHasher(2) self.assertEqual(set(hasher.table), set(range(256))) def test_two_bytes(self): hasher = PearsonHasher(2) self.assertEqual(hasher.hash(b'ni hao').hexdigest(), '1297') def test_two_bytes_custom_seed(self): hasher = PearsonHasher(2, seed = 'whatevs') self.assertEqual(hasher.hash(b'ni hao').hexdigest(), 'd710') def test_four_bytes(self): hasher = PearsonHasher(4) self.assertEqual(hasher.hash(b'ni hao').hexdigest(), '1297b8d9')
Add a few trivial tests
Add a few trivial tests
Python
mit
ze-phyr-us/pearhash
import unittest from pearhash import PearsonHasher class TestPearsonHasher(unittest.TestCase): def test_table_is_a_permutation_of_range_256(self): hasher = PearsonHasher(2) self.assertEqual(set(hasher.table), set(range(256))) + + def test_two_bytes(self): + hasher = PearsonHasher(2) + self.assertEqual(hasher.hash(b'ni hao').hexdigest(), '1297') + + + def test_two_bytes_custom_seed(self): + hasher = PearsonHasher(2, seed = 'whatevs') + self.assertEqual(hasher.hash(b'ni hao').hexdigest(), 'd710') + + + def test_four_bytes(self): + hasher = PearsonHasher(4) + self.assertEqual(hasher.hash(b'ni hao').hexdigest(), '1297b8d9') +
Add a few trivial tests
## Code Before: import unittest from pearhash import PearsonHasher class TestPearsonHasher(unittest.TestCase): def test_table_is_a_permutation_of_range_256(self): hasher = PearsonHasher(2) self.assertEqual(set(hasher.table), set(range(256))) ## Instruction: Add a few trivial tests ## Code After: import unittest from pearhash import PearsonHasher class TestPearsonHasher(unittest.TestCase): def test_table_is_a_permutation_of_range_256(self): hasher = PearsonHasher(2) self.assertEqual(set(hasher.table), set(range(256))) def test_two_bytes(self): hasher = PearsonHasher(2) self.assertEqual(hasher.hash(b'ni hao').hexdigest(), '1297') def test_two_bytes_custom_seed(self): hasher = PearsonHasher(2, seed = 'whatevs') self.assertEqual(hasher.hash(b'ni hao').hexdigest(), 'd710') def test_four_bytes(self): hasher = PearsonHasher(4) self.assertEqual(hasher.hash(b'ni hao').hexdigest(), '1297b8d9')
import unittest from pearhash import PearsonHasher class TestPearsonHasher(unittest.TestCase): def test_table_is_a_permutation_of_range_256(self): hasher = PearsonHasher(2) self.assertEqual(set(hasher.table), set(range(256))) + + + def test_two_bytes(self): + hasher = PearsonHasher(2) + self.assertEqual(hasher.hash(b'ni hao').hexdigest(), '1297') + + + def test_two_bytes_custom_seed(self): + hasher = PearsonHasher(2, seed = 'whatevs') + self.assertEqual(hasher.hash(b'ni hao').hexdigest(), 'd710') + + + def test_four_bytes(self): + hasher = PearsonHasher(4) + self.assertEqual(hasher.hash(b'ni hao').hexdigest(), '1297b8d9')
22e41d02d9c877703f21c5121202d295cb5fbcb0
test/swig/canvas.py
test/swig/canvas.py
import uwhd def main(): version = 1 black_score = 3 white_score = 5 time = 42 mgr = uwhd.GameModelManager() print('# SET-VERSION: %d' % (version,)) print('# SET-STATE: FirstHalf') print('# SET-BLACK: %d' % (black_score,)) print('# SET-WHITE: %d' % (white_score,)) print('# SET-TIME: %d' % (time,)) mgr.setGameStateFirstHalf() mgr.setBlackScore(black_score) mgr.setWhiteScore(white_score) mgr.setGameClock(time) canvas = uwhd.UWHDCanvas.create(32 * 3, 32) uwhd.renderGameDisplay(1, mgr.getModel(), canvas) ppmstr = uwhd.asPPMString(canvas) print(ppmstr) if __name__ == '__main__': main()
import uwhd def main(): version = 1 black_score = 3 white_score = 5 time = 42 # Build a GameModelManager with a known state: mgr = uwhd.GameModelManager() mgr.setGameStateFirstHalf() mgr.setBlackScore(black_score) mgr.setWhiteScore(white_score) mgr.setGameClock(time) # Render that state to a canvas: canvas = uwhd.UWHDCanvas.create(32 * 3, 32) uwhd.renderGameDisplay(version, mgr.getModel(), canvas) # Print out the expected and actual display state # for display-check to verify: print('# SET-VERSION: %d' % (version,)) print('# SET-STATE: FirstHalf') print('# SET-BLACK: %d' % (black_score,)) print('# SET-WHITE: %d' % (white_score,)) print('# SET-TIME: %d' % (time,)) print(uwhd.asPPMString(canvas)) if __name__ == '__main__': main()
Clean up the SWIG test. Add comments. NFC
[tests] Clean up the SWIG test. Add comments. NFC
Python
bsd-3-clause
Navisjon/uwh-display,Navisjon/uwh-display,Navisjon/uwh-display,jroelofs/uwh-display,Navisjon/uwh-display,jroelofs/uwh-display,jroelofs/uwh-display
import uwhd def main(): version = 1 black_score = 3 white_score = 5 time = 42 + # Build a GameModelManager with a known state: mgr = uwhd.GameModelManager() + mgr.setGameStateFirstHalf() + mgr.setBlackScore(black_score) + mgr.setWhiteScore(white_score) + mgr.setGameClock(time) + # Render that state to a canvas: + canvas = uwhd.UWHDCanvas.create(32 * 3, 32) + uwhd.renderGameDisplay(version, mgr.getModel(), canvas) + + # Print out the expected and actual display state + # for display-check to verify: print('# SET-VERSION: %d' % (version,)) print('# SET-STATE: FirstHalf') print('# SET-BLACK: %d' % (black_score,)) print('# SET-WHITE: %d' % (white_score,)) print('# SET-TIME: %d' % (time,)) - - mgr.setGameStateFirstHalf() - mgr.setBlackScore(black_score) - mgr.setWhiteScore(white_score) - mgr.setGameClock(time) - - canvas = uwhd.UWHDCanvas.create(32 * 3, 32) - uwhd.renderGameDisplay(1, mgr.getModel(), canvas) - ppmstr = uwhd.asPPMString(canvas) + print(uwhd.asPPMString(canvas)) - - print(ppmstr) if __name__ == '__main__': main()
Clean up the SWIG test. Add comments. NFC
## Code Before: import uwhd def main(): version = 1 black_score = 3 white_score = 5 time = 42 mgr = uwhd.GameModelManager() print('# SET-VERSION: %d' % (version,)) print('# SET-STATE: FirstHalf') print('# SET-BLACK: %d' % (black_score,)) print('# SET-WHITE: %d' % (white_score,)) print('# SET-TIME: %d' % (time,)) mgr.setGameStateFirstHalf() mgr.setBlackScore(black_score) mgr.setWhiteScore(white_score) mgr.setGameClock(time) canvas = uwhd.UWHDCanvas.create(32 * 3, 32) uwhd.renderGameDisplay(1, mgr.getModel(), canvas) ppmstr = uwhd.asPPMString(canvas) print(ppmstr) if __name__ == '__main__': main() ## Instruction: Clean up the SWIG test. Add comments. NFC ## Code After: import uwhd def main(): version = 1 black_score = 3 white_score = 5 time = 42 # Build a GameModelManager with a known state: mgr = uwhd.GameModelManager() mgr.setGameStateFirstHalf() mgr.setBlackScore(black_score) mgr.setWhiteScore(white_score) mgr.setGameClock(time) # Render that state to a canvas: canvas = uwhd.UWHDCanvas.create(32 * 3, 32) uwhd.renderGameDisplay(version, mgr.getModel(), canvas) # Print out the expected and actual display state # for display-check to verify: print('# SET-VERSION: %d' % (version,)) print('# SET-STATE: FirstHalf') print('# SET-BLACK: %d' % (black_score,)) print('# SET-WHITE: %d' % (white_score,)) print('# SET-TIME: %d' % (time,)) print(uwhd.asPPMString(canvas)) if __name__ == '__main__': main()
import uwhd def main(): version = 1 black_score = 3 white_score = 5 time = 42 + # Build a GameModelManager with a known state: mgr = uwhd.GameModelManager() + mgr.setGameStateFirstHalf() + mgr.setBlackScore(black_score) + mgr.setWhiteScore(white_score) + mgr.setGameClock(time) + # Render that state to a canvas: + canvas = uwhd.UWHDCanvas.create(32 * 3, 32) + uwhd.renderGameDisplay(version, mgr.getModel(), canvas) + + # Print out the expected and actual display state + # for display-check to verify: print('# SET-VERSION: %d' % (version,)) print('# SET-STATE: FirstHalf') print('# SET-BLACK: %d' % (black_score,)) print('# SET-WHITE: %d' % (white_score,)) print('# SET-TIME: %d' % (time,)) - - mgr.setGameStateFirstHalf() - mgr.setBlackScore(black_score) - mgr.setWhiteScore(white_score) - mgr.setGameClock(time) - - canvas = uwhd.UWHDCanvas.create(32 * 3, 32) - uwhd.renderGameDisplay(1, mgr.getModel(), canvas) - ppmstr = uwhd.asPPMString(canvas) ? ^^^ ^^^^ + print(uwhd.asPPMString(canvas)) ? ^^^ ^ + - - print(ppmstr) if __name__ == '__main__': main()
9f97f232a23dab38736e487bd69377b977dff752
candidates/tests/test_feeds.py
candidates/tests/test_feeds.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django_webtest import WebTest from .auth import TestUserMixin from ..models import LoggedAction class TestFeeds(TestUserMixin, WebTest): def setUp(self): self.action1 = LoggedAction.objects.create( user=self.user, action_type='person-create', ip_address='127.0.0.1', person_id='9876', popit_person_new_version='1234567890abcdef', source='Just for tests...', ) self.action2 = LoggedAction.objects.create( user=self.user, action_type='candidacy-delete', ip_address='127.0.0.1', person_id='1234', popit_person_new_version='987654321', source='Something with unicode in it…', ) def test_unicode(self): response = self.app.get('/feeds/changes.xml') self.assertTrue("Just for tests..." in response) self.assertTrue("Something with unicode in it…" in response) def tearDown(self): self.action2.delete() self.action1.delete()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django_webtest import WebTest from popolo.models import Person from .auth import TestUserMixin from ..models import LoggedAction class TestFeeds(TestUserMixin, WebTest): def setUp(self): self.person1 = Person.objects.create( name='Test Person1' ) self.person2 = Person.objects.create( name='Test Person2' ) self.action1 = LoggedAction.objects.create( user=self.user, action_type='person-create', ip_address='127.0.0.1', person=self.person1, popit_person_new_version='1234567890abcdef', source='Just for tests...', ) self.action2 = LoggedAction.objects.create( user=self.user, action_type='candidacy-delete', ip_address='127.0.0.1', person=self.person2, popit_person_new_version='987654321', source='Something with unicode in it…', ) def test_unicode(self): response = self.app.get('/feeds/changes.xml') self.assertTrue("Just for tests..." in response) self.assertTrue("Something with unicode in it…" in response) def tearDown(self): self.action2.delete() self.action1.delete() self.person2.delete() self.person1.delete()
Update feed tests to use a person object when creating LoggedAction
Update feed tests to use a person object when creating LoggedAction Otherwise the notification signal attached to LoggedAction for the alerts throws an error as it expects a Person to exist
Python
agpl-3.0
DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextmp-popit,mysociety/yournextmp-popit,neavouli/yournextrepresentative,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextmp-popit,neavouli/yournextrepresentative
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django_webtest import WebTest + from popolo.models import Person from .auth import TestUserMixin from ..models import LoggedAction class TestFeeds(TestUserMixin, WebTest): def setUp(self): + self.person1 = Person.objects.create( + name='Test Person1' + ) + self.person2 = Person.objects.create( + name='Test Person2' + ) self.action1 = LoggedAction.objects.create( user=self.user, action_type='person-create', ip_address='127.0.0.1', - person_id='9876', + person=self.person1, popit_person_new_version='1234567890abcdef', source='Just for tests...', ) self.action2 = LoggedAction.objects.create( user=self.user, action_type='candidacy-delete', ip_address='127.0.0.1', - person_id='1234', + person=self.person2, popit_person_new_version='987654321', source='Something with unicode in it…', ) def test_unicode(self): response = self.app.get('/feeds/changes.xml') self.assertTrue("Just for tests..." in response) self.assertTrue("Something with unicode in it…" in response) def tearDown(self): self.action2.delete() self.action1.delete() + self.person2.delete() + self.person1.delete()
Update feed tests to use a person object when creating LoggedAction
## Code Before: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django_webtest import WebTest from .auth import TestUserMixin from ..models import LoggedAction class TestFeeds(TestUserMixin, WebTest): def setUp(self): self.action1 = LoggedAction.objects.create( user=self.user, action_type='person-create', ip_address='127.0.0.1', person_id='9876', popit_person_new_version='1234567890abcdef', source='Just for tests...', ) self.action2 = LoggedAction.objects.create( user=self.user, action_type='candidacy-delete', ip_address='127.0.0.1', person_id='1234', popit_person_new_version='987654321', source='Something with unicode in it…', ) def test_unicode(self): response = self.app.get('/feeds/changes.xml') self.assertTrue("Just for tests..." in response) self.assertTrue("Something with unicode in it…" in response) def tearDown(self): self.action2.delete() self.action1.delete() ## Instruction: Update feed tests to use a person object when creating LoggedAction ## Code After: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django_webtest import WebTest from popolo.models import Person from .auth import TestUserMixin from ..models import LoggedAction class TestFeeds(TestUserMixin, WebTest): def setUp(self): self.person1 = Person.objects.create( name='Test Person1' ) self.person2 = Person.objects.create( name='Test Person2' ) self.action1 = LoggedAction.objects.create( user=self.user, action_type='person-create', ip_address='127.0.0.1', person=self.person1, popit_person_new_version='1234567890abcdef', source='Just for tests...', ) self.action2 = LoggedAction.objects.create( user=self.user, action_type='candidacy-delete', ip_address='127.0.0.1', person=self.person2, popit_person_new_version='987654321', source='Something with unicode in it…', ) def test_unicode(self): response = self.app.get('/feeds/changes.xml') self.assertTrue("Just for tests..." in response) self.assertTrue("Something with unicode in it…" in response) def tearDown(self): self.action2.delete() self.action1.delete() self.person2.delete() self.person1.delete()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django_webtest import WebTest + from popolo.models import Person from .auth import TestUserMixin from ..models import LoggedAction class TestFeeds(TestUserMixin, WebTest): def setUp(self): + self.person1 = Person.objects.create( + name='Test Person1' + ) + self.person2 = Person.objects.create( + name='Test Person2' + ) self.action1 = LoggedAction.objects.create( user=self.user, action_type='person-create', ip_address='127.0.0.1', - person_id='9876', + person=self.person1, popit_person_new_version='1234567890abcdef', source='Just for tests...', ) self.action2 = LoggedAction.objects.create( user=self.user, action_type='candidacy-delete', ip_address='127.0.0.1', - person_id='1234', + person=self.person2, popit_person_new_version='987654321', source='Something with unicode in it…', ) def test_unicode(self): response = self.app.get('/feeds/changes.xml') self.assertTrue("Just for tests..." in response) self.assertTrue("Something with unicode in it…" in response) def tearDown(self): self.action2.delete() self.action1.delete() + self.person2.delete() + self.person1.delete()
0b8aa961cb8aa6646aa1b660f6f669cf82492225
helper/windows.py
helper/windows.py
import subprocess import sys DETACHED_PROCESS = 8 class Daemon(object): """Daemonize the helper application, putting it in a forked background process. """ def __init__(self, controller): raise NotImplementedError #args = [sys.executable] #args.extend(sys.argv) #self.pid = subprocess.Popen(args, # creationflags=DETACHED_PROCESS, # shell=True).pid
import platform import subprocess import sys DETACHED_PROCESS = 8 def operating_system(): """Return a string identifying the operating system the application is running on. :rtype: str """ return '%s %s (%s)' % (platform.system(), platform.release(), platform.version()) class Daemon(object): """Daemonize the helper application, putting it in a forked background process. """ def __init__(self, controller): raise NotImplementedError #args = [sys.executable] #args.extend(sys.argv) #self.pid = subprocess.Popen(args, # creationflags=DETACHED_PROCESS, # shell=True).pid
Implement the operating_system() method for Windows
Implement the operating_system() method for Windows
Python
bsd-3-clause
dave-shawley/helper,gmr/helper,gmr/helper
+ import platform import subprocess import sys DETACHED_PROCESS = 8 + + + def operating_system(): + """Return a string identifying the operating system the application + is running on. + + :rtype: str + + """ + return '%s %s (%s)' % (platform.system(), + platform.release(), + platform.version()) class Daemon(object): """Daemonize the helper application, putting it in a forked background process. """ def __init__(self, controller): raise NotImplementedError #args = [sys.executable] #args.extend(sys.argv) #self.pid = subprocess.Popen(args, # creationflags=DETACHED_PROCESS, # shell=True).pid
Implement the operating_system() method for Windows
## Code Before: import subprocess import sys DETACHED_PROCESS = 8 class Daemon(object): """Daemonize the helper application, putting it in a forked background process. """ def __init__(self, controller): raise NotImplementedError #args = [sys.executable] #args.extend(sys.argv) #self.pid = subprocess.Popen(args, # creationflags=DETACHED_PROCESS, # shell=True).pid ## Instruction: Implement the operating_system() method for Windows ## Code After: import platform import subprocess import sys DETACHED_PROCESS = 8 def operating_system(): """Return a string identifying the operating system the application is running on. :rtype: str """ return '%s %s (%s)' % (platform.system(), platform.release(), platform.version()) class Daemon(object): """Daemonize the helper application, putting it in a forked background process. """ def __init__(self, controller): raise NotImplementedError #args = [sys.executable] #args.extend(sys.argv) #self.pid = subprocess.Popen(args, # creationflags=DETACHED_PROCESS, # shell=True).pid
+ import platform import subprocess import sys DETACHED_PROCESS = 8 + + + def operating_system(): + """Return a string identifying the operating system the application + is running on. + + :rtype: str + + """ + return '%s %s (%s)' % (platform.system(), + platform.release(), + platform.version()) class Daemon(object): """Daemonize the helper application, putting it in a forked background process. """ def __init__(self, controller): raise NotImplementedError #args = [sys.executable] #args.extend(sys.argv) #self.pid = subprocess.Popen(args, # creationflags=DETACHED_PROCESS, # shell=True).pid
b4ce232f050de073572f64c04b170a2e790fdc24
nefertari_mongodb/serializers.py
nefertari_mongodb/serializers.py
import logging import datetime import decimal import elasticsearch from bson import ObjectId, DBRef from nefertari.renderers import _JSONEncoder log = logging.getLogger(__name__) class JSONEncoder(_JSONEncoder): def default(self, obj): if isinstance(obj, (ObjectId, DBRef)): return str(obj) if isinstance(obj, decimal.Decimal): return float(obj) if isinstance(obj, (datetime.datetime, datetime.date)): return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso if isinstance(obj, datetime.time): return obj.strftime('%H:%M:%S') if isinstance(obj, datetime.timedelta): return obj.seconds if hasattr(obj, 'to_dict'): # If it got to this point, it means its a nested object. # outter objects would have been handled with DataProxy. return obj.to_dict(__nested=True) return super(JSONEncoder, self).default(obj) class ESJSONSerializer(elasticsearch.serializer.JSONSerializer): def default(self, obj): if isinstance(obj, (ObjectId, DBRef)): return str(obj) if isinstance(obj, (datetime.datetime, datetime.date)): return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso if isinstance(obj, datetime.time): return obj.strftime('%H:%M:%S') if isinstance(obj, datetime.timedelta): return obj.seconds if isinstance(obj, decimal.Decimal): return float(obj) try: return super(ESJSONSerializer, self).default(obj) except: import traceback log.error(traceback.format_exc())
import logging import datetime import decimal import elasticsearch from bson import ObjectId, DBRef from nefertari.renderers import _JSONEncoder log = logging.getLogger(__name__) class JSONEncoderMixin(object): def default(self, obj): if isinstance(obj, (ObjectId, DBRef)): return str(obj) if isinstance(obj, (datetime.datetime, datetime.date)): return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso if isinstance(obj, datetime.time): return obj.strftime('%H:%M:%S') if isinstance(obj, datetime.timedelta): return obj.seconds if isinstance(obj, decimal.Decimal): return float(obj) return super(JSONEncoderMixin, self).default(obj) class JSONEncoder(JSONEncoderMixin, _JSONEncoder): def default(self, obj): if hasattr(obj, 'to_dict'): # If it got to this point, it means its a nested object. # outter objects would have been handled with DataProxy. return obj.to_dict(__nested=True) return super(JSONEncoder, self).default(obj) class ESJSONSerializer(JSONEncoderMixin, elasticsearch.serializer.JSONSerializer): def default(self, obj): try: return super(ESJSONSerializer, self).default(obj) except: import traceback log.error(traceback.format_exc())
Refactor encoders to have base class
Refactor encoders to have base class
Python
apache-2.0
brandicted/nefertari-mongodb,ramses-tech/nefertari-mongodb
import logging import datetime import decimal import elasticsearch from bson import ObjectId, DBRef from nefertari.renderers import _JSONEncoder log = logging.getLogger(__name__) + class JSONEncoderMixin(object): - class JSONEncoder(_JSONEncoder): - def default(self, obj): - if isinstance(obj, (ObjectId, DBRef)): - return str(obj) - if isinstance(obj, decimal.Decimal): - return float(obj) - if isinstance(obj, (datetime.datetime, datetime.date)): - return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso - if isinstance(obj, datetime.time): - return obj.strftime('%H:%M:%S') - if isinstance(obj, datetime.timedelta): - return obj.seconds - - if hasattr(obj, 'to_dict'): - # If it got to this point, it means its a nested object. - # outter objects would have been handled with DataProxy. - return obj.to_dict(__nested=True) - - return super(JSONEncoder, self).default(obj) - - - class ESJSONSerializer(elasticsearch.serializer.JSONSerializer): def default(self, obj): if isinstance(obj, (ObjectId, DBRef)): return str(obj) if isinstance(obj, (datetime.datetime, datetime.date)): return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso if isinstance(obj, datetime.time): return obj.strftime('%H:%M:%S') if isinstance(obj, datetime.timedelta): return obj.seconds if isinstance(obj, decimal.Decimal): return float(obj) + return super(JSONEncoderMixin, self).default(obj) + + + class JSONEncoder(JSONEncoderMixin, _JSONEncoder): + def default(self, obj): + if hasattr(obj, 'to_dict'): + # If it got to this point, it means its a nested object. + # outter objects would have been handled with DataProxy. + return obj.to_dict(__nested=True) + return super(JSONEncoder, self).default(obj) + + + class ESJSONSerializer(JSONEncoderMixin, + elasticsearch.serializer.JSONSerializer): + def default(self, obj): try: return super(ESJSONSerializer, self).default(obj) except: import traceback log.error(traceback.format_exc())
Refactor encoders to have base class
## Code Before: import logging import datetime import decimal import elasticsearch from bson import ObjectId, DBRef from nefertari.renderers import _JSONEncoder log = logging.getLogger(__name__) class JSONEncoder(_JSONEncoder): def default(self, obj): if isinstance(obj, (ObjectId, DBRef)): return str(obj) if isinstance(obj, decimal.Decimal): return float(obj) if isinstance(obj, (datetime.datetime, datetime.date)): return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso if isinstance(obj, datetime.time): return obj.strftime('%H:%M:%S') if isinstance(obj, datetime.timedelta): return obj.seconds if hasattr(obj, 'to_dict'): # If it got to this point, it means its a nested object. # outter objects would have been handled with DataProxy. return obj.to_dict(__nested=True) return super(JSONEncoder, self).default(obj) class ESJSONSerializer(elasticsearch.serializer.JSONSerializer): def default(self, obj): if isinstance(obj, (ObjectId, DBRef)): return str(obj) if isinstance(obj, (datetime.datetime, datetime.date)): return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso if isinstance(obj, datetime.time): return obj.strftime('%H:%M:%S') if isinstance(obj, datetime.timedelta): return obj.seconds if isinstance(obj, decimal.Decimal): return float(obj) try: return super(ESJSONSerializer, self).default(obj) except: import traceback log.error(traceback.format_exc()) ## Instruction: Refactor encoders to have base class ## Code After: import logging import datetime import decimal import elasticsearch from bson import ObjectId, DBRef from nefertari.renderers import _JSONEncoder log = logging.getLogger(__name__) class JSONEncoderMixin(object): def default(self, obj): if isinstance(obj, (ObjectId, DBRef)): return str(obj) if isinstance(obj, (datetime.datetime, datetime.date)): return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso if isinstance(obj, datetime.time): return obj.strftime('%H:%M:%S') if isinstance(obj, datetime.timedelta): return obj.seconds if isinstance(obj, decimal.Decimal): return float(obj) return super(JSONEncoderMixin, self).default(obj) class JSONEncoder(JSONEncoderMixin, _JSONEncoder): def default(self, obj): if hasattr(obj, 'to_dict'): # If it got to this point, it means its a nested object. # outter objects would have been handled with DataProxy. return obj.to_dict(__nested=True) return super(JSONEncoder, self).default(obj) class ESJSONSerializer(JSONEncoderMixin, elasticsearch.serializer.JSONSerializer): def default(self, obj): try: return super(ESJSONSerializer, self).default(obj) except: import traceback log.error(traceback.format_exc())
import logging import datetime import decimal import elasticsearch from bson import ObjectId, DBRef from nefertari.renderers import _JSONEncoder log = logging.getLogger(__name__) + class JSONEncoderMixin(object): - class JSONEncoder(_JSONEncoder): - def default(self, obj): - if isinstance(obj, (ObjectId, DBRef)): - return str(obj) - if isinstance(obj, decimal.Decimal): - return float(obj) - if isinstance(obj, (datetime.datetime, datetime.date)): - return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso - if isinstance(obj, datetime.time): - return obj.strftime('%H:%M:%S') - if isinstance(obj, datetime.timedelta): - return obj.seconds - - if hasattr(obj, 'to_dict'): - # If it got to this point, it means its a nested object. - # outter objects would have been handled with DataProxy. - return obj.to_dict(__nested=True) - - return super(JSONEncoder, self).default(obj) - - - class ESJSONSerializer(elasticsearch.serializer.JSONSerializer): def default(self, obj): if isinstance(obj, (ObjectId, DBRef)): return str(obj) if isinstance(obj, (datetime.datetime, datetime.date)): return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso if isinstance(obj, datetime.time): return obj.strftime('%H:%M:%S') if isinstance(obj, datetime.timedelta): return obj.seconds if isinstance(obj, decimal.Decimal): return float(obj) + return super(JSONEncoderMixin, self).default(obj) + + + class JSONEncoder(JSONEncoderMixin, _JSONEncoder): + def default(self, obj): + if hasattr(obj, 'to_dict'): + # If it got to this point, it means its a nested object. + # outter objects would have been handled with DataProxy. + return obj.to_dict(__nested=True) + return super(JSONEncoder, self).default(obj) + + + class ESJSONSerializer(JSONEncoderMixin, + elasticsearch.serializer.JSONSerializer): + def default(self, obj): try: return super(ESJSONSerializer, self).default(obj) except: import traceback log.error(traceback.format_exc())
03d321f5700f2cd3f02de8aa2b601fa14d3de144
setup.py
setup.py
import os __author__ = "Andre Christoga" input = raw_input("> (eg plus, minus, divide...)") if input == "plus": os.system("pymain/plus.py") if input == "minus": os.system("pymain/minus.py") if input == "multi": os.system("pymain/multi.py") if input == "divide": os.system("pymain/divide.py") if input == "modulos": os.system("pymain/modulos.py") else : print "The script does not exists" # setup( # name="PyMaIn", # version="1.0.0", # author="Coding Smart School", # author_email="codingsmartschool@gmail.com", # url="https://github.com/codingsmartschool/pymain", # description="Python Math Input", # long_description=("PyMaIn is a python program that takes maths number" # " and give user the answer."), # classifiers=[ # 'Development Status :: 4 - Beta', # 'Programming Language :: Python', # ], # license="MIT", # packages=['pymain'], # )
import os __author__ = "Andre Christoga" input = raw_input("> (eg plus, minus, divide...)") if input == "plus": os.system("pymain/plus.py") if input == "minus": os.system("pymain/minus.py") if input == "multi": os.system("pymain/multi.py") if input == "divide": os.system("pymain/divide.py") if input == "modulos": os.system("pymain/modulos.py") # setup( # name="PyMaIn", # version="1.0.0", # author="Coding Smart School", # author_email="codingsmartschool@gmail.com", # url="https://github.com/codingsmartschool/pymain", # description="Python Math Input", # long_description=("PyMaIn is a python program that takes maths number" # " and give user the answer."), # classifiers=[ # 'Development Status :: 4 - Beta', # 'Programming Language :: Python', # ], # license="MIT", # packages=['pymain'], # )
Remove not found script message
Remove not found script message
Python
mit
codingsmartschool/PyMaIn
import os __author__ = "Andre Christoga" input = raw_input("> (eg plus, minus, divide...)") if input == "plus": os.system("pymain/plus.py") if input == "minus": os.system("pymain/minus.py") if input == "multi": os.system("pymain/multi.py") if input == "divide": os.system("pymain/divide.py") if input == "modulos": os.system("pymain/modulos.py") - else : - print "The script does not exists" # setup( # name="PyMaIn", # version="1.0.0", # author="Coding Smart School", # author_email="codingsmartschool@gmail.com", # url="https://github.com/codingsmartschool/pymain", # description="Python Math Input", # long_description=("PyMaIn is a python program that takes maths number" # " and give user the answer."), # classifiers=[ # 'Development Status :: 4 - Beta', # 'Programming Language :: Python', # ], # license="MIT", # packages=['pymain'], # )
Remove not found script message
## Code Before: import os __author__ = "Andre Christoga" input = raw_input("> (eg plus, minus, divide...)") if input == "plus": os.system("pymain/plus.py") if input == "minus": os.system("pymain/minus.py") if input == "multi": os.system("pymain/multi.py") if input == "divide": os.system("pymain/divide.py") if input == "modulos": os.system("pymain/modulos.py") else : print "The script does not exists" # setup( # name="PyMaIn", # version="1.0.0", # author="Coding Smart School", # author_email="codingsmartschool@gmail.com", # url="https://github.com/codingsmartschool/pymain", # description="Python Math Input", # long_description=("PyMaIn is a python program that takes maths number" # " and give user the answer."), # classifiers=[ # 'Development Status :: 4 - Beta', # 'Programming Language :: Python', # ], # license="MIT", # packages=['pymain'], # ) ## Instruction: Remove not found script message ## Code After: import os __author__ = "Andre Christoga" input = raw_input("> (eg plus, minus, divide...)") if input == "plus": os.system("pymain/plus.py") if input == "minus": os.system("pymain/minus.py") if input == "multi": os.system("pymain/multi.py") if input == "divide": os.system("pymain/divide.py") if input == "modulos": os.system("pymain/modulos.py") # setup( # name="PyMaIn", # version="1.0.0", # author="Coding Smart School", # author_email="codingsmartschool@gmail.com", # url="https://github.com/codingsmartschool/pymain", # description="Python Math Input", # long_description=("PyMaIn is a python program that takes maths number" # " and give user the answer."), # classifiers=[ # 'Development Status :: 4 - Beta', # 'Programming Language :: Python', # ], # license="MIT", # packages=['pymain'], # )
import os __author__ = "Andre Christoga" input = raw_input("> (eg plus, minus, divide...)") if input == "plus": os.system("pymain/plus.py") if input == "minus": os.system("pymain/minus.py") if input == "multi": os.system("pymain/multi.py") if input == "divide": os.system("pymain/divide.py") if input == "modulos": os.system("pymain/modulos.py") - else : - print "The script does not exists" # setup( # name="PyMaIn", # version="1.0.0", # author="Coding Smart School", # author_email="codingsmartschool@gmail.com", # url="https://github.com/codingsmartschool/pymain", # description="Python Math Input", # long_description=("PyMaIn is a python program that takes maths number" # " and give user the answer."), # classifiers=[ # 'Development Status :: 4 - Beta', # 'Programming Language :: Python', # ], # license="MIT", # packages=['pymain'], # )
3d4a71f6bb84fe4e5c7f51b109a55a7560ebb673
test/test_absolute_import.py
test/test_absolute_import.py
import jedi from jedi.parsing import Parser from . import base def test_explicit_absolute_imports(): """ Detect modules with ``from __future__ import absolute_import``. """ parser = Parser("from __future__ import absolute_import", "test.py") assert parser.scope.explicit_absolute_import def test_no_explicit_absolute_imports(): """ Detect modules without ``from __future__ import absolute_import``. """ parser = Parser("1", "test.py") assert not parser.scope.explicit_absolute_import def test_dont_break_imports_without_namespaces(): """ The code checking for ``from __future__ import absolute_import`` shouldn't assume that all imports have non-``None`` namespaces. """ src = "from __future__ import absolute_import\nimport xyzzy" parser = Parser(src, "test.py") assert parser.scope.explicit_absolute_import @base.cwd_at("test/absolute_import") def test_can_complete_when_shadowing(): filename = "unittest.py" with open(filename) as f: lines = f.readlines() src = "".join(lines) script = jedi.Script(src, len(lines), len(lines[1]), filename) assert script.completions()
import jedi from jedi.parsing import Parser from . import base def test_explicit_absolute_imports(): """ Detect modules with ``from __future__ import absolute_import``. """ parser = Parser("from __future__ import absolute_import", "test.py") assert parser.module.explicit_absolute_import def test_no_explicit_absolute_imports(): """ Detect modules without ``from __future__ import absolute_import``. """ parser = Parser("1", "test.py") assert not parser.module.explicit_absolute_import def test_dont_break_imports_without_namespaces(): """ The code checking for ``from __future__ import absolute_import`` shouldn't assume that all imports have non-``None`` namespaces. """ src = "from __future__ import absolute_import\nimport xyzzy" parser = Parser(src, "test.py") assert parser.module.explicit_absolute_import @base.cwd_at("test/absolute_import") def test_can_complete_when_shadowing(): filename = "unittest.py" with open(filename) as f: lines = f.readlines() src = "".join(lines) script = jedi.Script(src, len(lines), len(lines[1]), filename) assert script.completions()
Use Parser.module instead of Parser.scope
Use Parser.module instead of Parser.scope
Python
mit
jonashaag/jedi,WoLpH/jedi,tjwei/jedi,mfussenegger/jedi,dwillmer/jedi,tjwei/jedi,mfussenegger/jedi,WoLpH/jedi,jonashaag/jedi,flurischt/jedi,flurischt/jedi,dwillmer/jedi
import jedi from jedi.parsing import Parser from . import base def test_explicit_absolute_imports(): """ Detect modules with ``from __future__ import absolute_import``. """ parser = Parser("from __future__ import absolute_import", "test.py") - assert parser.scope.explicit_absolute_import + assert parser.module.explicit_absolute_import def test_no_explicit_absolute_imports(): """ Detect modules without ``from __future__ import absolute_import``. """ parser = Parser("1", "test.py") - assert not parser.scope.explicit_absolute_import + assert not parser.module.explicit_absolute_import def test_dont_break_imports_without_namespaces(): """ The code checking for ``from __future__ import absolute_import`` shouldn't assume that all imports have non-``None`` namespaces. """ src = "from __future__ import absolute_import\nimport xyzzy" parser = Parser(src, "test.py") - assert parser.scope.explicit_absolute_import + assert parser.module.explicit_absolute_import @base.cwd_at("test/absolute_import") def test_can_complete_when_shadowing(): filename = "unittest.py" with open(filename) as f: lines = f.readlines() src = "".join(lines) script = jedi.Script(src, len(lines), len(lines[1]), filename) assert script.completions()
Use Parser.module instead of Parser.scope
## Code Before: import jedi from jedi.parsing import Parser from . import base def test_explicit_absolute_imports(): """ Detect modules with ``from __future__ import absolute_import``. """ parser = Parser("from __future__ import absolute_import", "test.py") assert parser.scope.explicit_absolute_import def test_no_explicit_absolute_imports(): """ Detect modules without ``from __future__ import absolute_import``. """ parser = Parser("1", "test.py") assert not parser.scope.explicit_absolute_import def test_dont_break_imports_without_namespaces(): """ The code checking for ``from __future__ import absolute_import`` shouldn't assume that all imports have non-``None`` namespaces. """ src = "from __future__ import absolute_import\nimport xyzzy" parser = Parser(src, "test.py") assert parser.scope.explicit_absolute_import @base.cwd_at("test/absolute_import") def test_can_complete_when_shadowing(): filename = "unittest.py" with open(filename) as f: lines = f.readlines() src = "".join(lines) script = jedi.Script(src, len(lines), len(lines[1]), filename) assert script.completions() ## Instruction: Use Parser.module instead of Parser.scope ## Code After: import jedi from jedi.parsing import Parser from . import base def test_explicit_absolute_imports(): """ Detect modules with ``from __future__ import absolute_import``. """ parser = Parser("from __future__ import absolute_import", "test.py") assert parser.module.explicit_absolute_import def test_no_explicit_absolute_imports(): """ Detect modules without ``from __future__ import absolute_import``. """ parser = Parser("1", "test.py") assert not parser.module.explicit_absolute_import def test_dont_break_imports_without_namespaces(): """ The code checking for ``from __future__ import absolute_import`` shouldn't assume that all imports have non-``None`` namespaces. """ src = "from __future__ import absolute_import\nimport xyzzy" parser = Parser(src, "test.py") assert parser.module.explicit_absolute_import @base.cwd_at("test/absolute_import") def test_can_complete_when_shadowing(): filename = "unittest.py" with open(filename) as f: lines = f.readlines() src = "".join(lines) script = jedi.Script(src, len(lines), len(lines[1]), filename) assert script.completions()
import jedi from jedi.parsing import Parser from . import base def test_explicit_absolute_imports(): """ Detect modules with ``from __future__ import absolute_import``. """ parser = Parser("from __future__ import absolute_import", "test.py") - assert parser.scope.explicit_absolute_import ? ^^ ^ + assert parser.module.explicit_absolute_import ? ^ ^^^ def test_no_explicit_absolute_imports(): """ Detect modules without ``from __future__ import absolute_import``. """ parser = Parser("1", "test.py") - assert not parser.scope.explicit_absolute_import ? ^^ ^ + assert not parser.module.explicit_absolute_import ? ^ ^^^ def test_dont_break_imports_without_namespaces(): """ The code checking for ``from __future__ import absolute_import`` shouldn't assume that all imports have non-``None`` namespaces. """ src = "from __future__ import absolute_import\nimport xyzzy" parser = Parser(src, "test.py") - assert parser.scope.explicit_absolute_import ? ^^ ^ + assert parser.module.explicit_absolute_import ? ^ ^^^ @base.cwd_at("test/absolute_import") def test_can_complete_when_shadowing(): filename = "unittest.py" with open(filename) as f: lines = f.readlines() src = "".join(lines) script = jedi.Script(src, len(lines), len(lines[1]), filename) assert script.completions()
c0eb0f902b0fcbea29c8a3bf70f80ca9384cce9f
scripts/remove_after_use/send_mendeley_reauth_email.py
scripts/remove_after_use/send_mendeley_reauth_email.py
import sys import logging from website.app import setup_django setup_django() from website import mails from osf.models import OSFUser from addons.mendeley.models import UserSettings import progressbar from scripts import utils as script_utils logger = logging.getLogger(__name__) def main(dry=True): user = OSFUser.load('qrgl2') qs = UserSettings.objects.filter(owner__is_active=True).select_related('owner') pbar = progressbar.ProgressBar(maxval=qs.count()).start() for i, each in enumerate(qs): user = each.owner logger.info('Sending email to OSFUser {}'.format(user._id)) if not dry: mails.send_mail( mail=mails.MENDELEY_REAUTH, to_addr=user.username, can_change_preferences=False, user=user ) pbar.update(i + 1) if __name__ == '__main__': dry = '--dry' in sys.argv if not dry: script_utils.add_file_logger(logger, __file__) main(dry=dry)
import sys import logging from website.app import setup_django setup_django() from website import mails from osf.models import OSFUser from addons.mendeley.models import UserSettings import progressbar from scripts import utils as script_utils logger = logging.getLogger(__name__) def main(dry=True): qs = UserSettings.objects.filter(owner__is_active=True).select_related('owner').order_by('pk') count = qs.count() pbar = progressbar.ProgressBar(maxval=count).start() logger.info('Sending email to {} users'.format(count)) for i, each in enumerate(qs): user = each.owner logger.info('Sending email to OSFUser {}'.format(user._id)) if not dry: mails.send_mail( mail=mails.MENDELEY_REAUTH, to_addr=user.username, can_change_preferences=False, user=user ) pbar.update(i + 1) logger.info('Sent email to {} users'.format(count)) if __name__ == '__main__': dry = '--dry' in sys.argv if not dry: script_utils.add_file_logger(logger, __file__) main(dry=dry)
Remove junk and add more logging
Remove junk and add more logging
Python
apache-2.0
cslzchen/osf.io,icereval/osf.io,brianjgeiger/osf.io,mattclark/osf.io,pattisdr/osf.io,Johnetordoff/osf.io,baylee-d/osf.io,adlius/osf.io,cslzchen/osf.io,mattclark/osf.io,saradbowman/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,adlius/osf.io,mfraezz/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,icereval/osf.io,erinspace/osf.io,felliott/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,saradbowman/osf.io,felliott/osf.io,Johnetordoff/osf.io,caseyrollins/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,caseyrollins/osf.io,HalcyonChimera/osf.io,HalcyonChimera/osf.io,aaxelb/osf.io,cslzchen/osf.io,baylee-d/osf.io,felliott/osf.io,mfraezz/osf.io,pattisdr/osf.io,sloria/osf.io,felliott/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,sloria/osf.io,icereval/osf.io,sloria/osf.io,cslzchen/osf.io,caseyrollins/osf.io,erinspace/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,CenterForOpenScience/osf.io,mattclark/osf.io,erinspace/osf.io,adlius/osf.io,adlius/osf.io,HalcyonChimera/osf.io
import sys import logging from website.app import setup_django setup_django() from website import mails from osf.models import OSFUser from addons.mendeley.models import UserSettings import progressbar from scripts import utils as script_utils logger = logging.getLogger(__name__) def main(dry=True): - user = OSFUser.load('qrgl2') - qs = UserSettings.objects.filter(owner__is_active=True).select_related('owner') + qs = UserSettings.objects.filter(owner__is_active=True).select_related('owner').order_by('pk') + count = qs.count() - pbar = progressbar.ProgressBar(maxval=qs.count()).start() + pbar = progressbar.ProgressBar(maxval=count).start() + logger.info('Sending email to {} users'.format(count)) for i, each in enumerate(qs): user = each.owner logger.info('Sending email to OSFUser {}'.format(user._id)) if not dry: mails.send_mail( mail=mails.MENDELEY_REAUTH, to_addr=user.username, can_change_preferences=False, user=user ) pbar.update(i + 1) + logger.info('Sent email to {} users'.format(count)) if __name__ == '__main__': dry = '--dry' in sys.argv if not dry: script_utils.add_file_logger(logger, __file__) main(dry=dry)
Remove junk and add more logging
## Code Before: import sys import logging from website.app import setup_django setup_django() from website import mails from osf.models import OSFUser from addons.mendeley.models import UserSettings import progressbar from scripts import utils as script_utils logger = logging.getLogger(__name__) def main(dry=True): user = OSFUser.load('qrgl2') qs = UserSettings.objects.filter(owner__is_active=True).select_related('owner') pbar = progressbar.ProgressBar(maxval=qs.count()).start() for i, each in enumerate(qs): user = each.owner logger.info('Sending email to OSFUser {}'.format(user._id)) if not dry: mails.send_mail( mail=mails.MENDELEY_REAUTH, to_addr=user.username, can_change_preferences=False, user=user ) pbar.update(i + 1) if __name__ == '__main__': dry = '--dry' in sys.argv if not dry: script_utils.add_file_logger(logger, __file__) main(dry=dry) ## Instruction: Remove junk and add more logging ## Code After: import sys import logging from website.app import setup_django setup_django() from website import mails from osf.models import OSFUser from addons.mendeley.models import UserSettings import progressbar from scripts import utils as script_utils logger = logging.getLogger(__name__) def main(dry=True): qs = UserSettings.objects.filter(owner__is_active=True).select_related('owner').order_by('pk') count = qs.count() pbar = progressbar.ProgressBar(maxval=count).start() logger.info('Sending email to {} users'.format(count)) for i, each in enumerate(qs): user = each.owner logger.info('Sending email to OSFUser {}'.format(user._id)) if not dry: mails.send_mail( mail=mails.MENDELEY_REAUTH, to_addr=user.username, can_change_preferences=False, user=user ) pbar.update(i + 1) logger.info('Sent email to {} users'.format(count)) if __name__ == '__main__': dry = '--dry' in sys.argv if not dry: script_utils.add_file_logger(logger, __file__) main(dry=dry)
import sys import logging from website.app import setup_django setup_django() from website import mails from osf.models import OSFUser from addons.mendeley.models import UserSettings import progressbar from scripts import utils as script_utils logger = logging.getLogger(__name__) def main(dry=True): - user = OSFUser.load('qrgl2') - qs = UserSettings.objects.filter(owner__is_active=True).select_related('owner') + qs = UserSettings.objects.filter(owner__is_active=True).select_related('owner').order_by('pk') ? +++++++++++++++ + count = qs.count() - pbar = progressbar.ProgressBar(maxval=qs.count()).start() ? --- -- + pbar = progressbar.ProgressBar(maxval=count).start() + logger.info('Sending email to {} users'.format(count)) for i, each in enumerate(qs): user = each.owner logger.info('Sending email to OSFUser {}'.format(user._id)) if not dry: mails.send_mail( mail=mails.MENDELEY_REAUTH, to_addr=user.username, can_change_preferences=False, user=user ) pbar.update(i + 1) + logger.info('Sent email to {} users'.format(count)) if __name__ == '__main__': dry = '--dry' in sys.argv if not dry: script_utils.add_file_logger(logger, __file__) main(dry=dry)
d703d7cb8d75a5c660beabccdd0082794a8471d1
edisgo/tools/networkx_helper.py
edisgo/tools/networkx_helper.py
from networkx import OrderedGraph def translate_df_to_graph(buses_df, lines_df, transformers_df=None): graph = OrderedGraph() buses = buses_df.index # add nodes graph.add_nodes_from(buses) # add branches branches = [] for line_name, line in lines_df.iterrows(): branches.append( ( line.bus0, line.bus1, {"branch_name": line_name, "length": line.length}, ) ) if transformers_df is not None: for trafo_name, trafo in transformers_df.iterrows(): branches.append( ( trafo.bus0, trafo.bus1, {"branch_name": trafo_name, "length": 0}, ) ) graph.add_edges_from(branches) return graph
from networkx import Graph def translate_df_to_graph(buses_df, lines_df, transformers_df=None): graph = Graph() buses = [] for bus_name, bus in buses_df.iterrows(): pos = (bus.x, bus.y) buses.append((bus_name, {'pos': pos})) # add nodes graph.add_nodes_from(buses) # add branches branches = [] for line_name, line in lines_df.iterrows(): branches.append( ( line.bus0, line.bus1, {"branch_name": line_name, "length": line.length}, ) ) if transformers_df is not None: for trafo_name, trafo in transformers_df.iterrows(): branches.append( ( trafo.bus0, trafo.bus1, {"branch_name": trafo_name, "length": 0}, ) ) graph.add_edges_from(branches) return graph
Include the position into the graph
Include the position into the graph
Python
agpl-3.0
openego/eDisGo,openego/eDisGo
- from networkx import OrderedGraph + from networkx import Graph def translate_df_to_graph(buses_df, lines_df, transformers_df=None): - graph = OrderedGraph() + graph = Graph() - buses = buses_df.index + buses = [] + for bus_name, bus in buses_df.iterrows(): + pos = (bus.x, bus.y) + buses.append((bus_name, {'pos': pos})) - # add nodes + # add nodes graph.add_nodes_from(buses) # add branches branches = [] for line_name, line in lines_df.iterrows(): branches.append( ( line.bus0, line.bus1, {"branch_name": line_name, "length": line.length}, ) ) if transformers_df is not None: for trafo_name, trafo in transformers_df.iterrows(): branches.append( ( trafo.bus0, trafo.bus1, {"branch_name": trafo_name, "length": 0}, ) ) graph.add_edges_from(branches) return graph
Include the position into the graph
## Code Before: from networkx import OrderedGraph def translate_df_to_graph(buses_df, lines_df, transformers_df=None): graph = OrderedGraph() buses = buses_df.index # add nodes graph.add_nodes_from(buses) # add branches branches = [] for line_name, line in lines_df.iterrows(): branches.append( ( line.bus0, line.bus1, {"branch_name": line_name, "length": line.length}, ) ) if transformers_df is not None: for trafo_name, trafo in transformers_df.iterrows(): branches.append( ( trafo.bus0, trafo.bus1, {"branch_name": trafo_name, "length": 0}, ) ) graph.add_edges_from(branches) return graph ## Instruction: Include the position into the graph ## Code After: from networkx import Graph def translate_df_to_graph(buses_df, lines_df, transformers_df=None): graph = Graph() buses = [] for bus_name, bus in buses_df.iterrows(): pos = (bus.x, bus.y) buses.append((bus_name, {'pos': pos})) # add nodes graph.add_nodes_from(buses) # add branches branches = [] for line_name, line in lines_df.iterrows(): branches.append( ( line.bus0, line.bus1, {"branch_name": line_name, "length": line.length}, ) ) if transformers_df is not None: for trafo_name, trafo in transformers_df.iterrows(): branches.append( ( trafo.bus0, trafo.bus1, {"branch_name": trafo_name, "length": 0}, ) ) graph.add_edges_from(branches) return graph
- from networkx import OrderedGraph ? ------- + from networkx import Graph def translate_df_to_graph(buses_df, lines_df, transformers_df=None): - graph = OrderedGraph() ? ------- + graph = Graph() - buses = buses_df.index + buses = [] + for bus_name, bus in buses_df.iterrows(): + pos = (bus.x, bus.y) + buses.append((bus_name, {'pos': pos})) - # add nodes + # add nodes ? ++++ graph.add_nodes_from(buses) # add branches branches = [] for line_name, line in lines_df.iterrows(): branches.append( ( line.bus0, line.bus1, {"branch_name": line_name, "length": line.length}, ) ) if transformers_df is not None: for trafo_name, trafo in transformers_df.iterrows(): branches.append( ( trafo.bus0, trafo.bus1, {"branch_name": trafo_name, "length": 0}, ) ) graph.add_edges_from(branches) return graph
e07f095944a0a6edd125d75f4980a45fc10c6dfd
wiblog/util/comments.py
wiblog/util/comments.py
from fragdev.contact import validate_ham from django.forms import ModelForm from django import forms from wiblog.models import Comment class CommentForm(ModelForm): verify = forms.CharField(label='Anti-spam: Type in the word "power"',validators=[validate_ham],max_length=5) class Meta: model = Comment fields = ('name', 'url', 'comment')
from django.forms import ModelForm from django import forms from fragdev.util.validate_ham import ANTI_SPAM, validate_ham from wiblog.models import Comment class CommentForm(ModelForm): verify = forms.CharField(label='Anti-spam: Type in the word "{}"'\ .format(ANTI_SPAM), validators=[validate_ham], max_length=len(ANTI_SPAM)) class Meta: model = Comment fields = ('name', 'url', 'comment')
Fix wiblog's use of the anti-spam validator
Fix wiblog's use of the anti-spam validator
Python
agpl-3.0
lo-windigo/fragdev,lo-windigo/fragdev
- from fragdev.contact import validate_ham from django.forms import ModelForm from django import forms + from fragdev.util.validate_ham import ANTI_SPAM, validate_ham from wiblog.models import Comment class CommentForm(ModelForm): - verify = forms.CharField(label='Anti-spam: Type in the word "power"',validators=[validate_ham],max_length=5) + verify = forms.CharField(label='Anti-spam: Type in the word "{}"'\ + .format(ANTI_SPAM), + validators=[validate_ham], + max_length=len(ANTI_SPAM)) class Meta: model = Comment fields = ('name', 'url', 'comment')
Fix wiblog's use of the anti-spam validator
## Code Before: from fragdev.contact import validate_ham from django.forms import ModelForm from django import forms from wiblog.models import Comment class CommentForm(ModelForm): verify = forms.CharField(label='Anti-spam: Type in the word "power"',validators=[validate_ham],max_length=5) class Meta: model = Comment fields = ('name', 'url', 'comment') ## Instruction: Fix wiblog's use of the anti-spam validator ## Code After: from django.forms import ModelForm from django import forms from fragdev.util.validate_ham import ANTI_SPAM, validate_ham from wiblog.models import Comment class CommentForm(ModelForm): verify = forms.CharField(label='Anti-spam: Type in the word "{}"'\ .format(ANTI_SPAM), validators=[validate_ham], max_length=len(ANTI_SPAM)) class Meta: model = Comment fields = ('name', 'url', 'comment')
- from fragdev.contact import validate_ham from django.forms import ModelForm from django import forms + from fragdev.util.validate_ham import ANTI_SPAM, validate_ham from wiblog.models import Comment class CommentForm(ModelForm): - verify = forms.CharField(label='Anti-spam: Type in the word "power"',validators=[validate_ham],max_length=5) + verify = forms.CharField(label='Anti-spam: Type in the word "{}"'\ + .format(ANTI_SPAM), + validators=[validate_ham], + max_length=len(ANTI_SPAM)) class Meta: model = Comment fields = ('name', 'url', 'comment')
20df58bb9e605ecc53848ade31a3acb98118f00b
scripts/extract_clips_from_hdf5_file.py
scripts/extract_clips_from_hdf5_file.py
from pathlib import Path import wave import h5py DIR_PATH = Path('/Users/harold/Desktop/Clips') INPUT_FILE_PATH = DIR_PATH / 'Clips.h5' CLIP_COUNT = 5 def main(): with h5py.File(INPUT_FILE_PATH, 'r') as file_: clip_group = file_['clips'] for i, clip_id in enumerate(clip_group): if i == CLIP_COUNT: break samples, sample_rate = read_clip(clip_group, clip_id) print(clip_id, len(samples), samples.dtype, sample_rate) write_wave_file(clip_id, samples, sample_rate) def read_clip(clip_group, clip_id): clip = clip_group[clip_id] samples = clip[:] sample_rate = clip.attrs['sample_rate'] return samples, sample_rate def write_wave_file(i, samples, sample_rate): file_name = f'{i}.wav' file_path = DIR_PATH / file_name with wave.open(str(file_path), 'wb') as file_: file_.setparams((1, 2, sample_rate, len(samples), 'NONE', '')) file_.writeframes(samples.tobytes()) if __name__ == '__main__': main()
from pathlib import Path import wave import h5py DIR_PATH = Path('/Users/harold/Desktop/Clips') INPUT_FILE_PATH = DIR_PATH / 'Clips.h5' CLIP_COUNT = 5 def main(): with h5py.File(INPUT_FILE_PATH, 'r') as file_: clip_group = file_['clips'] for i, clip_id in enumerate(clip_group): if i == CLIP_COUNT: break samples, attributes = read_clip(clip_group, clip_id) show_clip(clip_id, samples, attributes) write_wave_file(clip_id, samples, attributes['sample_rate']) def read_clip(clip_group, clip_id): clip = clip_group[clip_id] samples = clip[:] attributes = dict((name, value) for name, value in clip.attrs.items()) return samples, attributes def show_clip(clip_id, samples, attributes): print(f'clip {clip_id}:') print(f' length: {len(samples)}') print(' attributes:') for key in sorted(attributes.keys()): value = attributes[key] print(f' {key}: {value}') print() def write_wave_file(i, samples, sample_rate): file_name = f'{i}.wav' file_path = DIR_PATH / file_name with wave.open(str(file_path), 'wb') as file_: file_.setparams((1, 2, sample_rate, len(samples), 'NONE', '')) file_.writeframes(samples.tobytes()) if __name__ == '__main__': main()
Add attribute display to clip extraction script.
Add attribute display to clip extraction script.
Python
mit
HaroldMills/Vesper,HaroldMills/Vesper,HaroldMills/Vesper,HaroldMills/Vesper,HaroldMills/Vesper
from pathlib import Path import wave import h5py DIR_PATH = Path('/Users/harold/Desktop/Clips') INPUT_FILE_PATH = DIR_PATH / 'Clips.h5' CLIP_COUNT = 5 def main(): with h5py.File(INPUT_FILE_PATH, 'r') as file_: clip_group = file_['clips'] for i, clip_id in enumerate(clip_group): if i == CLIP_COUNT: break - samples, sample_rate = read_clip(clip_group, clip_id) + samples, attributes = read_clip(clip_group, clip_id) - print(clip_id, len(samples), samples.dtype, sample_rate) + show_clip(clip_id, samples, attributes) - write_wave_file(clip_id, samples, sample_rate) + write_wave_file(clip_id, samples, attributes['sample_rate']) def read_clip(clip_group, clip_id): clip = clip_group[clip_id] samples = clip[:] - sample_rate = clip.attrs['sample_rate'] + attributes = dict((name, value) for name, value in clip.attrs.items()) - return samples, sample_rate + return samples, attributes + + def show_clip(clip_id, samples, attributes): + print(f'clip {clip_id}:') + print(f' length: {len(samples)}') + print(' attributes:') + for key in sorted(attributes.keys()): + value = attributes[key] + print(f' {key}: {value}') + print() + def write_wave_file(i, samples, sample_rate): file_name = f'{i}.wav' file_path = DIR_PATH / file_name with wave.open(str(file_path), 'wb') as file_: file_.setparams((1, 2, sample_rate, len(samples), 'NONE', '')) file_.writeframes(samples.tobytes()) if __name__ == '__main__': main()
Add attribute display to clip extraction script.
## Code Before: from pathlib import Path import wave import h5py DIR_PATH = Path('/Users/harold/Desktop/Clips') INPUT_FILE_PATH = DIR_PATH / 'Clips.h5' CLIP_COUNT = 5 def main(): with h5py.File(INPUT_FILE_PATH, 'r') as file_: clip_group = file_['clips'] for i, clip_id in enumerate(clip_group): if i == CLIP_COUNT: break samples, sample_rate = read_clip(clip_group, clip_id) print(clip_id, len(samples), samples.dtype, sample_rate) write_wave_file(clip_id, samples, sample_rate) def read_clip(clip_group, clip_id): clip = clip_group[clip_id] samples = clip[:] sample_rate = clip.attrs['sample_rate'] return samples, sample_rate def write_wave_file(i, samples, sample_rate): file_name = f'{i}.wav' file_path = DIR_PATH / file_name with wave.open(str(file_path), 'wb') as file_: file_.setparams((1, 2, sample_rate, len(samples), 'NONE', '')) file_.writeframes(samples.tobytes()) if __name__ == '__main__': main() ## Instruction: Add attribute display to clip extraction script. ## Code After: from pathlib import Path import wave import h5py DIR_PATH = Path('/Users/harold/Desktop/Clips') INPUT_FILE_PATH = DIR_PATH / 'Clips.h5' CLIP_COUNT = 5 def main(): with h5py.File(INPUT_FILE_PATH, 'r') as file_: clip_group = file_['clips'] for i, clip_id in enumerate(clip_group): if i == CLIP_COUNT: break samples, attributes = read_clip(clip_group, clip_id) show_clip(clip_id, samples, attributes) write_wave_file(clip_id, samples, attributes['sample_rate']) def read_clip(clip_group, clip_id): clip = clip_group[clip_id] samples = clip[:] attributes = dict((name, value) for name, value in clip.attrs.items()) return samples, attributes def show_clip(clip_id, samples, attributes): print(f'clip {clip_id}:') print(f' length: {len(samples)}') print(' attributes:') for key in sorted(attributes.keys()): value = attributes[key] print(f' {key}: {value}') print() def write_wave_file(i, samples, sample_rate): file_name = f'{i}.wav' file_path = DIR_PATH / file_name with wave.open(str(file_path), 'wb') as file_: file_.setparams((1, 2, sample_rate, len(samples), 'NONE', '')) file_.writeframes(samples.tobytes()) if __name__ == '__main__': main()
from pathlib import Path import wave import h5py DIR_PATH = Path('/Users/harold/Desktop/Clips') INPUT_FILE_PATH = DIR_PATH / 'Clips.h5' CLIP_COUNT = 5 def main(): with h5py.File(INPUT_FILE_PATH, 'r') as file_: clip_group = file_['clips'] for i, clip_id in enumerate(clip_group): if i == CLIP_COUNT: break - samples, sample_rate = read_clip(clip_group, clip_id) ? -------- + samples, attributes = read_clip(clip_group, clip_id) ? ++++++ + - print(clip_id, len(samples), samples.dtype, sample_rate) + show_clip(clip_id, samples, attributes) - write_wave_file(clip_id, samples, sample_rate) + write_wave_file(clip_id, samples, attributes['sample_rate']) ? ++++++++++++ ++ def read_clip(clip_group, clip_id): clip = clip_group[clip_id] samples = clip[:] - sample_rate = clip.attrs['sample_rate'] + attributes = dict((name, value) for name, value in clip.attrs.items()) - return samples, sample_rate ? -------- + return samples, attributes ? ++++++ + + + def show_clip(clip_id, samples, attributes): + print(f'clip {clip_id}:') + print(f' length: {len(samples)}') + print(' attributes:') + for key in sorted(attributes.keys()): + value = attributes[key] + print(f' {key}: {value}') + print() + def write_wave_file(i, samples, sample_rate): file_name = f'{i}.wav' file_path = DIR_PATH / file_name with wave.open(str(file_path), 'wb') as file_: file_.setparams((1, 2, sample_rate, len(samples), 'NONE', '')) file_.writeframes(samples.tobytes()) if __name__ == '__main__': main()
63f40971f8bc4858b32b41595d14315d2261169f
proselint/checks/garner/mondegreens.py
proselint/checks/garner/mondegreens.py
from tools import memoize, preferred_forms_check @memoize def check(text): """Suggest the preferred forms.""" err = "garner.mondegreens" msg = "'{}' is the preferred form." list = [ ["a girl with colitis goes by", "a girl with kaleidascope eyes"], ["a partridge in a pear tree", "a part-red gingerbread tree"], ["attorney and not a republic", "attorney and notary public"], ["beck and call", "beckon call"], ["for all intents and purposes", "for all intensive purposes"], ["laid him on the green", "Lady Mondegreen"], ["Olive, the other reindeer", "all of the other reindeer"], ["to the manner born", "to the manor born"], ] return preferred_forms_check(text, list, err, msg)
from tools import memoize, preferred_forms_check @memoize def check(text): """Suggest the preferred forms.""" err = "garner.mondegreens" msg = "'{}' is the preferred form." list = [ ["a girl with kaleidascope eyes", "a girl with colitis goes by"], ["a partridge in a pear tree", "a part-red gingerbread tree"], ["attorney and not a republic", "attorney and notary public"], ["beck and call", "beckon call"], ["for all intents and purposes", "for all intensive purposes"], ["laid him on the green", "Lady Mondegreen"], ["Olive, the other reindeer", "all of the other reindeer"], ["to the manner born", "to the manor born"], ] return preferred_forms_check(text, list, err, msg)
Fix bug in mondegreen rule
Fix bug in mondegreen rule (The correct versions should all be in the left column.)
Python
bsd-3-clause
jstewmon/proselint,jstewmon/proselint,amperser/proselint,amperser/proselint,jstewmon/proselint,amperser/proselint,amperser/proselint,amperser/proselint
from tools import memoize, preferred_forms_check @memoize def check(text): """Suggest the preferred forms.""" err = "garner.mondegreens" msg = "'{}' is the preferred form." list = [ - ["a girl with colitis goes by", "a girl with kaleidascope eyes"], + ["a girl with kaleidascope eyes", "a girl with colitis goes by"], - ["a partridge in a pear tree", "a part-red gingerbread tree"], + ["a partridge in a pear tree", "a part-red gingerbread tree"], - ["attorney and not a republic", "attorney and notary public"], + ["attorney and not a republic", "attorney and notary public"], - ["beck and call", "beckon call"], + ["beck and call", "beckon call"], - ["for all intents and purposes", "for all intensive purposes"], + ["for all intents and purposes", "for all intensive purposes"], - ["laid him on the green", "Lady Mondegreen"], + ["laid him on the green", "Lady Mondegreen"], - ["Olive, the other reindeer", "all of the other reindeer"], + ["Olive, the other reindeer", "all of the other reindeer"], - ["to the manner born", "to the manor born"], + ["to the manner born", "to the manor born"], ] return preferred_forms_check(text, list, err, msg)
Fix bug in mondegreen rule
## Code Before: from tools import memoize, preferred_forms_check @memoize def check(text): """Suggest the preferred forms.""" err = "garner.mondegreens" msg = "'{}' is the preferred form." list = [ ["a girl with colitis goes by", "a girl with kaleidascope eyes"], ["a partridge in a pear tree", "a part-red gingerbread tree"], ["attorney and not a republic", "attorney and notary public"], ["beck and call", "beckon call"], ["for all intents and purposes", "for all intensive purposes"], ["laid him on the green", "Lady Mondegreen"], ["Olive, the other reindeer", "all of the other reindeer"], ["to the manner born", "to the manor born"], ] return preferred_forms_check(text, list, err, msg) ## Instruction: Fix bug in mondegreen rule ## Code After: from tools import memoize, preferred_forms_check @memoize def check(text): """Suggest the preferred forms.""" err = "garner.mondegreens" msg = "'{}' is the preferred form." list = [ ["a girl with kaleidascope eyes", "a girl with colitis goes by"], ["a partridge in a pear tree", "a part-red gingerbread tree"], ["attorney and not a republic", "attorney and notary public"], ["beck and call", "beckon call"], ["for all intents and purposes", "for all intensive purposes"], ["laid him on the green", "Lady Mondegreen"], ["Olive, the other reindeer", "all of the other reindeer"], ["to the manner born", "to the manor born"], ] return preferred_forms_check(text, list, err, msg)
from tools import memoize, preferred_forms_check @memoize def check(text): """Suggest the preferred forms.""" err = "garner.mondegreens" msg = "'{}' is the preferred form." list = [ - ["a girl with colitis goes by", "a girl with kaleidascope eyes"], + ["a girl with kaleidascope eyes", "a girl with colitis goes by"], - ["a partridge in a pear tree", "a part-red gingerbread tree"], + ["a partridge in a pear tree", "a part-red gingerbread tree"], ? + - ["attorney and not a republic", "attorney and notary public"], + ["attorney and not a republic", "attorney and notary public"], ? + - ["beck and call", "beckon call"], + ["beck and call", "beckon call"], ? + - ["for all intents and purposes", "for all intensive purposes"], + ["for all intents and purposes", "for all intensive purposes"], ? + - ["laid him on the green", "Lady Mondegreen"], + ["laid him on the green", "Lady Mondegreen"], ? + - ["Olive, the other reindeer", "all of the other reindeer"], + ["Olive, the other reindeer", "all of the other reindeer"], ? + - ["to the manner born", "to the manor born"], + ["to the manner born", "to the manor born"], ? + ] return preferred_forms_check(text, list, err, msg)
1ee1a337cb3094ae5a5cc79b6d4c62c2f7f64dc3
setup.py
setup.py
from distutils.core import setup setup( name='dbtools', version=open("VERSION.txt").read().strip(), description='Lightweight SQLite interface', author='Jessica B. Hamrick', author_email='jhamrick@berkeley.edu', url='https://github.com/jhamrick/dbtools', packages=['dbtools'], keywords='sqlite pandas dataframe', classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: SQL", "Topic :: Database :: Front-Ends", "Topic :: Utilities", ], install_requires=[ 'pandas', 'numpy' ] )
from distutils.core import setup setup( name='dbtools', version=open("VERSION.txt").read().strip(), description='Lightweight SQLite interface', author='Jessica B. Hamrick', author_email='jhamrick@berkeley.edu', url='https://github.com/jhamrick/dbtools', packages=['dbtools'], keywords='sqlite pandas dataframe', classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: SQL", "Topic :: Database :: Front-Ends", "Topic :: Utilities", ], install_requires=[ 'pandas', 'numpy' ] )
Add trove classifier for Python 3
Add trove classifier for Python 3
Python
mit
jhamrick/dbtools,jhamrick/dbtools
from distutils.core import setup setup( name='dbtools', version=open("VERSION.txt").read().strip(), description='Lightweight SQLite interface', author='Jessica B. Hamrick', author_email='jhamrick@berkeley.edu', url='https://github.com/jhamrick/dbtools', packages=['dbtools'], keywords='sqlite pandas dataframe', classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3", "Programming Language :: SQL", "Topic :: Database :: Front-Ends", "Topic :: Utilities", ], install_requires=[ 'pandas', 'numpy' ] )
Add trove classifier for Python 3
## Code Before: from distutils.core import setup setup( name='dbtools', version=open("VERSION.txt").read().strip(), description='Lightweight SQLite interface', author='Jessica B. Hamrick', author_email='jhamrick@berkeley.edu', url='https://github.com/jhamrick/dbtools', packages=['dbtools'], keywords='sqlite pandas dataframe', classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: SQL", "Topic :: Database :: Front-Ends", "Topic :: Utilities", ], install_requires=[ 'pandas', 'numpy' ] ) ## Instruction: Add trove classifier for Python 3 ## Code After: from distutils.core import setup setup( name='dbtools', version=open("VERSION.txt").read().strip(), description='Lightweight SQLite interface', author='Jessica B. Hamrick', author_email='jhamrick@berkeley.edu', url='https://github.com/jhamrick/dbtools', packages=['dbtools'], keywords='sqlite pandas dataframe', classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: SQL", "Topic :: Database :: Front-Ends", "Topic :: Utilities", ], install_requires=[ 'pandas', 'numpy' ] )
from distutils.core import setup setup( name='dbtools', version=open("VERSION.txt").read().strip(), description='Lightweight SQLite interface', author='Jessica B. Hamrick', author_email='jhamrick@berkeley.edu', url='https://github.com/jhamrick/dbtools', packages=['dbtools'], keywords='sqlite pandas dataframe', classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3", "Programming Language :: SQL", "Topic :: Database :: Front-Ends", "Topic :: Utilities", ], install_requires=[ 'pandas', 'numpy' ] )
28c8dfd6e3da8525d8379a46244a510db9c34aa5
pytablewriter/writer/text/_spacealigned.py
pytablewriter/writer/text/_spacealigned.py
import copy import dataproperty from ._csv import CsvTableWriter class SpaceAlignedTableWriter(CsvTableWriter): """ A table writer class for space aligned format. :Example: :ref:`example-space-aligned-table-writer` .. py:method:: write_table |write_table| with space aligned format. :Example: :ref:`example-space-aligned-table-writer` """ FORMAT_NAME = "space_aligned" @property def format_name(self) -> str: return self.FORMAT_NAME def __init__(self) -> None: super().__init__() self.column_delimiter = " " self.is_padding = True self.is_formatting_float = True self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS)
import copy import dataproperty from ._csv import CsvTableWriter class SpaceAlignedTableWriter(CsvTableWriter): """ A table writer class for space aligned format. :Example: :ref:`example-space-aligned-table-writer` .. py:method:: write_table |write_table| with space aligned format. :Example: :ref:`example-space-aligned-table-writer` """ FORMAT_NAME = "space_aligned" @property def format_name(self) -> str: return self.FORMAT_NAME def __init__(self) -> None: super().__init__() self.column_delimiter = " " self.char_cross_point = " " self.is_padding = True self.is_formatting_float = True self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS)
Fix constructor for SpaceAlignedTableWriter class
Fix constructor for SpaceAlignedTableWriter class
Python
mit
thombashi/pytablewriter
import copy import dataproperty from ._csv import CsvTableWriter class SpaceAlignedTableWriter(CsvTableWriter): """ A table writer class for space aligned format. :Example: :ref:`example-space-aligned-table-writer` .. py:method:: write_table |write_table| with space aligned format. :Example: :ref:`example-space-aligned-table-writer` """ FORMAT_NAME = "space_aligned" @property def format_name(self) -> str: return self.FORMAT_NAME def __init__(self) -> None: super().__init__() self.column_delimiter = " " + self.char_cross_point = " " + self.is_padding = True self.is_formatting_float = True self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS)
Fix constructor for SpaceAlignedTableWriter class
## Code Before: import copy import dataproperty from ._csv import CsvTableWriter class SpaceAlignedTableWriter(CsvTableWriter): """ A table writer class for space aligned format. :Example: :ref:`example-space-aligned-table-writer` .. py:method:: write_table |write_table| with space aligned format. :Example: :ref:`example-space-aligned-table-writer` """ FORMAT_NAME = "space_aligned" @property def format_name(self) -> str: return self.FORMAT_NAME def __init__(self) -> None: super().__init__() self.column_delimiter = " " self.is_padding = True self.is_formatting_float = True self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS) ## Instruction: Fix constructor for SpaceAlignedTableWriter class ## Code After: import copy import dataproperty from ._csv import CsvTableWriter class SpaceAlignedTableWriter(CsvTableWriter): """ A table writer class for space aligned format. :Example: :ref:`example-space-aligned-table-writer` .. py:method:: write_table |write_table| with space aligned format. :Example: :ref:`example-space-aligned-table-writer` """ FORMAT_NAME = "space_aligned" @property def format_name(self) -> str: return self.FORMAT_NAME def __init__(self) -> None: super().__init__() self.column_delimiter = " " self.char_cross_point = " " self.is_padding = True self.is_formatting_float = True self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS)
import copy import dataproperty from ._csv import CsvTableWriter class SpaceAlignedTableWriter(CsvTableWriter): """ A table writer class for space aligned format. :Example: :ref:`example-space-aligned-table-writer` .. py:method:: write_table |write_table| with space aligned format. :Example: :ref:`example-space-aligned-table-writer` """ FORMAT_NAME = "space_aligned" @property def format_name(self) -> str: return self.FORMAT_NAME def __init__(self) -> None: super().__init__() self.column_delimiter = " " + self.char_cross_point = " " + self.is_padding = True self.is_formatting_float = True self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS)
ef72b229732610c3b6c8ccdd9c599002986707f3
test_knot.py
test_knot.py
import unittest from flask import Flask from flask.ext.knot import Knot def create_app(): app = Flask(__name__) app.config['TESTING'] = True return app class TestKnot(unittest.TestCase): def test_acts_like_container(self): app = create_app() dic = Knot(app) def foo(c): return 'bar' dic.add_factory(foo) self.assertEqual(dic.provide('foo'), 'bar') def test_does_use_app_config_on_initialization(self): app = create_app() app.config['foo'] = 'bar' dic = Knot(app) self.assertEqual(dic['foo'], 'bar') def test_does_not_use_app_config_after_initialization(self): app = create_app() app.config['foo'] = 'bar' dic = Knot() dic.init_app(app) self.assertRaises(KeyError, lambda: dic['foo']) if __name__ == '__main__': unittest.main()
import unittest from flask import Flask from flask.ext.knot import Knot, get_container def create_app(): app = Flask(__name__) app.config['TESTING'] = True return app class TestKnot(unittest.TestCase): def test_acts_like_container(self): app = create_app() dic = Knot(app) def foo(c): return 'bar' dic.add_factory(foo) self.assertEqual(dic.provide('foo'), 'bar') def test_does_use_app_config_on_initialization(self): app = create_app() app.config['foo'] = 'bar' dic = Knot(app) self.assertEqual(dic['foo'], 'bar') def test_does_not_use_app_config_after_initialization(self): app = create_app() app.config['foo'] = 'bar' dic = Knot() dic.init_app(app) self.assertRaises(KeyError, lambda: dic['foo']) def test_container_is_shared(self): app1 = create_app() app2 = create_app() dic = Knot() dic.init_app(app1) dic.init_app(app2) dic1 = get_container(app1) dic2 = get_container(app2) assert dic1 is dic2 if __name__ == '__main__': unittest.main()
Add test for shared container.
Add test for shared container.
Python
mit
jaapverloop/flask-knot
import unittest from flask import Flask - from flask.ext.knot import Knot + from flask.ext.knot import Knot, get_container def create_app(): app = Flask(__name__) app.config['TESTING'] = True return app class TestKnot(unittest.TestCase): def test_acts_like_container(self): app = create_app() dic = Knot(app) def foo(c): return 'bar' dic.add_factory(foo) self.assertEqual(dic.provide('foo'), 'bar') def test_does_use_app_config_on_initialization(self): app = create_app() app.config['foo'] = 'bar' dic = Knot(app) self.assertEqual(dic['foo'], 'bar') def test_does_not_use_app_config_after_initialization(self): app = create_app() app.config['foo'] = 'bar' dic = Knot() dic.init_app(app) self.assertRaises(KeyError, lambda: dic['foo']) + def test_container_is_shared(self): + app1 = create_app() + app2 = create_app() + + dic = Knot() + dic.init_app(app1) + dic.init_app(app2) + + dic1 = get_container(app1) + dic2 = get_container(app2) + + assert dic1 is dic2 + if __name__ == '__main__': unittest.main()
Add test for shared container.
## Code Before: import unittest from flask import Flask from flask.ext.knot import Knot def create_app(): app = Flask(__name__) app.config['TESTING'] = True return app class TestKnot(unittest.TestCase): def test_acts_like_container(self): app = create_app() dic = Knot(app) def foo(c): return 'bar' dic.add_factory(foo) self.assertEqual(dic.provide('foo'), 'bar') def test_does_use_app_config_on_initialization(self): app = create_app() app.config['foo'] = 'bar' dic = Knot(app) self.assertEqual(dic['foo'], 'bar') def test_does_not_use_app_config_after_initialization(self): app = create_app() app.config['foo'] = 'bar' dic = Knot() dic.init_app(app) self.assertRaises(KeyError, lambda: dic['foo']) if __name__ == '__main__': unittest.main() ## Instruction: Add test for shared container. ## Code After: import unittest from flask import Flask from flask.ext.knot import Knot, get_container def create_app(): app = Flask(__name__) app.config['TESTING'] = True return app class TestKnot(unittest.TestCase): def test_acts_like_container(self): app = create_app() dic = Knot(app) def foo(c): return 'bar' dic.add_factory(foo) self.assertEqual(dic.provide('foo'), 'bar') def test_does_use_app_config_on_initialization(self): app = create_app() app.config['foo'] = 'bar' dic = Knot(app) self.assertEqual(dic['foo'], 'bar') def test_does_not_use_app_config_after_initialization(self): app = create_app() app.config['foo'] = 'bar' dic = Knot() dic.init_app(app) self.assertRaises(KeyError, lambda: dic['foo']) def test_container_is_shared(self): app1 = create_app() app2 = create_app() dic = Knot() dic.init_app(app1) dic.init_app(app2) dic1 = get_container(app1) dic2 = get_container(app2) assert dic1 is dic2 if __name__ == '__main__': unittest.main()
import unittest from flask import Flask - from flask.ext.knot import Knot + from flask.ext.knot import Knot, get_container ? +++++++++++++++ def create_app(): app = Flask(__name__) app.config['TESTING'] = True return app class TestKnot(unittest.TestCase): def test_acts_like_container(self): app = create_app() dic = Knot(app) def foo(c): return 'bar' dic.add_factory(foo) self.assertEqual(dic.provide('foo'), 'bar') def test_does_use_app_config_on_initialization(self): app = create_app() app.config['foo'] = 'bar' dic = Knot(app) self.assertEqual(dic['foo'], 'bar') def test_does_not_use_app_config_after_initialization(self): app = create_app() app.config['foo'] = 'bar' dic = Knot() dic.init_app(app) self.assertRaises(KeyError, lambda: dic['foo']) + def test_container_is_shared(self): + app1 = create_app() + app2 = create_app() + + dic = Knot() + dic.init_app(app1) + dic.init_app(app2) + + dic1 = get_container(app1) + dic2 = get_container(app2) + + assert dic1 is dic2 + if __name__ == '__main__': unittest.main()
a40c617ea605bd667a9906f6c9400fc9562d7c0a
salt/daemons/flo/reactor.py
salt/daemons/flo/reactor.py
''' Start the reactor! ''' # Import salt libs import salt.utils.reactor # Import ioflo libs import ioflo.base.deeding @ioflo.base.deeding.deedify( 'SaltRaetReactorFork', ioinit={ 'opts': '.salt.opts', 'proc_mgr': '.salt.usr.proc_mgr'}) def reactor_fork(self): ''' Add a reactor object to the process manager ''' self.proc_mgr.add_process( salt.utils.reactor.Reactor, args=(self.opts.value,))
''' Start the reactor! ''' # Import salt libs import salt.utils.reactor import salt.utils.event # Import ioflo libs import ioflo.base.deeding @ioflo.base.deeding.deedify( 'SaltRaetReactorFork', ioinit={ 'opts': '.salt.opts', 'proc_mgr': '.salt.usr.proc_mgr'}) def reactor_fork(self): ''' Add a reactor object to the process manager ''' self.proc_mgr.add_process( salt.utils.reactor.Reactor, args=(self.opts.value,)) @ioflo.base.deeding.deedify( 'SaltRaetEventReturnFork', ioinit={ 'opts': '.salt.opts', 'proc_mgr': '.salt.usr.proc_mgr'}) def event_return_fork(self): ''' Add a reactor object to the process manager ''' self.proc_mgr.add_process( salt.utils.event.EventReturn, args=(self.opts.value,))
Add event return fork behavior
Add event return fork behavior
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
''' Start the reactor! ''' # Import salt libs import salt.utils.reactor + import salt.utils.event # Import ioflo libs import ioflo.base.deeding @ioflo.base.deeding.deedify( 'SaltRaetReactorFork', ioinit={ 'opts': '.salt.opts', 'proc_mgr': '.salt.usr.proc_mgr'}) def reactor_fork(self): ''' Add a reactor object to the process manager ''' self.proc_mgr.add_process( salt.utils.reactor.Reactor, args=(self.opts.value,)) + + @ioflo.base.deeding.deedify( + 'SaltRaetEventReturnFork', + ioinit={ + 'opts': '.salt.opts', + 'proc_mgr': '.salt.usr.proc_mgr'}) + def event_return_fork(self): + ''' + Add a reactor object to the process manager + ''' + self.proc_mgr.add_process( + salt.utils.event.EventReturn, + args=(self.opts.value,)) +
Add event return fork behavior
## Code Before: ''' Start the reactor! ''' # Import salt libs import salt.utils.reactor # Import ioflo libs import ioflo.base.deeding @ioflo.base.deeding.deedify( 'SaltRaetReactorFork', ioinit={ 'opts': '.salt.opts', 'proc_mgr': '.salt.usr.proc_mgr'}) def reactor_fork(self): ''' Add a reactor object to the process manager ''' self.proc_mgr.add_process( salt.utils.reactor.Reactor, args=(self.opts.value,)) ## Instruction: Add event return fork behavior ## Code After: ''' Start the reactor! ''' # Import salt libs import salt.utils.reactor import salt.utils.event # Import ioflo libs import ioflo.base.deeding @ioflo.base.deeding.deedify( 'SaltRaetReactorFork', ioinit={ 'opts': '.salt.opts', 'proc_mgr': '.salt.usr.proc_mgr'}) def reactor_fork(self): ''' Add a reactor object to the process manager ''' self.proc_mgr.add_process( salt.utils.reactor.Reactor, args=(self.opts.value,)) @ioflo.base.deeding.deedify( 'SaltRaetEventReturnFork', ioinit={ 'opts': '.salt.opts', 'proc_mgr': '.salt.usr.proc_mgr'}) def event_return_fork(self): ''' Add a reactor object to the process manager ''' self.proc_mgr.add_process( salt.utils.event.EventReturn, args=(self.opts.value,))
''' Start the reactor! ''' # Import salt libs import salt.utils.reactor + import salt.utils.event # Import ioflo libs import ioflo.base.deeding @ioflo.base.deeding.deedify( 'SaltRaetReactorFork', ioinit={ 'opts': '.salt.opts', 'proc_mgr': '.salt.usr.proc_mgr'}) def reactor_fork(self): ''' Add a reactor object to the process manager ''' self.proc_mgr.add_process( salt.utils.reactor.Reactor, args=(self.opts.value,)) + + + @ioflo.base.deeding.deedify( + 'SaltRaetEventReturnFork', + ioinit={ + 'opts': '.salt.opts', + 'proc_mgr': '.salt.usr.proc_mgr'}) + def event_return_fork(self): + ''' + Add a reactor object to the process manager + ''' + self.proc_mgr.add_process( + salt.utils.event.EventReturn, + args=(self.opts.value,))
e6c9ceb3f838a613d182a3fdea961ca1f73e90c4
translator/models.py
translator/models.py
from django.conf import settings from django.core.cache import cache from django.db import models from django.utils.decorators import classproperty from taggit.managers import TaggableManager from translator.util import get_key class TranslationBase(models.Model): key = models.CharField(max_length=255, unique=True) description = models.TextField() tags = TaggableManager(blank=True) class Meta: abstract = True def __unicode__(self): return self.key def save(self, force_insert=False, force_update=False, using=None, update_fields=None): all_translation_keys = self.__class__.objects.all().values_list('key', flat=True) for l in settings.LANGUAGES: cache.delete_many([get_key(l[0], k, self.cache_key_prefix) for k in all_translation_keys]) return super().save(force_insert, force_update, using, update_fields) @classproperty def cache_key_prefix(self): """To separate cache keys, we need to specify a unique prefix per model.""" return self._meta.db_table class Translation(TranslationBase): pass
from django.conf import settings from django.core.cache import cache from django.db import models from taggit.managers import TaggableManager from translator.util import get_key try: # Django 3.1 and above from django.utils.functional import classproperty except ImportError: from django.utils.decorators import classproperty class TranslationBase(models.Model): key = models.CharField(max_length=255, unique=True) description = models.TextField() tags = TaggableManager(blank=True) class Meta: abstract = True def __unicode__(self): return self.key def save(self, force_insert=False, force_update=False, using=None, update_fields=None): all_translation_keys = self.__class__.objects.all().values_list('key', flat=True) for l in settings.LANGUAGES: cache.delete_many([get_key(l[0], k, self.cache_key_prefix) for k in all_translation_keys]) return super().save(force_insert, force_update, using, update_fields) @classproperty def cache_key_prefix(self): """To separate cache keys, we need to specify a unique prefix per model.""" return self._meta.db_table class Translation(TranslationBase): pass
Update import for classproperty in django 3.1 and above
Update import for classproperty in django 3.1 and above
Python
mit
dreipol/django-translator
from django.conf import settings from django.core.cache import cache from django.db import models - from django.utils.decorators import classproperty from taggit.managers import TaggableManager from translator.util import get_key + + try: + # Django 3.1 and above + from django.utils.functional import classproperty + except ImportError: + from django.utils.decorators import classproperty class TranslationBase(models.Model): key = models.CharField(max_length=255, unique=True) description = models.TextField() tags = TaggableManager(blank=True) class Meta: abstract = True def __unicode__(self): return self.key def save(self, force_insert=False, force_update=False, using=None, update_fields=None): all_translation_keys = self.__class__.objects.all().values_list('key', flat=True) for l in settings.LANGUAGES: cache.delete_many([get_key(l[0], k, self.cache_key_prefix) for k in all_translation_keys]) return super().save(force_insert, force_update, using, update_fields) @classproperty def cache_key_prefix(self): """To separate cache keys, we need to specify a unique prefix per model.""" return self._meta.db_table class Translation(TranslationBase): pass
Update import for classproperty in django 3.1 and above
## Code Before: from django.conf import settings from django.core.cache import cache from django.db import models from django.utils.decorators import classproperty from taggit.managers import TaggableManager from translator.util import get_key class TranslationBase(models.Model): key = models.CharField(max_length=255, unique=True) description = models.TextField() tags = TaggableManager(blank=True) class Meta: abstract = True def __unicode__(self): return self.key def save(self, force_insert=False, force_update=False, using=None, update_fields=None): all_translation_keys = self.__class__.objects.all().values_list('key', flat=True) for l in settings.LANGUAGES: cache.delete_many([get_key(l[0], k, self.cache_key_prefix) for k in all_translation_keys]) return super().save(force_insert, force_update, using, update_fields) @classproperty def cache_key_prefix(self): """To separate cache keys, we need to specify a unique prefix per model.""" return self._meta.db_table class Translation(TranslationBase): pass ## Instruction: Update import for classproperty in django 3.1 and above ## Code After: from django.conf import settings from django.core.cache import cache from django.db import models from taggit.managers import TaggableManager from translator.util import get_key try: # Django 3.1 and above from django.utils.functional import classproperty except ImportError: from django.utils.decorators import classproperty class TranslationBase(models.Model): key = models.CharField(max_length=255, unique=True) description = models.TextField() tags = TaggableManager(blank=True) class Meta: abstract = True def __unicode__(self): return self.key def save(self, force_insert=False, force_update=False, using=None, update_fields=None): all_translation_keys = self.__class__.objects.all().values_list('key', flat=True) for l in settings.LANGUAGES: cache.delete_many([get_key(l[0], k, self.cache_key_prefix) for k in all_translation_keys]) return super().save(force_insert, force_update, using, update_fields) @classproperty def cache_key_prefix(self): """To separate cache keys, we need to specify a unique prefix per model.""" return self._meta.db_table class Translation(TranslationBase): pass
from django.conf import settings from django.core.cache import cache from django.db import models - from django.utils.decorators import classproperty from taggit.managers import TaggableManager from translator.util import get_key + + try: + # Django 3.1 and above + from django.utils.functional import classproperty + except ImportError: + from django.utils.decorators import classproperty class TranslationBase(models.Model): key = models.CharField(max_length=255, unique=True) description = models.TextField() tags = TaggableManager(blank=True) class Meta: abstract = True def __unicode__(self): return self.key def save(self, force_insert=False, force_update=False, using=None, update_fields=None): all_translation_keys = self.__class__.objects.all().values_list('key', flat=True) for l in settings.LANGUAGES: cache.delete_many([get_key(l[0], k, self.cache_key_prefix) for k in all_translation_keys]) return super().save(force_insert, force_update, using, update_fields) @classproperty def cache_key_prefix(self): """To separate cache keys, we need to specify a unique prefix per model.""" return self._meta.db_table class Translation(TranslationBase): pass
5495913d43606407c7fb646b2a0eb4b5d4b80ba1
network/admin.py
network/admin.py
from django.contrib import admin from .models.device import Device from .models.interface import Interface admin.site.register(Device) admin.site.register(Interface)
from django.contrib import admin from .models.device import Device from .models.interface import Interface from members.settings import MAX_INTERFACE_PER_DEVICE class InterfaceAdmin(admin.TabularInline): model = Interface max_num = MAX_INTERFACE_PER_DEVICE display = ('interface', 'mac_address', 'description') view_on_site = False @admin.register(Device) class DeviceAdmin(admin.ModelAdmin): list_display = ('user', 'device_name', 'description', 'add_date') readonly_fields = ('device_ip',) search_fields = ['user__username'] inlines = [InterfaceAdmin]
Add search box, show devices list in table, show interfaces in device detail
Add search box, show devices list in table, show interfaces in device detail
Python
mit
Atilla106/members.atilla.org,Atilla106/members.atilla.org,Atilla106/members.atilla.org,Atilla106/members.atilla.org,Atilla106/members.atilla.org
from django.contrib import admin from .models.device import Device from .models.interface import Interface + from members.settings import MAX_INTERFACE_PER_DEVICE - admin.site.register(Device) - admin.site.register(Interface) + class InterfaceAdmin(admin.TabularInline): + model = Interface + max_num = MAX_INTERFACE_PER_DEVICE + display = ('interface', 'mac_address', 'description') + view_on_site = False + + @admin.register(Device) + class DeviceAdmin(admin.ModelAdmin): + list_display = ('user', 'device_name', 'description', 'add_date') + readonly_fields = ('device_ip',) + search_fields = ['user__username'] + inlines = [InterfaceAdmin] +
Add search box, show devices list in table, show interfaces in device detail
## Code Before: from django.contrib import admin from .models.device import Device from .models.interface import Interface admin.site.register(Device) admin.site.register(Interface) ## Instruction: Add search box, show devices list in table, show interfaces in device detail ## Code After: from django.contrib import admin from .models.device import Device from .models.interface import Interface from members.settings import MAX_INTERFACE_PER_DEVICE class InterfaceAdmin(admin.TabularInline): model = Interface max_num = MAX_INTERFACE_PER_DEVICE display = ('interface', 'mac_address', 'description') view_on_site = False @admin.register(Device) class DeviceAdmin(admin.ModelAdmin): list_display = ('user', 'device_name', 'description', 'add_date') readonly_fields = ('device_ip',) search_fields = ['user__username'] inlines = [InterfaceAdmin]
from django.contrib import admin from .models.device import Device from .models.interface import Interface + from members.settings import MAX_INTERFACE_PER_DEVICE + class InterfaceAdmin(admin.TabularInline): + model = Interface + max_num = MAX_INTERFACE_PER_DEVICE + display = ('interface', 'mac_address', 'description') + view_on_site = False + + - admin.site.register(Device) ? ----- + @admin.register(Device) ? + - admin.site.register(Interface) + class DeviceAdmin(admin.ModelAdmin): + list_display = ('user', 'device_name', 'description', 'add_date') + readonly_fields = ('device_ip',) + search_fields = ['user__username'] + inlines = [InterfaceAdmin]
805c6097b3dc7e7e2468235a9c28d159cb99f187
satchless/cart/__init__.py
satchless/cart/__init__.py
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from .handler import AddToCartHandler add_to_cart_handler = AddToCartHandler('cart') if not getattr(settings, 'SATCHLESS_DEFAULT_CURRENCY', None): raise ImproperlyConfigured('You need to configure ' 'SATCHLESS_DEFAULT_CURRENCY')
class InvalidQuantityException(Exception): def __init__(self, reason, quantity_delta): self.reason = reason self.quantity_delta = quantity_delta def __str__(self): return self.reason
Add cart quantity exception, remove old handler
Add cart quantity exception, remove old handler
Python
bsd-3-clause
taedori81/satchless
+ class InvalidQuantityException(Exception): - from django.conf import settings - from django.core.exceptions import ImproperlyConfigured - from .handler import AddToCartHandler + def __init__(self, reason, quantity_delta): + self.reason = reason + self.quantity_delta = quantity_delta - add_to_cart_handler = AddToCartHandler('cart') + def __str__(self): + return self.reason + - if not getattr(settings, 'SATCHLESS_DEFAULT_CURRENCY', None): - raise ImproperlyConfigured('You need to configure ' - 'SATCHLESS_DEFAULT_CURRENCY')
Add cart quantity exception, remove old handler
## Code Before: from django.conf import settings from django.core.exceptions import ImproperlyConfigured from .handler import AddToCartHandler add_to_cart_handler = AddToCartHandler('cart') if not getattr(settings, 'SATCHLESS_DEFAULT_CURRENCY', None): raise ImproperlyConfigured('You need to configure ' 'SATCHLESS_DEFAULT_CURRENCY') ## Instruction: Add cart quantity exception, remove old handler ## Code After: class InvalidQuantityException(Exception): def __init__(self, reason, quantity_delta): self.reason = reason self.quantity_delta = quantity_delta def __str__(self): return self.reason
+ class InvalidQuantityException(Exception): - from django.conf import settings - from django.core.exceptions import ImproperlyConfigured - from .handler import AddToCartHandler + def __init__(self, reason, quantity_delta): + self.reason = reason + self.quantity_delta = quantity_delta - add_to_cart_handler = AddToCartHandler('cart') + def __str__(self): + return self.reason - if not getattr(settings, 'SATCHLESS_DEFAULT_CURRENCY', None): - raise ImproperlyConfigured('You need to configure ' - 'SATCHLESS_DEFAULT_CURRENCY')
a8708203a9de77c34d1df05986aee2f4033bdf63
invoice/tasks.py
invoice/tasks.py
import logging from celery import shared_task from django.utils import timezone from invoice.models import InvoiceUser from mail.service import queue_mail_message from mail.tasks import process_mail from .report import time_summary logger = logging.getLogger(__name__) @shared_task def mail_time_summary(): users = [] for item in InvoiceUser.objects.all(): if item.mail_time_summary and item.user.email: users.append(item.user) for user in users: logger.debug('mail_time_summary: {}'.format(user.username)) report = time_summary(user, days=1) message = '' for d, summary in report.items(): message = message + '\n\n{}, total time {}'.format( d.strftime('%d/%m/%Y %A'), summary['format_total'], ) for ticket in summary['tickets']: message = message + '\n{}: {}, {} ({})'.format( ticket['pk'], ticket['contact'], ticket['description'], ticket['format_minutes'], ) queue_mail_message( user, [user.email], 'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')), message, ) if users: process_mail.delay()
import logging from celery import shared_task from django.utils import timezone from invoice.models import InvoiceUser from mail.service import queue_mail_message from mail.tasks import process_mail from .report import time_summary logger = logging.getLogger(__name__) @shared_task def mail_time_summary(): users = [] for item in InvoiceUser.objects.all(): if item.mail_time_summary and item.user.email: users.append(item.user) for user in users: logger.info('mail_time_summary: {}'.format(user.username)) report = time_summary(user, days=1) message = '<table border="0">' for d, summary in report.items(): message = message + '<tr colspan="3">' message = message + '<td>{}</td>'.format(d.strftime('%d/%m/%Y %A')) message = message + '</tr>' for ticket in summary['tickets']: message = message + '<tr>' message = message + '<td>{}</td>'.format(ticket['pk']) message = message + '<td>{}, {}</td>'.format( ticket['contact'], ticket['description'], ) message = message + '<td>{}</td>'.format( ticket['format_minutes'], ) message = message + '</tr>' message = message + '<tr>' message = message + '<td></td><td></td>' message = message + '<td><b>{}</b></td>'.format( summary['format_total'] ) message = message + '</tr>' message = message + '</table>' queue_mail_message( user, [user.email], 'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')), message, ) if users: process_mail.delay()
Put the time summary in an html table
Put the time summary in an html table
Python
apache-2.0
pkimber/invoice,pkimber/invoice,pkimber/invoice
import logging from celery import shared_task from django.utils import timezone from invoice.models import InvoiceUser from mail.service import queue_mail_message from mail.tasks import process_mail from .report import time_summary logger = logging.getLogger(__name__) @shared_task def mail_time_summary(): users = [] for item in InvoiceUser.objects.all(): if item.mail_time_summary and item.user.email: users.append(item.user) for user in users: - logger.debug('mail_time_summary: {}'.format(user.username)) + logger.info('mail_time_summary: {}'.format(user.username)) report = time_summary(user, days=1) - message = '' + message = '<table border="0">' for d, summary in report.items(): + message = message + '<tr colspan="3">' + message = message + '<td>{}</td>'.format(d.strftime('%d/%m/%Y %A')) + message = message + '</tr>' - message = message + '\n\n{}, total time {}'.format( - d.strftime('%d/%m/%Y %A'), - summary['format_total'], - ) for ticket in summary['tickets']: + message = message + '<tr>' + message = message + '<td>{}</td>'.format(ticket['pk']) - message = message + '\n{}: {}, {} ({})'.format( + message = message + '<td>{}, {}</td>'.format( - ticket['pk'], ticket['contact'], ticket['description'], + ) + message = message + '<td>{}</td>'.format( ticket['format_minutes'], ) + message = message + '</tr>' + message = message + '<tr>' + message = message + '<td></td><td></td>' + message = message + '<td><b>{}</b></td>'.format( + summary['format_total'] + ) + message = message + '</tr>' + message = message + '</table>' queue_mail_message( user, [user.email], 'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')), message, ) if users: process_mail.delay()
Put the time summary in an html table
## Code Before: import logging from celery import shared_task from django.utils import timezone from invoice.models import InvoiceUser from mail.service import queue_mail_message from mail.tasks import process_mail from .report import time_summary logger = logging.getLogger(__name__) @shared_task def mail_time_summary(): users = [] for item in InvoiceUser.objects.all(): if item.mail_time_summary and item.user.email: users.append(item.user) for user in users: logger.debug('mail_time_summary: {}'.format(user.username)) report = time_summary(user, days=1) message = '' for d, summary in report.items(): message = message + '\n\n{}, total time {}'.format( d.strftime('%d/%m/%Y %A'), summary['format_total'], ) for ticket in summary['tickets']: message = message + '\n{}: {}, {} ({})'.format( ticket['pk'], ticket['contact'], ticket['description'], ticket['format_minutes'], ) queue_mail_message( user, [user.email], 'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')), message, ) if users: process_mail.delay() ## Instruction: Put the time summary in an html table ## Code After: import logging from celery import shared_task from django.utils import timezone from invoice.models import InvoiceUser from mail.service import queue_mail_message from mail.tasks import process_mail from .report import time_summary logger = logging.getLogger(__name__) @shared_task def mail_time_summary(): users = [] for item in InvoiceUser.objects.all(): if item.mail_time_summary and item.user.email: users.append(item.user) for user in users: logger.info('mail_time_summary: {}'.format(user.username)) report = time_summary(user, days=1) message = '<table border="0">' for d, summary in report.items(): message = message + '<tr colspan="3">' message = message + '<td>{}</td>'.format(d.strftime('%d/%m/%Y %A')) message = message + '</tr>' for ticket in summary['tickets']: message = message + '<tr>' message = message + '<td>{}</td>'.format(ticket['pk']) message = message + '<td>{}, {}</td>'.format( ticket['contact'], ticket['description'], ) message = message + '<td>{}</td>'.format( ticket['format_minutes'], ) message = message + '</tr>' message = message + '<tr>' message = message + '<td></td><td></td>' message = message + '<td><b>{}</b></td>'.format( summary['format_total'] ) message = message + '</tr>' message = message + '</table>' queue_mail_message( user, [user.email], 'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')), message, ) if users: process_mail.delay()
import logging from celery import shared_task from django.utils import timezone from invoice.models import InvoiceUser from mail.service import queue_mail_message from mail.tasks import process_mail from .report import time_summary logger = logging.getLogger(__name__) @shared_task def mail_time_summary(): users = [] for item in InvoiceUser.objects.all(): if item.mail_time_summary and item.user.email: users.append(item.user) for user in users: - logger.debug('mail_time_summary: {}'.format(user.username)) ? ^^^^^ + logger.info('mail_time_summary: {}'.format(user.username)) ? ^^^^ report = time_summary(user, days=1) - message = '' + message = '<table border="0">' for d, summary in report.items(): + message = message + '<tr colspan="3">' + message = message + '<td>{}</td>'.format(d.strftime('%d/%m/%Y %A')) + message = message + '</tr>' - message = message + '\n\n{}, total time {}'.format( - d.strftime('%d/%m/%Y %A'), - summary['format_total'], - ) for ticket in summary['tickets']: + message = message + '<tr>' + message = message + '<td>{}</td>'.format(ticket['pk']) - message = message + '\n{}: {}, {} ({})'.format( ? ^^^^^^ ^^^^^ + message = message + '<td>{}, {}</td>'.format( ? ^^^^ ^^^^^ - ticket['pk'], ticket['contact'], ticket['description'], + ) + message = message + '<td>{}</td>'.format( ticket['format_minutes'], ) + message = message + '</tr>' + message = message + '<tr>' + message = message + '<td></td><td></td>' + message = message + '<td><b>{}</b></td>'.format( + summary['format_total'] + ) + message = message + '</tr>' + message = message + '</table>' queue_mail_message( user, [user.email], 'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')), message, ) if users: process_mail.delay()
5e57dce84ffe7be7e699af1e2be953d5a65d8435
tests/test_module.py
tests/test_module.py
import sys import dill import test_mixins as module module.a = 1234 pik_mod = dill.dumps(module) module.a = 0 # remove module del sys.modules[module.__name__] del module module = dill.loads(pik_mod) assert module.a == 1234 assert module.double_add(1, 2, 3) == 2 * module.fx
import sys import dill import test_mixins as module cached = (module.__cached__ if hasattr(module, "__cached__") else module.__file__ + "c") module.a = 1234 pik_mod = dill.dumps(module) module.a = 0 # remove module del sys.modules[module.__name__] del module module = dill.loads(pik_mod) assert hasattr(module, "a") and module.a == 1234 assert module.double_add(1, 2, 3) == 2 * module.fx # clean up import os os.remove(cached) if os.path.exists("__pycache__") and not os.listdir("__pycache__"): os.removedirs("__pycache__")
Add code to clean up
Add code to clean up
Python
bsd-3-clause
wxiang7/dill,mindw/dill
import sys import dill import test_mixins as module + + cached = (module.__cached__ if hasattr(module, "__cached__") + else module.__file__ + "c") module.a = 1234 pik_mod = dill.dumps(module) module.a = 0 # remove module del sys.modules[module.__name__] del module module = dill.loads(pik_mod) - assert module.a == 1234 + assert hasattr(module, "a") and module.a == 1234 assert module.double_add(1, 2, 3) == 2 * module.fx + # clean up + import os + os.remove(cached) + if os.path.exists("__pycache__") and not os.listdir("__pycache__"): + os.removedirs("__pycache__") +
Add code to clean up
## Code Before: import sys import dill import test_mixins as module module.a = 1234 pik_mod = dill.dumps(module) module.a = 0 # remove module del sys.modules[module.__name__] del module module = dill.loads(pik_mod) assert module.a == 1234 assert module.double_add(1, 2, 3) == 2 * module.fx ## Instruction: Add code to clean up ## Code After: import sys import dill import test_mixins as module cached = (module.__cached__ if hasattr(module, "__cached__") else module.__file__ + "c") module.a = 1234 pik_mod = dill.dumps(module) module.a = 0 # remove module del sys.modules[module.__name__] del module module = dill.loads(pik_mod) assert hasattr(module, "a") and module.a == 1234 assert module.double_add(1, 2, 3) == 2 * module.fx # clean up import os os.remove(cached) if os.path.exists("__pycache__") and not os.listdir("__pycache__"): os.removedirs("__pycache__")
import sys import dill import test_mixins as module + + cached = (module.__cached__ if hasattr(module, "__cached__") + else module.__file__ + "c") module.a = 1234 pik_mod = dill.dumps(module) module.a = 0 # remove module del sys.modules[module.__name__] del module module = dill.loads(pik_mod) - assert module.a == 1234 + assert hasattr(module, "a") and module.a == 1234 assert module.double_add(1, 2, 3) == 2 * module.fx + + # clean up + import os + os.remove(cached) + if os.path.exists("__pycache__") and not os.listdir("__pycache__"): + os.removedirs("__pycache__")
eefff91804317f4fb2c518446ab8e2072af4d87f
app/models.py
app/models.py
from django.db import models import mongoengine from mongoengine import Document, EmbeddedDocument from mongoengine.fields import * # Create your models here. class Greeting(models.Model): when = models.DateTimeField('date created', auto_now_add=True) MONGODB_URI = 'mongodb+srv://fikaadmin:ZJ6TtyTZMXA@fikanotedb.ltkpy.mongodb.net/fikanotedb?retryWrites=true&w=majority' mongoengine.connect('fikanotedb', host=MONGODB_URI) class Shownote(EmbeddedDocument): url = URLField() title = StringField() date = DateTimeField() class FikanoteDB(Document): title = StringField() number = IntField() person = ListField(StringField()) agenda = StringField() date = DateTimeField() shownotes = ListField(EmbeddedDocumentField(Shownote)) meta = {'collection': 'fikanotedb'} class AgendaDB(Document): url = URLField() title = StringField() date = DateTimeField() meta = {'collection': 'agendadb'}
from django.db import models import mongoengine from mongoengine import Document, EmbeddedDocument from mongoengine.fields import * import os # Create your models here. class Greeting(models.Model): when = models.DateTimeField('date created', auto_now_add=True) USER = os.getenv('DATABASE_USER') PASWORD = os.getenv('DATABASE_PASSWORD') MONGODB_URI = "mongodb+srv://{}:{}@fikanotedb.ltkpy.mongodb.net/fikanotedb?retryWrites=true&w=majority".format(USER, PASWORD) mongoengine.connect('fikanotedb', host=MONGODB_URI) class Shownote(EmbeddedDocument): url = URLField() title = StringField() date = DateTimeField() class FikanoteDB(Document): title = StringField() number = IntField() person = ListField(StringField()) agenda = StringField() date = DateTimeField() shownotes = ListField(EmbeddedDocumentField(Shownote)) meta = {'collection': 'fikanotedb'} class AgendaDB(Document): url = URLField() title = StringField() date = DateTimeField() meta = {'collection': 'agendadb'}
Remove username and password from repository
Remove username and password from repository
Python
mit
gmkou/FikaNote,gmkou/FikaNote,gmkou/FikaNote
from django.db import models import mongoengine from mongoengine import Document, EmbeddedDocument from mongoengine.fields import * + import os # Create your models here. class Greeting(models.Model): when = models.DateTimeField('date created', auto_now_add=True) + USER = os.getenv('DATABASE_USER') + PASWORD = os.getenv('DATABASE_PASSWORD') - MONGODB_URI = 'mongodb+srv://fikaadmin:ZJ6TtyTZMXA@fikanotedb.ltkpy.mongodb.net/fikanotedb?retryWrites=true&w=majority' + MONGODB_URI = "mongodb+srv://{}:{}@fikanotedb.ltkpy.mongodb.net/fikanotedb?retryWrites=true&w=majority".format(USER, PASWORD) mongoengine.connect('fikanotedb', host=MONGODB_URI) class Shownote(EmbeddedDocument): url = URLField() title = StringField() date = DateTimeField() class FikanoteDB(Document): title = StringField() number = IntField() person = ListField(StringField()) agenda = StringField() date = DateTimeField() shownotes = ListField(EmbeddedDocumentField(Shownote)) meta = {'collection': 'fikanotedb'} class AgendaDB(Document): url = URLField() title = StringField() date = DateTimeField() meta = {'collection': 'agendadb'}
Remove username and password from repository
## Code Before: from django.db import models import mongoengine from mongoengine import Document, EmbeddedDocument from mongoengine.fields import * # Create your models here. class Greeting(models.Model): when = models.DateTimeField('date created', auto_now_add=True) MONGODB_URI = 'mongodb+srv://fikaadmin:ZJ6TtyTZMXA@fikanotedb.ltkpy.mongodb.net/fikanotedb?retryWrites=true&w=majority' mongoengine.connect('fikanotedb', host=MONGODB_URI) class Shownote(EmbeddedDocument): url = URLField() title = StringField() date = DateTimeField() class FikanoteDB(Document): title = StringField() number = IntField() person = ListField(StringField()) agenda = StringField() date = DateTimeField() shownotes = ListField(EmbeddedDocumentField(Shownote)) meta = {'collection': 'fikanotedb'} class AgendaDB(Document): url = URLField() title = StringField() date = DateTimeField() meta = {'collection': 'agendadb'} ## Instruction: Remove username and password from repository ## Code After: from django.db import models import mongoengine from mongoengine import Document, EmbeddedDocument from mongoengine.fields import * import os # Create your models here. class Greeting(models.Model): when = models.DateTimeField('date created', auto_now_add=True) USER = os.getenv('DATABASE_USER') PASWORD = os.getenv('DATABASE_PASSWORD') MONGODB_URI = "mongodb+srv://{}:{}@fikanotedb.ltkpy.mongodb.net/fikanotedb?retryWrites=true&w=majority".format(USER, PASWORD) mongoengine.connect('fikanotedb', host=MONGODB_URI) class Shownote(EmbeddedDocument): url = URLField() title = StringField() date = DateTimeField() class FikanoteDB(Document): title = StringField() number = IntField() person = ListField(StringField()) agenda = StringField() date = DateTimeField() shownotes = ListField(EmbeddedDocumentField(Shownote)) meta = {'collection': 'fikanotedb'} class AgendaDB(Document): url = URLField() title = StringField() date = DateTimeField() meta = {'collection': 'agendadb'}
from django.db import models import mongoengine from mongoengine import Document, EmbeddedDocument from mongoengine.fields import * + import os # Create your models here. class Greeting(models.Model): when = models.DateTimeField('date created', auto_now_add=True) + USER = os.getenv('DATABASE_USER') + PASWORD = os.getenv('DATABASE_PASSWORD') - MONGODB_URI = 'mongodb+srv://fikaadmin:ZJ6TtyTZMXA@fikanotedb.ltkpy.mongodb.net/fikanotedb?retryWrites=true&w=majority' ? ^ ^^^^^^^^^ ^^^^^^^^^^^ ^ + MONGODB_URI = "mongodb+srv://{}:{}@fikanotedb.ltkpy.mongodb.net/fikanotedb?retryWrites=true&w=majority".format(USER, PASWORD) ? ^ ^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^ mongoengine.connect('fikanotedb', host=MONGODB_URI) class Shownote(EmbeddedDocument): url = URLField() title = StringField() date = DateTimeField() class FikanoteDB(Document): title = StringField() number = IntField() person = ListField(StringField()) agenda = StringField() date = DateTimeField() shownotes = ListField(EmbeddedDocumentField(Shownote)) meta = {'collection': 'fikanotedb'} class AgendaDB(Document): url = URLField() title = StringField() date = DateTimeField() meta = {'collection': 'agendadb'}