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
669325d6ca93f81c4635d7d3d57120d8e23e5251
organizations/backends/forms.py
organizations/backends/forms.py
from django import forms from django.contrib.auth.models import User class InvitationRegistrationForm(forms.ModelForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) password = forms.CharField(max_length=30, widget=forms.PasswordInput) password_confirm = forms.CharField(max_length=30, widget=forms.PasswordInput) class Meta: model = User
from django import forms from django.contrib.auth.models import User class InvitationRegistrationForm(forms.ModelForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) password = forms.CharField(max_length=30, widget=forms.PasswordInput) password_confirm = forms.CharField(max_length=30, widget=forms.PasswordInput) def __init__(self, *args, **kwargs): super(InvitationRegistrationForm, self).__init__(*args, **kwargs) self.initial['username'] = '' class Meta: model = User exclude = ('is_staff', 'is_superuser', 'is_active', 'last_login', 'date_joined', 'groups', 'user_permissions')
Hide all unnecessary user info
Hide all unnecessary user info Excludes all User fields save for useranme, first/last name, email, and password. Also clears the username of its default data.
Python
bsd-2-clause
aptivate/django-organizations,arteria/django-ar-organizations,GauthamGoli/django-organizations,aptivate/django-organizations,DESHRAJ/django-organizations,DESHRAJ/django-organizations,GauthamGoli/django-organizations,st8st8/django-organizations,bennylope/django-organizations,arteria/django-ar-organizations,aptivate/django-organizations,st8st8/django-organizations,bennylope/django-organizations
from django import forms from django.contrib.auth.models import User class InvitationRegistrationForm(forms.ModelForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) password = forms.CharField(max_length=30, widget=forms.PasswordInput) password_confirm = forms.CharField(max_length=30, widget=forms.PasswordInput) + def __init__(self, *args, **kwargs): + super(InvitationRegistrationForm, self).__init__(*args, **kwargs) + self.initial['username'] = '' + class Meta: model = User + exclude = ('is_staff', 'is_superuser', 'is_active', 'last_login', + 'date_joined', 'groups', 'user_permissions')
Hide all unnecessary user info
## Code Before: from django import forms from django.contrib.auth.models import User class InvitationRegistrationForm(forms.ModelForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) password = forms.CharField(max_length=30, widget=forms.PasswordInput) password_confirm = forms.CharField(max_length=30, widget=forms.PasswordInput) class Meta: model = User ## Instruction: Hide all unnecessary user info ## Code After: from django import forms from django.contrib.auth.models import User class InvitationRegistrationForm(forms.ModelForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) password = forms.CharField(max_length=30, widget=forms.PasswordInput) password_confirm = forms.CharField(max_length=30, widget=forms.PasswordInput) def __init__(self, *args, **kwargs): super(InvitationRegistrationForm, self).__init__(*args, **kwargs) self.initial['username'] = '' class Meta: model = User exclude = ('is_staff', 'is_superuser', 'is_active', 'last_login', 'date_joined', 'groups', 'user_permissions')
from django import forms from django.contrib.auth.models import User class InvitationRegistrationForm(forms.ModelForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) password = forms.CharField(max_length=30, widget=forms.PasswordInput) password_confirm = forms.CharField(max_length=30, widget=forms.PasswordInput) + def __init__(self, *args, **kwargs): + super(InvitationRegistrationForm, self).__init__(*args, **kwargs) + self.initial['username'] = '' + class Meta: model = User + exclude = ('is_staff', 'is_superuser', 'is_active', 'last_login', + 'date_joined', 'groups', 'user_permissions')
890190f40b9061f7bfa15bbd7e56abc0f1b7d44a
redmapper/__init__.py
redmapper/__init__.py
from __future__ import division, absolute_import, print_function from ._version import __version__, __version_info__ version = __version__ from .configuration import Configuration from .runcat import RunCatalog from .solver_nfw import Solver from .catalog import DataObject, Entry, Catalog from .redsequence import RedSequenceColorPar from .chisq_dist import compute_chisq from .background import Background, ZredBackground from .cluster import Cluster, ClusterCatalog from .galaxy import Galaxy, GalaxyCatalog from .mask import Mask, HPMask, get_mask from .zlambda import Zlambda, ZlambdaCorrectionPar from .cluster_runner import ClusterRunner from .zred_color import ZredColor from .centering import Centering, CenteringWcenZred, CenteringBCG from .depthmap import DepthMap from .color_background import ColorBackground, ColorBackgroundGenerator
from __future__ import division, absolute_import, print_function from ._version import __version__, __version_info__ version = __version__ from .configuration import Configuration from .runcat import RunCatalog from .solver_nfw import Solver from .catalog import DataObject, Entry, Catalog from .redsequence import RedSequenceColorPar from .chisq_dist import compute_chisq from .background import Background, ZredBackground from .cluster import Cluster, ClusterCatalog from .galaxy import Galaxy, GalaxyCatalog from .mask import Mask, HPMask, get_mask from .zlambda import Zlambda, ZlambdaCorrectionPar from .cluster_runner import ClusterRunner from .zred_color import ZredColor from .centering import Centering, CenteringWcenZred, CenteringBCG from .depthmap import DepthMap from .color_background import ColorBackground, ColorBackgroundGenerator from .fitters import MedZFitter, RedSequenceFitter, RedSequenceOffDiagonalFitter, CorrectionFitter, EcgmmFitter
Make fitters available at main import level.
Make fitters available at main import level.
Python
apache-2.0
erykoff/redmapper,erykoff/redmapper
from __future__ import division, absolute_import, print_function from ._version import __version__, __version_info__ version = __version__ from .configuration import Configuration from .runcat import RunCatalog from .solver_nfw import Solver from .catalog import DataObject, Entry, Catalog from .redsequence import RedSequenceColorPar from .chisq_dist import compute_chisq from .background import Background, ZredBackground from .cluster import Cluster, ClusterCatalog from .galaxy import Galaxy, GalaxyCatalog from .mask import Mask, HPMask, get_mask from .zlambda import Zlambda, ZlambdaCorrectionPar from .cluster_runner import ClusterRunner from .zred_color import ZredColor from .centering import Centering, CenteringWcenZred, CenteringBCG from .depthmap import DepthMap from .color_background import ColorBackground, ColorBackgroundGenerator + from .fitters import MedZFitter, RedSequenceFitter, RedSequenceOffDiagonalFitter, CorrectionFitter, EcgmmFitter
Make fitters available at main import level.
## Code Before: from __future__ import division, absolute_import, print_function from ._version import __version__, __version_info__ version = __version__ from .configuration import Configuration from .runcat import RunCatalog from .solver_nfw import Solver from .catalog import DataObject, Entry, Catalog from .redsequence import RedSequenceColorPar from .chisq_dist import compute_chisq from .background import Background, ZredBackground from .cluster import Cluster, ClusterCatalog from .galaxy import Galaxy, GalaxyCatalog from .mask import Mask, HPMask, get_mask from .zlambda import Zlambda, ZlambdaCorrectionPar from .cluster_runner import ClusterRunner from .zred_color import ZredColor from .centering import Centering, CenteringWcenZred, CenteringBCG from .depthmap import DepthMap from .color_background import ColorBackground, ColorBackgroundGenerator ## Instruction: Make fitters available at main import level. ## Code After: from __future__ import division, absolute_import, print_function from ._version import __version__, __version_info__ version = __version__ from .configuration import Configuration from .runcat import RunCatalog from .solver_nfw import Solver from .catalog import DataObject, Entry, Catalog from .redsequence import RedSequenceColorPar from .chisq_dist import compute_chisq from .background import Background, ZredBackground from .cluster import Cluster, ClusterCatalog from .galaxy import Galaxy, GalaxyCatalog from .mask import Mask, HPMask, get_mask from .zlambda import Zlambda, ZlambdaCorrectionPar from .cluster_runner import ClusterRunner from .zred_color import ZredColor from .centering import Centering, CenteringWcenZred, CenteringBCG from .depthmap import DepthMap from .color_background import ColorBackground, ColorBackgroundGenerator from .fitters import MedZFitter, RedSequenceFitter, RedSequenceOffDiagonalFitter, CorrectionFitter, EcgmmFitter
from __future__ import division, absolute_import, print_function from ._version import __version__, __version_info__ version = __version__ from .configuration import Configuration from .runcat import RunCatalog from .solver_nfw import Solver from .catalog import DataObject, Entry, Catalog from .redsequence import RedSequenceColorPar from .chisq_dist import compute_chisq from .background import Background, ZredBackground from .cluster import Cluster, ClusterCatalog from .galaxy import Galaxy, GalaxyCatalog from .mask import Mask, HPMask, get_mask from .zlambda import Zlambda, ZlambdaCorrectionPar from .cluster_runner import ClusterRunner from .zred_color import ZredColor from .centering import Centering, CenteringWcenZred, CenteringBCG from .depthmap import DepthMap from .color_background import ColorBackground, ColorBackgroundGenerator + from .fitters import MedZFitter, RedSequenceFitter, RedSequenceOffDiagonalFitter, CorrectionFitter, EcgmmFitter
1f9bc1b6f9a796458d104c01b9a344cbb0c84a9b
Lib/fontParts/fontshell/groups.py
Lib/fontParts/fontshell/groups.py
import defcon from fontParts.base import BaseGroups from fontParts.fontshell.base import RBaseObject class RGroups(RBaseObject, BaseGroups): wrapClass = defcon.Groups def _items(self): return self.naked().items() def _contains(self, key): return key in self.naked() def _setItem(self, key, value): self.naked()[key] = value def _getItem(self, key): return self.naked()[key] def _delItem(self, key): del self.naked()[key]
import defcon from fontParts.base import BaseGroups from fontParts.fontshell.base import RBaseObject class RGroups(RBaseObject, BaseGroups): wrapClass = defcon.Groups def _get_base_side1KerningGroups(self): return self.naked().getRepresentation("defcon.groups.kerningSide1Groups") def _get_base_side2KerningGroups(self): return self.naked().getRepresentation("defcon.groups.kerningSide2Groups") def _items(self): return self.naked().items() def _contains(self, key): return key in self.naked() def _setItem(self, key, value): self.naked()[key] = value def _getItem(self, key): return self.naked()[key] def _delItem(self, key): del self.naked()[key]
Add defcon implementation of group lookup methods.
Add defcon implementation of group lookup methods.
Python
mit
robofab-developers/fontParts,robofab-developers/fontParts
import defcon from fontParts.base import BaseGroups from fontParts.fontshell.base import RBaseObject class RGroups(RBaseObject, BaseGroups): wrapClass = defcon.Groups + + def _get_base_side1KerningGroups(self): + return self.naked().getRepresentation("defcon.groups.kerningSide1Groups") + + def _get_base_side2KerningGroups(self): + return self.naked().getRepresentation("defcon.groups.kerningSide2Groups") def _items(self): return self.naked().items() def _contains(self, key): return key in self.naked() def _setItem(self, key, value): self.naked()[key] = value def _getItem(self, key): return self.naked()[key] def _delItem(self, key): del self.naked()[key]
Add defcon implementation of group lookup methods.
## Code Before: import defcon from fontParts.base import BaseGroups from fontParts.fontshell.base import RBaseObject class RGroups(RBaseObject, BaseGroups): wrapClass = defcon.Groups def _items(self): return self.naked().items() def _contains(self, key): return key in self.naked() def _setItem(self, key, value): self.naked()[key] = value def _getItem(self, key): return self.naked()[key] def _delItem(self, key): del self.naked()[key] ## Instruction: Add defcon implementation of group lookup methods. ## Code After: import defcon from fontParts.base import BaseGroups from fontParts.fontshell.base import RBaseObject class RGroups(RBaseObject, BaseGroups): wrapClass = defcon.Groups def _get_base_side1KerningGroups(self): return self.naked().getRepresentation("defcon.groups.kerningSide1Groups") def _get_base_side2KerningGroups(self): return self.naked().getRepresentation("defcon.groups.kerningSide2Groups") def _items(self): return self.naked().items() def _contains(self, key): return key in self.naked() def _setItem(self, key, value): self.naked()[key] = value def _getItem(self, key): return self.naked()[key] def _delItem(self, key): del self.naked()[key]
import defcon from fontParts.base import BaseGroups from fontParts.fontshell.base import RBaseObject class RGroups(RBaseObject, BaseGroups): wrapClass = defcon.Groups + + def _get_base_side1KerningGroups(self): + return self.naked().getRepresentation("defcon.groups.kerningSide1Groups") + + def _get_base_side2KerningGroups(self): + return self.naked().getRepresentation("defcon.groups.kerningSide2Groups") def _items(self): return self.naked().items() def _contains(self, key): return key in self.naked() def _setItem(self, key, value): self.naked()[key] = value def _getItem(self, key): return self.naked()[key] def _delItem(self, key): del self.naked()[key]
13e4d867e724f408b5d2dd21888b2f8a28d8fbc6
fabfile.py
fabfile.py
from __future__ import print_function import webbrowser import oinspect.sphinxify as oi def test_basic(): """Test with an empty context""" docstring = 'A test' content = oi.sphinxify(docstring, oi.generate_context()) page_name = '/tmp/test_basic.html' with open(page_name, 'w') as f: f.write(content) webbrowser.open_new_tab(page_name) def run_all(): """Run all tests""" test_basic()
from __future__ import print_function import webbrowser import oinspect.sphinxify as oi def _show_page(content, fname): with open(fname, 'w') as f: f.write(content) webbrowser.open_new_tab(fname) def test_basic(): """Test with an empty context""" docstring = 'A test' content = oi.sphinxify(docstring, oi.generate_context()) _show_page(content, '/tmp/test_basic.html') def test_math(): """Test a docstring with Latex on it""" docstring = 'This is a rational number :math:`\\frac{x}{y}`' content = oi.sphinxify(docstring, oi.generate_context()) _show_page(content, '/tmp/test_math.html') def run_all(): """Run all tests""" test_basic()
Add a test for math
Add a test for math
Python
bsd-3-clause
techtonik/docrepr,spyder-ide/docrepr,techtonik/docrepr,techtonik/docrepr,spyder-ide/docrepr,spyder-ide/docrepr
from __future__ import print_function import webbrowser import oinspect.sphinxify as oi + def _show_page(content, fname): + with open(fname, 'w') as f: + f.write(content) + webbrowser.open_new_tab(fname) + def test_basic(): """Test with an empty context""" docstring = 'A test' content = oi.sphinxify(docstring, oi.generate_context()) - page_name = '/tmp/test_basic.html' + _show_page(content, '/tmp/test_basic.html') - with open(page_name, 'w') as f: - f.write(content) - webbrowser.open_new_tab(page_name) + + def test_math(): + """Test a docstring with Latex on it""" + docstring = 'This is a rational number :math:`\\frac{x}{y}`' + content = oi.sphinxify(docstring, oi.generate_context()) + _show_page(content, '/tmp/test_math.html') def run_all(): """Run all tests""" test_basic()
Add a test for math
## Code Before: from __future__ import print_function import webbrowser import oinspect.sphinxify as oi def test_basic(): """Test with an empty context""" docstring = 'A test' content = oi.sphinxify(docstring, oi.generate_context()) page_name = '/tmp/test_basic.html' with open(page_name, 'w') as f: f.write(content) webbrowser.open_new_tab(page_name) def run_all(): """Run all tests""" test_basic() ## Instruction: Add a test for math ## Code After: from __future__ import print_function import webbrowser import oinspect.sphinxify as oi def _show_page(content, fname): with open(fname, 'w') as f: f.write(content) webbrowser.open_new_tab(fname) def test_basic(): """Test with an empty context""" docstring = 'A test' content = oi.sphinxify(docstring, oi.generate_context()) _show_page(content, '/tmp/test_basic.html') def test_math(): """Test a docstring with Latex on it""" docstring = 'This is a rational number :math:`\\frac{x}{y}`' content = oi.sphinxify(docstring, oi.generate_context()) _show_page(content, '/tmp/test_math.html') def run_all(): """Run all tests""" test_basic()
from __future__ import print_function import webbrowser import oinspect.sphinxify as oi + def _show_page(content, fname): + with open(fname, 'w') as f: + f.write(content) + webbrowser.open_new_tab(fname) + def test_basic(): """Test with an empty context""" docstring = 'A test' content = oi.sphinxify(docstring, oi.generate_context()) - page_name = '/tmp/test_basic.html' ? ^ ^^ ^^ + _show_page(content, '/tmp/test_basic.html') ? ++++++ ^^^ ^ ^^^ + - with open(page_name, 'w') as f: - f.write(content) - webbrowser.open_new_tab(page_name) + + def test_math(): + """Test a docstring with Latex on it""" + docstring = 'This is a rational number :math:`\\frac{x}{y}`' + content = oi.sphinxify(docstring, oi.generate_context()) + _show_page(content, '/tmp/test_math.html') def run_all(): """Run all tests""" test_basic()
220748a5cc481b8df76af6a1301af94def603ee2
paci/helpers/display_helper.py
paci/helpers/display_helper.py
"""Helper to output stuff""" from tabulate import tabulate def print_list(header, entries): """Prints out a list""" print(tabulate(entries, header, tablefmt="grid")) def print_table(entries): """Prints out a table""" print(tabulate(entries, tablefmt="plain")) def std_input(text, default): """Get input or return default if none is given.""" return input(text.format(default)) or default
"""Helper to output stuff""" from tabulate import tabulate import os def print_list(header, entries): """Prints out a list""" print(tabulate(fix_descriptions(entries), header, tablefmt="presto")) def print_table(entries): """Prints out a table""" print(tabulate(cleanup_entries(entries), tablefmt="plain")) def std_input(text, default): """Get input or return default if none is given.""" return input(text.format(default)) or default def fix_descriptions(entries): """Fixes the description to fit into the terminal""" clean_entries = [] ml = get_max_desc_width(get_longest_list(entries)) for entry in entries: clean_entry = entry max_value = max(entry, key=len) for idx, val in enumerate(entry): if val is max_value: clean_entry[idx] = entry[idx][:ml] + (entry[idx][ml:] and ' [..]') clean_entries.append(clean_entry) return clean_entries def get_longest_list(entries): max_list = ['']*len(entries[0]) for entry in entries: for idx, val in enumerate(entry): if len(val) > len(max_list[idx]): max_list[idx] = val return max_list def get_max_desc_width(lst): _, columns = os.popen('stty size', 'r').read().split() length = int(columns) max_value = max(lst, key=len) for val in lst: if val is not max_value: length -= len(val) return length - 15
Fix how tables are printed on smaller screens
Fix how tables are printed on smaller screens
Python
mit
tradebyte/paci,tradebyte/paci
"""Helper to output stuff""" from tabulate import tabulate + import os def print_list(header, entries): """Prints out a list""" - print(tabulate(entries, header, tablefmt="grid")) + print(tabulate(fix_descriptions(entries), header, tablefmt="presto")) def print_table(entries): """Prints out a table""" - print(tabulate(entries, tablefmt="plain")) + print(tabulate(cleanup_entries(entries), tablefmt="plain")) def std_input(text, default): """Get input or return default if none is given.""" return input(text.format(default)) or default + + def fix_descriptions(entries): + """Fixes the description to fit into the terminal""" + + clean_entries = [] + ml = get_max_desc_width(get_longest_list(entries)) + + for entry in entries: + clean_entry = entry + max_value = max(entry, key=len) + for idx, val in enumerate(entry): + if val is max_value: + clean_entry[idx] = entry[idx][:ml] + (entry[idx][ml:] and ' [..]') + clean_entries.append(clean_entry) + + return clean_entries + + + def get_longest_list(entries): + max_list = ['']*len(entries[0]) + for entry in entries: + for idx, val in enumerate(entry): + if len(val) > len(max_list[idx]): + max_list[idx] = val + return max_list + + + def get_max_desc_width(lst): + _, columns = os.popen('stty size', 'r').read().split() + length = int(columns) + max_value = max(lst, key=len) + for val in lst: + if val is not max_value: + length -= len(val) + + return length - 15 +
Fix how tables are printed on smaller screens
## Code Before: """Helper to output stuff""" from tabulate import tabulate def print_list(header, entries): """Prints out a list""" print(tabulate(entries, header, tablefmt="grid")) def print_table(entries): """Prints out a table""" print(tabulate(entries, tablefmt="plain")) def std_input(text, default): """Get input or return default if none is given.""" return input(text.format(default)) or default ## Instruction: Fix how tables are printed on smaller screens ## Code After: """Helper to output stuff""" from tabulate import tabulate import os def print_list(header, entries): """Prints out a list""" print(tabulate(fix_descriptions(entries), header, tablefmt="presto")) def print_table(entries): """Prints out a table""" print(tabulate(cleanup_entries(entries), tablefmt="plain")) def std_input(text, default): """Get input or return default if none is given.""" return input(text.format(default)) or default def fix_descriptions(entries): """Fixes the description to fit into the terminal""" clean_entries = [] ml = get_max_desc_width(get_longest_list(entries)) for entry in entries: clean_entry = entry max_value = max(entry, key=len) for idx, val in enumerate(entry): if val is max_value: clean_entry[idx] = entry[idx][:ml] + (entry[idx][ml:] and ' [..]') clean_entries.append(clean_entry) return clean_entries def get_longest_list(entries): max_list = ['']*len(entries[0]) for entry in entries: for idx, val in enumerate(entry): if len(val) > len(max_list[idx]): max_list[idx] = val return max_list def get_max_desc_width(lst): _, columns = os.popen('stty size', 'r').read().split() length = int(columns) max_value = max(lst, key=len) for val in lst: if val is not max_value: length -= len(val) return length - 15
"""Helper to output stuff""" from tabulate import tabulate + import os def print_list(header, entries): """Prints out a list""" - print(tabulate(entries, header, tablefmt="grid")) ? ^ ^^ + print(tabulate(fix_descriptions(entries), header, tablefmt="presto")) ? +++++++++++++++++ + ^ ^^^^ def print_table(entries): """Prints out a table""" - print(tabulate(entries, tablefmt="plain")) + print(tabulate(cleanup_entries(entries), tablefmt="plain")) ? ++++++++ +++++++++ def std_input(text, default): """Get input or return default if none is given.""" return input(text.format(default)) or default + + + def fix_descriptions(entries): + """Fixes the description to fit into the terminal""" + + clean_entries = [] + ml = get_max_desc_width(get_longest_list(entries)) + + for entry in entries: + clean_entry = entry + max_value = max(entry, key=len) + for idx, val in enumerate(entry): + if val is max_value: + clean_entry[idx] = entry[idx][:ml] + (entry[idx][ml:] and ' [..]') + clean_entries.append(clean_entry) + + return clean_entries + + + def get_longest_list(entries): + max_list = ['']*len(entries[0]) + for entry in entries: + for idx, val in enumerate(entry): + if len(val) > len(max_list[idx]): + max_list[idx] = val + return max_list + + + def get_max_desc_width(lst): + _, columns = os.popen('stty size', 'r').read().split() + length = int(columns) + max_value = max(lst, key=len) + for val in lst: + if val is not max_value: + length -= len(val) + + return length - 15
cc184c3e4a911bab38ec5feb62a3fbef3c81ff08
main/management/commands/poll_rss.py
main/management/commands/poll_rss.py
from datetime import datetime from time import mktime from django.core.management.base import BaseCommand from django.utils.timezone import get_default_timezone, make_aware from feedparser import parse from ...models import Link class Command(BaseCommand): def handle(self, *urls, **options): for url in urls: for entry in parse(url).entries: link = self.entry_to_link_dict(entry) try: Link.objects.get(link=link["link"]) except Link.DoesNotExist: Link.objects.create(**link) def entry_to_link_dict(self, entry): link = {"title": entry.title, "user_id": 1} try: link["link"] = entry.summary.split('href="')[2].split('"')[0] except IndexError: link["link"] = entry.link try: publish_date = entry.published_parsed except AttributeError: pass else: publish_date = datetime.fromtimestamp(mktime(publish_date)) publish_date = make_aware(publish_date, get_default_timezone()) link["publish_date"] = publish_date return link
from datetime import datetime from time import mktime from django.core.management.base import BaseCommand from django.utils.timezone import get_default_timezone, make_aware from feedparser import parse from ...models import Link class Command(BaseCommand): def handle(self, *urls, **options): for url in urls: for entry in parse(url).entries: link = self.entry_to_link_dict(entry) try: Link.objects.get(link=link["link"]) except Link.DoesNotExist: Link.objects.create(**link) def entry_to_link_dict(self, entry): link = {"title": entry.title, "user_id": 1, "gen_description": False} try: link["link"] = entry.summary.split('href="')[2].split('"')[0] except IndexError: link["link"] = entry.link try: publish_date = entry.published_parsed except AttributeError: pass else: publish_date = datetime.fromtimestamp(mktime(publish_date)) publish_date = make_aware(publish_date, get_default_timezone()) link["publish_date"] = publish_date return link
Set correct gen_description in rss importer.
Set correct gen_description in rss importer.
Python
bsd-2-clause
abendig/drum,abendig/drum,yodermk/drum,renyi/drum,baturay/ne-istiyoruz,stephenmcd/drum,yodermk/drum,skybluejamie/wikipeace,skybluejamie/wikipeace,renyi/drum,tsybulevskij/drum,sing1ee/drum,tsybulevskij/drum,baturay/ne-istiyoruz,stephenmcd/drum,renyi/drum,yodermk/drum,j00bar/drum,j00bar/drum,sing1ee/drum,j00bar/drum,tsybulevskij/drum,abendig/drum,sing1ee/drum
from datetime import datetime from time import mktime from django.core.management.base import BaseCommand from django.utils.timezone import get_default_timezone, make_aware from feedparser import parse from ...models import Link class Command(BaseCommand): def handle(self, *urls, **options): for url in urls: for entry in parse(url).entries: link = self.entry_to_link_dict(entry) try: Link.objects.get(link=link["link"]) except Link.DoesNotExist: Link.objects.create(**link) def entry_to_link_dict(self, entry): - link = {"title": entry.title, "user_id": 1} + link = {"title": entry.title, "user_id": 1, "gen_description": False} try: link["link"] = entry.summary.split('href="')[2].split('"')[0] except IndexError: link["link"] = entry.link try: publish_date = entry.published_parsed except AttributeError: pass else: publish_date = datetime.fromtimestamp(mktime(publish_date)) publish_date = make_aware(publish_date, get_default_timezone()) link["publish_date"] = publish_date return link
Set correct gen_description in rss importer.
## Code Before: from datetime import datetime from time import mktime from django.core.management.base import BaseCommand from django.utils.timezone import get_default_timezone, make_aware from feedparser import parse from ...models import Link class Command(BaseCommand): def handle(self, *urls, **options): for url in urls: for entry in parse(url).entries: link = self.entry_to_link_dict(entry) try: Link.objects.get(link=link["link"]) except Link.DoesNotExist: Link.objects.create(**link) def entry_to_link_dict(self, entry): link = {"title": entry.title, "user_id": 1} try: link["link"] = entry.summary.split('href="')[2].split('"')[0] except IndexError: link["link"] = entry.link try: publish_date = entry.published_parsed except AttributeError: pass else: publish_date = datetime.fromtimestamp(mktime(publish_date)) publish_date = make_aware(publish_date, get_default_timezone()) link["publish_date"] = publish_date return link ## Instruction: Set correct gen_description in rss importer. ## Code After: from datetime import datetime from time import mktime from django.core.management.base import BaseCommand from django.utils.timezone import get_default_timezone, make_aware from feedparser import parse from ...models import Link class Command(BaseCommand): def handle(self, *urls, **options): for url in urls: for entry in parse(url).entries: link = self.entry_to_link_dict(entry) try: Link.objects.get(link=link["link"]) except Link.DoesNotExist: Link.objects.create(**link) def entry_to_link_dict(self, entry): link = {"title": entry.title, "user_id": 1, "gen_description": False} try: link["link"] = entry.summary.split('href="')[2].split('"')[0] except IndexError: link["link"] = entry.link try: publish_date = entry.published_parsed except AttributeError: pass else: publish_date = datetime.fromtimestamp(mktime(publish_date)) publish_date = make_aware(publish_date, get_default_timezone()) link["publish_date"] = publish_date return link
from datetime import datetime from time import mktime from django.core.management.base import BaseCommand from django.utils.timezone import get_default_timezone, make_aware from feedparser import parse from ...models import Link class Command(BaseCommand): def handle(self, *urls, **options): for url in urls: for entry in parse(url).entries: link = self.entry_to_link_dict(entry) try: Link.objects.get(link=link["link"]) except Link.DoesNotExist: Link.objects.create(**link) def entry_to_link_dict(self, entry): - link = {"title": entry.title, "user_id": 1} + link = {"title": entry.title, "user_id": 1, "gen_description": False} ? ++++++++++++++++++++++++++ try: link["link"] = entry.summary.split('href="')[2].split('"')[0] except IndexError: link["link"] = entry.link try: publish_date = entry.published_parsed except AttributeError: pass else: publish_date = datetime.fromtimestamp(mktime(publish_date)) publish_date = make_aware(publish_date, get_default_timezone()) link["publish_date"] = publish_date return link
e264d00fa37dd1b326f1296badd74fa4ab599a45
project/runner.py
project/runner.py
from subprocess import Popen, PIPE from django.test.runner import DiscoverRunner class CustomTestRunner(DiscoverRunner): """ Same as the default Django test runner, except it also runs our node server as a subprocess so we can render React components. """ def setup_test_environment(self, **kwargs): # Start the node server self.node_server = Popen(['node', 'react-server.js'], stdout=PIPE) # Wait until the server is ready before proceeding _ = self.node_server.stdout.readline() super(CustomTestRunner, self).setup_test_environment(**kwargs) def teardown_test_environment(self, **kwargs): # Kill the node server self.node_server.terminate() super(CustomTestRunner, self).teardown_test_environment(**kwargs)
from subprocess import Popen, PIPE from django.test.runner import DiscoverRunner from django.conf import settings from react.render_server import render_server TEST_REACT_SERVER_HOST = getattr(settings, 'TEST_REACT_SERVER_HOST', '127.0.0.1') TEST_REACT_SERVER_PORT = getattr(settings, 'TEST_REACT_SERVER_PORT', 9008) class CustomTestRunner(DiscoverRunner): """ Same as the default Django test runner, except it also runs our node server as a subprocess so we can render React components. """ def setup_test_environment(self, **kwargs): # Start the test node server self.node_server = Popen( [ 'node', 'react-server.js', '--host=%s' % TEST_REACT_SERVER_HOST, '--port=%s' % TEST_REACT_SERVER_PORT ], stdout=PIPE ) # Wait until the server is ready before proceeding self.node_server.stdout.readline() # Point the renderer to our new test server render_server.url = 'http://%s:%s' % ( TEST_REACT_SERVER_HOST, TEST_REACT_SERVER_PORT) super(CustomTestRunner, self).setup_test_environment(**kwargs) def teardown_test_environment(self, **kwargs): # Kill the node server self.node_server.terminate() super(CustomTestRunner, self).teardown_test_environment(**kwargs)
Use separate node server when running the tests
Use separate node server when running the tests
Python
mit
jphalip/django-react-djangocon2015,jphalip/django-react-djangocon2015,jphalip/django-react-djangocon2015
from subprocess import Popen, PIPE from django.test.runner import DiscoverRunner + from django.conf import settings + from react.render_server import render_server + + + TEST_REACT_SERVER_HOST = getattr(settings, 'TEST_REACT_SERVER_HOST', '127.0.0.1') + TEST_REACT_SERVER_PORT = getattr(settings, 'TEST_REACT_SERVER_PORT', 9008) class CustomTestRunner(DiscoverRunner): """ Same as the default Django test runner, except it also runs our node server as a subprocess so we can render React components. """ def setup_test_environment(self, **kwargs): - # Start the node server + # Start the test node server - self.node_server = Popen(['node', 'react-server.js'], stdout=PIPE) + self.node_server = Popen( + [ + 'node', + 'react-server.js', + '--host=%s' % TEST_REACT_SERVER_HOST, + '--port=%s' % TEST_REACT_SERVER_PORT + ], + stdout=PIPE + ) # Wait until the server is ready before proceeding - _ = self.node_server.stdout.readline() + self.node_server.stdout.readline() + # Point the renderer to our new test server + render_server.url = 'http://%s:%s' % ( + TEST_REACT_SERVER_HOST, TEST_REACT_SERVER_PORT) super(CustomTestRunner, self).setup_test_environment(**kwargs) def teardown_test_environment(self, **kwargs): # Kill the node server self.node_server.terminate() super(CustomTestRunner, self).teardown_test_environment(**kwargs)
Use separate node server when running the tests
## Code Before: from subprocess import Popen, PIPE from django.test.runner import DiscoverRunner class CustomTestRunner(DiscoverRunner): """ Same as the default Django test runner, except it also runs our node server as a subprocess so we can render React components. """ def setup_test_environment(self, **kwargs): # Start the node server self.node_server = Popen(['node', 'react-server.js'], stdout=PIPE) # Wait until the server is ready before proceeding _ = self.node_server.stdout.readline() super(CustomTestRunner, self).setup_test_environment(**kwargs) def teardown_test_environment(self, **kwargs): # Kill the node server self.node_server.terminate() super(CustomTestRunner, self).teardown_test_environment(**kwargs) ## Instruction: Use separate node server when running the tests ## Code After: from subprocess import Popen, PIPE from django.test.runner import DiscoverRunner from django.conf import settings from react.render_server import render_server TEST_REACT_SERVER_HOST = getattr(settings, 'TEST_REACT_SERVER_HOST', '127.0.0.1') TEST_REACT_SERVER_PORT = getattr(settings, 'TEST_REACT_SERVER_PORT', 9008) class CustomTestRunner(DiscoverRunner): """ Same as the default Django test runner, except it also runs our node server as a subprocess so we can render React components. """ def setup_test_environment(self, **kwargs): # Start the test node server self.node_server = Popen( [ 'node', 'react-server.js', '--host=%s' % TEST_REACT_SERVER_HOST, '--port=%s' % TEST_REACT_SERVER_PORT ], stdout=PIPE ) # Wait until the server is ready before proceeding self.node_server.stdout.readline() # Point the renderer to our new test server render_server.url = 'http://%s:%s' % ( TEST_REACT_SERVER_HOST, TEST_REACT_SERVER_PORT) super(CustomTestRunner, self).setup_test_environment(**kwargs) def teardown_test_environment(self, **kwargs): # Kill the node server self.node_server.terminate() super(CustomTestRunner, self).teardown_test_environment(**kwargs)
from subprocess import Popen, PIPE from django.test.runner import DiscoverRunner + from django.conf import settings + from react.render_server import render_server + + + TEST_REACT_SERVER_HOST = getattr(settings, 'TEST_REACT_SERVER_HOST', '127.0.0.1') + TEST_REACT_SERVER_PORT = getattr(settings, 'TEST_REACT_SERVER_PORT', 9008) class CustomTestRunner(DiscoverRunner): """ Same as the default Django test runner, except it also runs our node server as a subprocess so we can render React components. """ def setup_test_environment(self, **kwargs): - # Start the node server + # Start the test node server ? +++++ - self.node_server = Popen(['node', 'react-server.js'], stdout=PIPE) + self.node_server = Popen( + [ + 'node', + 'react-server.js', + '--host=%s' % TEST_REACT_SERVER_HOST, + '--port=%s' % TEST_REACT_SERVER_PORT + ], + stdout=PIPE + ) # Wait until the server is ready before proceeding - _ = self.node_server.stdout.readline() ? ---- + self.node_server.stdout.readline() + # Point the renderer to our new test server + render_server.url = 'http://%s:%s' % ( + TEST_REACT_SERVER_HOST, TEST_REACT_SERVER_PORT) super(CustomTestRunner, self).setup_test_environment(**kwargs) def teardown_test_environment(self, **kwargs): # Kill the node server self.node_server.terminate() super(CustomTestRunner, self).teardown_test_environment(**kwargs)
0b5cc3f4702081eb565ef83c3175efc4e8b30e75
circuits/node/node.py
circuits/node/node.py
from .client import Client from .server import Server from circuits import handler, BaseComponent class Node(BaseComponent): """Node ... """ channel = "node" def __init__(self, bind=None, channel=channel, **kwargs): super(Node, self).__init__(channel=channel, **kwargs) self.bind = bind self.nodes = {} self.__client_event_firewall = kwargs.get( 'client_event_firewall', None ) if self.bind is not None: self.server = Server( self.bind, channel=channel, **kwargs ).register(self) else: self.server = None def add(self, name, host, port, **kwargs): channel = kwargs['channel'] if 'channel' in kwargs else \ '%s_client_%s' % (self.channel, name) node = Client(host, port, channel=channel, **kwargs) node.register(self) self.nodes[name] = node return channel @handler("remote") def _on_remote(self, event, e, client_name, channel=None): if self.__client_event_firewall and \ not self.__client_event_firewall(event, client_name, channel): return node = self.nodes[client_name] if channel is not None: e.channels = (channel,) return node.send(event, e)
from .client import Client from .server import Server from circuits import handler, BaseComponent class Node(BaseComponent): """Node ... """ channel = "node" def __init__(self, bind=None, channel=channel, **kwargs): super(Node, self).__init__(channel=channel, **kwargs) self.bind = bind self.nodes = {} self.__client_event_firewall = kwargs.get( 'client_event_firewall', None ) if self.bind is not None: self.server = Server( self.bind, channel=channel, **kwargs ).register(self) else: self.server = None def add(self, name, host, port, **kwargs): channel = kwargs.pop('channel', '%s_client_%s' % (self.channel, name)) node = Client(host, port, channel=channel, **kwargs) node.register(self) self.nodes[name] = node return channel @handler("remote") def _on_remote(self, event, e, client_name, channel=None): if self.__client_event_firewall and \ not self.__client_event_firewall(event, client_name, channel): return node = self.nodes[client_name] if channel is not None: e.channels = (channel,) return node.send(event, e)
Fix channel definition in add method
Fix channel definition in add method
Python
mit
eriol/circuits,eriol/circuits,treemo/circuits,nizox/circuits,eriol/circuits,treemo/circuits,treemo/circuits
from .client import Client from .server import Server from circuits import handler, BaseComponent class Node(BaseComponent): """Node ... """ channel = "node" def __init__(self, bind=None, channel=channel, **kwargs): super(Node, self).__init__(channel=channel, **kwargs) self.bind = bind self.nodes = {} self.__client_event_firewall = kwargs.get( 'client_event_firewall', None ) if self.bind is not None: self.server = Server( self.bind, channel=channel, **kwargs ).register(self) else: self.server = None def add(self, name, host, port, **kwargs): + channel = kwargs.pop('channel', '%s_client_%s' % (self.channel, name)) - channel = kwargs['channel'] if 'channel' in kwargs else \ - '%s_client_%s' % (self.channel, name) node = Client(host, port, channel=channel, **kwargs) node.register(self) self.nodes[name] = node return channel @handler("remote") def _on_remote(self, event, e, client_name, channel=None): if self.__client_event_firewall and \ not self.__client_event_firewall(event, client_name, channel): return node = self.nodes[client_name] if channel is not None: e.channels = (channel,) return node.send(event, e)
Fix channel definition in add method
## Code Before: from .client import Client from .server import Server from circuits import handler, BaseComponent class Node(BaseComponent): """Node ... """ channel = "node" def __init__(self, bind=None, channel=channel, **kwargs): super(Node, self).__init__(channel=channel, **kwargs) self.bind = bind self.nodes = {} self.__client_event_firewall = kwargs.get( 'client_event_firewall', None ) if self.bind is not None: self.server = Server( self.bind, channel=channel, **kwargs ).register(self) else: self.server = None def add(self, name, host, port, **kwargs): channel = kwargs['channel'] if 'channel' in kwargs else \ '%s_client_%s' % (self.channel, name) node = Client(host, port, channel=channel, **kwargs) node.register(self) self.nodes[name] = node return channel @handler("remote") def _on_remote(self, event, e, client_name, channel=None): if self.__client_event_firewall and \ not self.__client_event_firewall(event, client_name, channel): return node = self.nodes[client_name] if channel is not None: e.channels = (channel,) return node.send(event, e) ## Instruction: Fix channel definition in add method ## Code After: from .client import Client from .server import Server from circuits import handler, BaseComponent class Node(BaseComponent): """Node ... """ channel = "node" def __init__(self, bind=None, channel=channel, **kwargs): super(Node, self).__init__(channel=channel, **kwargs) self.bind = bind self.nodes = {} self.__client_event_firewall = kwargs.get( 'client_event_firewall', None ) if self.bind is not None: self.server = Server( self.bind, channel=channel, **kwargs ).register(self) else: self.server = None def add(self, name, host, port, **kwargs): channel = kwargs.pop('channel', '%s_client_%s' % (self.channel, name)) node = Client(host, port, channel=channel, **kwargs) node.register(self) self.nodes[name] = node return channel @handler("remote") def _on_remote(self, event, e, client_name, channel=None): if self.__client_event_firewall and \ not self.__client_event_firewall(event, client_name, channel): return node = self.nodes[client_name] if channel is not None: e.channels = (channel,) return node.send(event, e)
from .client import Client from .server import Server from circuits import handler, BaseComponent class Node(BaseComponent): """Node ... """ channel = "node" def __init__(self, bind=None, channel=channel, **kwargs): super(Node, self).__init__(channel=channel, **kwargs) self.bind = bind self.nodes = {} self.__client_event_firewall = kwargs.get( 'client_event_firewall', None ) if self.bind is not None: self.server = Server( self.bind, channel=channel, **kwargs ).register(self) else: self.server = None def add(self, name, host, port, **kwargs): - channel = kwargs['channel'] if 'channel' in kwargs else \ - '%s_client_%s' % (self.channel, name) ? ^ + channel = kwargs.pop('channel', '%s_client_%s' % (self.channel, name)) ? +++++++ + ^^^^^^^^^^^^^^^^^^^^^ + node = Client(host, port, channel=channel, **kwargs) node.register(self) self.nodes[name] = node return channel @handler("remote") def _on_remote(self, event, e, client_name, channel=None): if self.__client_event_firewall and \ not self.__client_event_firewall(event, client_name, channel): return node = self.nodes[client_name] if channel is not None: e.channels = (channel,) return node.send(event, e)
0166d699096aa506e37b6a2df8e51f94895c0b4f
fireplace/cards/wog/neutral_rare.py
fireplace/cards/wog/neutral_rare.py
from ..utils import * ## # Minions class OG_034: "Silithid Swarmer" update = (NUM_ATTACKS_THIS_TURN(FRIENDLY_HERO) == 0) & ( Refresh(SELF, {GameTag.CANT_ATTACK: True}) ) class OG_254: "Eater of Secrets" play = ( Buff(SELF, "OG_254e") * Count(ENEMY_SECRETS), Destroy(ENEMY_SECRETS) ) OG_254e = buff(+1, +1) class OG_322: "Blackwater Pirate" update = Refresh(FRIENDLY_HAND + WEAPON, {GameTag.COST: -2})
from ..utils import * ## # Minions class OG_034: "Silithid Swarmer" update = (NUM_ATTACKS_THIS_TURN(FRIENDLY_HERO) == 0) & ( Refresh(SELF, {GameTag.CANT_ATTACK: True}) ) class OG_147: "Corrupted Healbot" deathrattle = Heal(ENEMY_HERO, 8) class OG_161: "Corrupted Seer" play = Hit(ALL_MINIONS - MURLOC, 2) class OG_254: "Eater of Secrets" play = ( Buff(SELF, "OG_254e") * Count(ENEMY_SECRETS), Destroy(ENEMY_SECRETS) ) OG_254e = buff(+1, +1) class OG_320: "Midnight Drake" play = Buff(SELF, "OG_320e") * Count(FRIENDLY_HAND) OG_320e = buff(atk=1) class OG_322: "Blackwater Pirate" update = Refresh(FRIENDLY_HAND + WEAPON, {GameTag.COST: -2})
Implement Corrupted Healbot, Corrupted Seer, and Midnight Drake
Implement Corrupted Healbot, Corrupted Seer, and Midnight Drake
Python
agpl-3.0
NightKev/fireplace,beheh/fireplace,jleclanche/fireplace
from ..utils import * ## # Minions class OG_034: "Silithid Swarmer" update = (NUM_ATTACKS_THIS_TURN(FRIENDLY_HERO) == 0) & ( Refresh(SELF, {GameTag.CANT_ATTACK: True}) ) + class OG_147: + "Corrupted Healbot" + deathrattle = Heal(ENEMY_HERO, 8) + + + class OG_161: + "Corrupted Seer" + play = Hit(ALL_MINIONS - MURLOC, 2) + + class OG_254: "Eater of Secrets" play = ( Buff(SELF, "OG_254e") * Count(ENEMY_SECRETS), Destroy(ENEMY_SECRETS) ) OG_254e = buff(+1, +1) + class OG_320: + "Midnight Drake" + play = Buff(SELF, "OG_320e") * Count(FRIENDLY_HAND) + + OG_320e = buff(atk=1) + + class OG_322: "Blackwater Pirate" update = Refresh(FRIENDLY_HAND + WEAPON, {GameTag.COST: -2})
Implement Corrupted Healbot, Corrupted Seer, and Midnight Drake
## Code Before: from ..utils import * ## # Minions class OG_034: "Silithid Swarmer" update = (NUM_ATTACKS_THIS_TURN(FRIENDLY_HERO) == 0) & ( Refresh(SELF, {GameTag.CANT_ATTACK: True}) ) class OG_254: "Eater of Secrets" play = ( Buff(SELF, "OG_254e") * Count(ENEMY_SECRETS), Destroy(ENEMY_SECRETS) ) OG_254e = buff(+1, +1) class OG_322: "Blackwater Pirate" update = Refresh(FRIENDLY_HAND + WEAPON, {GameTag.COST: -2}) ## Instruction: Implement Corrupted Healbot, Corrupted Seer, and Midnight Drake ## Code After: from ..utils import * ## # Minions class OG_034: "Silithid Swarmer" update = (NUM_ATTACKS_THIS_TURN(FRIENDLY_HERO) == 0) & ( Refresh(SELF, {GameTag.CANT_ATTACK: True}) ) class OG_147: "Corrupted Healbot" deathrattle = Heal(ENEMY_HERO, 8) class OG_161: "Corrupted Seer" play = Hit(ALL_MINIONS - MURLOC, 2) class OG_254: "Eater of Secrets" play = ( Buff(SELF, "OG_254e") * Count(ENEMY_SECRETS), Destroy(ENEMY_SECRETS) ) OG_254e = buff(+1, +1) class OG_320: "Midnight Drake" play = Buff(SELF, "OG_320e") * Count(FRIENDLY_HAND) OG_320e = buff(atk=1) class OG_322: "Blackwater Pirate" update = Refresh(FRIENDLY_HAND + WEAPON, {GameTag.COST: -2})
from ..utils import * ## # Minions class OG_034: "Silithid Swarmer" update = (NUM_ATTACKS_THIS_TURN(FRIENDLY_HERO) == 0) & ( Refresh(SELF, {GameTag.CANT_ATTACK: True}) ) + class OG_147: + "Corrupted Healbot" + deathrattle = Heal(ENEMY_HERO, 8) + + + class OG_161: + "Corrupted Seer" + play = Hit(ALL_MINIONS - MURLOC, 2) + + class OG_254: "Eater of Secrets" play = ( Buff(SELF, "OG_254e") * Count(ENEMY_SECRETS), Destroy(ENEMY_SECRETS) ) OG_254e = buff(+1, +1) + class OG_320: + "Midnight Drake" + play = Buff(SELF, "OG_320e") * Count(FRIENDLY_HAND) + + OG_320e = buff(atk=1) + + class OG_322: "Blackwater Pirate" update = Refresh(FRIENDLY_HAND + WEAPON, {GameTag.COST: -2})
9ad378244cf8ca8a28b01ae1c7e166dbeff9a3fb
odoo/addons/test_main_flows/__manifest__.py
odoo/addons/test_main_flows/__manifest__.py
{ 'name': 'Test Main Flow', 'version': '1.0', 'category': 'Tools', 'description': """ This module will test the main workflow of Odoo. It will install some main apps and will try to execute the most important actions. """, 'depends': ['web_tour', 'crm', 'sale_timesheet', 'purchase', 'mrp', 'account_accountant'], 'data': [ 'views/templates.xml', ], 'installable': True, }
{ 'name': 'Test Main Flow', 'version': '1.0', 'category': 'Tools', 'description': """ This module will test the main workflow of Odoo. It will install some main apps and will try to execute the most important actions. """, 'depends': ['web_tour', 'crm', 'sale_timesheet', 'purchase', 'mrp', 'account'], 'data': [ 'views/templates.xml', ], 'installable': True, }
Revert "[FIX] test_main_flows: missing dependency to run it in a browser"
Revert "[FIX] test_main_flows: missing dependency to run it in a browser" This reverts commit 58e914425033a9604885fb0cdd7de1a6a144c4da.
Python
agpl-3.0
ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo
{ 'name': 'Test Main Flow', 'version': '1.0', 'category': 'Tools', 'description': """ This module will test the main workflow of Odoo. It will install some main apps and will try to execute the most important actions. """, - 'depends': ['web_tour', 'crm', 'sale_timesheet', 'purchase', 'mrp', 'account_accountant'], + 'depends': ['web_tour', 'crm', 'sale_timesheet', 'purchase', 'mrp', 'account'], 'data': [ 'views/templates.xml', ], 'installable': True, }
Revert "[FIX] test_main_flows: missing dependency to run it in a browser"
## Code Before: { 'name': 'Test Main Flow', 'version': '1.0', 'category': 'Tools', 'description': """ This module will test the main workflow of Odoo. It will install some main apps and will try to execute the most important actions. """, 'depends': ['web_tour', 'crm', 'sale_timesheet', 'purchase', 'mrp', 'account_accountant'], 'data': [ 'views/templates.xml', ], 'installable': True, } ## Instruction: Revert "[FIX] test_main_flows: missing dependency to run it in a browser" ## Code After: { 'name': 'Test Main Flow', 'version': '1.0', 'category': 'Tools', 'description': """ This module will test the main workflow of Odoo. It will install some main apps and will try to execute the most important actions. """, 'depends': ['web_tour', 'crm', 'sale_timesheet', 'purchase', 'mrp', 'account'], 'data': [ 'views/templates.xml', ], 'installable': True, }
{ 'name': 'Test Main Flow', 'version': '1.0', 'category': 'Tools', 'description': """ This module will test the main workflow of Odoo. It will install some main apps and will try to execute the most important actions. """, - 'depends': ['web_tour', 'crm', 'sale_timesheet', 'purchase', 'mrp', 'account_accountant'], ? ----------- + 'depends': ['web_tour', 'crm', 'sale_timesheet', 'purchase', 'mrp', 'account'], 'data': [ 'views/templates.xml', ], 'installable': True, }
9a8f27fb6b3cec373d841b0973ee59f2ddd0b875
fabfile.py
fabfile.py
from fabric.api import env, local, cd, run env.use_ssh_config = True env.hosts = ['root@skylines'] def deploy(branch='master', force=False): push(branch, force) restart() def push(branch='master', force=False): cmd = 'git push %s:/opt/skylines/src/ %s:master' % (env.host_string, branch) if force: cmd += ' --force' local(cmd) def restart(): with cd('/opt/skylines/src'): run('git reset --hard') # compile i18n .mo files run('./manage.py babel compile') # generate JS/CSS assets run('./manage.py assets build') # do database migrations run('sudo -u skylines ./manage.py migrate upgrade') # restart services restart_service('skylines-fastcgi') restart_service('mapserver-fastcgi') restart_service('skylines-daemon') restart_service('celery-daemon') def restart_service(service): run('sv restart ' + service)
from fabric.api import env, local, cd, run, settings, sudo env.use_ssh_config = True env.hosts = ['root@skylines'] def deploy(branch='master', force=False): push(branch, force) restart() def push(branch='master', force=False): cmd = 'git push %s:/opt/skylines/src/ %s:master' % (env.host_string, branch) if force: cmd += ' --force' local(cmd) def restart(): with cd('/opt/skylines/src'): run('git reset --hard') # compile i18n .mo files run('./manage.py babel compile') # generate JS/CSS assets run('./manage.py assets build') # do database migrations with settings(sudo_user='skylines'): sudo('./manage.py migrate upgrade') # restart services restart_service('skylines-fastcgi') restart_service('mapserver-fastcgi') restart_service('skylines-daemon') restart_service('celery-daemon') def restart_service(service): run('sv restart ' + service)
Use sudo() function for db migration call
fabric: Use sudo() function for db migration call
Python
agpl-3.0
RBE-Avionik/skylines,shadowoneau/skylines,RBE-Avionik/skylines,Harry-R/skylines,Turbo87/skylines,Harry-R/skylines,skylines-project/skylines,TobiasLohner/SkyLines,shadowoneau/skylines,RBE-Avionik/skylines,kerel-fs/skylines,kerel-fs/skylines,snip/skylines,skylines-project/skylines,shadowoneau/skylines,Harry-R/skylines,shadowoneau/skylines,snip/skylines,TobiasLohner/SkyLines,Turbo87/skylines,Harry-R/skylines,snip/skylines,skylines-project/skylines,Turbo87/skylines,kerel-fs/skylines,Turbo87/skylines,TobiasLohner/SkyLines,RBE-Avionik/skylines,skylines-project/skylines
- from fabric.api import env, local, cd, run + from fabric.api import env, local, cd, run, settings, sudo env.use_ssh_config = True env.hosts = ['root@skylines'] def deploy(branch='master', force=False): push(branch, force) restart() def push(branch='master', force=False): cmd = 'git push %s:/opt/skylines/src/ %s:master' % (env.host_string, branch) if force: cmd += ' --force' local(cmd) def restart(): with cd('/opt/skylines/src'): run('git reset --hard') # compile i18n .mo files run('./manage.py babel compile') # generate JS/CSS assets run('./manage.py assets build') # do database migrations + with settings(sudo_user='skylines'): - run('sudo -u skylines ./manage.py migrate upgrade') + sudo('./manage.py migrate upgrade') # restart services restart_service('skylines-fastcgi') restart_service('mapserver-fastcgi') restart_service('skylines-daemon') restart_service('celery-daemon') def restart_service(service): run('sv restart ' + service)
Use sudo() function for db migration call
## Code Before: from fabric.api import env, local, cd, run env.use_ssh_config = True env.hosts = ['root@skylines'] def deploy(branch='master', force=False): push(branch, force) restart() def push(branch='master', force=False): cmd = 'git push %s:/opt/skylines/src/ %s:master' % (env.host_string, branch) if force: cmd += ' --force' local(cmd) def restart(): with cd('/opt/skylines/src'): run('git reset --hard') # compile i18n .mo files run('./manage.py babel compile') # generate JS/CSS assets run('./manage.py assets build') # do database migrations run('sudo -u skylines ./manage.py migrate upgrade') # restart services restart_service('skylines-fastcgi') restart_service('mapserver-fastcgi') restart_service('skylines-daemon') restart_service('celery-daemon') def restart_service(service): run('sv restart ' + service) ## Instruction: Use sudo() function for db migration call ## Code After: from fabric.api import env, local, cd, run, settings, sudo env.use_ssh_config = True env.hosts = ['root@skylines'] def deploy(branch='master', force=False): push(branch, force) restart() def push(branch='master', force=False): cmd = 'git push %s:/opt/skylines/src/ %s:master' % (env.host_string, branch) if force: cmd += ' --force' local(cmd) def restart(): with cd('/opt/skylines/src'): run('git reset --hard') # compile i18n .mo files run('./manage.py babel compile') # generate JS/CSS assets run('./manage.py assets build') # do database migrations with settings(sudo_user='skylines'): sudo('./manage.py migrate upgrade') # restart services restart_service('skylines-fastcgi') restart_service('mapserver-fastcgi') restart_service('skylines-daemon') restart_service('celery-daemon') def restart_service(service): run('sv restart ' + service)
- from fabric.api import env, local, cd, run + from fabric.api import env, local, cd, run, settings, sudo ? ++++++++++++++++ env.use_ssh_config = True env.hosts = ['root@skylines'] def deploy(branch='master', force=False): push(branch, force) restart() def push(branch='master', force=False): cmd = 'git push %s:/opt/skylines/src/ %s:master' % (env.host_string, branch) if force: cmd += ' --force' local(cmd) def restart(): with cd('/opt/skylines/src'): run('git reset --hard') # compile i18n .mo files run('./manage.py babel compile') # generate JS/CSS assets run('./manage.py assets build') # do database migrations + with settings(sudo_user='skylines'): - run('sudo -u skylines ./manage.py migrate upgrade') ? ^^^^^ ^^^^^^^^^^^^^ + sudo('./manage.py migrate upgrade') ? ^^^^ ^^ # restart services restart_service('skylines-fastcgi') restart_service('mapserver-fastcgi') restart_service('skylines-daemon') restart_service('celery-daemon') def restart_service(service): run('sv restart ' + service)
1ec9e85604eb8c69771a06d69681e7d7dbb00de7
node/delta.py
node/delta.py
import datetime from nodes import Node class Delta(Node): char = "$" args = 1 results = 1 @Node.test_func([[1, 2, 3, 5]], [[1, 1, 2]]) def delta(self, seq: Node.sequence): """Return the difference in terms in the input sequence. Returns a sequence of the same type, one shorter.""" deltas = [] for i in range(len(seq)-1): deltas.append(seq[i+1]-seq[i]) return[type(seq)(deltas)] def float(self, inp:Node.number): """float(inp)""" return float(inp) @Node.test_func(["HELLO"], [0]) @Node.test_func(["world"], [1]) @Node.test_func(["@"], [0]) def is_lower(self, string:str): """Is a string lower case?""" return int(string.islower()) def get_day_of_week(self, time: Node.clock): new_time = datetime.datetime(*time.time_obj[:7]) return new_time.weekday()
import datetime from nodes import Node class Delta(Node): char = "$" args = 1 results = 1 contents = ["PADDING", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] @Node.test_func([[1, 2, 3, 5]], [[1, 1, 2]]) def delta(self, seq: Node.sequence): """Return the difference in terms in the input sequence. Returns a sequence of the same type, one shorter.""" deltas = [] for i in range(len(seq)-1): deltas.append(seq[i+1]-seq[i]) return[type(seq)(deltas)] def float(self, inp:Node.number): """float(inp)""" return float(inp) @Node.test_func(["HELLO"], [0]) @Node.test_func(["world"], [1]) @Node.test_func(["@"], [0]) def is_lower(self, string:str): """Is a string lower case?""" return int(string.islower()) def get_day_of_week(self, time: Node.clock): new_time = datetime.datetime(*time.time_obj[:7]) return new_time.weekday()
Update month names of year
Update month names of year
Python
mit
muddyfish/PYKE,muddyfish/PYKE
import datetime from nodes import Node class Delta(Node): char = "$" args = 1 results = 1 + contents = ["PADDING", + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December"] @Node.test_func([[1, 2, 3, 5]], [[1, 1, 2]]) def delta(self, seq: Node.sequence): """Return the difference in terms in the input sequence. Returns a sequence of the same type, one shorter.""" deltas = [] for i in range(len(seq)-1): deltas.append(seq[i+1]-seq[i]) return[type(seq)(deltas)] def float(self, inp:Node.number): """float(inp)""" return float(inp) @Node.test_func(["HELLO"], [0]) @Node.test_func(["world"], [1]) @Node.test_func(["@"], [0]) def is_lower(self, string:str): """Is a string lower case?""" return int(string.islower()) def get_day_of_week(self, time: Node.clock): new_time = datetime.datetime(*time.time_obj[:7]) return new_time.weekday()
Update month names of year
## Code Before: import datetime from nodes import Node class Delta(Node): char = "$" args = 1 results = 1 @Node.test_func([[1, 2, 3, 5]], [[1, 1, 2]]) def delta(self, seq: Node.sequence): """Return the difference in terms in the input sequence. Returns a sequence of the same type, one shorter.""" deltas = [] for i in range(len(seq)-1): deltas.append(seq[i+1]-seq[i]) return[type(seq)(deltas)] def float(self, inp:Node.number): """float(inp)""" return float(inp) @Node.test_func(["HELLO"], [0]) @Node.test_func(["world"], [1]) @Node.test_func(["@"], [0]) def is_lower(self, string:str): """Is a string lower case?""" return int(string.islower()) def get_day_of_week(self, time: Node.clock): new_time = datetime.datetime(*time.time_obj[:7]) return new_time.weekday() ## Instruction: Update month names of year ## Code After: import datetime from nodes import Node class Delta(Node): char = "$" args = 1 results = 1 contents = ["PADDING", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] @Node.test_func([[1, 2, 3, 5]], [[1, 1, 2]]) def delta(self, seq: Node.sequence): """Return the difference in terms in the input sequence. Returns a sequence of the same type, one shorter.""" deltas = [] for i in range(len(seq)-1): deltas.append(seq[i+1]-seq[i]) return[type(seq)(deltas)] def float(self, inp:Node.number): """float(inp)""" return float(inp) @Node.test_func(["HELLO"], [0]) @Node.test_func(["world"], [1]) @Node.test_func(["@"], [0]) def is_lower(self, string:str): """Is a string lower case?""" return int(string.islower()) def get_day_of_week(self, time: Node.clock): new_time = datetime.datetime(*time.time_obj[:7]) return new_time.weekday()
import datetime from nodes import Node class Delta(Node): char = "$" args = 1 results = 1 + contents = ["PADDING", + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December"] @Node.test_func([[1, 2, 3, 5]], [[1, 1, 2]]) def delta(self, seq: Node.sequence): """Return the difference in terms in the input sequence. Returns a sequence of the same type, one shorter.""" deltas = [] for i in range(len(seq)-1): deltas.append(seq[i+1]-seq[i]) return[type(seq)(deltas)] def float(self, inp:Node.number): """float(inp)""" return float(inp) @Node.test_func(["HELLO"], [0]) @Node.test_func(["world"], [1]) @Node.test_func(["@"], [0]) def is_lower(self, string:str): """Is a string lower case?""" return int(string.islower()) def get_day_of_week(self, time: Node.clock): new_time = datetime.datetime(*time.time_obj[:7]) return new_time.weekday()
8c00c71de736c54c22fedfae86101eb99846ba4f
anyjson.py
anyjson.py
__version__ = "0.1" __author__ = "Rune Halvorsen <[email protected]>" __homepage__ = "http://bitbucket.org/runeh/anyjson/" __docformat__ = "restructuredtext" """ .. function:: serialize(obj) Serialize the object to JSON. .. function:: deserialize(obj) Deserialize JSON-encoded object to a Python object. """ # Try to import a module that provides json parsing and emitting, starting # with the fastest alternative and falling back to the slower ones. try: # cjson is the fastest import cjson serialize = cjson.encode deserialize = cjson.decode except ImportError: try: # Then try to find simplejson. Later versions has C speedups which # makes it pretty fast. import simplejson serialize = simplejson.dumps deserialize = simplejson.loads except ImportError: try: # Then try to find the python 2.6 stdlib json module. import json serialize = json.dumps deserialize = json.loads except ImportError: # If all of the above fails, try to fallback to the simplejson # embedded in Django. from django.utils import simplejson serialize = simplejson.dumps deserialize = simplejson.loads
__version__ = "0.1" __author__ = "Rune Halvorsen <[email protected]>" __homepage__ = "http://bitbucket.org/runeh/anyjson/" __docformat__ = "restructuredtext" """ .. function:: serialize(obj) Serialize the object to JSON. .. function:: deserialize(obj) Deserialize JSON-encoded object to a Python object. """ # Try to import a module that provides json parsing and emitting, starting # with the fastest alternative and falling back to the slower ones. try: # cjson is the fastest import cjson serialize = cjson.encode deserialize = cjson.decode except ImportError: try: # Then try to find simplejson. Later versions has C speedups which # makes it pretty fast. import simplejson serialize = simplejson.dumps deserialize = simplejson.loads except ImportError: try: # Then try to find the python 2.6 stdlib json module. import json serialize = json.dumps deserialize = json.loads except ImportError: try: # If all of the above fails, try to fallback to the simplejson # embedded in Django. from django.utils import simplejson serialize = simplejson.dumps deserialize = simplejson.loads except: raise ImportError("No json module found")
Raise our own ImportError if all fails. Looks better than to complain about django when that happens
Raise our own ImportError if all fails. Looks better than to complain about django when that happens
Python
bsd-3-clause
newvem/anyjson,kennethreitz-archive/anyjson
__version__ = "0.1" __author__ = "Rune Halvorsen <[email protected]>" __homepage__ = "http://bitbucket.org/runeh/anyjson/" __docformat__ = "restructuredtext" """ .. function:: serialize(obj) Serialize the object to JSON. .. function:: deserialize(obj) Deserialize JSON-encoded object to a Python object. """ # Try to import a module that provides json parsing and emitting, starting # with the fastest alternative and falling back to the slower ones. try: # cjson is the fastest import cjson serialize = cjson.encode deserialize = cjson.decode except ImportError: try: # Then try to find simplejson. Later versions has C speedups which # makes it pretty fast. import simplejson serialize = simplejson.dumps deserialize = simplejson.loads except ImportError: try: # Then try to find the python 2.6 stdlib json module. import json serialize = json.dumps deserialize = json.loads except ImportError: + try: - # If all of the above fails, try to fallback to the simplejson + # If all of the above fails, try to fallback to the simplejson - # embedded in Django. + # embedded in Django. - from django.utils import simplejson + from django.utils import simplejson - serialize = simplejson.dumps + serialize = simplejson.dumps - deserialize = simplejson.loads + deserialize = simplejson.loads + except: + raise ImportError("No json module found") +
Raise our own ImportError if all fails. Looks better than to complain about django when that happens
## Code Before: __version__ = "0.1" __author__ = "Rune Halvorsen <[email protected]>" __homepage__ = "http://bitbucket.org/runeh/anyjson/" __docformat__ = "restructuredtext" """ .. function:: serialize(obj) Serialize the object to JSON. .. function:: deserialize(obj) Deserialize JSON-encoded object to a Python object. """ # Try to import a module that provides json parsing and emitting, starting # with the fastest alternative and falling back to the slower ones. try: # cjson is the fastest import cjson serialize = cjson.encode deserialize = cjson.decode except ImportError: try: # Then try to find simplejson. Later versions has C speedups which # makes it pretty fast. import simplejson serialize = simplejson.dumps deserialize = simplejson.loads except ImportError: try: # Then try to find the python 2.6 stdlib json module. import json serialize = json.dumps deserialize = json.loads except ImportError: # If all of the above fails, try to fallback to the simplejson # embedded in Django. from django.utils import simplejson serialize = simplejson.dumps deserialize = simplejson.loads ## Instruction: Raise our own ImportError if all fails. Looks better than to complain about django when that happens ## Code After: __version__ = "0.1" __author__ = "Rune Halvorsen <[email protected]>" __homepage__ = "http://bitbucket.org/runeh/anyjson/" __docformat__ = "restructuredtext" """ .. function:: serialize(obj) Serialize the object to JSON. .. function:: deserialize(obj) Deserialize JSON-encoded object to a Python object. """ # Try to import a module that provides json parsing and emitting, starting # with the fastest alternative and falling back to the slower ones. try: # cjson is the fastest import cjson serialize = cjson.encode deserialize = cjson.decode except ImportError: try: # Then try to find simplejson. Later versions has C speedups which # makes it pretty fast. import simplejson serialize = simplejson.dumps deserialize = simplejson.loads except ImportError: try: # Then try to find the python 2.6 stdlib json module. import json serialize = json.dumps deserialize = json.loads except ImportError: try: # If all of the above fails, try to fallback to the simplejson # embedded in Django. from django.utils import simplejson serialize = simplejson.dumps deserialize = simplejson.loads except: raise ImportError("No json module found")
__version__ = "0.1" __author__ = "Rune Halvorsen <[email protected]>" __homepage__ = "http://bitbucket.org/runeh/anyjson/" __docformat__ = "restructuredtext" """ .. function:: serialize(obj) Serialize the object to JSON. .. function:: deserialize(obj) Deserialize JSON-encoded object to a Python object. """ # Try to import a module that provides json parsing and emitting, starting # with the fastest alternative and falling back to the slower ones. try: # cjson is the fastest import cjson serialize = cjson.encode deserialize = cjson.decode except ImportError: try: # Then try to find simplejson. Later versions has C speedups which # makes it pretty fast. import simplejson serialize = simplejson.dumps deserialize = simplejson.loads except ImportError: try: # Then try to find the python 2.6 stdlib json module. import json serialize = json.dumps deserialize = json.loads except ImportError: + try: - # If all of the above fails, try to fallback to the simplejson + # If all of the above fails, try to fallback to the simplejson ? ++++ - # embedded in Django. + # embedded in Django. ? ++++ - from django.utils import simplejson + from django.utils import simplejson ? ++++ - serialize = simplejson.dumps + serialize = simplejson.dumps ? ++++ - deserialize = simplejson.loads + deserialize = simplejson.loads ? ++++ + except: + raise ImportError("No json module found") +
8da30d3752fd6a056891960aa2892bcd8001c79b
lintreview/processor.py
lintreview/processor.py
import logging import lintreview.tools as tools from lintreview.diff import DiffCollection from lintreview.review import Problems from lintreview.review import Review log = logging.getLogger(__name__) class Processor(object): def __init__(self, client, number, head, target_path): self._client = client self._number = number self._head = head self._target_path = target_path self._changes = None self._problems = Problems(target_path) self._review = Review(client, number) def load_changes(self): log.info('Loading pull request patches from github.') files = self._client.pull_requests.list_files(self._number) pull_request_patches = files.all() self._changes = DiffCollection(pull_request_patches) self._problems.set_changes(self._changes) def run_tools(self, repo_config): if not self._changes: raise RuntimeError('No loaded changes, cannot run tools. ' 'Try calling load_changes first.') files_to_check = self._changes.get_files(append_base=self._target_path) tools.run( repo_config, self._problems, files_to_check, self._target_path) def publish(self, wait_time=0): self._problems.limit_to_changes() self._review.publish(self._problems, self._head, wait_time)
import logging import lintreview.tools as tools from lintreview.diff import DiffCollection from lintreview.review import Problems from lintreview.review import Review log = logging.getLogger(__name__) class Processor(object): def __init__(self, client, number, head, target_path): self._client = client self._number = number self._head = head self._target_path = target_path self._changes = None self._problems = Problems(target_path) self._review = Review(client, number) def load_changes(self): log.info('Loading pull request patches from github.') files = self._client.pull_requests.list_files(self._number) pull_request_patches = files.all() self._changes = DiffCollection(pull_request_patches) self._problems.set_changes(self._changes) def run_tools(self, repo_config): if self._changes is None: raise RuntimeError('No loaded changes, cannot run tools. ' 'Try calling load_changes first.') files_to_check = self._changes.get_files(append_base=self._target_path) tools.run( repo_config, self._problems, files_to_check, self._target_path) def publish(self, wait_time=0): self._problems.limit_to_changes() self._review.publish(self._problems, self._head, wait_time)
Make check against None instead of falsey things.
Make check against None instead of falsey things.
Python
mit
markstory/lint-review,markstory/lint-review,adrianmoisey/lint-review,zoidbergwill/lint-review,zoidbergwill/lint-review,adrianmoisey/lint-review,zoidbergwill/lint-review,markstory/lint-review
import logging import lintreview.tools as tools from lintreview.diff import DiffCollection from lintreview.review import Problems from lintreview.review import Review log = logging.getLogger(__name__) class Processor(object): def __init__(self, client, number, head, target_path): self._client = client self._number = number self._head = head self._target_path = target_path self._changes = None self._problems = Problems(target_path) self._review = Review(client, number) def load_changes(self): log.info('Loading pull request patches from github.') files = self._client.pull_requests.list_files(self._number) pull_request_patches = files.all() self._changes = DiffCollection(pull_request_patches) self._problems.set_changes(self._changes) def run_tools(self, repo_config): - if not self._changes: + if self._changes is None: raise RuntimeError('No loaded changes, cannot run tools. ' 'Try calling load_changes first.') files_to_check = self._changes.get_files(append_base=self._target_path) tools.run( repo_config, self._problems, files_to_check, self._target_path) def publish(self, wait_time=0): self._problems.limit_to_changes() self._review.publish(self._problems, self._head, wait_time)
Make check against None instead of falsey things.
## Code Before: import logging import lintreview.tools as tools from lintreview.diff import DiffCollection from lintreview.review import Problems from lintreview.review import Review log = logging.getLogger(__name__) class Processor(object): def __init__(self, client, number, head, target_path): self._client = client self._number = number self._head = head self._target_path = target_path self._changes = None self._problems = Problems(target_path) self._review = Review(client, number) def load_changes(self): log.info('Loading pull request patches from github.') files = self._client.pull_requests.list_files(self._number) pull_request_patches = files.all() self._changes = DiffCollection(pull_request_patches) self._problems.set_changes(self._changes) def run_tools(self, repo_config): if not self._changes: raise RuntimeError('No loaded changes, cannot run tools. ' 'Try calling load_changes first.') files_to_check = self._changes.get_files(append_base=self._target_path) tools.run( repo_config, self._problems, files_to_check, self._target_path) def publish(self, wait_time=0): self._problems.limit_to_changes() self._review.publish(self._problems, self._head, wait_time) ## Instruction: Make check against None instead of falsey things. ## Code After: import logging import lintreview.tools as tools from lintreview.diff import DiffCollection from lintreview.review import Problems from lintreview.review import Review log = logging.getLogger(__name__) class Processor(object): def __init__(self, client, number, head, target_path): self._client = client self._number = number self._head = head self._target_path = target_path self._changes = None self._problems = Problems(target_path) self._review = Review(client, number) def load_changes(self): log.info('Loading pull request patches from github.') files = self._client.pull_requests.list_files(self._number) pull_request_patches = files.all() self._changes = DiffCollection(pull_request_patches) self._problems.set_changes(self._changes) def run_tools(self, repo_config): if self._changes is None: raise RuntimeError('No loaded changes, cannot run tools. ' 'Try calling load_changes first.') files_to_check = self._changes.get_files(append_base=self._target_path) tools.run( repo_config, self._problems, files_to_check, self._target_path) def publish(self, wait_time=0): self._problems.limit_to_changes() self._review.publish(self._problems, self._head, wait_time)
import logging import lintreview.tools as tools from lintreview.diff import DiffCollection from lintreview.review import Problems from lintreview.review import Review log = logging.getLogger(__name__) class Processor(object): def __init__(self, client, number, head, target_path): self._client = client self._number = number self._head = head self._target_path = target_path self._changes = None self._problems = Problems(target_path) self._review = Review(client, number) def load_changes(self): log.info('Loading pull request patches from github.') files = self._client.pull_requests.list_files(self._number) pull_request_patches = files.all() self._changes = DiffCollection(pull_request_patches) self._problems.set_changes(self._changes) def run_tools(self, repo_config): - if not self._changes: ? ---- + if self._changes is None: ? ++++++++ raise RuntimeError('No loaded changes, cannot run tools. ' 'Try calling load_changes first.') files_to_check = self._changes.get_files(append_base=self._target_path) tools.run( repo_config, self._problems, files_to_check, self._target_path) def publish(self, wait_time=0): self._problems.limit_to_changes() self._review.publish(self._problems, self._head, wait_time)
fe76abc03f7152f318712e1a233aad42f2e9870a
jsonfield/widgets.py
jsonfield/widgets.py
from django import forms from django.utils import simplejson as json import staticmedia class JSONWidget(forms.Textarea): def render(self, name, value, attrs=None): if value is None: value = "" if not isinstance(value, basestring): value = json.dumps(value, indent=2) return super(JSONWidget, self).render(name, value, attrs) class JSONSelectWidget(forms.SelectMultiple): pass class JSONTableWidget(JSONWidget): class Media: js = ( staticmedia.url('js/jquery.js'), staticmedia.url('js/jquery.tmpl.js'), staticmedia.url('js/json-table.js'), staticmedia.url('js/json-table-templates.js'), )
from django import forms from django.utils import simplejson as json from django.conf import settings class JSONWidget(forms.Textarea): def render(self, name, value, attrs=None): if value is None: value = "" if not isinstance(value, basestring): value = json.dumps(value, indent=2) return super(JSONWidget, self).render(name, value, attrs) class JSONSelectWidget(forms.SelectMultiple): pass class JSONTableWidget(JSONWidget): class Media: js = ( settings.STATICFILES_URL + 'js/jquery.js', settings.STATICFILES_URL + 'js/jquery.tmpl.js', settings.STATICFILES_URL + 'js/json-table.js', settings.STATICFILES_URL + 'js/json-table-templates.js', )
Use staticfiles instead of staticmedia
Use staticfiles instead of staticmedia
Python
bsd-3-clause
SideStudios/django-jsonfield,chrismeyersfsu/django-jsonfield
from django import forms from django.utils import simplejson as json - import staticmedia + from django.conf import settings class JSONWidget(forms.Textarea): def render(self, name, value, attrs=None): if value is None: value = "" if not isinstance(value, basestring): value = json.dumps(value, indent=2) return super(JSONWidget, self).render(name, value, attrs) class JSONSelectWidget(forms.SelectMultiple): pass class JSONTableWidget(JSONWidget): class Media: js = ( - staticmedia.url('js/jquery.js'), - staticmedia.url('js/jquery.tmpl.js'), - staticmedia.url('js/json-table.js'), - staticmedia.url('js/json-table-templates.js'), + settings.STATICFILES_URL + 'js/jquery.js', + settings.STATICFILES_URL + 'js/jquery.tmpl.js', + settings.STATICFILES_URL + 'js/json-table.js', + settings.STATICFILES_URL + 'js/json-table-templates.js', )
Use staticfiles instead of staticmedia
## Code Before: from django import forms from django.utils import simplejson as json import staticmedia class JSONWidget(forms.Textarea): def render(self, name, value, attrs=None): if value is None: value = "" if not isinstance(value, basestring): value = json.dumps(value, indent=2) return super(JSONWidget, self).render(name, value, attrs) class JSONSelectWidget(forms.SelectMultiple): pass class JSONTableWidget(JSONWidget): class Media: js = ( staticmedia.url('js/jquery.js'), staticmedia.url('js/jquery.tmpl.js'), staticmedia.url('js/json-table.js'), staticmedia.url('js/json-table-templates.js'), ) ## Instruction: Use staticfiles instead of staticmedia ## Code After: from django import forms from django.utils import simplejson as json from django.conf import settings class JSONWidget(forms.Textarea): def render(self, name, value, attrs=None): if value is None: value = "" if not isinstance(value, basestring): value = json.dumps(value, indent=2) return super(JSONWidget, self).render(name, value, attrs) class JSONSelectWidget(forms.SelectMultiple): pass class JSONTableWidget(JSONWidget): class Media: js = ( settings.STATICFILES_URL + 'js/jquery.js', settings.STATICFILES_URL + 'js/jquery.tmpl.js', settings.STATICFILES_URL + 'js/json-table.js', settings.STATICFILES_URL + 'js/json-table-templates.js', )
from django import forms from django.utils import simplejson as json - import staticmedia + from django.conf import settings class JSONWidget(forms.Textarea): def render(self, name, value, attrs=None): if value is None: value = "" if not isinstance(value, basestring): value = json.dumps(value, indent=2) return super(JSONWidget, self).render(name, value, attrs) class JSONSelectWidget(forms.SelectMultiple): pass class JSONTableWidget(JSONWidget): class Media: js = ( - staticmedia.url('js/jquery.js'), - staticmedia.url('js/jquery.tmpl.js'), - staticmedia.url('js/json-table.js'), - staticmedia.url('js/json-table-templates.js'), + settings.STATICFILES_URL + 'js/jquery.js', + settings.STATICFILES_URL + 'js/jquery.tmpl.js', + settings.STATICFILES_URL + 'js/json-table.js', + settings.STATICFILES_URL + 'js/json-table-templates.js', )
75075e85ef82aabee2a261b6a58502b32c60d348
tests/test_project/gallery/models.py
tests/test_project/gallery/models.py
from django.db import models from pyuploadcare.dj.models import FileField, ImageField, ImageGroupField class Gallery(models.Model): title = models.CharField(max_length=255) def __unicode__(self): return self.title class Photo(models.Model): gallery = models.ForeignKey(Gallery) title = models.CharField(max_length=255) arbitrary_file = FileField(blank=True, null=True) photo_2x3 = ImageField(manual_crop='2:3', blank=True) def __unicode__(self): return self.title class GalleryMultiupload(models.Model): title = models.CharField(max_length=255) photos = ImageGroupField() def __unicode__(self): return self.title
from django.db import models from pyuploadcare.dj.models import FileField, ImageField, ImageGroupField class Gallery(models.Model): title = models.CharField(max_length=255) def __unicode__(self): return self.title class Photo(models.Model): gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE) title = models.CharField(max_length=255) arbitrary_file = FileField(blank=True, null=True) photo_2x3 = ImageField(manual_crop='2:3', blank=True) def __unicode__(self): return self.title class GalleryMultiupload(models.Model): title = models.CharField(max_length=255) photos = ImageGroupField() def __unicode__(self): return self.title
Add `on_delete` argument for `Photo.gallery` field
Add `on_delete` argument for `Photo.gallery` field
Python
mit
uploadcare/pyuploadcare
from django.db import models from pyuploadcare.dj.models import FileField, ImageField, ImageGroupField class Gallery(models.Model): title = models.CharField(max_length=255) def __unicode__(self): return self.title class Photo(models.Model): - gallery = models.ForeignKey(Gallery) + gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE) title = models.CharField(max_length=255) arbitrary_file = FileField(blank=True, null=True) photo_2x3 = ImageField(manual_crop='2:3', blank=True) def __unicode__(self): return self.title class GalleryMultiupload(models.Model): title = models.CharField(max_length=255) photos = ImageGroupField() def __unicode__(self): return self.title
Add `on_delete` argument for `Photo.gallery` field
## Code Before: from django.db import models from pyuploadcare.dj.models import FileField, ImageField, ImageGroupField class Gallery(models.Model): title = models.CharField(max_length=255) def __unicode__(self): return self.title class Photo(models.Model): gallery = models.ForeignKey(Gallery) title = models.CharField(max_length=255) arbitrary_file = FileField(blank=True, null=True) photo_2x3 = ImageField(manual_crop='2:3', blank=True) def __unicode__(self): return self.title class GalleryMultiupload(models.Model): title = models.CharField(max_length=255) photos = ImageGroupField() def __unicode__(self): return self.title ## Instruction: Add `on_delete` argument for `Photo.gallery` field ## Code After: from django.db import models from pyuploadcare.dj.models import FileField, ImageField, ImageGroupField class Gallery(models.Model): title = models.CharField(max_length=255) def __unicode__(self): return self.title class Photo(models.Model): gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE) title = models.CharField(max_length=255) arbitrary_file = FileField(blank=True, null=True) photo_2x3 = ImageField(manual_crop='2:3', blank=True) def __unicode__(self): return self.title class GalleryMultiupload(models.Model): title = models.CharField(max_length=255) photos = ImageGroupField() def __unicode__(self): return self.title
from django.db import models from pyuploadcare.dj.models import FileField, ImageField, ImageGroupField class Gallery(models.Model): title = models.CharField(max_length=255) def __unicode__(self): return self.title class Photo(models.Model): - gallery = models.ForeignKey(Gallery) + gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE) ? ++++++++++++++++++++++++++ title = models.CharField(max_length=255) arbitrary_file = FileField(blank=True, null=True) photo_2x3 = ImageField(manual_crop='2:3', blank=True) def __unicode__(self): return self.title class GalleryMultiupload(models.Model): title = models.CharField(max_length=255) photos = ImageGroupField() def __unicode__(self): return self.title
edb10e7ae1f428dade04a9976c3b3f985065d458
settings/__init__.py
settings/__init__.py
from __future__ import print_function # Standard Library import sys if "test" in sys.argv: print("\033[1;91mNo django tests.\033[0m") print("Try: \033[1;33mpy.test\033[0m") sys.exit(0) from .common import * # noqa try: from .dev import * # noqa from .prod import * # noqa except ImportError: pass
from __future__ import print_function # Standard Library import sys if "test" in sys.argv: print("\033[1;91mNo django tests.\033[0m") print("Try: \033[1;33mpy.test\033[0m") sys.exit(0) from .common import * # noqa try: from .dev import * # noqa except ImportError: pass try: from .prod import * # noqa except ImportError: pass
Make sure prod.py is read in settings
Make sure prod.py is read in settings
Python
mit
hTrap/junction,farhaanbukhsh/junction,ChillarAnand/junction,farhaanbukhsh/junction,akshayaurora/junction,NabeelValapra/junction,pythonindia/junction,shashisp/junction,hTrap/junction,ChillarAnand/junction,shashisp/junction,nava45/junction,NabeelValapra/junction,shashisp/junction,farhaanbukhsh/junction,akshayaurora/junction,shashisp/junction,nava45/junction,pythonindia/junction,Rahul91/junction,NabeelValapra/junction,hTrap/junction,Rahul91/junction,Rahul91/junction,praba230890/junction,Rahul91/junction,akshayaurora/junction,nava45/junction,nava45/junction,hTrap/junction,pythonindia/junction,ChillarAnand/junction,pythonindia/junction,akshayaurora/junction,praba230890/junction,NabeelValapra/junction,praba230890/junction,ChillarAnand/junction,farhaanbukhsh/junction,praba230890/junction
from __future__ import print_function # Standard Library import sys if "test" in sys.argv: print("\033[1;91mNo django tests.\033[0m") print("Try: \033[1;33mpy.test\033[0m") sys.exit(0) from .common import * # noqa try: from .dev import * # noqa + except ImportError: + pass + + try: from .prod import * # noqa except ImportError: pass
Make sure prod.py is read in settings
## Code Before: from __future__ import print_function # Standard Library import sys if "test" in sys.argv: print("\033[1;91mNo django tests.\033[0m") print("Try: \033[1;33mpy.test\033[0m") sys.exit(0) from .common import * # noqa try: from .dev import * # noqa from .prod import * # noqa except ImportError: pass ## Instruction: Make sure prod.py is read in settings ## Code After: from __future__ import print_function # Standard Library import sys if "test" in sys.argv: print("\033[1;91mNo django tests.\033[0m") print("Try: \033[1;33mpy.test\033[0m") sys.exit(0) from .common import * # noqa try: from .dev import * # noqa except ImportError: pass try: from .prod import * # noqa except ImportError: pass
from __future__ import print_function # Standard Library import sys if "test" in sys.argv: print("\033[1;91mNo django tests.\033[0m") print("Try: \033[1;33mpy.test\033[0m") sys.exit(0) from .common import * # noqa try: from .dev import * # noqa + except ImportError: + pass + + try: from .prod import * # noqa except ImportError: pass
5690b8dfe529dd83b1531517d900a7e8512aa061
utilities/python/graph_dfs.py
utilities/python/graph_dfs.py
def graph_dfs(matrix): rows, cols = len(matrix), len(matrix[0]) visited = set() directions = ((0, 1), (0, -1), (1, 0), (-1, 0)) def dfs(i, j): if (i, j) in visited: return visited.add((i, j)) # Traverse neighbors. for direction in directions: next_i, next_j = i + direction[0], j + direction[1] if 0 <= next_i < rows and 0 <= next_j < cols: # Check boundary. # Add any other checking here ^ dfs(next_i, next_j) for i in range(rows): for j in range(cols): dfs(i, j) graph_dfs([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ])
def graph_dfs(matrix): rows, cols = len(matrix), len(matrix[0]) visited = set() directions = ((0, 1), (0, -1), (1, 0), (-1, 0)) def dfs(i, j): if (i, j) in visited: return visited.add((i, j)) # Traverse neighbors. for direction in directions: next_i, next_j = i + direction[0], j + direction[1] if 0 <= next_i < rows and 0 <= next_j < cols: # Check boundary. # Add any other checking here ^ dfs(next_i, next_j) for i in range(rows): for j in range(cols): dfs(i, j) # Follow up: # 1) Diagonal cells are considered neighbors # 2) View the matrix like Earth, right boundary is adjacent to the left boundary, top adjacent to left, etc. def graph_dfs_diagonals(matrix): rows, cols = len(matrix), len(matrix[0]) visited = set() # Change 1: Add 4 more diagonal directions. directions = ((0, 1), (0, -1), (1, 0), (-1, 0), (-1, -1), (1, 1), (1, -1), (-1, 1)) def dfs(i, j): if (i, j) in visited: return print(matrix[i][j]) visited.add((i, j)) for direction in directions: # Change 2: No more boundary, use modulo to allow traversal that exceed boundaries to wrap around. next_i, next_j = (i + direction[0] + rows) % rows, (j + direction[1] + cols) % cols dfs(next_i, next_j) for i in range(rows): for j in range(cols): dfs(i, j) graph_dfs([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ])
Add follow up with matrix traversal
Add follow up with matrix traversal
Python
mit
yangshun/tech-interview-handbook,yangshun/tech-interview-handbook,yangshun/tech-interview-handbook,yangshun/tech-interview-handbook,yangshun/tech-interview-handbook
def graph_dfs(matrix): rows, cols = len(matrix), len(matrix[0]) visited = set() directions = ((0, 1), (0, -1), (1, 0), (-1, 0)) def dfs(i, j): if (i, j) in visited: return visited.add((i, j)) # Traverse neighbors. for direction in directions: next_i, next_j = i + direction[0], j + direction[1] if 0 <= next_i < rows and 0 <= next_j < cols: # Check boundary. # Add any other checking here ^ dfs(next_i, next_j) for i in range(rows): for j in range(cols): dfs(i, j) + # Follow up: + # 1) Diagonal cells are considered neighbors + # 2) View the matrix like Earth, right boundary is adjacent to the left boundary, top adjacent to left, etc. + def graph_dfs_diagonals(matrix): + rows, cols = len(matrix), len(matrix[0]) + visited = set() + # Change 1: Add 4 more diagonal directions. + directions = ((0, 1), (0, -1), (1, 0), (-1, 0), (-1, -1), (1, 1), (1, -1), (-1, 1)) + def dfs(i, j): + if (i, j) in visited: + return + print(matrix[i][j]) + visited.add((i, j)) + for direction in directions: + # Change 2: No more boundary, use modulo to allow traversal that exceed boundaries to wrap around. + next_i, next_j = (i + direction[0] + rows) % rows, (j + direction[1] + cols) % cols + dfs(next_i, next_j) + + for i in range(rows): + for j in range(cols): + dfs(i, j) + graph_dfs([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ])
Add follow up with matrix traversal
## Code Before: def graph_dfs(matrix): rows, cols = len(matrix), len(matrix[0]) visited = set() directions = ((0, 1), (0, -1), (1, 0), (-1, 0)) def dfs(i, j): if (i, j) in visited: return visited.add((i, j)) # Traverse neighbors. for direction in directions: next_i, next_j = i + direction[0], j + direction[1] if 0 <= next_i < rows and 0 <= next_j < cols: # Check boundary. # Add any other checking here ^ dfs(next_i, next_j) for i in range(rows): for j in range(cols): dfs(i, j) graph_dfs([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ]) ## Instruction: Add follow up with matrix traversal ## Code After: def graph_dfs(matrix): rows, cols = len(matrix), len(matrix[0]) visited = set() directions = ((0, 1), (0, -1), (1, 0), (-1, 0)) def dfs(i, j): if (i, j) in visited: return visited.add((i, j)) # Traverse neighbors. for direction in directions: next_i, next_j = i + direction[0], j + direction[1] if 0 <= next_i < rows and 0 <= next_j < cols: # Check boundary. # Add any other checking here ^ dfs(next_i, next_j) for i in range(rows): for j in range(cols): dfs(i, j) # Follow up: # 1) Diagonal cells are considered neighbors # 2) View the matrix like Earth, right boundary is adjacent to the left boundary, top adjacent to left, etc. def graph_dfs_diagonals(matrix): rows, cols = len(matrix), len(matrix[0]) visited = set() # Change 1: Add 4 more diagonal directions. directions = ((0, 1), (0, -1), (1, 0), (-1, 0), (-1, -1), (1, 1), (1, -1), (-1, 1)) def dfs(i, j): if (i, j) in visited: return print(matrix[i][j]) visited.add((i, j)) for direction in directions: # Change 2: No more boundary, use modulo to allow traversal that exceed boundaries to wrap around. next_i, next_j = (i + direction[0] + rows) % rows, (j + direction[1] + cols) % cols dfs(next_i, next_j) for i in range(rows): for j in range(cols): dfs(i, j) graph_dfs([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ])
def graph_dfs(matrix): rows, cols = len(matrix), len(matrix[0]) visited = set() directions = ((0, 1), (0, -1), (1, 0), (-1, 0)) def dfs(i, j): if (i, j) in visited: return visited.add((i, j)) # Traverse neighbors. for direction in directions: next_i, next_j = i + direction[0], j + direction[1] if 0 <= next_i < rows and 0 <= next_j < cols: # Check boundary. # Add any other checking here ^ dfs(next_i, next_j) for i in range(rows): for j in range(cols): dfs(i, j) + # Follow up: + # 1) Diagonal cells are considered neighbors + # 2) View the matrix like Earth, right boundary is adjacent to the left boundary, top adjacent to left, etc. + def graph_dfs_diagonals(matrix): + rows, cols = len(matrix), len(matrix[0]) + visited = set() + # Change 1: Add 4 more diagonal directions. + directions = ((0, 1), (0, -1), (1, 0), (-1, 0), (-1, -1), (1, 1), (1, -1), (-1, 1)) + def dfs(i, j): + if (i, j) in visited: + return + print(matrix[i][j]) + visited.add((i, j)) + for direction in directions: + # Change 2: No more boundary, use modulo to allow traversal that exceed boundaries to wrap around. + next_i, next_j = (i + direction[0] + rows) % rows, (j + direction[1] + cols) % cols + dfs(next_i, next_j) + + for i in range(rows): + for j in range(cols): + dfs(i, j) + graph_dfs([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ])
84c2c987151451180281f1aecb0483321462340c
influxalchemy/__init__.py
influxalchemy/__init__.py
""" InfluxDB Alchemy. """ from .client import InfluxAlchemy from .measurement import Measurement __version__ = "0.1.0"
""" InfluxDB Alchemy. """ import pkg_resources from .client import InfluxAlchemy from .measurement import Measurement try: __version__ = pkg_resources.get_distribution(__package__).version except pkg_resources.DistributionNotFound: # pragma: no cover __version__ = None # pragma: no cover
Use package version for __version__
Use package version for __version__
Python
mit
amancevice/influxalchemy
""" InfluxDB Alchemy. """ + import pkg_resources from .client import InfluxAlchemy from .measurement import Measurement - __version__ = "0.1.0" + try: + __version__ = pkg_resources.get_distribution(__package__).version + except pkg_resources.DistributionNotFound: # pragma: no cover + __version__ = None # pragma: no cover +
Use package version for __version__
## Code Before: """ InfluxDB Alchemy. """ from .client import InfluxAlchemy from .measurement import Measurement __version__ = "0.1.0" ## Instruction: Use package version for __version__ ## Code After: """ InfluxDB Alchemy. """ import pkg_resources from .client import InfluxAlchemy from .measurement import Measurement try: __version__ = pkg_resources.get_distribution(__package__).version except pkg_resources.DistributionNotFound: # pragma: no cover __version__ = None # pragma: no cover
""" InfluxDB Alchemy. """ + import pkg_resources from .client import InfluxAlchemy from .measurement import Measurement - __version__ = "0.1.0" + + try: + __version__ = pkg_resources.get_distribution(__package__).version + except pkg_resources.DistributionNotFound: # pragma: no cover + __version__ = None # pragma: no cover
6795e8f5c97ba2f10d05725faf4999cfba785fdd
molecule/default/tests/test_default.py
molecule/default/tests/test_default.py
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_service_elasticsearch_running(host): assert host.service("elasticsearch").is_running is True def test_service_mongodb_running(host): assert host.service("mongod").is_running is True def test_is_graylog_installed(host): assert host.package('graylog-server').is_installed def test_service_graylog_running(host): assert host.service("graylog-server").is_running is True
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_service_elasticsearch_running(host): assert host.service("elasticsearch").is_running is True def test_service_mongodb_running(host): if host.system_info.distribution == 'ubuntu' and host.system_info.codename == 'focal': mongodb_service_name = 'mongodb' else: mongodb_service_name = 'mongod' assert host.service(mongodb_service_name).is_running is True def test_is_graylog_installed(host): assert host.package('graylog-server').is_installed def test_service_graylog_running(host): assert host.service("graylog-server").is_running is True
Fix test in Ubuntu 20.04.
Fix test in Ubuntu 20.04.
Python
apache-2.0
Graylog2/graylog-ansible-role
import os import testinfra.utils.ansible_runner + testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') - testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( - os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_service_elasticsearch_running(host): assert host.service("elasticsearch").is_running is True def test_service_mongodb_running(host): + if host.system_info.distribution == 'ubuntu' and host.system_info.codename == 'focal': + mongodb_service_name = 'mongodb' + else: + mongodb_service_name = 'mongod' + - assert host.service("mongod").is_running is True + assert host.service(mongodb_service_name).is_running is True def test_is_graylog_installed(host): assert host.package('graylog-server').is_installed def test_service_graylog_running(host): assert host.service("graylog-server").is_running is True
Fix test in Ubuntu 20.04.
## Code Before: import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_service_elasticsearch_running(host): assert host.service("elasticsearch").is_running is True def test_service_mongodb_running(host): assert host.service("mongod").is_running is True def test_is_graylog_installed(host): assert host.package('graylog-server').is_installed def test_service_graylog_running(host): assert host.service("graylog-server").is_running is True ## Instruction: Fix test in Ubuntu 20.04. ## Code After: import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_service_elasticsearch_running(host): assert host.service("elasticsearch").is_running is True def test_service_mongodb_running(host): if host.system_info.distribution == 'ubuntu' and host.system_info.codename == 'focal': mongodb_service_name = 'mongodb' else: mongodb_service_name = 'mongod' assert host.service(mongodb_service_name).is_running is True def test_is_graylog_installed(host): assert host.package('graylog-server').is_installed def test_service_graylog_running(host): assert host.service("graylog-server").is_running is True
import os import testinfra.utils.ansible_runner + testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') - testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( - os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_service_elasticsearch_running(host): assert host.service("elasticsearch").is_running is True def test_service_mongodb_running(host): + if host.system_info.distribution == 'ubuntu' and host.system_info.codename == 'focal': + mongodb_service_name = 'mongodb' + else: + mongodb_service_name = 'mongod' + - assert host.service("mongod").is_running is True ? - ^ + assert host.service(mongodb_service_name).is_running is True ? ^^^^^^^^^^^^^^ def test_is_graylog_installed(host): assert host.package('graylog-server').is_installed def test_service_graylog_running(host): assert host.service("graylog-server").is_running is True
44650a0b3d395b4201a039bd2f3eb916987dce8d
_grains/osqueryinfo.py
_grains/osqueryinfo.py
import salt.utils import salt.modules.cmdmod __salt__ = {'cmd.run': salt.modules.cmdmod._run_quiet} def osquerygrain(): ''' Return osquery version in grain ''' # Provides: # osqueryversion # osquerybinpath grains = {} option = '--version' # Prefer our /opt/osquery/osqueryi if present osqueryipaths = ('/opt/osquery/osqueryi', 'osqueryi', '/usr/bin/osqueryi') for path in osqueryipaths: if salt.utils.which(path): for item in __salt__['cmd.run']('{0} {1}'.format(path, option)).split(): if item[:1].isdigit(): grains['osqueryversion'] = item grains['osquerybinpath'] = salt.utils.which(path) break break return grains
import salt.utils import salt.modules.cmdmod __salt__ = {'cmd.run': salt.modules.cmdmod._run_quiet} def osquerygrain(): ''' Return osquery version in grain ''' # Provides: # osqueryversion # osquerybinpath grains = {} option = '--version' # Prefer our /opt/osquery/osqueryi if present osqueryipaths = ('/opt/osquery/osqueryi', 'osqueryi', '/usr/bin/osqueryi') for path in osqueryipaths: if salt.utils.path.which(path): for item in __salt__['cmd.run']('{0} {1}'.format(path, option)).split(): if item[:1].isdigit(): grains['osqueryversion'] = item grains['osquerybinpath'] = salt.utils.path.which(path) break break return grains
Use of salt.utils.which detected. This function has been moved to salt.utils.path.which as of Salt 2018.3.0
DeprecationWarning: Use of salt.utils.which detected. This function has been moved to salt.utils.path.which as of Salt 2018.3.0
Python
apache-2.0
hubblestack/hubble-salt
import salt.utils import salt.modules.cmdmod __salt__ = {'cmd.run': salt.modules.cmdmod._run_quiet} def osquerygrain(): ''' Return osquery version in grain ''' # Provides: # osqueryversion # osquerybinpath grains = {} option = '--version' # Prefer our /opt/osquery/osqueryi if present osqueryipaths = ('/opt/osquery/osqueryi', 'osqueryi', '/usr/bin/osqueryi') for path in osqueryipaths: - if salt.utils.which(path): + if salt.utils.path.which(path): for item in __salt__['cmd.run']('{0} {1}'.format(path, option)).split(): if item[:1].isdigit(): grains['osqueryversion'] = item - grains['osquerybinpath'] = salt.utils.which(path) + grains['osquerybinpath'] = salt.utils.path.which(path) break break return grains
Use of salt.utils.which detected. This function has been moved to salt.utils.path.which as of Salt 2018.3.0
## Code Before: import salt.utils import salt.modules.cmdmod __salt__ = {'cmd.run': salt.modules.cmdmod._run_quiet} def osquerygrain(): ''' Return osquery version in grain ''' # Provides: # osqueryversion # osquerybinpath grains = {} option = '--version' # Prefer our /opt/osquery/osqueryi if present osqueryipaths = ('/opt/osquery/osqueryi', 'osqueryi', '/usr/bin/osqueryi') for path in osqueryipaths: if salt.utils.which(path): for item in __salt__['cmd.run']('{0} {1}'.format(path, option)).split(): if item[:1].isdigit(): grains['osqueryversion'] = item grains['osquerybinpath'] = salt.utils.which(path) break break return grains ## Instruction: Use of salt.utils.which detected. This function has been moved to salt.utils.path.which as of Salt 2018.3.0 ## Code After: import salt.utils import salt.modules.cmdmod __salt__ = {'cmd.run': salt.modules.cmdmod._run_quiet} def osquerygrain(): ''' Return osquery version in grain ''' # Provides: # osqueryversion # osquerybinpath grains = {} option = '--version' # Prefer our /opt/osquery/osqueryi if present osqueryipaths = ('/opt/osquery/osqueryi', 'osqueryi', '/usr/bin/osqueryi') for path in osqueryipaths: if salt.utils.path.which(path): for item in __salt__['cmd.run']('{0} {1}'.format(path, option)).split(): if item[:1].isdigit(): grains['osqueryversion'] = item grains['osquerybinpath'] = salt.utils.path.which(path) break break return grains
import salt.utils import salt.modules.cmdmod __salt__ = {'cmd.run': salt.modules.cmdmod._run_quiet} def osquerygrain(): ''' Return osquery version in grain ''' # Provides: # osqueryversion # osquerybinpath grains = {} option = '--version' # Prefer our /opt/osquery/osqueryi if present osqueryipaths = ('/opt/osquery/osqueryi', 'osqueryi', '/usr/bin/osqueryi') for path in osqueryipaths: - if salt.utils.which(path): + if salt.utils.path.which(path): ? +++++ for item in __salt__['cmd.run']('{0} {1}'.format(path, option)).split(): if item[:1].isdigit(): grains['osqueryversion'] = item - grains['osquerybinpath'] = salt.utils.which(path) + grains['osquerybinpath'] = salt.utils.path.which(path) ? +++++ break break return grains
4a84fe0c774638b7a00d37864b6d634200512f99
tests.py
tests.py
import unittest from stacklogger import srcfile class TestUtils(unittest.TestCase): def test_srcfile(self): self.assertTrue(srcfile("foo.py").endswith("foo.py")) self.assertTrue(srcfile("foo.pyc").endswith("foo.py")) self.assertTrue(srcfile("foo.pyo").endswith("foo.py")) self.assertTrue(srcfile("foo").endswith("foo"))
import inspect import unittest from stacklogger import srcfile currentframe = inspect.currentframe class FakeFrames(object): def fake_method(self): return currentframe() @property def fake_property(self): return currentframe() @classmethod def fake_classmethod(cls): return currentframe() @staticmethod def fake_staticmethod(): return currentframe() def fake_function(): return currentframe() class TestUtils(unittest.TestCase): def test_srcfile(self): self.assertTrue(srcfile("foo.py").endswith("foo.py")) self.assertTrue(srcfile("foo.pyc").endswith("foo.py")) self.assertTrue(srcfile("foo.pyo").endswith("foo.py")) self.assertTrue(srcfile("foo").endswith("foo"))
Build fake frames for later testing.
Build fake frames for later testing.
Python
isc
whilp/stacklogger
+ import inspect import unittest from stacklogger import srcfile + + currentframe = inspect.currentframe + + class FakeFrames(object): + + def fake_method(self): + return currentframe() + + @property + def fake_property(self): + return currentframe() + + @classmethod + def fake_classmethod(cls): + return currentframe() + + @staticmethod + def fake_staticmethod(): + return currentframe() + + def fake_function(): + return currentframe() class TestUtils(unittest.TestCase): def test_srcfile(self): self.assertTrue(srcfile("foo.py").endswith("foo.py")) self.assertTrue(srcfile("foo.pyc").endswith("foo.py")) self.assertTrue(srcfile("foo.pyo").endswith("foo.py")) self.assertTrue(srcfile("foo").endswith("foo"))
Build fake frames for later testing.
## Code Before: import unittest from stacklogger import srcfile class TestUtils(unittest.TestCase): def test_srcfile(self): self.assertTrue(srcfile("foo.py").endswith("foo.py")) self.assertTrue(srcfile("foo.pyc").endswith("foo.py")) self.assertTrue(srcfile("foo.pyo").endswith("foo.py")) self.assertTrue(srcfile("foo").endswith("foo")) ## Instruction: Build fake frames for later testing. ## Code After: import inspect import unittest from stacklogger import srcfile currentframe = inspect.currentframe class FakeFrames(object): def fake_method(self): return currentframe() @property def fake_property(self): return currentframe() @classmethod def fake_classmethod(cls): return currentframe() @staticmethod def fake_staticmethod(): return currentframe() def fake_function(): return currentframe() class TestUtils(unittest.TestCase): def test_srcfile(self): self.assertTrue(srcfile("foo.py").endswith("foo.py")) self.assertTrue(srcfile("foo.pyc").endswith("foo.py")) self.assertTrue(srcfile("foo.pyo").endswith("foo.py")) self.assertTrue(srcfile("foo").endswith("foo"))
+ import inspect import unittest from stacklogger import srcfile + + currentframe = inspect.currentframe + + class FakeFrames(object): + + def fake_method(self): + return currentframe() + + @property + def fake_property(self): + return currentframe() + + @classmethod + def fake_classmethod(cls): + return currentframe() + + @staticmethod + def fake_staticmethod(): + return currentframe() + + def fake_function(): + return currentframe() class TestUtils(unittest.TestCase): def test_srcfile(self): self.assertTrue(srcfile("foo.py").endswith("foo.py")) self.assertTrue(srcfile("foo.pyc").endswith("foo.py")) self.assertTrue(srcfile("foo.pyo").endswith("foo.py")) self.assertTrue(srcfile("foo").endswith("foo"))
5dd81b09db46927cb7710b21ab682a6c3ecc182e
esios/__init__.py
esios/__init__.py
try: VERSION = __import__('pkg_resources') \ .get_distribution(__name__).version except Exception as e: VERSION = 'unknown' from .service import Esios
from __future__ import absolute_import try: VERSION = __import__('pkg_resources') \ .get_distribution(__name__).version except Exception as e: VERSION = 'unknown' from .service import Esios
Enforce absolute imports through __future__
Enforce absolute imports through __future__
Python
mit
gisce/esios
+ from __future__ import absolute_import + try: VERSION = __import__('pkg_resources') \ .get_distribution(__name__).version except Exception as e: VERSION = 'unknown' from .service import Esios
Enforce absolute imports through __future__
## Code Before: try: VERSION = __import__('pkg_resources') \ .get_distribution(__name__).version except Exception as e: VERSION = 'unknown' from .service import Esios ## Instruction: Enforce absolute imports through __future__ ## Code After: from __future__ import absolute_import try: VERSION = __import__('pkg_resources') \ .get_distribution(__name__).version except Exception as e: VERSION = 'unknown' from .service import Esios
+ from __future__ import absolute_import + try: VERSION = __import__('pkg_resources') \ .get_distribution(__name__).version except Exception as e: VERSION = 'unknown' from .service import Esios
e50655479c0d3a96edd4005f834541889839fca3
binary_to_text.py
binary_to_text.py
import Gen.caffe_pb2 as pb2 import google.protobuf.text_format as pb2_text import sys def binary_to_text(binary_file, text_file): msg = pb2.NetParameter() with open(binary_file) as f: msg.ParseFromString(f.read()) with open(text_file, "w") as f: f.write(pb2_text.MessageToString(msg)) if __name__ == "__main__": binary_file = sys.argv[1] text_file = sys.argv[2] binary_to_text(binary_file, text_file)
import Gen.caffe_pb2 as pb2 import google.protobuf.text_format as pb2_text import sys class ParameterTypeException(Exception): pass def binary_to_text(binary_file, text_file, parameter_type): if (parameter_type == "Net"): msg = pb2.NetParameter() elif (parameter_type == "Solver"): msg = pb2.SolverParameter() else: raise ParameterTypeException("Unexpected Parameter Type: " + parameter_type) with open(binary_file) as f: msg.ParseFromString(f.read()) with open(text_file, "w") as f: f.write(pb2_text.MessageToString(msg)) if __name__ == "__main__": binary_file = sys.argv[1] text_file = sys.argv[2] try: parameter_type = sys.argv[3] except IndexError: parameter_type = "Net" binary_to_text(binary_file, text_file, parameter_type)
Add option to process SolverParameters.
Add option to process SolverParameters.
Python
bsd-3-clause
BeautifulDestinations/dnngraph,BeautifulDestinations/dnngraph
import Gen.caffe_pb2 as pb2 import google.protobuf.text_format as pb2_text import sys + class ParameterTypeException(Exception): pass - def binary_to_text(binary_file, text_file): + def binary_to_text(binary_file, text_file, parameter_type): + if (parameter_type == "Net"): - msg = pb2.NetParameter() + msg = pb2.NetParameter() + elif (parameter_type == "Solver"): + msg = pb2.SolverParameter() + else: + raise ParameterTypeException("Unexpected Parameter Type: " + parameter_type) with open(binary_file) as f: msg.ParseFromString(f.read()) with open(text_file, "w") as f: f.write(pb2_text.MessageToString(msg)) if __name__ == "__main__": binary_file = sys.argv[1] text_file = sys.argv[2] + try: + parameter_type = sys.argv[3] + except IndexError: + parameter_type = "Net" - binary_to_text(binary_file, text_file) + binary_to_text(binary_file, text_file, parameter_type)
Add option to process SolverParameters.
## Code Before: import Gen.caffe_pb2 as pb2 import google.protobuf.text_format as pb2_text import sys def binary_to_text(binary_file, text_file): msg = pb2.NetParameter() with open(binary_file) as f: msg.ParseFromString(f.read()) with open(text_file, "w") as f: f.write(pb2_text.MessageToString(msg)) if __name__ == "__main__": binary_file = sys.argv[1] text_file = sys.argv[2] binary_to_text(binary_file, text_file) ## Instruction: Add option to process SolverParameters. ## Code After: import Gen.caffe_pb2 as pb2 import google.protobuf.text_format as pb2_text import sys class ParameterTypeException(Exception): pass def binary_to_text(binary_file, text_file, parameter_type): if (parameter_type == "Net"): msg = pb2.NetParameter() elif (parameter_type == "Solver"): msg = pb2.SolverParameter() else: raise ParameterTypeException("Unexpected Parameter Type: " + parameter_type) with open(binary_file) as f: msg.ParseFromString(f.read()) with open(text_file, "w") as f: f.write(pb2_text.MessageToString(msg)) if __name__ == "__main__": binary_file = sys.argv[1] text_file = sys.argv[2] try: parameter_type = sys.argv[3] except IndexError: parameter_type = "Net" binary_to_text(binary_file, text_file, parameter_type)
import Gen.caffe_pb2 as pb2 import google.protobuf.text_format as pb2_text import sys + class ParameterTypeException(Exception): pass - def binary_to_text(binary_file, text_file): + def binary_to_text(binary_file, text_file, parameter_type): ? ++++++++++++++++ + if (parameter_type == "Net"): - msg = pb2.NetParameter() + msg = pb2.NetParameter() ? ++++ + elif (parameter_type == "Solver"): + msg = pb2.SolverParameter() + else: + raise ParameterTypeException("Unexpected Parameter Type: " + parameter_type) with open(binary_file) as f: msg.ParseFromString(f.read()) with open(text_file, "w") as f: f.write(pb2_text.MessageToString(msg)) if __name__ == "__main__": binary_file = sys.argv[1] text_file = sys.argv[2] + try: + parameter_type = sys.argv[3] + except IndexError: + parameter_type = "Net" - binary_to_text(binary_file, text_file) + binary_to_text(binary_file, text_file, parameter_type) ? ++++++++++++++++
925fefdcdaf32123a9ed4ed2b038bcb11269d77d
main/appengine_config.py
main/appengine_config.py
import os import sys sys.path.insert(0, 'libx') if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'): sys.path.insert(0, 'lib.zip') else: import re from google.appengine.tools.devappserver2.python import stubs re_ = stubs.FakeFile._skip_files.pattern.replace('|^lib/.*', '') re_ = re.compile(re_) stubs.FakeFile._skip_files = re_ sys.path.insert(0, 'lib') sys.path.insert(0, 'libx')
import os import sys if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'): sys.path.insert(0, 'lib.zip') else: import re from google.appengine.tools.devappserver2.python import stubs re_ = stubs.FakeFile._skip_files.pattern.replace('|^lib/.*', '') re_ = re.compile(re_) stubs.FakeFile._skip_files = re_ sys.path.insert(0, 'lib') sys.path.insert(0, 'libx')
Remove duplicate libx path insertion
Remove duplicate libx path insertion
Python
mit
gae-init/gae-init-babel,lipis/life-line,lipis/life-line,mdxs/gae-init-babel,gae-init/gae-init-babel,gae-init/gae-init-babel,mdxs/gae-init-babel,gae-init/gae-init-babel,mdxs/gae-init-babel,lipis/life-line
import os import sys - sys.path.insert(0, 'libx') if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'): sys.path.insert(0, 'lib.zip') else: import re from google.appengine.tools.devappserver2.python import stubs re_ = stubs.FakeFile._skip_files.pattern.replace('|^lib/.*', '') re_ = re.compile(re_) stubs.FakeFile._skip_files = re_ sys.path.insert(0, 'lib') sys.path.insert(0, 'libx')
Remove duplicate libx path insertion
## Code Before: import os import sys sys.path.insert(0, 'libx') if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'): sys.path.insert(0, 'lib.zip') else: import re from google.appengine.tools.devappserver2.python import stubs re_ = stubs.FakeFile._skip_files.pattern.replace('|^lib/.*', '') re_ = re.compile(re_) stubs.FakeFile._skip_files = re_ sys.path.insert(0, 'lib') sys.path.insert(0, 'libx') ## Instruction: Remove duplicate libx path insertion ## Code After: import os import sys if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'): sys.path.insert(0, 'lib.zip') else: import re from google.appengine.tools.devappserver2.python import stubs re_ = stubs.FakeFile._skip_files.pattern.replace('|^lib/.*', '') re_ = re.compile(re_) stubs.FakeFile._skip_files = re_ sys.path.insert(0, 'lib') sys.path.insert(0, 'libx')
import os import sys - sys.path.insert(0, 'libx') if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'): sys.path.insert(0, 'lib.zip') else: import re from google.appengine.tools.devappserver2.python import stubs re_ = stubs.FakeFile._skip_files.pattern.replace('|^lib/.*', '') re_ = re.compile(re_) stubs.FakeFile._skip_files = re_ sys.path.insert(0, 'lib') sys.path.insert(0, 'libx')
46e1672bb0226ae8157d63a2d73edbfefcd644e9
src/test/test_google_maps.py
src/test/test_google_maps.py
import unittest import googlemaps from pyrules2.googlemaps import driving_roundtrip COP = 'Copenhagen, Denmark' MAD = 'Madrid, Spain' BER = 'Berlin, Germany' LIS = 'Lisbon, Portugal' KM = 1000 class Test(unittest.TestCase): def setUp(self): # TODO: Sane way to import key with open('/Users/nhc/git/pyrules/google-maps-api-key.txt') as f: self.key = f.read() def test_roundtrip(self): c = googlemaps.Client(key=self.key) r = driving_roundtrip(c, COP, MAD, BER, LIS) self.assertGreater(r.distance(), 10000 * KM) # Bad min_dist, best_itinerary = min(((a.distance(), a.itinerary()) for a in r.alternatives())) self.assertLess(min_dist, 6500 * KM) # Good self.assertListEqual([COP, LIS, MAD, BER, COP], best_itinerary) if __name__ == "__main__": unittest.main()
from os import environ import unittest import googlemaps from pyrules2.googlemaps import driving_roundtrip COP = 'Copenhagen, Denmark' MAD = 'Madrid, Spain' BER = 'Berlin, Germany' LIS = 'Lisbon, Portugal' KM = 1000 class Test(unittest.TestCase): def setUp(self): try: key = environ['GOOGLE_MAPS_API_KEY'] except KeyError: self.fail('This test requires an API key for Google Maps in the environment variable GOOGLE_MAPS_API_KEY') self.client = googlemaps.Client(key=key) def test_roundtrip(self): r = driving_roundtrip(self.client, COP, MAD, BER, LIS) self.assertGreater(r.distance(), 10000 * KM) # Bad min_dist, itinerary = min(((a.distance(), a.itinerary()) for a in r.alternatives())) self.assertLess(min_dist, 6500 * KM) # Good self.assertListEqual([COP, LIS, MAD, BER, COP], itinerary) if __name__ == "__main__": unittest.main()
Move API key to environment variable
Move API key to environment variable
Python
mit
mr-niels-christensen/pyrules
+ from os import environ import unittest import googlemaps from pyrules2.googlemaps import driving_roundtrip COP = 'Copenhagen, Denmark' MAD = 'Madrid, Spain' BER = 'Berlin, Germany' LIS = 'Lisbon, Portugal' KM = 1000 class Test(unittest.TestCase): def setUp(self): - # TODO: Sane way to import key - with open('/Users/nhc/git/pyrules/google-maps-api-key.txt') as f: - self.key = f.read() + try: + key = environ['GOOGLE_MAPS_API_KEY'] + except KeyError: + self.fail('This test requires an API key for Google Maps in the environment variable GOOGLE_MAPS_API_KEY') + self.client = googlemaps.Client(key=key) def test_roundtrip(self): - c = googlemaps.Client(key=self.key) - r = driving_roundtrip(c, COP, MAD, BER, LIS) + r = driving_roundtrip(self.client, COP, MAD, BER, LIS) self.assertGreater(r.distance(), 10000 * KM) # Bad - min_dist, best_itinerary = min(((a.distance(), a.itinerary()) for a in r.alternatives())) + min_dist, itinerary = min(((a.distance(), a.itinerary()) for a in r.alternatives())) self.assertLess(min_dist, 6500 * KM) # Good - self.assertListEqual([COP, LIS, MAD, BER, COP], best_itinerary) + self.assertListEqual([COP, LIS, MAD, BER, COP], itinerary) if __name__ == "__main__": unittest.main()
Move API key to environment variable
## Code Before: import unittest import googlemaps from pyrules2.googlemaps import driving_roundtrip COP = 'Copenhagen, Denmark' MAD = 'Madrid, Spain' BER = 'Berlin, Germany' LIS = 'Lisbon, Portugal' KM = 1000 class Test(unittest.TestCase): def setUp(self): # TODO: Sane way to import key with open('/Users/nhc/git/pyrules/google-maps-api-key.txt') as f: self.key = f.read() def test_roundtrip(self): c = googlemaps.Client(key=self.key) r = driving_roundtrip(c, COP, MAD, BER, LIS) self.assertGreater(r.distance(), 10000 * KM) # Bad min_dist, best_itinerary = min(((a.distance(), a.itinerary()) for a in r.alternatives())) self.assertLess(min_dist, 6500 * KM) # Good self.assertListEqual([COP, LIS, MAD, BER, COP], best_itinerary) if __name__ == "__main__": unittest.main() ## Instruction: Move API key to environment variable ## Code After: from os import environ import unittest import googlemaps from pyrules2.googlemaps import driving_roundtrip COP = 'Copenhagen, Denmark' MAD = 'Madrid, Spain' BER = 'Berlin, Germany' LIS = 'Lisbon, Portugal' KM = 1000 class Test(unittest.TestCase): def setUp(self): try: key = environ['GOOGLE_MAPS_API_KEY'] except KeyError: self.fail('This test requires an API key for Google Maps in the environment variable GOOGLE_MAPS_API_KEY') self.client = googlemaps.Client(key=key) def test_roundtrip(self): r = driving_roundtrip(self.client, COP, MAD, BER, LIS) self.assertGreater(r.distance(), 10000 * KM) # Bad min_dist, itinerary = min(((a.distance(), a.itinerary()) for a in r.alternatives())) self.assertLess(min_dist, 6500 * KM) # Good self.assertListEqual([COP, LIS, MAD, BER, COP], itinerary) if __name__ == "__main__": unittest.main()
+ from os import environ import unittest import googlemaps from pyrules2.googlemaps import driving_roundtrip COP = 'Copenhagen, Denmark' MAD = 'Madrid, Spain' BER = 'Berlin, Germany' LIS = 'Lisbon, Portugal' KM = 1000 class Test(unittest.TestCase): def setUp(self): - # TODO: Sane way to import key - with open('/Users/nhc/git/pyrules/google-maps-api-key.txt') as f: - self.key = f.read() + try: + key = environ['GOOGLE_MAPS_API_KEY'] + except KeyError: + self.fail('This test requires an API key for Google Maps in the environment variable GOOGLE_MAPS_API_KEY') + self.client = googlemaps.Client(key=key) def test_roundtrip(self): - c = googlemaps.Client(key=self.key) - r = driving_roundtrip(c, COP, MAD, BER, LIS) + r = driving_roundtrip(self.client, COP, MAD, BER, LIS) ? +++++ +++++ self.assertGreater(r.distance(), 10000 * KM) # Bad - min_dist, best_itinerary = min(((a.distance(), a.itinerary()) for a in r.alternatives())) ? ----- + min_dist, itinerary = min(((a.distance(), a.itinerary()) for a in r.alternatives())) self.assertLess(min_dist, 6500 * KM) # Good - self.assertListEqual([COP, LIS, MAD, BER, COP], best_itinerary) ? ----- + self.assertListEqual([COP, LIS, MAD, BER, COP], itinerary) if __name__ == "__main__": unittest.main()
ec8d7181be646498717b8efa97dd6770d61f067a
test/viz/test_pca.py
test/viz/test_pca.py
def test_pca(): from sequana.viz.pca import PCA from sequana import sequana_data import pandas as pd data = sequana_data("test_pca.csv") df = pd.read_csv(data) df = df.set_index("Id") p = PCA(df, colors={ "A1": 'r', "A2": 'r', 'A3': 'r', "B1": 'b', "B2": 'b', 'B3': 'b'}) p.plot(n_components=2, switch_y=True) p.plot(n_components=2, switch_x=True) p.plot(n_components=3, switch_z=True) p.plot_pca_vs_max_features(n_components=4) p.plot_pca_vs_max_features(step=50000)
import pytest @pytest.mark.timeout(10) def test_pca(): from sequana.viz.pca import PCA from sequana import sequana_data import pandas as pd data = sequana_data("test_pca.csv") df = pd.read_csv(data) df = df.set_index("Id") p = PCA(df, colors={ "A1": 'r', "A2": 'r', 'A3': 'r', "B1": 'b', "B2": 'b', 'B3': 'b'}) p.plot(n_components=2, switch_y=True) p.plot(n_components=2, switch_x=True) p.plot(n_components=3, switch_z=True) p.plot_pca_vs_max_features(n_components=4) p.plot_pca_vs_max_features(step=50000)
Set timeout on pca test
Set timeout on pca test
Python
bsd-3-clause
sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana
+ import pytest + @pytest.mark.timeout(10) def test_pca(): from sequana.viz.pca import PCA from sequana import sequana_data import pandas as pd data = sequana_data("test_pca.csv") df = pd.read_csv(data) df = df.set_index("Id") p = PCA(df, colors={ "A1": 'r', "A2": 'r', 'A3': 'r', "B1": 'b', "B2": 'b', 'B3': 'b'}) p.plot(n_components=2, switch_y=True) p.plot(n_components=2, switch_x=True) p.plot(n_components=3, switch_z=True) p.plot_pca_vs_max_features(n_components=4) p.plot_pca_vs_max_features(step=50000)
Set timeout on pca test
## Code Before: def test_pca(): from sequana.viz.pca import PCA from sequana import sequana_data import pandas as pd data = sequana_data("test_pca.csv") df = pd.read_csv(data) df = df.set_index("Id") p = PCA(df, colors={ "A1": 'r', "A2": 'r', 'A3': 'r', "B1": 'b', "B2": 'b', 'B3': 'b'}) p.plot(n_components=2, switch_y=True) p.plot(n_components=2, switch_x=True) p.plot(n_components=3, switch_z=True) p.plot_pca_vs_max_features(n_components=4) p.plot_pca_vs_max_features(step=50000) ## Instruction: Set timeout on pca test ## Code After: import pytest @pytest.mark.timeout(10) def test_pca(): from sequana.viz.pca import PCA from sequana import sequana_data import pandas as pd data = sequana_data("test_pca.csv") df = pd.read_csv(data) df = df.set_index("Id") p = PCA(df, colors={ "A1": 'r', "A2": 'r', 'A3': 'r', "B1": 'b', "B2": 'b', 'B3': 'b'}) p.plot(n_components=2, switch_y=True) p.plot(n_components=2, switch_x=True) p.plot(n_components=3, switch_z=True) p.plot_pca_vs_max_features(n_components=4) p.plot_pca_vs_max_features(step=50000)
+ import pytest + @pytest.mark.timeout(10) def test_pca(): from sequana.viz.pca import PCA from sequana import sequana_data import pandas as pd data = sequana_data("test_pca.csv") df = pd.read_csv(data) df = df.set_index("Id") p = PCA(df, colors={ "A1": 'r', "A2": 'r', 'A3': 'r', "B1": 'b', "B2": 'b', 'B3': 'b'}) p.plot(n_components=2, switch_y=True) p.plot(n_components=2, switch_x=True) p.plot(n_components=3, switch_z=True) p.plot_pca_vs_max_features(n_components=4) p.plot_pca_vs_max_features(step=50000)
62a76827ecf7c148101b62925dea04f63709012a
sublime/User/update_user_settings.py
sublime/User/update_user_settings.py
import json import urllib2 import sublime import sublime_plugin GIST_URL = u'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa class UpdateUserSettingsCommand(sublime_plugin.TextCommand): def run(self, edit): gist_settings = self._get_settings_from_gist(GIST_URL) sublime_settings = sublime.load_settings( 'Preferences.sublime-settings' ) self._update_settings(gist_settings, sublime_settings) @staticmethod def _get_settings_from_gist(url): try: response = urllib2.urlopen(url) settings = json.loads(response.read()) except (urllib2.URLError, ValueError) as e: sublime.error_message('Could not retrieve settings: {}'.format(e)) raise return settings @staticmethod def _update_settings(settings_dict, sublime_settings): for key, value in settings_dict.items(): sublime_settings.set(key, value) sublime.save_settings('Preferences.sublime-settings') sublime.status_message('Settings updated')
import json import urllib import sublime import sublime_plugin GIST_URL = 'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa class UpdateUserSettingsCommand(sublime_plugin.TextCommand): def run(self, edit): gist_settings = self._get_settings_from_gist(GIST_URL) sublime_settings = sublime.load_settings( 'Preferences.sublime-settings' ) self._update_settings(gist_settings, sublime_settings) @staticmethod def _get_settings_from_gist(url): try: response = urllib.request.urlopen(url) settings = json.loads(response.read().decode('utf-8')) except (urllib.error.URLError, ValueError) as e: sublime.error_message('Could not retrieve settings: {}'.format(e)) raise return settings @staticmethod def _update_settings(settings_dict, sublime_settings): for key, value in settings_dict.items(): sublime_settings.set(key, value) sublime.save_settings('Preferences.sublime-settings') sublime.status_message('Settings updated')
Update command to work with sublime 3
Update command to work with sublime 3
Python
apache-2.0
RomuloOliveira/dot-files,RomuloOliveira/unix-files,RomuloOliveira/dot-files
import json - import urllib2 + import urllib import sublime import sublime_plugin - GIST_URL = u'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa + GIST_URL = 'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa class UpdateUserSettingsCommand(sublime_plugin.TextCommand): - + def run(self, edit): gist_settings = self._get_settings_from_gist(GIST_URL) sublime_settings = sublime.load_settings( 'Preferences.sublime-settings' ) self._update_settings(gist_settings, sublime_settings) @staticmethod def _get_settings_from_gist(url): try: - response = urllib2.urlopen(url) + response = urllib.request.urlopen(url) - settings = json.loads(response.read()) + settings = json.loads(response.read().decode('utf-8')) - except (urllib2.URLError, ValueError) as e: + except (urllib.error.URLError, ValueError) as e: sublime.error_message('Could not retrieve settings: {}'.format(e)) raise return settings @staticmethod def _update_settings(settings_dict, sublime_settings): for key, value in settings_dict.items(): sublime_settings.set(key, value) sublime.save_settings('Preferences.sublime-settings') sublime.status_message('Settings updated')
Update command to work with sublime 3
## Code Before: import json import urllib2 import sublime import sublime_plugin GIST_URL = u'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa class UpdateUserSettingsCommand(sublime_plugin.TextCommand): def run(self, edit): gist_settings = self._get_settings_from_gist(GIST_URL) sublime_settings = sublime.load_settings( 'Preferences.sublime-settings' ) self._update_settings(gist_settings, sublime_settings) @staticmethod def _get_settings_from_gist(url): try: response = urllib2.urlopen(url) settings = json.loads(response.read()) except (urllib2.URLError, ValueError) as e: sublime.error_message('Could not retrieve settings: {}'.format(e)) raise return settings @staticmethod def _update_settings(settings_dict, sublime_settings): for key, value in settings_dict.items(): sublime_settings.set(key, value) sublime.save_settings('Preferences.sublime-settings') sublime.status_message('Settings updated') ## Instruction: Update command to work with sublime 3 ## Code After: import json import urllib import sublime import sublime_plugin GIST_URL = 'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa class UpdateUserSettingsCommand(sublime_plugin.TextCommand): def run(self, edit): gist_settings = self._get_settings_from_gist(GIST_URL) sublime_settings = sublime.load_settings( 'Preferences.sublime-settings' ) self._update_settings(gist_settings, sublime_settings) @staticmethod def _get_settings_from_gist(url): try: response = urllib.request.urlopen(url) settings = json.loads(response.read().decode('utf-8')) except (urllib.error.URLError, ValueError) as e: sublime.error_message('Could not retrieve settings: {}'.format(e)) raise return settings @staticmethod def _update_settings(settings_dict, sublime_settings): for key, value in settings_dict.items(): sublime_settings.set(key, value) sublime.save_settings('Preferences.sublime-settings') sublime.status_message('Settings updated')
import json - import urllib2 ? - + import urllib import sublime import sublime_plugin - GIST_URL = u'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa ? - + GIST_URL = 'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa class UpdateUserSettingsCommand(sublime_plugin.TextCommand): - + def run(self, edit): gist_settings = self._get_settings_from_gist(GIST_URL) sublime_settings = sublime.load_settings( 'Preferences.sublime-settings' ) self._update_settings(gist_settings, sublime_settings) @staticmethod def _get_settings_from_gist(url): try: - response = urllib2.urlopen(url) ? ^ + response = urllib.request.urlopen(url) ? ^^^^^^^^ - settings = json.loads(response.read()) + settings = json.loads(response.read().decode('utf-8')) ? +++++++++++++++ + - except (urllib2.URLError, ValueError) as e: ? ^ + except (urllib.error.URLError, ValueError) as e: ? ^^^^^^ sublime.error_message('Could not retrieve settings: {}'.format(e)) raise return settings @staticmethod def _update_settings(settings_dict, sublime_settings): for key, value in settings_dict.items(): sublime_settings.set(key, value) sublime.save_settings('Preferences.sublime-settings') sublime.status_message('Settings updated')
355040c346ee26f763561529422b951e312e3db2
profile/files/openstack/horizon/overrides.py
profile/files/openstack/horizon/overrides.py
from openstack_dashboard.dashboards.project.access_and_security import tabs from openstack_dashboard.dashboards.project.instances import tables import horizon NO = lambda *x: False tabs.FloatingIPsTab.allowed = NO tabs.APIAccessTab.allowed = NO tables.AssociateIP.allowed = NO tables.SimpleAssociateIP.allowed = NO tables.SimpleDisassociateIP.allowed = NO project_dashboard = horizon.get_dashboard("project") # Completely remove panel Network->Routers routers_panel = project_dashboard.get_panel("routers") project_dashboard.unregister(routers_panel.__class__) # Completely remove panel Network->Networks networks_panel = project_dashboard.get_panel("networks") project_dashboard.unregister(networks_panel.__class__) # Disable Floating IPs # Remove "Volume Consistency Groups" tab from openstack_dashboard.dashboards.project.volumes import tabs tabs.CGroupsTab.allowed = NO
from openstack_dashboard.dashboards.project.access_and_security import tabs from openstack_dashboard.dashboards.project.instances import tables import horizon NO = lambda *x: False tabs.FloatingIPsTab.allowed = NO tabs.APIAccessTab.allowed = NO tables.AssociateIP.allowed = NO tables.SimpleAssociateIP.allowed = NO tables.SimpleDisassociateIP.allowed = NO project_dashboard = horizon.get_dashboard("project") # Completely remove panel Network->Routers routers_panel = project_dashboard.get_panel("routers") project_dashboard.unregister(routers_panel.__class__) # Completely remove panel Network->Networks networks_panel = project_dashboard.get_panel("networks") project_dashboard.unregister(networks_panel.__class__) # Disable Floating IPs # Completely remove panel Network->Network Topology topology_panel = project_dashboard.get_panel("network_topology") project_dashboard.unregister(topology_panel.__class__) # Remove "Volume Consistency Groups" tab from openstack_dashboard.dashboards.project.volumes import tabs tabs.CGroupsTab.allowed = NO
Remove non-working network topology panel
Remove non-working network topology panel
Python
apache-2.0
eckhart/himlar,tanzr/himlar,TorLdre/himlar,mikaeld66/himlar,norcams/himlar,raykrist/himlar,eckhart/himlar,norcams/himlar,TorLdre/himlar,norcams/himlar,norcams/himlar,raykrist/himlar,mikaeld66/himlar,eckhart/himlar,TorLdre/himlar,tanzr/himlar,mikaeld66/himlar,tanzr/himlar,TorLdre/himlar,mikaeld66/himlar,eckhart/himlar,norcams/himlar,mikaeld66/himlar,raykrist/himlar,raykrist/himlar,TorLdre/himlar,tanzr/himlar,tanzr/himlar,raykrist/himlar
from openstack_dashboard.dashboards.project.access_and_security import tabs from openstack_dashboard.dashboards.project.instances import tables import horizon NO = lambda *x: False tabs.FloatingIPsTab.allowed = NO tabs.APIAccessTab.allowed = NO tables.AssociateIP.allowed = NO tables.SimpleAssociateIP.allowed = NO tables.SimpleDisassociateIP.allowed = NO project_dashboard = horizon.get_dashboard("project") # Completely remove panel Network->Routers routers_panel = project_dashboard.get_panel("routers") project_dashboard.unregister(routers_panel.__class__) # Completely remove panel Network->Networks networks_panel = project_dashboard.get_panel("networks") project_dashboard.unregister(networks_panel.__class__) # Disable Floating IPs + # Completely remove panel Network->Network Topology + topology_panel = project_dashboard.get_panel("network_topology") + project_dashboard.unregister(topology_panel.__class__) + # Remove "Volume Consistency Groups" tab from openstack_dashboard.dashboards.project.volumes import tabs tabs.CGroupsTab.allowed = NO
Remove non-working network topology panel
## Code Before: from openstack_dashboard.dashboards.project.access_and_security import tabs from openstack_dashboard.dashboards.project.instances import tables import horizon NO = lambda *x: False tabs.FloatingIPsTab.allowed = NO tabs.APIAccessTab.allowed = NO tables.AssociateIP.allowed = NO tables.SimpleAssociateIP.allowed = NO tables.SimpleDisassociateIP.allowed = NO project_dashboard = horizon.get_dashboard("project") # Completely remove panel Network->Routers routers_panel = project_dashboard.get_panel("routers") project_dashboard.unregister(routers_panel.__class__) # Completely remove panel Network->Networks networks_panel = project_dashboard.get_panel("networks") project_dashboard.unregister(networks_panel.__class__) # Disable Floating IPs # Remove "Volume Consistency Groups" tab from openstack_dashboard.dashboards.project.volumes import tabs tabs.CGroupsTab.allowed = NO ## Instruction: Remove non-working network topology panel ## Code After: from openstack_dashboard.dashboards.project.access_and_security import tabs from openstack_dashboard.dashboards.project.instances import tables import horizon NO = lambda *x: False tabs.FloatingIPsTab.allowed = NO tabs.APIAccessTab.allowed = NO tables.AssociateIP.allowed = NO tables.SimpleAssociateIP.allowed = NO tables.SimpleDisassociateIP.allowed = NO project_dashboard = horizon.get_dashboard("project") # Completely remove panel Network->Routers routers_panel = project_dashboard.get_panel("routers") project_dashboard.unregister(routers_panel.__class__) # Completely remove panel Network->Networks networks_panel = project_dashboard.get_panel("networks") project_dashboard.unregister(networks_panel.__class__) # Disable Floating IPs # Completely remove panel Network->Network Topology topology_panel = project_dashboard.get_panel("network_topology") project_dashboard.unregister(topology_panel.__class__) # Remove "Volume Consistency Groups" tab from openstack_dashboard.dashboards.project.volumes import tabs tabs.CGroupsTab.allowed = NO
from openstack_dashboard.dashboards.project.access_and_security import tabs from openstack_dashboard.dashboards.project.instances import tables import horizon NO = lambda *x: False tabs.FloatingIPsTab.allowed = NO tabs.APIAccessTab.allowed = NO tables.AssociateIP.allowed = NO tables.SimpleAssociateIP.allowed = NO tables.SimpleDisassociateIP.allowed = NO project_dashboard = horizon.get_dashboard("project") # Completely remove panel Network->Routers routers_panel = project_dashboard.get_panel("routers") project_dashboard.unregister(routers_panel.__class__) # Completely remove panel Network->Networks networks_panel = project_dashboard.get_panel("networks") project_dashboard.unregister(networks_panel.__class__) # Disable Floating IPs + # Completely remove panel Network->Network Topology + topology_panel = project_dashboard.get_panel("network_topology") + project_dashboard.unregister(topology_panel.__class__) + # Remove "Volume Consistency Groups" tab from openstack_dashboard.dashboards.project.volumes import tabs tabs.CGroupsTab.allowed = NO
9a8544eaccde1420e6cbac7b4c5115155d6402f3
django_docutils/__about__.py
django_docutils/__about__.py
__title__ = 'django-docutils' __package_name__ = 'django_docutils' __description__ = 'Documentation Utilities (Docutils, reStructuredText) for django.' __version__ = '0.4.0' __author__ = 'Tony Narlock' __email__ = '[email protected]' __license__ = 'BSD' __copyright__ = 'Copyright 2013-2015 Tony Narlock'
__title__ = 'django-docutils' __package_name__ = 'django_docutils' __description__ = 'Documentation Utilities (Docutils, reStructuredText) for django.' __version__ = '0.4.0' __author__ = 'Tony Narlock' __github__ = 'https://github.com/tony/django-docutils' __pypi__ = 'https://pypi.org/project/django-docutils/' __email__ = '[email protected]' __license__ = 'BSD' __copyright__ = 'Copyright 2013- Tony Narlock'
Add github + pypi to metadata
Add github + pypi to metadata
Python
mit
tony/django-docutils,tony/django-docutils
__title__ = 'django-docutils' __package_name__ = 'django_docutils' __description__ = 'Documentation Utilities (Docutils, reStructuredText) for django.' __version__ = '0.4.0' __author__ = 'Tony Narlock' + __github__ = 'https://github.com/tony/django-docutils' + __pypi__ = 'https://pypi.org/project/django-docutils/' __email__ = '[email protected]' __license__ = 'BSD' - __copyright__ = 'Copyright 2013-2015 Tony Narlock' + __copyright__ = 'Copyright 2013- Tony Narlock'
Add github + pypi to metadata
## Code Before: __title__ = 'django-docutils' __package_name__ = 'django_docutils' __description__ = 'Documentation Utilities (Docutils, reStructuredText) for django.' __version__ = '0.4.0' __author__ = 'Tony Narlock' __email__ = '[email protected]' __license__ = 'BSD' __copyright__ = 'Copyright 2013-2015 Tony Narlock' ## Instruction: Add github + pypi to metadata ## Code After: __title__ = 'django-docutils' __package_name__ = 'django_docutils' __description__ = 'Documentation Utilities (Docutils, reStructuredText) for django.' __version__ = '0.4.0' __author__ = 'Tony Narlock' __github__ = 'https://github.com/tony/django-docutils' __pypi__ = 'https://pypi.org/project/django-docutils/' __email__ = '[email protected]' __license__ = 'BSD' __copyright__ = 'Copyright 2013- Tony Narlock'
__title__ = 'django-docutils' __package_name__ = 'django_docutils' __description__ = 'Documentation Utilities (Docutils, reStructuredText) for django.' __version__ = '0.4.0' __author__ = 'Tony Narlock' + __github__ = 'https://github.com/tony/django-docutils' + __pypi__ = 'https://pypi.org/project/django-docutils/' __email__ = '[email protected]' __license__ = 'BSD' - __copyright__ = 'Copyright 2013-2015 Tony Narlock' ? ---- + __copyright__ = 'Copyright 2013- Tony Narlock'
f76015fdf37db44a54ce0e0038b4b85978c39839
tests/test_utils.py
tests/test_utils.py
import __future__ # noqa: F401 import json # noqa: F401 from os import path # noqa: F401 from re import IGNORECASE, sub # noqa: F401 import my_module # noqa: F401 from my_module.utils import add_two_numbers import pytest class TestUtils: # noqa: D101 @pytest.mark.parametrize('number_left, number_right', [ (None, 1), (1, None), (None, None) ]) def test_add_two_numbers_no_input(self, number_left, number_right): """Basic input validation.""" with pytest.raises(ValueError): add_two_numbers(number_left, number_right) def test_add_two_numbers_regular_input(self): """Basic asserting test.""" assert add_two_numbers(2, 3) == 5
import __future__ # noqa: F401 import json # noqa: F401 from os import path # noqa: F401 from re import IGNORECASE, sub # noqa: F401 import click # noqa: F401 import my_module # noqa: F401 from my_module.utils import add_two_numbers import pytest import requests # noqa: F401 class TestUtils: # noqa: D101 @pytest.mark.parametrize('number_left, number_right', [ (None, 1), (1, None), (None, None) ]) def test_add_two_numbers_no_input(self, number_left, number_right): """Basic input validation.""" with pytest.raises(ValueError): add_two_numbers(number_left, number_right) def test_add_two_numbers_regular_input(self): """Basic asserting test.""" assert add_two_numbers(2, 3) == 5
Add import statements breaking linter
Add import statements breaking linter
Python
apache-2.0
BastiTee/bastis-python-toolbox
import __future__ # noqa: F401 import json # noqa: F401 from os import path # noqa: F401 from re import IGNORECASE, sub # noqa: F401 + import click # noqa: F401 import my_module # noqa: F401 from my_module.utils import add_two_numbers import pytest + import requests # noqa: F401 class TestUtils: # noqa: D101 @pytest.mark.parametrize('number_left, number_right', [ (None, 1), (1, None), (None, None) ]) def test_add_two_numbers_no_input(self, number_left, number_right): """Basic input validation.""" with pytest.raises(ValueError): add_two_numbers(number_left, number_right) def test_add_two_numbers_regular_input(self): """Basic asserting test.""" assert add_two_numbers(2, 3) == 5
Add import statements breaking linter
## Code Before: import __future__ # noqa: F401 import json # noqa: F401 from os import path # noqa: F401 from re import IGNORECASE, sub # noqa: F401 import my_module # noqa: F401 from my_module.utils import add_two_numbers import pytest class TestUtils: # noqa: D101 @pytest.mark.parametrize('number_left, number_right', [ (None, 1), (1, None), (None, None) ]) def test_add_two_numbers_no_input(self, number_left, number_right): """Basic input validation.""" with pytest.raises(ValueError): add_two_numbers(number_left, number_right) def test_add_two_numbers_regular_input(self): """Basic asserting test.""" assert add_two_numbers(2, 3) == 5 ## Instruction: Add import statements breaking linter ## Code After: import __future__ # noqa: F401 import json # noqa: F401 from os import path # noqa: F401 from re import IGNORECASE, sub # noqa: F401 import click # noqa: F401 import my_module # noqa: F401 from my_module.utils import add_two_numbers import pytest import requests # noqa: F401 class TestUtils: # noqa: D101 @pytest.mark.parametrize('number_left, number_right', [ (None, 1), (1, None), (None, None) ]) def test_add_two_numbers_no_input(self, number_left, number_right): """Basic input validation.""" with pytest.raises(ValueError): add_two_numbers(number_left, number_right) def test_add_two_numbers_regular_input(self): """Basic asserting test.""" assert add_two_numbers(2, 3) == 5
import __future__ # noqa: F401 import json # noqa: F401 from os import path # noqa: F401 from re import IGNORECASE, sub # noqa: F401 + import click # noqa: F401 import my_module # noqa: F401 from my_module.utils import add_two_numbers import pytest + import requests # noqa: F401 class TestUtils: # noqa: D101 @pytest.mark.parametrize('number_left, number_right', [ (None, 1), (1, None), (None, None) ]) def test_add_two_numbers_no_input(self, number_left, number_right): """Basic input validation.""" with pytest.raises(ValueError): add_two_numbers(number_left, number_right) def test_add_two_numbers_regular_input(self): """Basic asserting test.""" assert add_two_numbers(2, 3) == 5
020e48affc34162676193ab97dad7f8ffbdaaaa6
jupyter_kernel/magics/shell_magic.py
jupyter_kernel/magics/shell_magic.py
from jupyter_kernel import Magic import subprocess class ShellMagic(Magic): def line_shell(self, *args): """%shell COMMAND - run the line as a shell command""" command = " ".join(args) try: process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retval, error = process.communicate() if error: self.kernel.Error(error) except Exception as e: self.kernel.Error(e.message) retval = None if retval: self.kernel.Print(retval) def cell_shell(self): """%%shell - run the contents of the cell as shell commands""" self.line_shell(self.code) self.evaluate = False def register_magics(kernel): kernel.register_magics(ShellMagic)
from jupyter_kernel import Magic import subprocess class ShellMagic(Magic): def line_shell(self, *args): """%shell COMMAND - run the line as a shell command""" command = " ".join(args) try: process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retval, error = process.communicate() if error: self.kernel.Error(error) except Exception as e: self.kernel.Error(e.message) retval = None if retval: retval = retval.decode('utf-8') self.kernel.Print(retval) def cell_shell(self): """%%shell - run the contents of the cell as shell commands""" self.line_shell(self.code) self.evaluate = False def register_magics(kernel): kernel.register_magics(ShellMagic)
Fix bytes problem on python 3.
Fix bytes problem on python 3.
Python
bsd-3-clause
Calysto/metakernel
from jupyter_kernel import Magic import subprocess class ShellMagic(Magic): def line_shell(self, *args): """%shell COMMAND - run the line as a shell command""" command = " ".join(args) try: process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retval, error = process.communicate() if error: self.kernel.Error(error) except Exception as e: self.kernel.Error(e.message) retval = None if retval: + retval = retval.decode('utf-8') self.kernel.Print(retval) def cell_shell(self): """%%shell - run the contents of the cell as shell commands""" self.line_shell(self.code) self.evaluate = False def register_magics(kernel): kernel.register_magics(ShellMagic)
Fix bytes problem on python 3.
## Code Before: from jupyter_kernel import Magic import subprocess class ShellMagic(Magic): def line_shell(self, *args): """%shell COMMAND - run the line as a shell command""" command = " ".join(args) try: process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retval, error = process.communicate() if error: self.kernel.Error(error) except Exception as e: self.kernel.Error(e.message) retval = None if retval: self.kernel.Print(retval) def cell_shell(self): """%%shell - run the contents of the cell as shell commands""" self.line_shell(self.code) self.evaluate = False def register_magics(kernel): kernel.register_magics(ShellMagic) ## Instruction: Fix bytes problem on python 3. ## Code After: from jupyter_kernel import Magic import subprocess class ShellMagic(Magic): def line_shell(self, *args): """%shell COMMAND - run the line as a shell command""" command = " ".join(args) try: process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retval, error = process.communicate() if error: self.kernel.Error(error) except Exception as e: self.kernel.Error(e.message) retval = None if retval: retval = retval.decode('utf-8') self.kernel.Print(retval) def cell_shell(self): """%%shell - run the contents of the cell as shell commands""" self.line_shell(self.code) self.evaluate = False def register_magics(kernel): kernel.register_magics(ShellMagic)
from jupyter_kernel import Magic import subprocess class ShellMagic(Magic): def line_shell(self, *args): """%shell COMMAND - run the line as a shell command""" command = " ".join(args) try: process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retval, error = process.communicate() if error: self.kernel.Error(error) except Exception as e: self.kernel.Error(e.message) retval = None if retval: + retval = retval.decode('utf-8') self.kernel.Print(retval) def cell_shell(self): """%%shell - run the contents of the cell as shell commands""" self.line_shell(self.code) self.evaluate = False def register_magics(kernel): kernel.register_magics(ShellMagic)
a7dc058cf8a1d08d02b16a635b7a05d93ab42c1f
shuup/core/utils/db.py
shuup/core/utils/db.py
import math def extend_sqlite_functions(connection=None, **kwargs): """ Extends SQLite with trigonometry functions """ if connection and connection.vendor == 'sqlite': connection.connection.create_function("sin", 1, math.sin) connection.connection.create_function("cos", 1, math.cos) connection.connection.create_function("acos", 1, math.acos) connection.connection.create_function("degrees", 1, math.degrees) connection.connection.create_function("radians", 1, math.radians)
import math def float_wrap(value, func): try: return func(float(value)) except: return None def extend_sqlite_functions(connection=None, **kwargs): """ Extends SQLite with trigonometry functions """ if connection and connection.vendor == 'sqlite': connection.connection.create_function("sin", 1, lambda x: float_wrap(x, math.sin)) connection.connection.create_function("cos", 1, lambda x: float_wrap(x, math.cos)) connection.connection.create_function("acos", 1, lambda x: float_wrap(x, math.acos)) connection.connection.create_function("degrees", 1, lambda x: float_wrap(x, math.degrees)) connection.connection.create_function("radians", 1, lambda x: float_wrap(x, math.radians))
Add wrapper to parse values to float in SQLite
Add wrapper to parse values to float in SQLite Refs TREES-359
Python
agpl-3.0
suutari-ai/shoop,shoopio/shoop,shoopio/shoop,suutari-ai/shoop,suutari-ai/shoop,shoopio/shoop
import math + + + def float_wrap(value, func): + try: + return func(float(value)) + except: + return None def extend_sqlite_functions(connection=None, **kwargs): """ Extends SQLite with trigonometry functions """ if connection and connection.vendor == 'sqlite': - connection.connection.create_function("sin", 1, math.sin) + connection.connection.create_function("sin", 1, lambda x: float_wrap(x, math.sin)) - connection.connection.create_function("cos", 1, math.cos) + connection.connection.create_function("cos", 1, lambda x: float_wrap(x, math.cos)) - connection.connection.create_function("acos", 1, math.acos) + connection.connection.create_function("acos", 1, lambda x: float_wrap(x, math.acos)) - connection.connection.create_function("degrees", 1, math.degrees) + connection.connection.create_function("degrees", 1, lambda x: float_wrap(x, math.degrees)) - connection.connection.create_function("radians", 1, math.radians) + connection.connection.create_function("radians", 1, lambda x: float_wrap(x, math.radians))
Add wrapper to parse values to float in SQLite
## Code Before: import math def extend_sqlite_functions(connection=None, **kwargs): """ Extends SQLite with trigonometry functions """ if connection and connection.vendor == 'sqlite': connection.connection.create_function("sin", 1, math.sin) connection.connection.create_function("cos", 1, math.cos) connection.connection.create_function("acos", 1, math.acos) connection.connection.create_function("degrees", 1, math.degrees) connection.connection.create_function("radians", 1, math.radians) ## Instruction: Add wrapper to parse values to float in SQLite ## Code After: import math def float_wrap(value, func): try: return func(float(value)) except: return None def extend_sqlite_functions(connection=None, **kwargs): """ Extends SQLite with trigonometry functions """ if connection and connection.vendor == 'sqlite': connection.connection.create_function("sin", 1, lambda x: float_wrap(x, math.sin)) connection.connection.create_function("cos", 1, lambda x: float_wrap(x, math.cos)) connection.connection.create_function("acos", 1, lambda x: float_wrap(x, math.acos)) connection.connection.create_function("degrees", 1, lambda x: float_wrap(x, math.degrees)) connection.connection.create_function("radians", 1, lambda x: float_wrap(x, math.radians))
import math + + + def float_wrap(value, func): + try: + return func(float(value)) + except: + return None def extend_sqlite_functions(connection=None, **kwargs): """ Extends SQLite with trigonometry functions """ if connection and connection.vendor == 'sqlite': - connection.connection.create_function("sin", 1, math.sin) + connection.connection.create_function("sin", 1, lambda x: float_wrap(x, math.sin)) ? ++++++++++++++++++++++++ + - connection.connection.create_function("cos", 1, math.cos) + connection.connection.create_function("cos", 1, lambda x: float_wrap(x, math.cos)) ? ++++++++++++++++++++++++ + - connection.connection.create_function("acos", 1, math.acos) + connection.connection.create_function("acos", 1, lambda x: float_wrap(x, math.acos)) ? ++++++++++++++++++++++++ + - connection.connection.create_function("degrees", 1, math.degrees) + connection.connection.create_function("degrees", 1, lambda x: float_wrap(x, math.degrees)) ? ++++++++++++++++++++++++ + - connection.connection.create_function("radians", 1, math.radians) + connection.connection.create_function("radians", 1, lambda x: float_wrap(x, math.radians)) ? ++++++++++++++++++++++++ +
30f0b99a2233c6009a3c41d9b22e3f946c40c3cf
kitchen/urls.py
kitchen/urls.py
"""Root URL routing""" from django.conf.urls.defaults import patterns from django.conf.urls.static import static from django.views.generic import TemplateView from kitchen.dashboard import api import kitchen.settings as settings urlpatterns = patterns('', (r'^$', 'kitchen.dashboard.views.list'), (r'^virt/$', 'kitchen.dashboard.views.virt'), (r'^graph/$', 'kitchen.dashboard.views.graph'), (r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'), (r'^api/nodes/(?P<name>\w+)$', api.get_node), (r'^api/nodes', api.get_nodes), (r'^api/roles', api.get_roles), (r'^404', TemplateView.as_view(template_name="404.html")), ) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
"""Root URL routing""" from django.conf.urls.defaults import patterns from django.conf.urls.static import static from django.views.generic import TemplateView from kitchen.dashboard import api import kitchen.settings as settings if settings.SHOW_LIST_VIEW: root_view = 'kitchen.dashboard.views.list' elif settings.SHOW_VIRT_VIEW: root_view = 'kitchen.dashboard.views.virt' elif settings.SHOW_GRAPH_VIEW: root_view = 'kitchen.dashboard.views.graph' else: raise Exception("No views enabled! Please edit settings.py.") urlpatterns = patterns('', (r'^$', root_view), (r'^virt/$', 'kitchen.dashboard.views.virt'), (r'^graph/$', 'kitchen.dashboard.views.graph'), (r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'), (r'^api/nodes/(?P<name>\w+)$', api.get_node), (r'^api/nodes', api.get_nodes), (r'^api/roles', api.get_roles), (r'^404', TemplateView.as_view(template_name="404.html")), ) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Set root view depending on what views are enabled
Set root view depending on what views are enabled
Python
apache-2.0
edelight/kitchen,edelight/kitchen,edelight/kitchen,edelight/kitchen
"""Root URL routing""" from django.conf.urls.defaults import patterns from django.conf.urls.static import static from django.views.generic import TemplateView from kitchen.dashboard import api import kitchen.settings as settings + if settings.SHOW_LIST_VIEW: + root_view = 'kitchen.dashboard.views.list' + elif settings.SHOW_VIRT_VIEW: + root_view = 'kitchen.dashboard.views.virt' + elif settings.SHOW_GRAPH_VIEW: + root_view = 'kitchen.dashboard.views.graph' + else: + raise Exception("No views enabled! Please edit settings.py.") + + urlpatterns = patterns('', - (r'^$', 'kitchen.dashboard.views.list'), + (r'^$', root_view), (r'^virt/$', 'kitchen.dashboard.views.virt'), (r'^graph/$', 'kitchen.dashboard.views.graph'), (r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'), (r'^api/nodes/(?P<name>\w+)$', api.get_node), (r'^api/nodes', api.get_nodes), (r'^api/roles', api.get_roles), (r'^404', TemplateView.as_view(template_name="404.html")), ) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Set root view depending on what views are enabled
## Code Before: """Root URL routing""" from django.conf.urls.defaults import patterns from django.conf.urls.static import static from django.views.generic import TemplateView from kitchen.dashboard import api import kitchen.settings as settings urlpatterns = patterns('', (r'^$', 'kitchen.dashboard.views.list'), (r'^virt/$', 'kitchen.dashboard.views.virt'), (r'^graph/$', 'kitchen.dashboard.views.graph'), (r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'), (r'^api/nodes/(?P<name>\w+)$', api.get_node), (r'^api/nodes', api.get_nodes), (r'^api/roles', api.get_roles), (r'^404', TemplateView.as_view(template_name="404.html")), ) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ## Instruction: Set root view depending on what views are enabled ## Code After: """Root URL routing""" from django.conf.urls.defaults import patterns from django.conf.urls.static import static from django.views.generic import TemplateView from kitchen.dashboard import api import kitchen.settings as settings if settings.SHOW_LIST_VIEW: root_view = 'kitchen.dashboard.views.list' elif settings.SHOW_VIRT_VIEW: root_view = 'kitchen.dashboard.views.virt' elif settings.SHOW_GRAPH_VIEW: root_view = 'kitchen.dashboard.views.graph' else: raise Exception("No views enabled! Please edit settings.py.") urlpatterns = patterns('', (r'^$', root_view), (r'^virt/$', 'kitchen.dashboard.views.virt'), (r'^graph/$', 'kitchen.dashboard.views.graph'), (r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'), (r'^api/nodes/(?P<name>\w+)$', api.get_node), (r'^api/nodes', api.get_nodes), (r'^api/roles', api.get_roles), (r'^404', TemplateView.as_view(template_name="404.html")), ) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
"""Root URL routing""" from django.conf.urls.defaults import patterns from django.conf.urls.static import static from django.views.generic import TemplateView from kitchen.dashboard import api import kitchen.settings as settings + if settings.SHOW_LIST_VIEW: + root_view = 'kitchen.dashboard.views.list' + elif settings.SHOW_VIRT_VIEW: + root_view = 'kitchen.dashboard.views.virt' + elif settings.SHOW_GRAPH_VIEW: + root_view = 'kitchen.dashboard.views.graph' + else: + raise Exception("No views enabled! Please edit settings.py.") + + urlpatterns = patterns('', - (r'^$', 'kitchen.dashboard.views.list'), + (r'^$', root_view), (r'^virt/$', 'kitchen.dashboard.views.virt'), (r'^graph/$', 'kitchen.dashboard.views.graph'), (r'^plugins/((?P<plugin_type>(virt|v|list|l))/)?(?P<name>[\w\-\_]+)/(?P<method>\w+)/?$', 'kitchen.dashboard.views.plugins'), (r'^api/nodes/(?P<name>\w+)$', api.get_node), (r'^api/nodes', api.get_nodes), (r'^api/roles', api.get_roles), (r'^404', TemplateView.as_view(template_name="404.html")), ) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
1090b8b4e17b29b69eb205ac0c7fea65f597807f
ffdnispdb/__init__.py
ffdnispdb/__init__.py
from flask import Flask, g from flask.ext.babel import Babel from flask.ext.sqlalchemy import SQLAlchemy, event from .sessions import MySessionInterface app = Flask(__name__) app.config.from_object('config') babel = Babel(app) db = SQLAlchemy(app) app.session_interface = MySessionInterface(db.engine, db.metadata) @event.listens_for(db.engine, "connect") def connect(sqlite, connection_rec): sqlite.enable_load_extension(True) sqlite.execute('select load_extension("libspatialite.so")') sqlite.enable_load_extension(False) from . import views from . import models
from flask import Flask, g from flask.ext.babel import Babel from flask.ext.sqlalchemy import SQLAlchemy, event from werkzeug.contrib.cache import NullCache from .sessions import MySessionInterface app = Flask(__name__) app.config.from_object('config') babel = Babel(app) db = SQLAlchemy(app) app.session_interface = MySessionInterface(db.engine, db.metadata) cache = NullCache() @event.listens_for(db.engine, "connect") def connect(sqlite, connection_rec): sqlite.enable_load_extension(True) sqlite.execute('select load_extension("libspatialite.so")') sqlite.enable_load_extension(False) from . import views from . import models
Enable NullCache so we can start implementing cache
Enable NullCache so we can start implementing cache
Python
bsd-3-clause
Psycojoker/ffdn-db,Psycojoker/ffdn-db
from flask import Flask, g from flask.ext.babel import Babel from flask.ext.sqlalchemy import SQLAlchemy, event + from werkzeug.contrib.cache import NullCache from .sessions import MySessionInterface app = Flask(__name__) app.config.from_object('config') babel = Babel(app) db = SQLAlchemy(app) app.session_interface = MySessionInterface(db.engine, db.metadata) + cache = NullCache() @event.listens_for(db.engine, "connect") def connect(sqlite, connection_rec): sqlite.enable_load_extension(True) sqlite.execute('select load_extension("libspatialite.so")') sqlite.enable_load_extension(False) from . import views from . import models
Enable NullCache so we can start implementing cache
## Code Before: from flask import Flask, g from flask.ext.babel import Babel from flask.ext.sqlalchemy import SQLAlchemy, event from .sessions import MySessionInterface app = Flask(__name__) app.config.from_object('config') babel = Babel(app) db = SQLAlchemy(app) app.session_interface = MySessionInterface(db.engine, db.metadata) @event.listens_for(db.engine, "connect") def connect(sqlite, connection_rec): sqlite.enable_load_extension(True) sqlite.execute('select load_extension("libspatialite.so")') sqlite.enable_load_extension(False) from . import views from . import models ## Instruction: Enable NullCache so we can start implementing cache ## Code After: from flask import Flask, g from flask.ext.babel import Babel from flask.ext.sqlalchemy import SQLAlchemy, event from werkzeug.contrib.cache import NullCache from .sessions import MySessionInterface app = Flask(__name__) app.config.from_object('config') babel = Babel(app) db = SQLAlchemy(app) app.session_interface = MySessionInterface(db.engine, db.metadata) cache = NullCache() @event.listens_for(db.engine, "connect") def connect(sqlite, connection_rec): sqlite.enable_load_extension(True) sqlite.execute('select load_extension("libspatialite.so")') sqlite.enable_load_extension(False) from . import views from . import models
from flask import Flask, g from flask.ext.babel import Babel from flask.ext.sqlalchemy import SQLAlchemy, event + from werkzeug.contrib.cache import NullCache from .sessions import MySessionInterface app = Flask(__name__) app.config.from_object('config') babel = Babel(app) db = SQLAlchemy(app) app.session_interface = MySessionInterface(db.engine, db.metadata) + cache = NullCache() @event.listens_for(db.engine, "connect") def connect(sqlite, connection_rec): sqlite.enable_load_extension(True) sqlite.execute('select load_extension("libspatialite.so")') sqlite.enable_load_extension(False) from . import views from . import models
9b02a09be67c8ec3d3b4b652d98f2cd5c3fdc863
app/timetables/admin.py
app/timetables/admin.py
from django.contrib import admin from .models import Course, Meal, MealOption, Weekday, Timetable, Dish admin.site.register(Weekday) admin.site.register(Meal) admin.site.register(MealOption) admin.site.register(Course) admin.site.register(Timetable) admin.site.register(Dish)
from django.contrib import admin from .models import * admin.site.register(Weekday) admin.site.register(Meal) admin.site.register(MealOption) admin.site.register(Course) admin.site.register(Timetable) admin.site.register(Dish) admin.site.register(Admin)
Add Timetables Admin model to Django Admin Interface
Add Timetables Admin model to Django Admin Interface
Python
mit
teamtaverna/core
from django.contrib import admin + from .models import * - from .models import Course, Meal, MealOption, Weekday, Timetable, Dish - admin.site.register(Weekday) admin.site.register(Meal) admin.site.register(MealOption) admin.site.register(Course) admin.site.register(Timetable) admin.site.register(Dish) + admin.site.register(Admin)
Add Timetables Admin model to Django Admin Interface
## Code Before: from django.contrib import admin from .models import Course, Meal, MealOption, Weekday, Timetable, Dish admin.site.register(Weekday) admin.site.register(Meal) admin.site.register(MealOption) admin.site.register(Course) admin.site.register(Timetable) admin.site.register(Dish) ## Instruction: Add Timetables Admin model to Django Admin Interface ## Code After: from django.contrib import admin from .models import * admin.site.register(Weekday) admin.site.register(Meal) admin.site.register(MealOption) admin.site.register(Course) admin.site.register(Timetable) admin.site.register(Dish) admin.site.register(Admin)
from django.contrib import admin + from .models import * - from .models import Course, Meal, MealOption, Weekday, Timetable, Dish - admin.site.register(Weekday) admin.site.register(Meal) admin.site.register(MealOption) admin.site.register(Course) admin.site.register(Timetable) admin.site.register(Dish) + admin.site.register(Admin)
56236454f252ab8feee461c49c26b9eee70a7e09
vpython/_vector_import_helper.py
vpython/_vector_import_helper.py
import platform try: if platform.python_implementation() == 'PyPy': from .vector import * # use pure python vector for PyPy else: from .cyvector import * v = vector(0,0,0) except: from .vector import * # synonyms in GlowScript vec = vector
import platform try: if platform.python_implementation() == 'PyPy': from .vector import * # use pure python vector for PyPy else: from .cyvector import * v = vector(0,0,0) except: from .vector import * # Remove platform from the namespace now that we are done with it del platform # synonyms in GlowScript vec = vector
Delete platform so that it doesn't end up in the user's namespace
Delete platform so that it doesn't end up in the user's namespace
Python
mit
BruceSherwood/vpython-jupyter,mwcraig/vpython-jupyter,BruceSherwood/vpython-jupyter,mwcraig/vpython-jupyter,mwcraig/vpython-jupyter,mwcraig/vpython-jupyter,BruceSherwood/vpython-jupyter,BruceSherwood/vpython-jupyter
import platform try: if platform.python_implementation() == 'PyPy': from .vector import * # use pure python vector for PyPy else: from .cyvector import * v = vector(0,0,0) except: from .vector import * + # Remove platform from the namespace now that we are done with it + del platform + # synonyms in GlowScript vec = vector
Delete platform so that it doesn't end up in the user's namespace
## Code Before: import platform try: if platform.python_implementation() == 'PyPy': from .vector import * # use pure python vector for PyPy else: from .cyvector import * v = vector(0,0,0) except: from .vector import * # synonyms in GlowScript vec = vector ## Instruction: Delete platform so that it doesn't end up in the user's namespace ## Code After: import platform try: if platform.python_implementation() == 'PyPy': from .vector import * # use pure python vector for PyPy else: from .cyvector import * v = vector(0,0,0) except: from .vector import * # Remove platform from the namespace now that we are done with it del platform # synonyms in GlowScript vec = vector
import platform try: if platform.python_implementation() == 'PyPy': from .vector import * # use pure python vector for PyPy else: from .cyvector import * v = vector(0,0,0) except: from .vector import * + # Remove platform from the namespace now that we are done with it + del platform + # synonyms in GlowScript vec = vector
c4dd6502bc7b9d5970a659c57e6aa2d25cc00fe5
catwatch/lib/util_datetime.py
catwatch/lib/util_datetime.py
import datetime def timedelta_months(months, compare_date=None): """ Return a JSON response. :param months: Amount of months to offset :type months: int :param compare_date: Date to compare at :type compare_date: date :return: Flask response """ if compare_date is None: compare_date = datetime.date.today() delta = months * 365 / 12 compare_date_with_delta = compare_date + datetime.timedelta(delta) return compare_date_with_delta
import datetime def timedelta_months(months, compare_date=None): """ Return a new datetime with a month offset applied. :param months: Amount of months to offset :type months: int :param compare_date: Date to compare at :type compare_date: date :return: datetime """ if compare_date is None: compare_date = datetime.date.today() delta = months * 365 / 12 compare_date_with_delta = compare_date + datetime.timedelta(delta) return compare_date_with_delta
Update timedelta_months docstring to be accurate
Update timedelta_months docstring to be accurate
Python
mit
z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask
import datetime def timedelta_months(months, compare_date=None): """ - Return a JSON response. + Return a new datetime with a month offset applied. :param months: Amount of months to offset :type months: int :param compare_date: Date to compare at :type compare_date: date - :return: Flask response + :return: datetime """ if compare_date is None: compare_date = datetime.date.today() delta = months * 365 / 12 compare_date_with_delta = compare_date + datetime.timedelta(delta) return compare_date_with_delta
Update timedelta_months docstring to be accurate
## Code Before: import datetime def timedelta_months(months, compare_date=None): """ Return a JSON response. :param months: Amount of months to offset :type months: int :param compare_date: Date to compare at :type compare_date: date :return: Flask response """ if compare_date is None: compare_date = datetime.date.today() delta = months * 365 / 12 compare_date_with_delta = compare_date + datetime.timedelta(delta) return compare_date_with_delta ## Instruction: Update timedelta_months docstring to be accurate ## Code After: import datetime def timedelta_months(months, compare_date=None): """ Return a new datetime with a month offset applied. :param months: Amount of months to offset :type months: int :param compare_date: Date to compare at :type compare_date: date :return: datetime """ if compare_date is None: compare_date = datetime.date.today() delta = months * 365 / 12 compare_date_with_delta = compare_date + datetime.timedelta(delta) return compare_date_with_delta
import datetime def timedelta_months(months, compare_date=None): """ - Return a JSON response. + Return a new datetime with a month offset applied. :param months: Amount of months to offset :type months: int :param compare_date: Date to compare at :type compare_date: date - :return: Flask response + :return: datetime """ if compare_date is None: compare_date = datetime.date.today() delta = months * 365 / 12 compare_date_with_delta = compare_date + datetime.timedelta(delta) return compare_date_with_delta
002a598afbdf86472611c018d17d0eff8a9690aa
flocker/provision/_sphinx.py
flocker/provision/_sphinx.py
from docutils.parsers.rst import Directive from twisted.python.reflect import namedAny from docutils import nodes from docutils.statemachine import StringList class FakeRunner(object): def __init__(self): self.commands = [] def run(self, command): self.commands.extend(command.splitlines()) def put(self, content, path): raise NotImplementedError("put not supported.") class TaskDirective(Directive): """ Implementation of the C{frameimage} directive. """ required_arguments = 1 def run(self): task = self.arguments[0] runner = FakeRunner() try: namedAny(task)(runner) except NotImplementedError as e: raise self.error("task: %s" % (e.args[0],)) lines = ['.. code-block:: bash', ''] lines += [' %s' % (command,) for command in runner.commands] node = nodes.Element() text = StringList(lines) self.state.nested_parse(text, self.content_offset, node) return node.children def setup(app): """ Entry point for sphinx extension. """ app.add_directive('task', TaskDirective)
from inspect import getsourcefile from docutils.parsers.rst import Directive from docutils import nodes from docutils.statemachine import StringList from twisted.python.reflect import namedAny class FakeRunner(object): def __init__(self): self.commands = [] def run(self, command): self.commands.extend(command.splitlines()) def put(self, content, path): raise NotImplementedError("put not supported.") class TaskDirective(Directive): """ Implementation of the C{frameimage} directive. """ required_arguments = 1 def run(self): task = namedAny(self.arguments[0]) runner = FakeRunner() try: task(runner) except NotImplementedError as e: raise self.error("task: %s" % (e.args[0],)) lines = ['.. code-block:: bash', ''] lines += [' %s' % (command,) for command in runner.commands] # The following three lines record (some?) of the dependencies of the # directive, so automatic regeneration happens. Specifically, it # records this file, and the file where the task is declared. task_file = getsourcefile(task) self.state.document.settings.record_dependencies.add(task_file) self.state.document.settings.record_dependencies.add(__file__) node = nodes.Element() text = StringList(lines) self.state.nested_parse(text, self.content_offset, node) return node.children def setup(app): """ Entry point for sphinx extension. """ app.add_directive('task', TaskDirective)
Add state change to sphinx plugin.
Add state change to sphinx plugin.
Python
apache-2.0
jml/flocker,wallnerryan/flocker-profiles,runcom/flocker,adamtheturtle/flocker,lukemarsden/flocker,1d4Nf6/flocker,mbrukman/flocker,Azulinho/flocker,moypray/flocker,AndyHuu/flocker,lukemarsden/flocker,agonzalezro/flocker,jml/flocker,1d4Nf6/flocker,runcom/flocker,agonzalezro/flocker,hackday-profilers/flocker,achanda/flocker,LaynePeng/flocker,AndyHuu/flocker,moypray/flocker,mbrukman/flocker,runcom/flocker,LaynePeng/flocker,AndyHuu/flocker,adamtheturtle/flocker,lukemarsden/flocker,Azulinho/flocker,agonzalezro/flocker,w4ngyi/flocker,adamtheturtle/flocker,jml/flocker,moypray/flocker,wallnerryan/flocker-profiles,mbrukman/flocker,achanda/flocker,w4ngyi/flocker,1d4Nf6/flocker,w4ngyi/flocker,achanda/flocker,hackday-profilers/flocker,LaynePeng/flocker,hackday-profilers/flocker,wallnerryan/flocker-profiles,Azulinho/flocker
+ + from inspect import getsourcefile from docutils.parsers.rst import Directive - from twisted.python.reflect import namedAny from docutils import nodes from docutils.statemachine import StringList + + from twisted.python.reflect import namedAny class FakeRunner(object): def __init__(self): self.commands = [] def run(self, command): self.commands.extend(command.splitlines()) def put(self, content, path): raise NotImplementedError("put not supported.") class TaskDirective(Directive): """ Implementation of the C{frameimage} directive. """ required_arguments = 1 def run(self): - task = self.arguments[0] + task = namedAny(self.arguments[0]) runner = FakeRunner() try: - namedAny(task)(runner) + task(runner) except NotImplementedError as e: raise self.error("task: %s" % (e.args[0],)) + lines = ['.. code-block:: bash', ''] lines += [' %s' % (command,) for command in runner.commands] + + # The following three lines record (some?) of the dependencies of the + # directive, so automatic regeneration happens. Specifically, it + # records this file, and the file where the task is declared. + task_file = getsourcefile(task) + self.state.document.settings.record_dependencies.add(task_file) + self.state.document.settings.record_dependencies.add(__file__) + node = nodes.Element() text = StringList(lines) self.state.nested_parse(text, self.content_offset, node) return node.children def setup(app): """ Entry point for sphinx extension. """ app.add_directive('task', TaskDirective)
Add state change to sphinx plugin.
## Code Before: from docutils.parsers.rst import Directive from twisted.python.reflect import namedAny from docutils import nodes from docutils.statemachine import StringList class FakeRunner(object): def __init__(self): self.commands = [] def run(self, command): self.commands.extend(command.splitlines()) def put(self, content, path): raise NotImplementedError("put not supported.") class TaskDirective(Directive): """ Implementation of the C{frameimage} directive. """ required_arguments = 1 def run(self): task = self.arguments[0] runner = FakeRunner() try: namedAny(task)(runner) except NotImplementedError as e: raise self.error("task: %s" % (e.args[0],)) lines = ['.. code-block:: bash', ''] lines += [' %s' % (command,) for command in runner.commands] node = nodes.Element() text = StringList(lines) self.state.nested_parse(text, self.content_offset, node) return node.children def setup(app): """ Entry point for sphinx extension. """ app.add_directive('task', TaskDirective) ## Instruction: Add state change to sphinx plugin. ## Code After: from inspect import getsourcefile from docutils.parsers.rst import Directive from docutils import nodes from docutils.statemachine import StringList from twisted.python.reflect import namedAny class FakeRunner(object): def __init__(self): self.commands = [] def run(self, command): self.commands.extend(command.splitlines()) def put(self, content, path): raise NotImplementedError("put not supported.") class TaskDirective(Directive): """ Implementation of the C{frameimage} directive. """ required_arguments = 1 def run(self): task = namedAny(self.arguments[0]) runner = FakeRunner() try: task(runner) except NotImplementedError as e: raise self.error("task: %s" % (e.args[0],)) lines = ['.. code-block:: bash', ''] lines += [' %s' % (command,) for command in runner.commands] # The following three lines record (some?) of the dependencies of the # directive, so automatic regeneration happens. Specifically, it # records this file, and the file where the task is declared. task_file = getsourcefile(task) self.state.document.settings.record_dependencies.add(task_file) self.state.document.settings.record_dependencies.add(__file__) node = nodes.Element() text = StringList(lines) self.state.nested_parse(text, self.content_offset, node) return node.children def setup(app): """ Entry point for sphinx extension. """ app.add_directive('task', TaskDirective)
+ + from inspect import getsourcefile from docutils.parsers.rst import Directive - from twisted.python.reflect import namedAny from docutils import nodes from docutils.statemachine import StringList + + from twisted.python.reflect import namedAny class FakeRunner(object): def __init__(self): self.commands = [] def run(self, command): self.commands.extend(command.splitlines()) def put(self, content, path): raise NotImplementedError("put not supported.") class TaskDirective(Directive): """ Implementation of the C{frameimage} directive. """ required_arguments = 1 def run(self): - task = self.arguments[0] + task = namedAny(self.arguments[0]) ? +++++++++ + runner = FakeRunner() try: - namedAny(task)(runner) ? --------- - + task(runner) except NotImplementedError as e: raise self.error("task: %s" % (e.args[0],)) + lines = ['.. code-block:: bash', ''] lines += [' %s' % (command,) for command in runner.commands] + + # The following three lines record (some?) of the dependencies of the + # directive, so automatic regeneration happens. Specifically, it + # records this file, and the file where the task is declared. + task_file = getsourcefile(task) + self.state.document.settings.record_dependencies.add(task_file) + self.state.document.settings.record_dependencies.add(__file__) + node = nodes.Element() text = StringList(lines) self.state.nested_parse(text, self.content_offset, node) return node.children def setup(app): """ Entry point for sphinx extension. """ app.add_directive('task', TaskDirective)
7ccacd1390e3f3ee86a1d21534db2c775003e432
writeboards/models.py
writeboards/models.py
from django.contrib.auth.models import User from django.db import models from django.utils.translation import ugettext_lazy as _ from tagging.models import Tag from tagging.fields import TagField class Writeboard(models.model): writeboard_name = models.CharField(_('writeboard name'), max_length=100) slug = models.SlugField(_('slug'), unique=True) creator = models.ForeignKey(_('creator'), User, related_name=_("creator")) create_date = models.DateTimeField(_("created"), default=datetime.now) writeboard_id = models.IntegerField(_('writeboard id'),) tags = TagField() active = models.BooleanField(default=True) def __unicode__(self): return self.writeboard_name class Meta(object): verbose_name = _('writeboard') verbose_name_plural = _('writeboards') ordering=['modified'] @models.permalink def get_absolute_url(self): return ('writeboard_detail', None, {'slug': self.slug})
from django.contrib.auth.models import User from django.db import models from django.utils.translation import ugettext_lazy as _ from tagging.models import Tag from tagging.fields import TagField class Writeboard(models.model): """ Plaintext password field could simply be filled in with a reminder of. """ writeboard_name = models.CharField(_('writeboard name'), max_length=100) slug = models.SlugField(_('slug'), unique=True) creator = models.ForeignKey(_('creator'), User, related_name=_("creator")) create_date = models.DateTimeField(_("created"), default=datetime.now) writeboard_id = models.IntegerField(_('writeboard id'),) tags = TagField() public = models.BooleanField(default=True) plaintext_password = models.CharField(_('plaintext password'), max_length=100, blank =True, null =True, help_text="no encryption") active = models.BooleanField(default=True) def __unicode__(self): return self.writeboard_name class Meta(object): verbose_name = _('writeboard') verbose_name_plural = _('writeboards') ordering=['modified'] def create_a_writeboard(): return ('http://writeboard.com/') @models.permalink def get_absolute_url(self): return ('writeboard_detail', None, {'slug': self.slug})
Add writeboard specific fields to model
Add writeboard specific fields to model
Python
mit
rizumu/django-paste-organizer
from django.contrib.auth.models import User from django.db import models from django.utils.translation import ugettext_lazy as _ from tagging.models import Tag from tagging.fields import TagField class Writeboard(models.model): + """ + Plaintext password field could simply be filled in with a reminder of. + """ writeboard_name = models.CharField(_('writeboard name'), max_length=100) slug = models.SlugField(_('slug'), unique=True) creator = models.ForeignKey(_('creator'), User, related_name=_("creator")) create_date = models.DateTimeField(_("created"), default=datetime.now) writeboard_id = models.IntegerField(_('writeboard id'),) tags = TagField() + public = models.BooleanField(default=True) + plaintext_password = models.CharField(_('plaintext password'), + max_length=100, blank =True, null =True, help_text="no encryption") - active = models.BooleanField(default=True) + active = models.BooleanField(default=True) def __unicode__(self): return self.writeboard_name class Meta(object): verbose_name = _('writeboard') verbose_name_plural = _('writeboards') ordering=['modified'] + def create_a_writeboard(): + return ('http://writeboard.com/') + @models.permalink def get_absolute_url(self): return ('writeboard_detail', None, {'slug': self.slug})
Add writeboard specific fields to model
## Code Before: from django.contrib.auth.models import User from django.db import models from django.utils.translation import ugettext_lazy as _ from tagging.models import Tag from tagging.fields import TagField class Writeboard(models.model): writeboard_name = models.CharField(_('writeboard name'), max_length=100) slug = models.SlugField(_('slug'), unique=True) creator = models.ForeignKey(_('creator'), User, related_name=_("creator")) create_date = models.DateTimeField(_("created"), default=datetime.now) writeboard_id = models.IntegerField(_('writeboard id'),) tags = TagField() active = models.BooleanField(default=True) def __unicode__(self): return self.writeboard_name class Meta(object): verbose_name = _('writeboard') verbose_name_plural = _('writeboards') ordering=['modified'] @models.permalink def get_absolute_url(self): return ('writeboard_detail', None, {'slug': self.slug}) ## Instruction: Add writeboard specific fields to model ## Code After: from django.contrib.auth.models import User from django.db import models from django.utils.translation import ugettext_lazy as _ from tagging.models import Tag from tagging.fields import TagField class Writeboard(models.model): """ Plaintext password field could simply be filled in with a reminder of. """ writeboard_name = models.CharField(_('writeboard name'), max_length=100) slug = models.SlugField(_('slug'), unique=True) creator = models.ForeignKey(_('creator'), User, related_name=_("creator")) create_date = models.DateTimeField(_("created"), default=datetime.now) writeboard_id = models.IntegerField(_('writeboard id'),) tags = TagField() public = models.BooleanField(default=True) plaintext_password = models.CharField(_('plaintext password'), max_length=100, blank =True, null =True, help_text="no encryption") active = models.BooleanField(default=True) def __unicode__(self): return self.writeboard_name class Meta(object): verbose_name = _('writeboard') verbose_name_plural = _('writeboards') ordering=['modified'] def create_a_writeboard(): return ('http://writeboard.com/') @models.permalink def get_absolute_url(self): return ('writeboard_detail', None, {'slug': self.slug})
from django.contrib.auth.models import User from django.db import models from django.utils.translation import ugettext_lazy as _ from tagging.models import Tag from tagging.fields import TagField class Writeboard(models.model): + """ + Plaintext password field could simply be filled in with a reminder of. + """ writeboard_name = models.CharField(_('writeboard name'), max_length=100) slug = models.SlugField(_('slug'), unique=True) creator = models.ForeignKey(_('creator'), User, related_name=_("creator")) create_date = models.DateTimeField(_("created"), default=datetime.now) writeboard_id = models.IntegerField(_('writeboard id'),) tags = TagField() + public = models.BooleanField(default=True) + plaintext_password = models.CharField(_('plaintext password'), + max_length=100, blank =True, null =True, help_text="no encryption") - active = models.BooleanField(default=True) ? ---- + active = models.BooleanField(default=True) def __unicode__(self): return self.writeboard_name class Meta(object): verbose_name = _('writeboard') verbose_name_plural = _('writeboards') ordering=['modified'] + def create_a_writeboard(): + return ('http://writeboard.com/') + @models.permalink def get_absolute_url(self): return ('writeboard_detail', None, {'slug': self.slug})
076ef01bd3334d2a1941df369286e4972223901e
PyramidSort.py
PyramidSort.py
import sublime, sublime_plugin def pyramid_sort(txt): txt = list(filter(lambda s: s.strip(), txt)) txt.sort(key = lambda s: len(s)) return txt class PyramidSortCommand(sublime_plugin.TextCommand): def run(self, edit): regions = [s for s in self.view.sel() if not s.empty()] if regions: for r in regions: txt = self.view.substr(r) lines = txt.splitlines() lines = pyramid_sort(lines) self.view.replace(edit, r, u"\n".join(lines))
import sublime, sublime_plugin def pyramid_sort(txt): txt = list(filter(lambda s: s.strip(), txt)) txt.sort(key = lambda s: len(s)) return txt class PyramidSortCommand(sublime_plugin.TextCommand): def run(self, edit): regions = [s for s in self.view.sel() if not s.empty()] if regions: for r in regions: lr = self.view.line(r) txt = self.view.substr(lr) lines = txt.splitlines() lines = pyramid_sort(lines) self.view.replace(edit, lr, u"\n".join(lines))
Revert "removed grab line from region, gives some unexpected behaviour. Instead just replace exactly what is marked"
Revert "removed grab line from region, gives some unexpected behaviour. Instead just replace exactly what is marked" This reverts commit 9c944db3affc8181146fa27d8483a58d2731756b.
Python
apache-2.0
kenglxn/PyramidSortSublimeTextPlugin,kenglxn/PyramidSortSublimeTextPlugin
+ import sublime, sublime_plugin def pyramid_sort(txt): txt = list(filter(lambda s: s.strip(), txt)) txt.sort(key = lambda s: len(s)) return txt class PyramidSortCommand(sublime_plugin.TextCommand): def run(self, edit): regions = [s for s in self.view.sel() if not s.empty()] if regions: for r in regions: + lr = self.view.line(r) - txt = self.view.substr(r) + txt = self.view.substr(lr) lines = txt.splitlines() lines = pyramid_sort(lines) - self.view.replace(edit, r, u"\n".join(lines)) + self.view.replace(edit, lr, u"\n".join(lines))
Revert "removed grab line from region, gives some unexpected behaviour. Instead just replace exactly what is marked"
## Code Before: import sublime, sublime_plugin def pyramid_sort(txt): txt = list(filter(lambda s: s.strip(), txt)) txt.sort(key = lambda s: len(s)) return txt class PyramidSortCommand(sublime_plugin.TextCommand): def run(self, edit): regions = [s for s in self.view.sel() if not s.empty()] if regions: for r in regions: txt = self.view.substr(r) lines = txt.splitlines() lines = pyramid_sort(lines) self.view.replace(edit, r, u"\n".join(lines)) ## Instruction: Revert "removed grab line from region, gives some unexpected behaviour. Instead just replace exactly what is marked" ## Code After: import sublime, sublime_plugin def pyramid_sort(txt): txt = list(filter(lambda s: s.strip(), txt)) txt.sort(key = lambda s: len(s)) return txt class PyramidSortCommand(sublime_plugin.TextCommand): def run(self, edit): regions = [s for s in self.view.sel() if not s.empty()] if regions: for r in regions: lr = self.view.line(r) txt = self.view.substr(lr) lines = txt.splitlines() lines = pyramid_sort(lines) self.view.replace(edit, lr, u"\n".join(lines))
+ import sublime, sublime_plugin def pyramid_sort(txt): txt = list(filter(lambda s: s.strip(), txt)) txt.sort(key = lambda s: len(s)) return txt class PyramidSortCommand(sublime_plugin.TextCommand): def run(self, edit): regions = [s for s in self.view.sel() if not s.empty()] if regions: for r in regions: + lr = self.view.line(r) - txt = self.view.substr(r) + txt = self.view.substr(lr) ? + lines = txt.splitlines() lines = pyramid_sort(lines) - self.view.replace(edit, r, u"\n".join(lines)) + self.view.replace(edit, lr, u"\n".join(lines)) ? +
6524d4711e5fa03b1f11979fd3d0319cd268d116
setup.py
setup.py
from distutils.core import setup import refmanage setup(name="refmanage", version=refmanage.__version__, author="Joshua Ryan Smith", author_email="[email protected]", packages=["refmanage"], url="https://github.com/jrsmith3/refmanage", description="Manage a BibTeX database", classifiers=["Programming Language :: Python", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Development Status :: 3 - Alpha", "Intended Audience :: Science/Research", "Topic :: Text Processing", "Natural Language :: English", ], install_requires=["pybtex"], )
from distutils.core import setup import refmanage setup(name="refmanage", version=refmanage.__version__, author="Joshua Ryan Smith", author_email="[email protected]", packages=["refmanage"], url="https://github.com/jrsmith3/refmanage", description="Manage a BibTeX database", classifiers=["Programming Language :: Python", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Development Status :: 3 - Alpha", "Intended Audience :: Science/Research", "Topic :: Text Processing", "Natural Language :: English", ], install_requires=["pybtex"], entry_points={"console_scripts":"ref=refmanage.refmanage:main"},)
Add entry_point for command-line application
Add entry_point for command-line application Closes #31.
Python
mit
jrsmith3/refmanage
from distutils.core import setup import refmanage setup(name="refmanage", version=refmanage.__version__, author="Joshua Ryan Smith", author_email="[email protected]", packages=["refmanage"], url="https://github.com/jrsmith3/refmanage", description="Manage a BibTeX database", classifiers=["Programming Language :: Python", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Development Status :: 3 - Alpha", "Intended Audience :: Science/Research", "Topic :: Text Processing", "Natural Language :: English", ], - install_requires=["pybtex"], ) + install_requires=["pybtex"], + entry_points={"console_scripts":"ref=refmanage.refmanage:main"},) +
Add entry_point for command-line application
## Code Before: from distutils.core import setup import refmanage setup(name="refmanage", version=refmanage.__version__, author="Joshua Ryan Smith", author_email="[email protected]", packages=["refmanage"], url="https://github.com/jrsmith3/refmanage", description="Manage a BibTeX database", classifiers=["Programming Language :: Python", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Development Status :: 3 - Alpha", "Intended Audience :: Science/Research", "Topic :: Text Processing", "Natural Language :: English", ], install_requires=["pybtex"], ) ## Instruction: Add entry_point for command-line application ## Code After: from distutils.core import setup import refmanage setup(name="refmanage", version=refmanage.__version__, author="Joshua Ryan Smith", author_email="[email protected]", packages=["refmanage"], url="https://github.com/jrsmith3/refmanage", description="Manage a BibTeX database", classifiers=["Programming Language :: Python", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Development Status :: 3 - Alpha", "Intended Audience :: Science/Research", "Topic :: Text Processing", "Natural Language :: English", ], install_requires=["pybtex"], entry_points={"console_scripts":"ref=refmanage.refmanage:main"},)
from distutils.core import setup import refmanage setup(name="refmanage", version=refmanage.__version__, author="Joshua Ryan Smith", author_email="[email protected]", packages=["refmanage"], url="https://github.com/jrsmith3/refmanage", description="Manage a BibTeX database", classifiers=["Programming Language :: Python", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Development Status :: 3 - Alpha", "Intended Audience :: Science/Research", "Topic :: Text Processing", "Natural Language :: English", ], - install_requires=["pybtex"], ) ? -- + install_requires=["pybtex"], + entry_points={"console_scripts":"ref=refmanage.refmanage:main"},)
c28de968845f98c6590784df1fe5beff7b3d021e
workshops/templatetags/training_progress.py
workshops/templatetags/training_progress.py
from django import template from django.utils.safestring import mark_safe from workshops.models import TrainingProgress register = template.Library() @register.simple_tag def progress_label(progress): assert isinstance(progress, TrainingProgress) if progress.discarded: additional_label = 'default' else: switch = { 'n': 'warning', 'f': 'danger', 'p': 'success', } additional_label = switch[progress.state] fmt = 'label label-{}'.format(additional_label) return mark_safe(fmt) @register.simple_tag def progress_description(progress): assert isinstance(progress, TrainingProgress) text = '{discarded}{state} {type}<br />{evaluated_by}<br />on {day}.{notes}'.format( discarded='discarded ' if progress.discarded else '', state=progress.get_state_display(), type=progress.requirement, evaluated_by=('evaluated by {}'.format( progress.evaluated_by.full_name) if progress.evaluated_by is not None else 'submitted'), day=progress.created_at.strftime('%A %d %B %Y at %H:%M'), notes='<br />Notes: {}'.format(progress.notes) if progress.notes else '', ) text = text[0].upper() + text[1:] return mark_safe(text)
from django import template from django.template.defaultfilters import escape from django.utils.safestring import mark_safe from workshops.models import TrainingProgress register = template.Library() @register.simple_tag def progress_label(progress): assert isinstance(progress, TrainingProgress) if progress.discarded: additional_label = 'default' else: switch = { 'n': 'warning', 'f': 'danger', 'p': 'success', } additional_label = switch[progress.state] fmt = 'label label-{}'.format(additional_label) return mark_safe(fmt) @register.simple_tag def progress_description(progress): assert isinstance(progress, TrainingProgress) text = '{discarded}{state} {type}<br />{evaluated_by}<br />on {day}.{notes}'.format( discarded='discarded ' if progress.discarded else '', state=progress.get_state_display(), type=progress.requirement, evaluated_by=('evaluated by {}'.format( progress.evaluated_by.full_name) if progress.evaluated_by is not None else 'submitted'), day=progress.created_at.strftime('%A %d %B %Y at %H:%M'), notes='<br />Notes: {}'.format(escape(progress.notes)) if progress.notes else '', ) text = text[0].upper() + text[1:] return mark_safe(text)
Fix unescaped content in training progress description templatetag
Fix unescaped content in training progress description templatetag This template tag was using content from entry notes directly. In cases of some users this messed up the display of label in the templates.
Python
mit
pbanaszkiewicz/amy,pbanaszkiewicz/amy,swcarpentry/amy,swcarpentry/amy,pbanaszkiewicz/amy,swcarpentry/amy
from django import template + from django.template.defaultfilters import escape from django.utils.safestring import mark_safe from workshops.models import TrainingProgress register = template.Library() @register.simple_tag def progress_label(progress): assert isinstance(progress, TrainingProgress) if progress.discarded: additional_label = 'default' else: switch = { 'n': 'warning', 'f': 'danger', 'p': 'success', } additional_label = switch[progress.state] fmt = 'label label-{}'.format(additional_label) return mark_safe(fmt) @register.simple_tag def progress_description(progress): assert isinstance(progress, TrainingProgress) text = '{discarded}{state} {type}<br />{evaluated_by}<br />on {day}.{notes}'.format( discarded='discarded ' if progress.discarded else '', state=progress.get_state_display(), type=progress.requirement, evaluated_by=('evaluated by {}'.format( progress.evaluated_by.full_name) if progress.evaluated_by is not None else 'submitted'), day=progress.created_at.strftime('%A %d %B %Y at %H:%M'), - notes='<br />Notes: {}'.format(progress.notes) if progress.notes else '', + notes='<br />Notes: {}'.format(escape(progress.notes)) if progress.notes else '', ) text = text[0].upper() + text[1:] return mark_safe(text)
Fix unescaped content in training progress description templatetag
## Code Before: from django import template from django.utils.safestring import mark_safe from workshops.models import TrainingProgress register = template.Library() @register.simple_tag def progress_label(progress): assert isinstance(progress, TrainingProgress) if progress.discarded: additional_label = 'default' else: switch = { 'n': 'warning', 'f': 'danger', 'p': 'success', } additional_label = switch[progress.state] fmt = 'label label-{}'.format(additional_label) return mark_safe(fmt) @register.simple_tag def progress_description(progress): assert isinstance(progress, TrainingProgress) text = '{discarded}{state} {type}<br />{evaluated_by}<br />on {day}.{notes}'.format( discarded='discarded ' if progress.discarded else '', state=progress.get_state_display(), type=progress.requirement, evaluated_by=('evaluated by {}'.format( progress.evaluated_by.full_name) if progress.evaluated_by is not None else 'submitted'), day=progress.created_at.strftime('%A %d %B %Y at %H:%M'), notes='<br />Notes: {}'.format(progress.notes) if progress.notes else '', ) text = text[0].upper() + text[1:] return mark_safe(text) ## Instruction: Fix unescaped content in training progress description templatetag ## Code After: from django import template from django.template.defaultfilters import escape from django.utils.safestring import mark_safe from workshops.models import TrainingProgress register = template.Library() @register.simple_tag def progress_label(progress): assert isinstance(progress, TrainingProgress) if progress.discarded: additional_label = 'default' else: switch = { 'n': 'warning', 'f': 'danger', 'p': 'success', } additional_label = switch[progress.state] fmt = 'label label-{}'.format(additional_label) return mark_safe(fmt) @register.simple_tag def progress_description(progress): assert isinstance(progress, TrainingProgress) text = '{discarded}{state} {type}<br />{evaluated_by}<br />on {day}.{notes}'.format( discarded='discarded ' if progress.discarded else '', state=progress.get_state_display(), type=progress.requirement, evaluated_by=('evaluated by {}'.format( progress.evaluated_by.full_name) if progress.evaluated_by is not None else 'submitted'), day=progress.created_at.strftime('%A %d %B %Y at %H:%M'), notes='<br />Notes: {}'.format(escape(progress.notes)) if progress.notes else '', ) text = text[0].upper() + text[1:] return mark_safe(text)
from django import template + from django.template.defaultfilters import escape from django.utils.safestring import mark_safe from workshops.models import TrainingProgress register = template.Library() @register.simple_tag def progress_label(progress): assert isinstance(progress, TrainingProgress) if progress.discarded: additional_label = 'default' else: switch = { 'n': 'warning', 'f': 'danger', 'p': 'success', } additional_label = switch[progress.state] fmt = 'label label-{}'.format(additional_label) return mark_safe(fmt) @register.simple_tag def progress_description(progress): assert isinstance(progress, TrainingProgress) text = '{discarded}{state} {type}<br />{evaluated_by}<br />on {day}.{notes}'.format( discarded='discarded ' if progress.discarded else '', state=progress.get_state_display(), type=progress.requirement, evaluated_by=('evaluated by {}'.format( progress.evaluated_by.full_name) if progress.evaluated_by is not None else 'submitted'), day=progress.created_at.strftime('%A %d %B %Y at %H:%M'), - notes='<br />Notes: {}'.format(progress.notes) if progress.notes else '', + notes='<br />Notes: {}'.format(escape(progress.notes)) if progress.notes else '', ? +++++++ + ) text = text[0].upper() + text[1:] return mark_safe(text)
7cc8699f7100cfc969b1b76efbcc47e1fafb2363
paiji2_shoutbox/models.py
paiji2_shoutbox/models.py
from django.db import models from django.utils.translation import ugettext as _ from django.utils.timezone import now try: from django.contrib.auth import get_user_model User = get_user_model() except: from django.contrib.auth.models import User class Note(models.Model): author = models.ForeignKey( User, verbose_name=_('author'), related_name='notes', ) message = models.CharField( _('message'), max_length=200, ) posted_at = models.DateTimeField( _('publication date'), ) def save(self, *args, **kwargs): if self.pk is None: self.posted_at = now() super(Note, self).save(*args, **kwargs) class Meta: verbose_name = _('note') verbose_name_plural = _('notes') ordering = ('-posted_at', )
from django.db import models from django.utils.translation import ugettext as _ from django.utils.timezone import now try: from django.contrib.auth import get_user_model User = get_user_model() except: from django.contrib.auth.models import User class Note(models.Model): author = models.ForeignKey( User, verbose_name=_('author'), related_name='notes', ) message = models.CharField( _('message'), max_length=200, ) posted_at = models.DateTimeField( _('publication date'), auto_now_add=True, ) class Meta: verbose_name = _('note') verbose_name_plural = _('notes') ordering = ('-posted_at', )
Remove save method for auto_now_add=True
Remove save method for auto_now_add=True
Python
agpl-3.0
rezometz/django-paiji2-shoutbox,rezometz/django-paiji2-shoutbox
from django.db import models from django.utils.translation import ugettext as _ from django.utils.timezone import now try: from django.contrib.auth import get_user_model User = get_user_model() except: from django.contrib.auth.models import User class Note(models.Model): author = models.ForeignKey( User, verbose_name=_('author'), related_name='notes', ) message = models.CharField( _('message'), max_length=200, ) posted_at = models.DateTimeField( _('publication date'), + auto_now_add=True, ) - - def save(self, *args, **kwargs): - if self.pk is None: - self.posted_at = now() - super(Note, self).save(*args, **kwargs) class Meta: verbose_name = _('note') verbose_name_plural = _('notes') ordering = ('-posted_at', )
Remove save method for auto_now_add=True
## Code Before: from django.db import models from django.utils.translation import ugettext as _ from django.utils.timezone import now try: from django.contrib.auth import get_user_model User = get_user_model() except: from django.contrib.auth.models import User class Note(models.Model): author = models.ForeignKey( User, verbose_name=_('author'), related_name='notes', ) message = models.CharField( _('message'), max_length=200, ) posted_at = models.DateTimeField( _('publication date'), ) def save(self, *args, **kwargs): if self.pk is None: self.posted_at = now() super(Note, self).save(*args, **kwargs) class Meta: verbose_name = _('note') verbose_name_plural = _('notes') ordering = ('-posted_at', ) ## Instruction: Remove save method for auto_now_add=True ## Code After: from django.db import models from django.utils.translation import ugettext as _ from django.utils.timezone import now try: from django.contrib.auth import get_user_model User = get_user_model() except: from django.contrib.auth.models import User class Note(models.Model): author = models.ForeignKey( User, verbose_name=_('author'), related_name='notes', ) message = models.CharField( _('message'), max_length=200, ) posted_at = models.DateTimeField( _('publication date'), auto_now_add=True, ) class Meta: verbose_name = _('note') verbose_name_plural = _('notes') ordering = ('-posted_at', )
from django.db import models from django.utils.translation import ugettext as _ from django.utils.timezone import now try: from django.contrib.auth import get_user_model User = get_user_model() except: from django.contrib.auth.models import User class Note(models.Model): author = models.ForeignKey( User, verbose_name=_('author'), related_name='notes', ) message = models.CharField( _('message'), max_length=200, ) posted_at = models.DateTimeField( _('publication date'), + auto_now_add=True, ) - - def save(self, *args, **kwargs): - if self.pk is None: - self.posted_at = now() - super(Note, self).save(*args, **kwargs) class Meta: verbose_name = _('note') verbose_name_plural = _('notes') ordering = ('-posted_at', )
913ae38e48591000195166a93e18e96a82d1d222
lily/messaging/email/migrations/0013_fix_multple_default_templates.py
lily/messaging/email/migrations/0013_fix_multple_default_templates.py
from __future__ import unicode_literals from django.db import models, migrations def fix_multiple_default_templates(apps, schema_editor): # Some users have more than 1 default template. # This shouldn't be possible, make sure is will be just 1. User = apps.get_model('users', 'LilyUser') DefaultEmailTemplate = apps.get_model('email', 'DefaultEmailTemplate') print('\nFixing default template for the following users:') for user in User.objects.all(): templates = DefaultEmailTemplate.objects.filter(user=user.pk).order_by('id') if templates.count() > 1: # User has more than one default template. # Best guess would be that the user prefers the last set template to be the default. # So remove all except the last one. template_to_keep = templates.last() templates.exclude(id=template_to_keep.id).delete() print('%d:\t%s' % (user.pk, user.email)) class Migration(migrations.Migration): dependencies = [ ('email', '0012_auto_20160715_1423'), ] operations = [ migrations.RunPython(fix_multiple_default_templates), ]
from __future__ import unicode_literals from django.db import models, migrations def fix_multiple_default_templates(apps, schema_editor): # Some users have more than 1 default template. # This shouldn't be possible, make sure is will be just 1. User = apps.get_model('users', 'LilyUser') DefaultEmailTemplate = apps.get_model('email', 'DefaultEmailTemplate') for user in User.objects.all(): templates = DefaultEmailTemplate.objects.filter(user=user.pk).order_by('id') if templates.count() > 1: # User has more than one default template. # Best guess would be that the user prefers the last set template to be the default. # So remove all except the last one. template_to_keep = templates.last() templates.exclude(id=template_to_keep.id).delete() class Migration(migrations.Migration): dependencies = [ ('email', '0012_auto_20160715_1423'), ] operations = [ migrations.RunPython(fix_multiple_default_templates), ]
Remove print statements, not usefull anymore.
Remove print statements, not usefull anymore.
Python
agpl-3.0
HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily
from __future__ import unicode_literals from django.db import models, migrations def fix_multiple_default_templates(apps, schema_editor): # Some users have more than 1 default template. # This shouldn't be possible, make sure is will be just 1. User = apps.get_model('users', 'LilyUser') DefaultEmailTemplate = apps.get_model('email', 'DefaultEmailTemplate') - print('\nFixing default template for the following users:') for user in User.objects.all(): templates = DefaultEmailTemplate.objects.filter(user=user.pk).order_by('id') if templates.count() > 1: # User has more than one default template. # Best guess would be that the user prefers the last set template to be the default. # So remove all except the last one. template_to_keep = templates.last() templates.exclude(id=template_to_keep.id).delete() - - print('%d:\t%s' % (user.pk, user.email)) class Migration(migrations.Migration): dependencies = [ ('email', '0012_auto_20160715_1423'), ] operations = [ migrations.RunPython(fix_multiple_default_templates), ]
Remove print statements, not usefull anymore.
## Code Before: from __future__ import unicode_literals from django.db import models, migrations def fix_multiple_default_templates(apps, schema_editor): # Some users have more than 1 default template. # This shouldn't be possible, make sure is will be just 1. User = apps.get_model('users', 'LilyUser') DefaultEmailTemplate = apps.get_model('email', 'DefaultEmailTemplate') print('\nFixing default template for the following users:') for user in User.objects.all(): templates = DefaultEmailTemplate.objects.filter(user=user.pk).order_by('id') if templates.count() > 1: # User has more than one default template. # Best guess would be that the user prefers the last set template to be the default. # So remove all except the last one. template_to_keep = templates.last() templates.exclude(id=template_to_keep.id).delete() print('%d:\t%s' % (user.pk, user.email)) class Migration(migrations.Migration): dependencies = [ ('email', '0012_auto_20160715_1423'), ] operations = [ migrations.RunPython(fix_multiple_default_templates), ] ## Instruction: Remove print statements, not usefull anymore. ## Code After: from __future__ import unicode_literals from django.db import models, migrations def fix_multiple_default_templates(apps, schema_editor): # Some users have more than 1 default template. # This shouldn't be possible, make sure is will be just 1. User = apps.get_model('users', 'LilyUser') DefaultEmailTemplate = apps.get_model('email', 'DefaultEmailTemplate') for user in User.objects.all(): templates = DefaultEmailTemplate.objects.filter(user=user.pk).order_by('id') if templates.count() > 1: # User has more than one default template. # Best guess would be that the user prefers the last set template to be the default. # So remove all except the last one. template_to_keep = templates.last() templates.exclude(id=template_to_keep.id).delete() class Migration(migrations.Migration): dependencies = [ ('email', '0012_auto_20160715_1423'), ] operations = [ migrations.RunPython(fix_multiple_default_templates), ]
from __future__ import unicode_literals from django.db import models, migrations def fix_multiple_default_templates(apps, schema_editor): # Some users have more than 1 default template. # This shouldn't be possible, make sure is will be just 1. User = apps.get_model('users', 'LilyUser') DefaultEmailTemplate = apps.get_model('email', 'DefaultEmailTemplate') - print('\nFixing default template for the following users:') for user in User.objects.all(): templates = DefaultEmailTemplate.objects.filter(user=user.pk).order_by('id') if templates.count() > 1: # User has more than one default template. # Best guess would be that the user prefers the last set template to be the default. # So remove all except the last one. template_to_keep = templates.last() templates.exclude(id=template_to_keep.id).delete() - - print('%d:\t%s' % (user.pk, user.email)) class Migration(migrations.Migration): dependencies = [ ('email', '0012_auto_20160715_1423'), ] operations = [ migrations.RunPython(fix_multiple_default_templates), ]
59b920d3c5d699c180be4dafec86f50a0c636028
work/print-traceback.py
work/print-traceback.py
from pprint import pprint import json import sys if __name__ == '__main__': if len(sys.argv) >= 2: path = sys.argv[1].split('.') else: path = ['error', 'stack'] obj = json.load(sys.stdin) try: for part in path: obj = obj[part] except KeyError: pass if isinstance(obj, str): print(obj) else: pprint(obj)
from pprint import pprint import json import sys def get(obj, path): try: for part in path: obj = obj[part] return obj except KeyError: return None if __name__ == '__main__': if len(sys.argv) >= 2: paths = [sys.argv[1].split('.')] else: paths = [ ['meta', 'error', 'stack'], ['error', 'stack'], ['traceback'], ] obj = json.load(sys.stdin) for path in paths: subobj = get(obj, path) if subobj is not None: obj = subobj break if isinstance(obj, str): print(obj) else: pprint(obj)
Improve stacktrace print for traceback.
Improve stacktrace print for traceback.
Python
mit
ammongit/scripts,ammongit/scripts,ammongit/scripts,ammongit/scripts
from pprint import pprint import json import sys + def get(obj, path): + try: + for part in path: + obj = obj[part] + return obj + except KeyError: + return None + if __name__ == '__main__': if len(sys.argv) >= 2: - path = sys.argv[1].split('.') + paths = [sys.argv[1].split('.')] else: + paths = [ + ['meta', 'error', 'stack'], - path = ['error', 'stack'] + ['error', 'stack'], + ['traceback'], + ] obj = json.load(sys.stdin) - try: - for part in path: + for path in paths: + subobj = get(obj, path) + if subobj is not None: - obj = obj[part] + obj = subobj + break - except KeyError: - pass if isinstance(obj, str): print(obj) else: pprint(obj)
Improve stacktrace print for traceback.
## Code Before: from pprint import pprint import json import sys if __name__ == '__main__': if len(sys.argv) >= 2: path = sys.argv[1].split('.') else: path = ['error', 'stack'] obj = json.load(sys.stdin) try: for part in path: obj = obj[part] except KeyError: pass if isinstance(obj, str): print(obj) else: pprint(obj) ## Instruction: Improve stacktrace print for traceback. ## Code After: from pprint import pprint import json import sys def get(obj, path): try: for part in path: obj = obj[part] return obj except KeyError: return None if __name__ == '__main__': if len(sys.argv) >= 2: paths = [sys.argv[1].split('.')] else: paths = [ ['meta', 'error', 'stack'], ['error', 'stack'], ['traceback'], ] obj = json.load(sys.stdin) for path in paths: subobj = get(obj, path) if subobj is not None: obj = subobj break if isinstance(obj, str): print(obj) else: pprint(obj)
from pprint import pprint import json import sys + def get(obj, path): + try: + for part in path: + obj = obj[part] + return obj + except KeyError: + return None + if __name__ == '__main__': if len(sys.argv) >= 2: - path = sys.argv[1].split('.') + paths = [sys.argv[1].split('.')] ? + + + else: + paths = [ + ['meta', 'error', 'stack'], - path = ['error', 'stack'] ? ---- ^ + ['error', 'stack'], ? ^^ + + ['traceback'], + ] obj = json.load(sys.stdin) - try: - for part in path: ? ---- - + for path in paths: ? + + + subobj = get(obj, path) + if subobj is not None: - obj = obj[part] ? ------ + obj = subobj ? +++ + break - except KeyError: - pass if isinstance(obj, str): print(obj) else: pprint(obj)
0f446d166818ec6b218b59751a1dce80842ce677
app/auth/views.py
app/auth/views.py
__author__ = "Filippo Panessa <[email protected]>" __copyright__ = ("Copyright (c) 2016 S3IT, Zentrale Informatik," " University of Zurich") from flask import jsonify from . import auth from app.auth.decorators import requires_auth @auth.route('/test') @requires_auth def authTest(): return jsonify({'status': 200, 'code': 'authorization_success', 'description': "All good. You only get this message if you're authenticated." })
__author__ = "Filippo Panessa <[email protected]>" __copyright__ = ("Copyright (c) 2016 S3IT, Zentrale Informatik," " University of Zurich") from flask import jsonify from . import auth from app.auth.decorators import requires_auth @auth.route('/test') @requires_auth def authTest(): return jsonify({'code': 'authorization_success', 'description': "All good. You only get this message if you're authenticated." })
Remove code field from API /auth/test response
Remove code field from API /auth/test response
Python
agpl-3.0
uzh/msregistry
__author__ = "Filippo Panessa <[email protected]>" __copyright__ = ("Copyright (c) 2016 S3IT, Zentrale Informatik," " University of Zurich") from flask import jsonify from . import auth from app.auth.decorators import requires_auth @auth.route('/test') @requires_auth def authTest(): + return jsonify({'code': 'authorization_success', - return jsonify({'status': 200, - 'code': 'authorization_success', 'description': "All good. You only get this message if you're authenticated." })
Remove code field from API /auth/test response
## Code Before: __author__ = "Filippo Panessa <[email protected]>" __copyright__ = ("Copyright (c) 2016 S3IT, Zentrale Informatik," " University of Zurich") from flask import jsonify from . import auth from app.auth.decorators import requires_auth @auth.route('/test') @requires_auth def authTest(): return jsonify({'status': 200, 'code': 'authorization_success', 'description': "All good. You only get this message if you're authenticated." }) ## Instruction: Remove code field from API /auth/test response ## Code After: __author__ = "Filippo Panessa <[email protected]>" __copyright__ = ("Copyright (c) 2016 S3IT, Zentrale Informatik," " University of Zurich") from flask import jsonify from . import auth from app.auth.decorators import requires_auth @auth.route('/test') @requires_auth def authTest(): return jsonify({'code': 'authorization_success', 'description': "All good. You only get this message if you're authenticated." })
__author__ = "Filippo Panessa <[email protected]>" __copyright__ = ("Copyright (c) 2016 S3IT, Zentrale Informatik," " University of Zurich") from flask import jsonify from . import auth from app.auth.decorators import requires_auth @auth.route('/test') @requires_auth def authTest(): + return jsonify({'code': 'authorization_success', - return jsonify({'status': 200, - 'code': 'authorization_success', 'description': "All good. You only get this message if you're authenticated." })
9fbef73081b0cb608e32c91a57502aaefa0599cc
tests/test_basic.py
tests/test_basic.py
import unittest import os, sys PROJECT_ROOT = os.path.dirname(__file__) sys.path.append(os.path.join(PROJECT_ROOT, "..")) from CodeConverter import CodeConverter class TestBasic(unittest.TestCase): def setUp(self): pass def test_initialize(self): self.assertEqual(CodeConverter('foo').s, 'foo') if __name__ == '__main__': unittest.main()
import unittest import os, sys PROJECT_ROOT = os.path.dirname(__file__) sys.path.append(os.path.join(PROJECT_ROOT, "..")) from CodeConverter import CodeConverter class TestBasic(unittest.TestCase): def setUp(self): pass def test_initialize(self): self.assertEqual(CodeConverter('foo').s, 'foo') # def test_python_version(self): # # Python for Sublime Text 2 is 2.6.7 (r267:88850, Oct 11 2012, 20:15:00) # if sys.version_info[:3] != (2, 6, 7): # print 'Sublime Text 2 uses python 2.6.7' # print 'Your version is ' + '.'.join(str(x) for x in sys.version_info[:3]) # self.assertTrue(True) if __name__ == '__main__': unittest.main()
Add test to check python version
Add test to check python version
Python
mit
kyamaguchi/SublimeObjC2RubyMotion,kyamaguchi/SublimeObjC2RubyMotion
import unittest import os, sys PROJECT_ROOT = os.path.dirname(__file__) sys.path.append(os.path.join(PROJECT_ROOT, "..")) from CodeConverter import CodeConverter class TestBasic(unittest.TestCase): def setUp(self): pass def test_initialize(self): self.assertEqual(CodeConverter('foo').s, 'foo') + # def test_python_version(self): + # # Python for Sublime Text 2 is 2.6.7 (r267:88850, Oct 11 2012, 20:15:00) + # if sys.version_info[:3] != (2, 6, 7): + # print 'Sublime Text 2 uses python 2.6.7' + # print 'Your version is ' + '.'.join(str(x) for x in sys.version_info[:3]) + # self.assertTrue(True) + if __name__ == '__main__': unittest.main()
Add test to check python version
## Code Before: import unittest import os, sys PROJECT_ROOT = os.path.dirname(__file__) sys.path.append(os.path.join(PROJECT_ROOT, "..")) from CodeConverter import CodeConverter class TestBasic(unittest.TestCase): def setUp(self): pass def test_initialize(self): self.assertEqual(CodeConverter('foo').s, 'foo') if __name__ == '__main__': unittest.main() ## Instruction: Add test to check python version ## Code After: import unittest import os, sys PROJECT_ROOT = os.path.dirname(__file__) sys.path.append(os.path.join(PROJECT_ROOT, "..")) from CodeConverter import CodeConverter class TestBasic(unittest.TestCase): def setUp(self): pass def test_initialize(self): self.assertEqual(CodeConverter('foo').s, 'foo') # def test_python_version(self): # # Python for Sublime Text 2 is 2.6.7 (r267:88850, Oct 11 2012, 20:15:00) # if sys.version_info[:3] != (2, 6, 7): # print 'Sublime Text 2 uses python 2.6.7' # print 'Your version is ' + '.'.join(str(x) for x in sys.version_info[:3]) # self.assertTrue(True) if __name__ == '__main__': unittest.main()
import unittest import os, sys PROJECT_ROOT = os.path.dirname(__file__) sys.path.append(os.path.join(PROJECT_ROOT, "..")) from CodeConverter import CodeConverter class TestBasic(unittest.TestCase): def setUp(self): pass def test_initialize(self): self.assertEqual(CodeConverter('foo').s, 'foo') + # def test_python_version(self): + # # Python for Sublime Text 2 is 2.6.7 (r267:88850, Oct 11 2012, 20:15:00) + # if sys.version_info[:3] != (2, 6, 7): + # print 'Sublime Text 2 uses python 2.6.7' + # print 'Your version is ' + '.'.join(str(x) for x in sys.version_info[:3]) + # self.assertTrue(True) + if __name__ == '__main__': unittest.main()
7cf867e9ee7a3764b3168cd9671f6de0d0b1b090
numpy/distutils/command/install_clib.py
numpy/distutils/command/install_clib.py
import os from distutils.core import Command from numpy.distutils.misc_util import get_cmd class install_clib(Command): description = "Command to install installable C libraries" user_options = [] def initialize_options(self): self.install_dir = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) def run (self): # We need the compiler to get the library name -> filename association from distutils.ccompiler import new_compiler compiler = new_compiler(compiler=None) compiler.customize(self.distribution) build_dir = get_cmd("build_clib").build_clib for l in self.distribution.installed_libraries: target_dir = os.path.join(self.install_dir, l.target_dir) name = compiler.library_filename(l.name) source = os.path.join(build_dir, name) self.mkpath(target_dir) self.outfiles.append(self.copy_file(source, target_dir)[0]) def get_outputs(self): return self.outfiles
import os from distutils.core import Command from distutils.ccompiler import new_compiler from numpy.distutils.misc_util import get_cmd class install_clib(Command): description = "Command to install installable C libraries" user_options = [] def initialize_options(self): self.install_dir = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) def run (self): # We need the compiler to get the library name -> filename association compiler = new_compiler(compiler=None) compiler.customize(self.distribution) build_dir = get_cmd("build_clib").build_clib for l in self.distribution.installed_libraries: target_dir = os.path.join(self.install_dir, l.target_dir) name = compiler.library_filename(l.name) source = os.path.join(build_dir, name) self.mkpath(target_dir) self.outfiles.append(self.copy_file(source, target_dir)[0]) def get_outputs(self): return self.outfiles
Move import at the top of module.
Move import at the top of module. git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@7278 94b884b6-d6fd-0310-90d3-974f1d3f35e1
Python
bsd-3-clause
teoliphant/numpy-refactor,illume/numpy3k,Ademan/NumPy-GSoC,Ademan/NumPy-GSoC,teoliphant/numpy-refactor,chadnetzer/numpy-gaurdro,Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,illume/numpy3k,teoliphant/numpy-refactor,chadnetzer/numpy-gaurdro,illume/numpy3k,chadnetzer/numpy-gaurdro,jasonmccampbell/numpy-refactor-sprint,illume/numpy3k,teoliphant/numpy-refactor,Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint,chadnetzer/numpy-gaurdro
import os from distutils.core import Command + from distutils.ccompiler import new_compiler from numpy.distutils.misc_util import get_cmd class install_clib(Command): description = "Command to install installable C libraries" user_options = [] def initialize_options(self): self.install_dir = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) def run (self): # We need the compiler to get the library name -> filename association - from distutils.ccompiler import new_compiler compiler = new_compiler(compiler=None) compiler.customize(self.distribution) build_dir = get_cmd("build_clib").build_clib for l in self.distribution.installed_libraries: target_dir = os.path.join(self.install_dir, l.target_dir) name = compiler.library_filename(l.name) source = os.path.join(build_dir, name) self.mkpath(target_dir) self.outfiles.append(self.copy_file(source, target_dir)[0]) def get_outputs(self): return self.outfiles
Move import at the top of module.
## Code Before: import os from distutils.core import Command from numpy.distutils.misc_util import get_cmd class install_clib(Command): description = "Command to install installable C libraries" user_options = [] def initialize_options(self): self.install_dir = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) def run (self): # We need the compiler to get the library name -> filename association from distutils.ccompiler import new_compiler compiler = new_compiler(compiler=None) compiler.customize(self.distribution) build_dir = get_cmd("build_clib").build_clib for l in self.distribution.installed_libraries: target_dir = os.path.join(self.install_dir, l.target_dir) name = compiler.library_filename(l.name) source = os.path.join(build_dir, name) self.mkpath(target_dir) self.outfiles.append(self.copy_file(source, target_dir)[0]) def get_outputs(self): return self.outfiles ## Instruction: Move import at the top of module. ## Code After: import os from distutils.core import Command from distutils.ccompiler import new_compiler from numpy.distutils.misc_util import get_cmd class install_clib(Command): description = "Command to install installable C libraries" user_options = [] def initialize_options(self): self.install_dir = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) def run (self): # We need the compiler to get the library name -> filename association compiler = new_compiler(compiler=None) compiler.customize(self.distribution) build_dir = get_cmd("build_clib").build_clib for l in self.distribution.installed_libraries: target_dir = os.path.join(self.install_dir, l.target_dir) name = compiler.library_filename(l.name) source = os.path.join(build_dir, name) self.mkpath(target_dir) self.outfiles.append(self.copy_file(source, target_dir)[0]) def get_outputs(self): return self.outfiles
import os from distutils.core import Command + from distutils.ccompiler import new_compiler from numpy.distutils.misc_util import get_cmd class install_clib(Command): description = "Command to install installable C libraries" user_options = [] def initialize_options(self): self.install_dir = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) def run (self): # We need the compiler to get the library name -> filename association - from distutils.ccompiler import new_compiler compiler = new_compiler(compiler=None) compiler.customize(self.distribution) build_dir = get_cmd("build_clib").build_clib for l in self.distribution.installed_libraries: target_dir = os.path.join(self.install_dir, l.target_dir) name = compiler.library_filename(l.name) source = os.path.join(build_dir, name) self.mkpath(target_dir) self.outfiles.append(self.copy_file(source, target_dir)[0]) def get_outputs(self): return self.outfiles
122ba850fb9d7c9ca51d66714dd38cb2187134f3
Lib/setup.py
Lib/setup.py
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) #config.add_subpackage('cluster') #config.add_subpackage('fftpack') #config.add_subpackage('integrate') #config.add_subpackage('interpolate') #config.add_subpackage('io') config.add_subpackage('lib') config.add_subpackage('linalg') #config.add_subpackage('linsolve') #config.add_subpackage('maxentropy') config.add_subpackage('misc') #config.add_subpackage('montecarlo') config.add_subpackage('optimize') #config.add_subpackage('sandbox') #config.add_subpackage('signal') #config.add_subpackage('sparse') config.add_subpackage('special') config.add_subpackage('stats') #config.add_subpackage('ndimage') #config.add_subpackage('weave') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) config.add_subpackage('cluster') config.add_subpackage('fftpack') config.add_subpackage('integrate') config.add_subpackage('interpolate') config.add_subpackage('io') config.add_subpackage('lib') config.add_subpackage('linalg') config.add_subpackage('linsolve') config.add_subpackage('maxentropy') config.add_subpackage('misc') #config.add_subpackage('montecarlo') config.add_subpackage('optimize') config.add_subpackage('sandbox') config.add_subpackage('signal') config.add_subpackage('sparse') config.add_subpackage('special') config.add_subpackage('stats') config.add_subpackage('ndimage') config.add_subpackage('weave') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
Fix problem with __all__ variable and update weave docs a bit. Update compiler_cxx too.
Fix problem with __all__ variable and update weave docs a bit. Update compiler_cxx too.
Python
bsd-3-clause
josephcslater/scipy,rmcgibbo/scipy,ndchorley/scipy,lukauskas/scipy,vberaudi/scipy,dch312/scipy,gfyoung/scipy,andyfaff/scipy,chatcannon/scipy,WarrenWeckesser/scipy,mtrbean/scipy,argriffing/scipy,nvoron23/scipy,WillieMaddox/scipy,aarchiba/scipy,anntzer/scipy,lhilt/scipy,nonhermitian/scipy,teoliphant/scipy,minhlongdo/scipy,WarrenWeckesser/scipy,piyush0609/scipy,dominicelse/scipy,mingwpy/scipy,ales-erjavec/scipy,gef756/scipy,mtrbean/scipy,pnedunuri/scipy,zerothi/scipy,andim/scipy,nvoron23/scipy,jseabold/scipy,lukauskas/scipy,lhilt/scipy,minhlongdo/scipy,Stefan-Endres/scipy,chatcannon/scipy,gef756/scipy,niknow/scipy,rgommers/scipy,scipy/scipy,mortada/scipy,andyfaff/scipy,giorgiop/scipy,sauliusl/scipy,mortonjt/scipy,arokem/scipy,raoulbq/scipy,ChanderG/scipy,Shaswat27/scipy,argriffing/scipy,felipebetancur/scipy,gef756/scipy,sonnyhu/scipy,endolith/scipy,grlee77/scipy,niknow/scipy,kleskjr/scipy,Shaswat27/scipy,mgaitan/scipy,niknow/scipy,surhudm/scipy,pizzathief/scipy,josephcslater/scipy,mhogg/scipy,pyramania/scipy,Stefan-Endres/scipy,efiring/scipy,nonhermitian/scipy,WillieMaddox/scipy,ales-erjavec/scipy,cpaulik/scipy,gfyoung/scipy,kalvdans/scipy,jjhelmus/scipy,hainm/scipy,maniteja123/scipy,witcxc/scipy,ortylp/scipy,gef756/scipy,fernand/scipy,Srisai85/scipy,njwilson23/scipy,pyramania/scipy,pschella/scipy,jjhelmus/scipy,behzadnouri/scipy,mhogg/scipy,rmcgibbo/scipy,ndchorley/scipy,trankmichael/scipy,pizzathief/scipy,jjhelmus/scipy,woodscn/scipy,anntzer/scipy,anielsen001/scipy,chatcannon/scipy,ChanderG/scipy,gfyoung/scipy,Gillu13/scipy,sargas/scipy,futurulus/scipy,vberaudi/scipy,tylerjereddy/scipy,jsilter/scipy,woodscn/scipy,tylerjereddy/scipy,perimosocordiae/scipy,matthewalbani/scipy,ales-erjavec/scipy,woodscn/scipy,Newman101/scipy,andim/scipy,jonycgn/scipy,njwilson23/scipy,hainm/scipy,vhaasteren/scipy,pbrod/scipy,newemailjdm/scipy,behzadnouri/scipy,aman-iitj/scipy,scipy/scipy,juliantaylor/scipy,ChanderG/scipy,mortonjt/scipy,Eric89GXL/scipy,jor-/scipy,aeklant/scipy,aman-iitj/scipy,mikebenfield/scipy,sonnyhu/scipy,pschella/scipy,matthewalbani/scipy,petebachant/scipy,zaxliu/scipy,jonycgn/scipy,mgaitan/scipy,aarchiba/scipy,hainm/scipy,kalvdans/scipy,minhlongdo/scipy,Stefan-Endres/scipy,jjhelmus/scipy,kleskjr/scipy,behzadnouri/scipy,e-q/scipy,newemailjdm/scipy,witcxc/scipy,Kamp9/scipy,endolith/scipy,aarchiba/scipy,rmcgibbo/scipy,piyush0609/scipy,rgommers/scipy,rgommers/scipy,jsilter/scipy,pizzathief/scipy,argriffing/scipy,futurulus/scipy,sonnyhu/scipy,piyush0609/scipy,ilayn/scipy,pnedunuri/scipy,vhaasteren/scipy,ndchorley/scipy,e-q/scipy,fredrikw/scipy,vanpact/scipy,newemailjdm/scipy,nvoron23/scipy,mortada/scipy,ogrisel/scipy,pbrod/scipy,matthew-brett/scipy,tylerjereddy/scipy,scipy/scipy,Srisai85/scipy,FRidh/scipy,pschella/scipy,maciejkula/scipy,jor-/scipy,trankmichael/scipy,Eric89GXL/scipy,mtrbean/scipy,jsilter/scipy,grlee77/scipy,ogrisel/scipy,anielsen001/scipy,jakevdp/scipy,Stefan-Endres/scipy,juliantaylor/scipy,nmayorov/scipy,befelix/scipy,jakevdp/scipy,raoulbq/scipy,rmcgibbo/scipy,ndchorley/scipy,futurulus/scipy,zxsted/scipy,befelix/scipy,sonnyhu/scipy,petebachant/scipy,haudren/scipy,Gillu13/scipy,trankmichael/scipy,endolith/scipy,gertingold/scipy,mtrbean/scipy,raoulbq/scipy,efiring/scipy,ortylp/scipy,gertingold/scipy,mingwpy/scipy,befelix/scipy,zaxliu/scipy,njwilson23/scipy,maciejkula/scipy,mdhaber/scipy,raoulbq/scipy,dominicelse/scipy,bkendzior/scipy,Kamp9/scipy,Newman101/scipy,argriffing/scipy,sriki18/scipy,maniteja123/scipy,pbrod/scipy,zxsted/scipy,haudren/scipy,FRidh/scipy,kleskjr/scipy,larsmans/scipy,grlee77/scipy,richardotis/scipy,jonycgn/scipy,dch312/scipy,futurulus/scipy,futurulus/scipy,sauliusl/scipy,andim/scipy,matthew-brett/scipy,sauliusl/scipy,rmcgibbo/scipy,rgommers/scipy,ogrisel/scipy,Shaswat27/scipy,jakevdp/scipy,aeklant/scipy,mingwpy/scipy,vanpact/scipy,pyramania/scipy,Shaswat27/scipy,bkendzior/scipy,njwilson23/scipy,mhogg/scipy,gdooper/scipy,Dapid/scipy,raoulbq/scipy,felipebetancur/scipy,ilayn/scipy,pnedunuri/scipy,anielsen001/scipy,Dapid/scipy,nonhermitian/scipy,rgommers/scipy,cpaulik/scipy,andyfaff/scipy,Gillu13/scipy,gertingold/scipy,matthewalbani/scipy,jsilter/scipy,jonycgn/scipy,kleskjr/scipy,haudren/scipy,jakevdp/scipy,efiring/scipy,e-q/scipy,perimosocordiae/scipy,minhlongdo/scipy,Eric89GXL/scipy,fredrikw/scipy,nmayorov/scipy,Eric89GXL/scipy,mortada/scipy,cpaulik/scipy,Stefan-Endres/scipy,matthew-brett/scipy,apbard/scipy,anntzer/scipy,sriki18/scipy,nmayorov/scipy,witcxc/scipy,Shaswat27/scipy,bkendzior/scipy,jamestwebber/scipy,jonycgn/scipy,pyramania/scipy,petebachant/scipy,mdhaber/scipy,larsmans/scipy,cpaulik/scipy,minhlongdo/scipy,jonycgn/scipy,njwilson23/scipy,apbard/scipy,josephcslater/scipy,trankmichael/scipy,sonnyhu/scipy,person142/scipy,ales-erjavec/scipy,sargas/scipy,gertingold/scipy,mhogg/scipy,efiring/scipy,ilayn/scipy,vhaasteren/scipy,piyush0609/scipy,futurulus/scipy,Gillu13/scipy,maniteja123/scipy,arokem/scipy,fernand/scipy,surhudm/scipy,dch312/scipy,vigna/scipy,josephcslater/scipy,andim/scipy,jseabold/scipy,woodscn/scipy,perimosocordiae/scipy,mikebenfield/scipy,kleskjr/scipy,zerothi/scipy,surhudm/scipy,zerothi/scipy,arokem/scipy,dominicelse/scipy,mhogg/scipy,pizzathief/scipy,vhaasteren/scipy,nonhermitian/scipy,mingwpy/scipy,anntzer/scipy,mortada/scipy,aman-iitj/scipy,richardotis/scipy,zxsted/scipy,petebachant/scipy,mhogg/scipy,zerothi/scipy,sonnyhu/scipy,pnedunuri/scipy,nonhermitian/scipy,mortonjt/scipy,mikebenfield/scipy,fredrikw/scipy,Newman101/scipy,vigna/scipy,efiring/scipy,anntzer/scipy,niknow/scipy,vhaasteren/scipy,tylerjereddy/scipy,andyfaff/scipy,ndchorley/scipy,giorgiop/scipy,fredrikw/scipy,jjhelmus/scipy,piyush0609/scipy,ortylp/scipy,richardotis/scipy,zerothi/scipy,aarchiba/scipy,andyfaff/scipy,jamestwebber/scipy,ortylp/scipy,fernand/scipy,teoliphant/scipy,ales-erjavec/scipy,bkendzior/scipy,sargas/scipy,lukauskas/scipy,e-q/scipy,maniteja123/scipy,dominicelse/scipy,petebachant/scipy,endolith/scipy,maciejkula/scipy,anntzer/scipy,jseabold/scipy,sauliusl/scipy,larsmans/scipy,gef756/scipy,richardotis/scipy,Srisai85/scipy,anielsen001/scipy,josephcslater/scipy,WarrenWeckesser/scipy,felipebetancur/scipy,piyush0609/scipy,vberaudi/scipy,apbard/scipy,woodscn/scipy,person142/scipy,mdhaber/scipy,zaxliu/scipy,maniteja123/scipy,pbrod/scipy,njwilson23/scipy,kleskjr/scipy,ChanderG/scipy,Newman101/scipy,felipebetancur/scipy,behzadnouri/scipy,argriffing/scipy,maciejkula/scipy,matthewalbani/scipy,grlee77/scipy,nmayorov/scipy,Dapid/scipy,jor-/scipy,Srisai85/scipy,matthew-brett/scipy,minhlongdo/scipy,apbard/scipy,mortonjt/scipy,mdhaber/scipy,giorgiop/scipy,larsmans/scipy,ndchorley/scipy,scipy/scipy,mtrbean/scipy,WarrenWeckesser/scipy,dch312/scipy,lukauskas/scipy,juliantaylor/scipy,mgaitan/scipy,fernand/scipy,perimosocordiae/scipy,pbrod/scipy,gfyoung/scipy,person142/scipy,richardotis/scipy,zaxliu/scipy,mgaitan/scipy,trankmichael/scipy,Kamp9/scipy,haudren/scipy,mikebenfield/scipy,trankmichael/scipy,aman-iitj/scipy,surhudm/scipy,jseabold/scipy,kalvdans/scipy,gertingold/scipy,person142/scipy,fernand/scipy,Shaswat27/scipy,ogrisel/scipy,mortonjt/scipy,nvoron23/scipy,giorgiop/scipy,WillieMaddox/scipy,pizzathief/scipy,mgaitan/scipy,zxsted/scipy,Eric89GXL/scipy,mortada/scipy,fredrikw/scipy,apbard/scipy,woodscn/scipy,Kamp9/scipy,ilayn/scipy,sriki18/scipy,arokem/scipy,WillieMaddox/scipy,newemailjdm/scipy,andyfaff/scipy,kalvdans/scipy,vigna/scipy,nvoron23/scipy,aman-iitj/scipy,dominicelse/scipy,endolith/scipy,aarchiba/scipy,sargas/scipy,lhilt/scipy,juliantaylor/scipy,cpaulik/scipy,felipebetancur/scipy,arokem/scipy,Newman101/scipy,FRidh/scipy,andim/scipy,mdhaber/scipy,scipy/scipy,zaxliu/scipy,jor-/scipy,Gillu13/scipy,sauliusl/scipy,felipebetancur/scipy,jseabold/scipy,surhudm/scipy,WillieMaddox/scipy,dch312/scipy,jor-/scipy,zxsted/scipy,pnedunuri/scipy,gdooper/scipy,ortylp/scipy,Newman101/scipy,zaxliu/scipy,mgaitan/scipy,vanpact/scipy,Stefan-Endres/scipy,sriki18/scipy,teoliphant/scipy,aeklant/scipy,witcxc/scipy,bkendzior/scipy,mingwpy/scipy,e-q/scipy,efiring/scipy,anielsen001/scipy,vigna/scipy,hainm/scipy,behzadnouri/scipy,andim/scipy,FRidh/scipy,FRidh/scipy,sargas/scipy,lhilt/scipy,hainm/scipy,aeklant/scipy,perimosocordiae/scipy,jseabold/scipy,scipy/scipy,rmcgibbo/scipy,Eric89GXL/scipy,befelix/scipy,gef756/scipy,ilayn/scipy,pbrod/scipy,jsilter/scipy,matthewalbani/scipy,vberaudi/scipy,vanpact/scipy,anielsen001/scipy,kalvdans/scipy,haudren/scipy,surhudm/scipy,jamestwebber/scipy,newemailjdm/scipy,witcxc/scipy,nmayorov/scipy,sriki18/scipy,Srisai85/scipy,giorgiop/scipy,Dapid/scipy,fredrikw/scipy,gfyoung/scipy,mingwpy/scipy,zerothi/scipy,person142/scipy,WillieMaddox/scipy,sriki18/scipy,maniteja123/scipy,vberaudi/scipy,chatcannon/scipy,matthew-brett/scipy,perimosocordiae/scipy,hainm/scipy,ortylp/scipy,raoulbq/scipy,sauliusl/scipy,vanpact/scipy,chatcannon/scipy,larsmans/scipy,pnedunuri/scipy,ogrisel/scipy,maciejkula/scipy,WarrenWeckesser/scipy,mtrbean/scipy,nvoron23/scipy,ales-erjavec/scipy,juliantaylor/scipy,Kamp9/scipy,jakevdp/scipy,vhaasteren/scipy,niknow/scipy,aman-iitj/scipy,Dapid/scipy,pschella/scipy,lukauskas/scipy,jamestwebber/scipy,vigna/scipy,teoliphant/scipy,ChanderG/scipy,argriffing/scipy,Srisai85/scipy,behzadnouri/scipy,niknow/scipy,mortonjt/scipy,Dapid/scipy,FRidh/scipy,aeklant/scipy,giorgiop/scipy,endolith/scipy,larsmans/scipy,vanpact/scipy,ChanderG/scipy,WarrenWeckesser/scipy,mikebenfield/scipy,mdhaber/scipy,haudren/scipy,grlee77/scipy,pyramania/scipy,gdooper/scipy,fernand/scipy,lhilt/scipy,newemailjdm/scipy,gdooper/scipy,gdooper/scipy,zxsted/scipy,lukauskas/scipy,Kamp9/scipy,jamestwebber/scipy,richardotis/scipy,tylerjereddy/scipy,chatcannon/scipy,befelix/scipy,mortada/scipy,pschella/scipy,petebachant/scipy,Gillu13/scipy,vberaudi/scipy,teoliphant/scipy,ilayn/scipy,cpaulik/scipy
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) - #config.add_subpackage('cluster') + config.add_subpackage('cluster') - #config.add_subpackage('fftpack') + config.add_subpackage('fftpack') - #config.add_subpackage('integrate') + config.add_subpackage('integrate') - #config.add_subpackage('interpolate') + config.add_subpackage('interpolate') - #config.add_subpackage('io') + config.add_subpackage('io') config.add_subpackage('lib') config.add_subpackage('linalg') - #config.add_subpackage('linsolve') + config.add_subpackage('linsolve') - #config.add_subpackage('maxentropy') + config.add_subpackage('maxentropy') config.add_subpackage('misc') #config.add_subpackage('montecarlo') config.add_subpackage('optimize') - #config.add_subpackage('sandbox') + config.add_subpackage('sandbox') - #config.add_subpackage('signal') + config.add_subpackage('signal') - #config.add_subpackage('sparse') + config.add_subpackage('sparse') config.add_subpackage('special') config.add_subpackage('stats') - #config.add_subpackage('ndimage') + config.add_subpackage('ndimage') - #config.add_subpackage('weave') + config.add_subpackage('weave') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
Fix problem with __all__ variable and update weave docs a bit. Update compiler_cxx too.
## Code Before: def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) #config.add_subpackage('cluster') #config.add_subpackage('fftpack') #config.add_subpackage('integrate') #config.add_subpackage('interpolate') #config.add_subpackage('io') config.add_subpackage('lib') config.add_subpackage('linalg') #config.add_subpackage('linsolve') #config.add_subpackage('maxentropy') config.add_subpackage('misc') #config.add_subpackage('montecarlo') config.add_subpackage('optimize') #config.add_subpackage('sandbox') #config.add_subpackage('signal') #config.add_subpackage('sparse') config.add_subpackage('special') config.add_subpackage('stats') #config.add_subpackage('ndimage') #config.add_subpackage('weave') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict()) ## Instruction: Fix problem with __all__ variable and update weave docs a bit. Update compiler_cxx too. ## Code After: def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) config.add_subpackage('cluster') config.add_subpackage('fftpack') config.add_subpackage('integrate') config.add_subpackage('interpolate') config.add_subpackage('io') config.add_subpackage('lib') config.add_subpackage('linalg') config.add_subpackage('linsolve') config.add_subpackage('maxentropy') config.add_subpackage('misc') #config.add_subpackage('montecarlo') config.add_subpackage('optimize') config.add_subpackage('sandbox') config.add_subpackage('signal') config.add_subpackage('sparse') config.add_subpackage('special') config.add_subpackage('stats') config.add_subpackage('ndimage') config.add_subpackage('weave') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) - #config.add_subpackage('cluster') ? - + config.add_subpackage('cluster') - #config.add_subpackage('fftpack') ? - + config.add_subpackage('fftpack') - #config.add_subpackage('integrate') ? - + config.add_subpackage('integrate') - #config.add_subpackage('interpolate') ? - + config.add_subpackage('interpolate') - #config.add_subpackage('io') ? - + config.add_subpackage('io') config.add_subpackage('lib') config.add_subpackage('linalg') - #config.add_subpackage('linsolve') ? - + config.add_subpackage('linsolve') - #config.add_subpackage('maxentropy') ? - + config.add_subpackage('maxentropy') config.add_subpackage('misc') #config.add_subpackage('montecarlo') config.add_subpackage('optimize') - #config.add_subpackage('sandbox') ? - + config.add_subpackage('sandbox') - #config.add_subpackage('signal') ? - + config.add_subpackage('signal') - #config.add_subpackage('sparse') ? - + config.add_subpackage('sparse') config.add_subpackage('special') config.add_subpackage('stats') - #config.add_subpackage('ndimage') ? - + config.add_subpackage('ndimage') - #config.add_subpackage('weave') ? - + config.add_subpackage('weave') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
86e9e5a8da58b2902f5848353df9b05151bd08fa
turbustat/tests/test_cramer.py
turbustat/tests/test_cramer.py
''' Test functions for Cramer ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testCramer(TestCase): def setUp(self): self.dataset1 = dataset1 self.dataset2 = dataset2 def test_cramer(self): self.tester = Cramer_Distance(dataset1["cube"][0], dataset2["cube"][0]) self.tester.distance_metric() assert np.allclose(self.tester.data_matrix1, computed_data["cramer_val"]) npt.assert_almost_equal(self.tester.distance, computed_distances['cramer_distance'])
''' Test functions for Cramer ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testCramer(TestCase): def setUp(self): self.dataset1 = dataset1 self.dataset2 = dataset2 def test_cramer(self): self.tester = Cramer_Distance(dataset1["cube"][0], dataset2["cube"][0]) self.tester.distance_metric() assert np.allclose(self.tester.data_matrix1, computed_data["cramer_val"]) npt.assert_almost_equal(self.tester.distance, computed_distances['cramer_distance']) def test_cramer_spatial_diff(self): small_data = dataset1["cube"][0][:, :26, :26] self.tester2 = Cramer_Distance(small_data, dataset2["cube"][0]) self.tester3 = Cramer_Distance(dataset2["cube"][0], small_data) npt.assert_almost_equal(self.tester2.distance, self.tester3.distance)
Add test for Cramer with different spatial sizes
Add test for Cramer with different spatial sizes
Python
mit
Astroua/TurbuStat,e-koch/TurbuStat
''' Test functions for Cramer ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testCramer(TestCase): def setUp(self): self.dataset1 = dataset1 self.dataset2 = dataset2 def test_cramer(self): self.tester = Cramer_Distance(dataset1["cube"][0], dataset2["cube"][0]) self.tester.distance_metric() assert np.allclose(self.tester.data_matrix1, computed_data["cramer_val"]) npt.assert_almost_equal(self.tester.distance, computed_distances['cramer_distance']) + def test_cramer_spatial_diff(self): + + small_data = dataset1["cube"][0][:, :26, :26] + + self.tester2 = Cramer_Distance(small_data, dataset2["cube"][0]) + self.tester3 = Cramer_Distance(dataset2["cube"][0], small_data) + + npt.assert_almost_equal(self.tester2.distance, self.tester3.distance) + +
Add test for Cramer with different spatial sizes
## Code Before: ''' Test functions for Cramer ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testCramer(TestCase): def setUp(self): self.dataset1 = dataset1 self.dataset2 = dataset2 def test_cramer(self): self.tester = Cramer_Distance(dataset1["cube"][0], dataset2["cube"][0]) self.tester.distance_metric() assert np.allclose(self.tester.data_matrix1, computed_data["cramer_val"]) npt.assert_almost_equal(self.tester.distance, computed_distances['cramer_distance']) ## Instruction: Add test for Cramer with different spatial sizes ## Code After: ''' Test functions for Cramer ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testCramer(TestCase): def setUp(self): self.dataset1 = dataset1 self.dataset2 = dataset2 def test_cramer(self): self.tester = Cramer_Distance(dataset1["cube"][0], dataset2["cube"][0]) self.tester.distance_metric() assert np.allclose(self.tester.data_matrix1, computed_data["cramer_val"]) npt.assert_almost_equal(self.tester.distance, computed_distances['cramer_distance']) def test_cramer_spatial_diff(self): small_data = dataset1["cube"][0][:, :26, :26] self.tester2 = Cramer_Distance(small_data, dataset2["cube"][0]) self.tester3 = Cramer_Distance(dataset2["cube"][0], small_data) npt.assert_almost_equal(self.tester2.distance, self.tester3.distance)
''' Test functions for Cramer ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testCramer(TestCase): def setUp(self): self.dataset1 = dataset1 self.dataset2 = dataset2 def test_cramer(self): self.tester = Cramer_Distance(dataset1["cube"][0], dataset2["cube"][0]) self.tester.distance_metric() assert np.allclose(self.tester.data_matrix1, computed_data["cramer_val"]) npt.assert_almost_equal(self.tester.distance, computed_distances['cramer_distance']) + + def test_cramer_spatial_diff(self): + + small_data = dataset1["cube"][0][:, :26, :26] + + self.tester2 = Cramer_Distance(small_data, dataset2["cube"][0]) + self.tester3 = Cramer_Distance(dataset2["cube"][0], small_data) + + npt.assert_almost_equal(self.tester2.distance, self.tester3.distance) +
767b9867a1e28063fae33ea46478372818b5a129
cla_backend/apps/core/views.py
cla_backend/apps/core/views.py
from django.views import defaults from sentry_sdk import capture_message, push_scope def page_not_found(request, *args, **kwargs): with push_scope() as scope: scope.set_tag("type", "404") scope.set_extra("path", request.path) capture_message("Page not found", level="error") return defaults.page_not_found(request, *args, **kwargs)
from django.views import defaults from sentry_sdk import capture_message, push_scope def page_not_found(request, *args, **kwargs): with push_scope() as scope: scope.set_tag("path", request.path) for i, part in enumerate(request.path.strip("/").split("/")): scope.set_tag("path_{}".format(i), part) capture_message("Page not found", level="error") return defaults.page_not_found(request, *args, **kwargs)
Tag sentry event with each part of path
Tag sentry event with each part of path
Python
mit
ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend
from django.views import defaults from sentry_sdk import capture_message, push_scope def page_not_found(request, *args, **kwargs): with push_scope() as scope: - scope.set_tag("type", "404") - scope.set_extra("path", request.path) + scope.set_tag("path", request.path) + for i, part in enumerate(request.path.strip("/").split("/")): + scope.set_tag("path_{}".format(i), part) capture_message("Page not found", level="error") return defaults.page_not_found(request, *args, **kwargs)
Tag sentry event with each part of path
## Code Before: from django.views import defaults from sentry_sdk import capture_message, push_scope def page_not_found(request, *args, **kwargs): with push_scope() as scope: scope.set_tag("type", "404") scope.set_extra("path", request.path) capture_message("Page not found", level="error") return defaults.page_not_found(request, *args, **kwargs) ## Instruction: Tag sentry event with each part of path ## Code After: from django.views import defaults from sentry_sdk import capture_message, push_scope def page_not_found(request, *args, **kwargs): with push_scope() as scope: scope.set_tag("path", request.path) for i, part in enumerate(request.path.strip("/").split("/")): scope.set_tag("path_{}".format(i), part) capture_message("Page not found", level="error") return defaults.page_not_found(request, *args, **kwargs)
from django.views import defaults from sentry_sdk import capture_message, push_scope def page_not_found(request, *args, **kwargs): with push_scope() as scope: - scope.set_tag("type", "404") - scope.set_extra("path", request.path) ? -- - + scope.set_tag("path", request.path) ? + + for i, part in enumerate(request.path.strip("/").split("/")): + scope.set_tag("path_{}".format(i), part) capture_message("Page not found", level="error") return defaults.page_not_found(request, *args, **kwargs)
23d92f1a24e919bd1b232cb529dbe022f6cdd463
gwv/gwv.py
gwv/gwv.py
import os import sys from gwv import version from validator import validate def main(args=None): if args is None: args = sys.argv[1:] import argparse parser = argparse.ArgumentParser(description="GlyphWiki data validator") parser.add_argument("dumpfile") parser.add_argument("-o", "--out", help="File to write the output JSON to") parser.add_argument("-n", "--names", nargs="*", help="Names of validators") parser.add_argument("-v", "--version", action="store_true", help="Names of validators") opts = parser.parse_args(args) if opts.version: print(version) return outpath = opts.out or os.path.join(os.path.dirname(opts.dumpfile), "gwv_result.json") dumpfile = open(opts.dumpfile) result = validate(dumpfile, opts.names or None) with open(outpath, "w") as outfile: outfile.write(result) if __name__ == '__main__': main()
import os import sys from gwv import version from validator import validate def open_dump(filename): dump = {} with open(filename) as f: if filename[-4:] == ".csv": for l in f: row = l.rstrip("\n").split(",") if len(row) != 3: continue dump[row[0]] = (row[1], row[2]) else: # dump_newest_only.txt line = f.readline() # header line = f.readline() # ------ while line: l = [x.strip() for x in line.split("|")] if len(l) != 3: line = f.readline() continue dump[row[0]] = (row[1], row[2]) line = f.readline() return dump def main(args=None): if args is None: args = sys.argv[1:] import argparse parser = argparse.ArgumentParser(description="GlyphWiki data validator") parser.add_argument("dumpfile") parser.add_argument("-o", "--out", help="File to write the output JSON to") parser.add_argument("-n", "--names", nargs="*", help="Names of validators") parser.add_argument("-v", "--version", action="store_true", help="Names of validators") opts = parser.parse_args(args) if opts.version: print(version) return outpath = opts.out or os.path.join( os.path.dirname(opts.dumpfile), "gwv_result.json") dump = open_dump(opts.dumpfile) result = validate(dump, opts.names or None) with open(outpath, "w") as outfile: outfile.write(result) if __name__ == '__main__': main()
Use dict for dump data format
Use dict for dump data format
Python
mit
kurgm/gwv
import os import sys from gwv import version from validator import validate + + + def open_dump(filename): + dump = {} + with open(filename) as f: + if filename[-4:] == ".csv": + for l in f: + row = l.rstrip("\n").split(",") + if len(row) != 3: + continue + dump[row[0]] = (row[1], row[2]) + else: + # dump_newest_only.txt + line = f.readline() # header + line = f.readline() # ------ + while line: + l = [x.strip() for x in line.split("|")] + if len(l) != 3: + line = f.readline() + continue + dump[row[0]] = (row[1], row[2]) + line = f.readline() + return dump def main(args=None): if args is None: args = sys.argv[1:] import argparse parser = argparse.ArgumentParser(description="GlyphWiki data validator") parser.add_argument("dumpfile") parser.add_argument("-o", "--out", help="File to write the output JSON to") parser.add_argument("-n", "--names", nargs="*", help="Names of validators") - parser.add_argument("-v", "--version", action="store_true", help="Names of validators") + parser.add_argument("-v", "--version", action="store_true", + help="Names of validators") opts = parser.parse_args(args) if opts.version: print(version) return - outpath = opts.out or os.path.join(os.path.dirname(opts.dumpfile), "gwv_result.json") + outpath = opts.out or os.path.join( + os.path.dirname(opts.dumpfile), "gwv_result.json") - dumpfile = open(opts.dumpfile) + dump = open_dump(opts.dumpfile) - result = validate(dumpfile, opts.names or None) + result = validate(dump, opts.names or None) with open(outpath, "w") as outfile: outfile.write(result) if __name__ == '__main__': main()
Use dict for dump data format
## Code Before: import os import sys from gwv import version from validator import validate def main(args=None): if args is None: args = sys.argv[1:] import argparse parser = argparse.ArgumentParser(description="GlyphWiki data validator") parser.add_argument("dumpfile") parser.add_argument("-o", "--out", help="File to write the output JSON to") parser.add_argument("-n", "--names", nargs="*", help="Names of validators") parser.add_argument("-v", "--version", action="store_true", help="Names of validators") opts = parser.parse_args(args) if opts.version: print(version) return outpath = opts.out or os.path.join(os.path.dirname(opts.dumpfile), "gwv_result.json") dumpfile = open(opts.dumpfile) result = validate(dumpfile, opts.names or None) with open(outpath, "w") as outfile: outfile.write(result) if __name__ == '__main__': main() ## Instruction: Use dict for dump data format ## Code After: import os import sys from gwv import version from validator import validate def open_dump(filename): dump = {} with open(filename) as f: if filename[-4:] == ".csv": for l in f: row = l.rstrip("\n").split(",") if len(row) != 3: continue dump[row[0]] = (row[1], row[2]) else: # dump_newest_only.txt line = f.readline() # header line = f.readline() # ------ while line: l = [x.strip() for x in line.split("|")] if len(l) != 3: line = f.readline() continue dump[row[0]] = (row[1], row[2]) line = f.readline() return dump def main(args=None): if args is None: args = sys.argv[1:] import argparse parser = argparse.ArgumentParser(description="GlyphWiki data validator") parser.add_argument("dumpfile") parser.add_argument("-o", "--out", help="File to write the output JSON to") parser.add_argument("-n", "--names", nargs="*", help="Names of validators") parser.add_argument("-v", "--version", action="store_true", help="Names of validators") opts = parser.parse_args(args) if opts.version: print(version) return outpath = opts.out or os.path.join( os.path.dirname(opts.dumpfile), "gwv_result.json") dump = open_dump(opts.dumpfile) result = validate(dump, opts.names or None) with open(outpath, "w") as outfile: outfile.write(result) if __name__ == '__main__': main()
import os import sys from gwv import version from validator import validate + + + def open_dump(filename): + dump = {} + with open(filename) as f: + if filename[-4:] == ".csv": + for l in f: + row = l.rstrip("\n").split(",") + if len(row) != 3: + continue + dump[row[0]] = (row[1], row[2]) + else: + # dump_newest_only.txt + line = f.readline() # header + line = f.readline() # ------ + while line: + l = [x.strip() for x in line.split("|")] + if len(l) != 3: + line = f.readline() + continue + dump[row[0]] = (row[1], row[2]) + line = f.readline() + return dump def main(args=None): if args is None: args = sys.argv[1:] import argparse parser = argparse.ArgumentParser(description="GlyphWiki data validator") parser.add_argument("dumpfile") parser.add_argument("-o", "--out", help="File to write the output JSON to") parser.add_argument("-n", "--names", nargs="*", help="Names of validators") - parser.add_argument("-v", "--version", action="store_true", help="Names of validators") ? ---------------------------- + parser.add_argument("-v", "--version", action="store_true", + help="Names of validators") opts = parser.parse_args(args) if opts.version: print(version) return + outpath = opts.out or os.path.join( - outpath = opts.out or os.path.join(os.path.dirname(opts.dumpfile), "gwv_result.json") ? ------- - -------- -- ------------- + os.path.dirname(opts.dumpfile), "gwv_result.json") - dumpfile = open(opts.dumpfile) ? ---- + dump = open_dump(opts.dumpfile) ? +++++ - result = validate(dumpfile, opts.names or None) ? ---- + result = validate(dump, opts.names or None) with open(outpath, "w") as outfile: outfile.write(result) if __name__ == '__main__': main()
ec1f7db3f1bd637807b4b9d69a0b702af36fbef1
morenines/ignores.py
morenines/ignores.py
import os from fnmatch import fnmatchcase import click class Ignores(object): @classmethod def read(cls, path): ignores = cls() if path: with click.open_file(path, 'r') as stream: ignores.patterns = [line.strip() for line in stream] return ignores def __init__(self): self.patterns = [] def match(self, path): filename = os.path.basename(path) if any(fnmatchcase(filename, pattern) for pattern in self.patterns): return True else: return False
import os from fnmatch import fnmatchcase import click from morenines.util import find_file class Ignores(object): @classmethod def read(cls, path): if not path: path = find_file('.mnignore') ignores = cls() if path: with click.open_file(path, 'r') as stream: ignores.patterns = [line.strip() for line in stream] return ignores def __init__(self): self.patterns = [] def match(self, path): filename = os.path.basename(path) if any(fnmatchcase(filename, pattern) for pattern in self.patterns): return True else: return False
Make Ignores try to find '.mnignore'
Make Ignores try to find '.mnignore' If it doesn't find it, that's okay, and no action is required.
Python
mit
mcgid/morenines,mcgid/morenines
import os from fnmatch import fnmatchcase import click + from morenines.util import find_file + + class Ignores(object): @classmethod def read(cls, path): + if not path: + path = find_file('.mnignore') + ignores = cls() if path: with click.open_file(path, 'r') as stream: ignores.patterns = [line.strip() for line in stream] return ignores def __init__(self): self.patterns = [] def match(self, path): filename = os.path.basename(path) if any(fnmatchcase(filename, pattern) for pattern in self.patterns): return True else: return False
Make Ignores try to find '.mnignore'
## Code Before: import os from fnmatch import fnmatchcase import click class Ignores(object): @classmethod def read(cls, path): ignores = cls() if path: with click.open_file(path, 'r') as stream: ignores.patterns = [line.strip() for line in stream] return ignores def __init__(self): self.patterns = [] def match(self, path): filename = os.path.basename(path) if any(fnmatchcase(filename, pattern) for pattern in self.patterns): return True else: return False ## Instruction: Make Ignores try to find '.mnignore' ## Code After: import os from fnmatch import fnmatchcase import click from morenines.util import find_file class Ignores(object): @classmethod def read(cls, path): if not path: path = find_file('.mnignore') ignores = cls() if path: with click.open_file(path, 'r') as stream: ignores.patterns = [line.strip() for line in stream] return ignores def __init__(self): self.patterns = [] def match(self, path): filename = os.path.basename(path) if any(fnmatchcase(filename, pattern) for pattern in self.patterns): return True else: return False
import os from fnmatch import fnmatchcase import click + from morenines.util import find_file + + class Ignores(object): @classmethod def read(cls, path): + if not path: + path = find_file('.mnignore') + ignores = cls() if path: with click.open_file(path, 'r') as stream: ignores.patterns = [line.strip() for line in stream] return ignores def __init__(self): self.patterns = [] def match(self, path): filename = os.path.basename(path) if any(fnmatchcase(filename, pattern) for pattern in self.patterns): return True else: return False
69f0b89c306b6a616e3db2716669a2aa04453222
cogs/default.py
cogs/default.py
import time from discord.ext import commands class Default: @commands.command(aliases=['p']) async def ping(self, ctx): """Get the ping to the websocket.""" msg = await ctx.send("Pong! :ping_pong:") before = time.monotonic() await (await ctx.bot.ws.ping()) after = time.monotonic() ping_time = (after - before) * 1000 await msg.edit(content=f'{msg.content} **{ping_time:.0f}ms**') @commands.command() async def source(self, ctx): """Get the source for the bot.""" await ctx.send('https://github.com/BeatButton/beattie') @commands.command() async def invite(self, ctx): """Get the invite for the bot.""" url = 'https://discordapp.com/oauth2/authorize?client_id={}&scope=bot' await ctx.send(url.format(ctx.me.id)) @commands.command(hidden=True, aliases=['thank', 'thx']) async def thanks(self, ctx): await ctx.send('no u') @commands.command(hidden=True) async def confetti(self, ctx, num: int=1): if num > 200: await ctx.send("I don't have that much confetti " '<:blobpensive:337436989676716033>') else: await ctx.send('🎉' * num) def setup(bot): bot.add_cog(Default())
from discord.ext import commands class Default: @commands.command(aliases=['p']) async def ping(self, ctx): """Get the ping to the websocket.""" await ctx.send(f'Pong! :ping_pong: **{ctx.bot.latency*1000:.0f}ms**') @commands.command() async def source(self, ctx): """Get the source for the bot.""" await ctx.send('https://github.com/BeatButton/beattie') @commands.command() async def invite(self, ctx): """Get the invite for the bot.""" url = 'https://discordapp.com/oauth2/authorize?client_id={}&scope=bot' await ctx.send(url.format(ctx.me.id)) @commands.command(hidden=True, aliases=['thank', 'thx']) async def thanks(self, ctx): await ctx.send('no u') @commands.command(hidden=True) async def confetti(self, ctx, num: int=1): if num > 200: await ctx.send("I don't have that much confetti " '<:blobpensive:337436989676716033>') else: await ctx.send('🎉' * num) def setup(bot): bot.add_cog(Default())
Use bot.latency for ping time
Use bot.latency for ping time
Python
mit
BeatButton/beattie,BeatButton/beattie-bot
- import time - from discord.ext import commands class Default: @commands.command(aliases=['p']) async def ping(self, ctx): """Get the ping to the websocket.""" + await ctx.send(f'Pong! :ping_pong: **{ctx.bot.latency*1000:.0f}ms**') - msg = await ctx.send("Pong! :ping_pong:") - - before = time.monotonic() - await (await ctx.bot.ws.ping()) - after = time.monotonic() - ping_time = (after - before) * 1000 - - await msg.edit(content=f'{msg.content} **{ping_time:.0f}ms**') @commands.command() async def source(self, ctx): """Get the source for the bot.""" await ctx.send('https://github.com/BeatButton/beattie') @commands.command() async def invite(self, ctx): """Get the invite for the bot.""" url = 'https://discordapp.com/oauth2/authorize?client_id={}&scope=bot' await ctx.send(url.format(ctx.me.id)) @commands.command(hidden=True, aliases=['thank', 'thx']) async def thanks(self, ctx): await ctx.send('no u') @commands.command(hidden=True) async def confetti(self, ctx, num: int=1): if num > 200: await ctx.send("I don't have that much confetti " '<:blobpensive:337436989676716033>') else: await ctx.send('🎉' * num) def setup(bot): bot.add_cog(Default())
Use bot.latency for ping time
## Code Before: import time from discord.ext import commands class Default: @commands.command(aliases=['p']) async def ping(self, ctx): """Get the ping to the websocket.""" msg = await ctx.send("Pong! :ping_pong:") before = time.monotonic() await (await ctx.bot.ws.ping()) after = time.monotonic() ping_time = (after - before) * 1000 await msg.edit(content=f'{msg.content} **{ping_time:.0f}ms**') @commands.command() async def source(self, ctx): """Get the source for the bot.""" await ctx.send('https://github.com/BeatButton/beattie') @commands.command() async def invite(self, ctx): """Get the invite for the bot.""" url = 'https://discordapp.com/oauth2/authorize?client_id={}&scope=bot' await ctx.send(url.format(ctx.me.id)) @commands.command(hidden=True, aliases=['thank', 'thx']) async def thanks(self, ctx): await ctx.send('no u') @commands.command(hidden=True) async def confetti(self, ctx, num: int=1): if num > 200: await ctx.send("I don't have that much confetti " '<:blobpensive:337436989676716033>') else: await ctx.send('🎉' * num) def setup(bot): bot.add_cog(Default()) ## Instruction: Use bot.latency for ping time ## Code After: from discord.ext import commands class Default: @commands.command(aliases=['p']) async def ping(self, ctx): """Get the ping to the websocket.""" await ctx.send(f'Pong! :ping_pong: **{ctx.bot.latency*1000:.0f}ms**') @commands.command() async def source(self, ctx): """Get the source for the bot.""" await ctx.send('https://github.com/BeatButton/beattie') @commands.command() async def invite(self, ctx): """Get the invite for the bot.""" url = 'https://discordapp.com/oauth2/authorize?client_id={}&scope=bot' await ctx.send(url.format(ctx.me.id)) @commands.command(hidden=True, aliases=['thank', 'thx']) async def thanks(self, ctx): await ctx.send('no u') @commands.command(hidden=True) async def confetti(self, ctx, num: int=1): if num > 200: await ctx.send("I don't have that much confetti " '<:blobpensive:337436989676716033>') else: await ctx.send('🎉' * num) def setup(bot): bot.add_cog(Default())
- import time - from discord.ext import commands class Default: @commands.command(aliases=['p']) async def ping(self, ctx): """Get the ping to the websocket.""" + await ctx.send(f'Pong! :ping_pong: **{ctx.bot.latency*1000:.0f}ms**') - msg = await ctx.send("Pong! :ping_pong:") - - before = time.monotonic() - await (await ctx.bot.ws.ping()) - after = time.monotonic() - ping_time = (after - before) * 1000 - - await msg.edit(content=f'{msg.content} **{ping_time:.0f}ms**') @commands.command() async def source(self, ctx): """Get the source for the bot.""" await ctx.send('https://github.com/BeatButton/beattie') @commands.command() async def invite(self, ctx): """Get the invite for the bot.""" url = 'https://discordapp.com/oauth2/authorize?client_id={}&scope=bot' await ctx.send(url.format(ctx.me.id)) @commands.command(hidden=True, aliases=['thank', 'thx']) async def thanks(self, ctx): await ctx.send('no u') @commands.command(hidden=True) async def confetti(self, ctx, num: int=1): if num > 200: await ctx.send("I don't have that much confetti " '<:blobpensive:337436989676716033>') else: await ctx.send('🎉' * num) def setup(bot): bot.add_cog(Default())
b5acf414e9fcbecee8da15e2757a60ce10cc5c10
examples/last.py
examples/last.py
from pymisp import PyMISP from keys import misp_url, misp_key import argparse import os import json # Usage for pipe masters: ./last.py -l 5h | jq . def init(url, key): return PyMISP(url, key, True, 'json') def download_last(m, last, out=None): result = m.download_last(last) if out is None: for e in result['response']: print(json.dumps(e) + '\n') else: with open(out, 'w') as f: for e in result['response']: f.write(json.dumps(e) + '\n') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Download latest events from a MISP instance.') parser.add_argument("-l", "--last", required=True, help="can be defined in days, hours, minutes (for example 5d or 12h or 30m).") parser.add_argument("-o", "--output", help="Output file") args = parser.parse_args() if args.output is not None and os.path.exists(args.output): print('Output file already exists, abord.') exit(0) misp = init(misp_url, misp_key) download_last(misp, args.last, args.output)
from pymisp import PyMISP from keys import misp_url, misp_key import argparse import os import json # Usage for pipe masters: ./last.py -l 5h | jq . def init(url, key): return PyMISP(url, key, True, 'json') def download_last(m, last, out=None): result = m.download_last(last) if out is None: if 'response' in result: for e in result['response']: print(json.dumps(e) + '\n') else: print('No results for that time period') exit(0) else: with open(out, 'w') as f: for e in result['response']: f.write(json.dumps(e) + '\n') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Download latest events from a MISP instance.') parser.add_argument("-l", "--last", required=True, help="can be defined in days, hours, minutes (for example 5d or 12h or 30m).") parser.add_argument("-o", "--output", help="Output file") args = parser.parse_args() if args.output is not None and os.path.exists(args.output): print('Output file already exists, abord.') exit(0) misp = init(misp_url, misp_key) download_last(misp, args.last, args.output)
Fix KeyError when no results in time period
Fix KeyError when no results in time period Fix a KeyError when no results were found for the specified time period.
Python
bsd-2-clause
pombredanne/PyMISP,iglocska/PyMISP
from pymisp import PyMISP from keys import misp_url, misp_key import argparse import os import json # Usage for pipe masters: ./last.py -l 5h | jq . def init(url, key): return PyMISP(url, key, True, 'json') def download_last(m, last, out=None): result = m.download_last(last) if out is None: + if 'response' in result: - for e in result['response']: + for e in result['response']: - print(json.dumps(e) + '\n') + print(json.dumps(e) + '\n') + else: + print('No results for that time period') + exit(0) else: with open(out, 'w') as f: for e in result['response']: f.write(json.dumps(e) + '\n') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Download latest events from a MISP instance.') parser.add_argument("-l", "--last", required=True, help="can be defined in days, hours, minutes (for example 5d or 12h or 30m).") parser.add_argument("-o", "--output", help="Output file") args = parser.parse_args() if args.output is not None and os.path.exists(args.output): print('Output file already exists, abord.') exit(0) misp = init(misp_url, misp_key) download_last(misp, args.last, args.output)
Fix KeyError when no results in time period
## Code Before: from pymisp import PyMISP from keys import misp_url, misp_key import argparse import os import json # Usage for pipe masters: ./last.py -l 5h | jq . def init(url, key): return PyMISP(url, key, True, 'json') def download_last(m, last, out=None): result = m.download_last(last) if out is None: for e in result['response']: print(json.dumps(e) + '\n') else: with open(out, 'w') as f: for e in result['response']: f.write(json.dumps(e) + '\n') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Download latest events from a MISP instance.') parser.add_argument("-l", "--last", required=True, help="can be defined in days, hours, minutes (for example 5d or 12h or 30m).") parser.add_argument("-o", "--output", help="Output file") args = parser.parse_args() if args.output is not None and os.path.exists(args.output): print('Output file already exists, abord.') exit(0) misp = init(misp_url, misp_key) download_last(misp, args.last, args.output) ## Instruction: Fix KeyError when no results in time period ## Code After: from pymisp import PyMISP from keys import misp_url, misp_key import argparse import os import json # Usage for pipe masters: ./last.py -l 5h | jq . def init(url, key): return PyMISP(url, key, True, 'json') def download_last(m, last, out=None): result = m.download_last(last) if out is None: if 'response' in result: for e in result['response']: print(json.dumps(e) + '\n') else: print('No results for that time period') exit(0) else: with open(out, 'w') as f: for e in result['response']: f.write(json.dumps(e) + '\n') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Download latest events from a MISP instance.') parser.add_argument("-l", "--last", required=True, help="can be defined in days, hours, minutes (for example 5d or 12h or 30m).") parser.add_argument("-o", "--output", help="Output file") args = parser.parse_args() if args.output is not None and os.path.exists(args.output): print('Output file already exists, abord.') exit(0) misp = init(misp_url, misp_key) download_last(misp, args.last, args.output)
from pymisp import PyMISP from keys import misp_url, misp_key import argparse import os import json # Usage for pipe masters: ./last.py -l 5h | jq . def init(url, key): return PyMISP(url, key, True, 'json') def download_last(m, last, out=None): result = m.download_last(last) if out is None: + if 'response' in result: - for e in result['response']: + for e in result['response']: ? ++++ - print(json.dumps(e) + '\n') + print(json.dumps(e) + '\n') ? ++++ + else: + print('No results for that time period') + exit(0) else: with open(out, 'w') as f: for e in result['response']: f.write(json.dumps(e) + '\n') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Download latest events from a MISP instance.') parser.add_argument("-l", "--last", required=True, help="can be defined in days, hours, minutes (for example 5d or 12h or 30m).") parser.add_argument("-o", "--output", help="Output file") args = parser.parse_args() if args.output is not None and os.path.exists(args.output): print('Output file already exists, abord.') exit(0) misp = init(misp_url, misp_key) download_last(misp, args.last, args.output)
730c7e6982f737c166924e1cae73eb34024fc4ef
AWSLambdas/vote.py
AWSLambdas/vote.py
import json import boto3 import time import decimal import base64 from boto3.dynamodb.conditions import Key, Attr def consolidate_disposition(disposition_map, records): for record in records: type = record['eventName'] disposition = 0 if type == "INSERT" or type == "MODIFY": disposition = int(record['dynamodb']['NewImage']['vote']['N']) if type == "MODIFY" or type == "REMOVE": disposition += -int(record['dynamodb']['OldImage']['vote']['N']) sample = record['dynamodb']['Keys']['sample']['B'] disposition_map[sample] = disposition_map.get(sample, 0) + disposition def vote_handler(event, context): dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('Samples') ratings = dict() consolidate_disposition(ratings, event['Records']) for (sample, vote) in ratings.iteritems(): ident = sample[0:19] event = base64.standard_b64decode(sample[18:]) print ident print event
import json import boto3 import time import decimal import base64 from boto3.dynamodb.conditions import Key, Attr from decimal import Decimal def consolidate_disposition(disposition_map, records): for record in records: type = record['eventName'] disposition = 0 if type == "INSERT" or type == "MODIFY": disposition = int(record['dynamodb']['NewImage']['vote']['N']) if type == "MODIFY" or type == "REMOVE": disposition += -int(record['dynamodb']['OldImage']['vote']['N']) sample = record['dynamodb']['Keys']['sample']['B'] disposition_map[sample] = disposition_map.get(sample, 0) + disposition def vote_handler(event, context): dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('Samples') ratings = dict() consolidate_disposition(ratings, event['Records']) for (sample, vote) in ratings.iteritems(): ident = "b74z7/Q1TdqouIVyIXp+DQU=" """sample[0:19]""" event = "ChIJ1QvXETf7Z0sRBkcNQqQ89ag" """base64.standard_b64decode(sample[18:])""" up = 1 down = -1 table.update_item( Key={'event': event, 'id': ident}, UpdateExpression='ADD ups :up, downs :down', ExpressionAttributeValues={':up':{'N': up}, ':down':{'N': down}} )
Update the ups and downs members of the Samples items.
Update the ups and downs members of the Samples items.
Python
mit
SandcastleApps/partyup,SandcastleApps/partyup,SandcastleApps/partyup
import json import boto3 import time import decimal import base64 from boto3.dynamodb.conditions import Key, Attr + from decimal import Decimal def consolidate_disposition(disposition_map, records): for record in records: type = record['eventName'] disposition = 0 if type == "INSERT" or type == "MODIFY": disposition = int(record['dynamodb']['NewImage']['vote']['N']) if type == "MODIFY" or type == "REMOVE": disposition += -int(record['dynamodb']['OldImage']['vote']['N']) sample = record['dynamodb']['Keys']['sample']['B'] disposition_map[sample] = disposition_map.get(sample, 0) + disposition def vote_handler(event, context): dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('Samples') ratings = dict() consolidate_disposition(ratings, event['Records']) - + for (sample, vote) in ratings.iteritems(): - ident = sample[0:19] + ident = "b74z7/Q1TdqouIVyIXp+DQU=" """sample[0:19]""" - event = base64.standard_b64decode(sample[18:]) + event = "ChIJ1QvXETf7Z0sRBkcNQqQ89ag" """base64.standard_b64decode(sample[18:])""" - print ident - print event - + up = 1 + down = -1 + table.update_item( + Key={'event': event, 'id': ident}, + UpdateExpression='ADD ups :up, downs :down', + ExpressionAttributeValues={':up':{'N': up}, ':down':{'N': down}} + )
Update the ups and downs members of the Samples items.
## Code Before: import json import boto3 import time import decimal import base64 from boto3.dynamodb.conditions import Key, Attr def consolidate_disposition(disposition_map, records): for record in records: type = record['eventName'] disposition = 0 if type == "INSERT" or type == "MODIFY": disposition = int(record['dynamodb']['NewImage']['vote']['N']) if type == "MODIFY" or type == "REMOVE": disposition += -int(record['dynamodb']['OldImage']['vote']['N']) sample = record['dynamodb']['Keys']['sample']['B'] disposition_map[sample] = disposition_map.get(sample, 0) + disposition def vote_handler(event, context): dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('Samples') ratings = dict() consolidate_disposition(ratings, event['Records']) for (sample, vote) in ratings.iteritems(): ident = sample[0:19] event = base64.standard_b64decode(sample[18:]) print ident print event ## Instruction: Update the ups and downs members of the Samples items. ## Code After: import json import boto3 import time import decimal import base64 from boto3.dynamodb.conditions import Key, Attr from decimal import Decimal def consolidate_disposition(disposition_map, records): for record in records: type = record['eventName'] disposition = 0 if type == "INSERT" or type == "MODIFY": disposition = int(record['dynamodb']['NewImage']['vote']['N']) if type == "MODIFY" or type == "REMOVE": disposition += -int(record['dynamodb']['OldImage']['vote']['N']) sample = record['dynamodb']['Keys']['sample']['B'] disposition_map[sample] = disposition_map.get(sample, 0) + disposition def vote_handler(event, context): dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('Samples') ratings = dict() consolidate_disposition(ratings, event['Records']) for (sample, vote) in ratings.iteritems(): ident = "b74z7/Q1TdqouIVyIXp+DQU=" """sample[0:19]""" event = "ChIJ1QvXETf7Z0sRBkcNQqQ89ag" """base64.standard_b64decode(sample[18:])""" up = 1 down = -1 table.update_item( Key={'event': event, 'id': ident}, UpdateExpression='ADD ups :up, downs :down', ExpressionAttributeValues={':up':{'N': up}, ':down':{'N': down}} )
import json import boto3 import time import decimal import base64 from boto3.dynamodb.conditions import Key, Attr + from decimal import Decimal def consolidate_disposition(disposition_map, records): for record in records: type = record['eventName'] disposition = 0 if type == "INSERT" or type == "MODIFY": disposition = int(record['dynamodb']['NewImage']['vote']['N']) if type == "MODIFY" or type == "REMOVE": disposition += -int(record['dynamodb']['OldImage']['vote']['N']) sample = record['dynamodb']['Keys']['sample']['B'] disposition_map[sample] = disposition_map.get(sample, 0) + disposition def vote_handler(event, context): dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('Samples') ratings = dict() consolidate_disposition(ratings, event['Records']) - + for (sample, vote) in ratings.iteritems(): - ident = sample[0:19] + ident = "b74z7/Q1TdqouIVyIXp+DQU=" """sample[0:19]""" - event = base64.standard_b64decode(sample[18:]) + event = "ChIJ1QvXETf7Z0sRBkcNQqQ89ag" """base64.standard_b64decode(sample[18:])""" ? +++++++++++++++++++++++++++++++++ +++ - print ident - print event - + up = 1 + down = -1 + table.update_item( + Key={'event': event, 'id': ident}, + UpdateExpression='ADD ups :up, downs :down', + ExpressionAttributeValues={':up':{'N': up}, ':down':{'N': down}} + )
b5a43a7fdfc69abfa687d2b31a2add0d52ed5235
motobot/core_plugins/ctcp.py
motobot/core_plugins/ctcp.py
from motobot import match, Notice, Eat, __VERSION__ from time import strftime, localtime @match(r'\x01(.+)\x01', priority=Priority.max) def ctcp_match(bot, context, message, match): mapping = { 'VERSION': 'MotoBot Version ' + __VERSION__, 'FINGER': 'Oh you dirty man!', 'TIME': strftime('%a %b %d %H:%M:%S', localtime()), 'PING': message } try: ctcp_req = match.group(1) reply = ctcp_response[ctcp_req] return reply, Notice(context.nick), Eat except KeyError: return None
from motobot import match, Notice, Eat, Priority, __VERSION__ from time import strftime, localtime @match(r'\x01(.+)\x01', priority=Priority.max) def ctcp_match(bot, context, message, match): ctcp_response = { 'VERSION': 'MotoBot Version ' + __VERSION__, 'FINGER': 'Oh you dirty man!', 'TIME': strftime('%a %b %d %H:%M:%S', localtime()), 'PING': message } try: ctcp_req = match.group(1) reply = ctcp_response[ctcp_req] return reply, Notice(context.nick), Eat except KeyError: return None
Fix CTCP import and naming bug
Fix CTCP import and naming bug
Python
mit
Motoko11/MotoBot
- from motobot import match, Notice, Eat, __VERSION__ + from motobot import match, Notice, Eat, Priority, __VERSION__ from time import strftime, localtime @match(r'\x01(.+)\x01', priority=Priority.max) def ctcp_match(bot, context, message, match): - mapping = { + ctcp_response = { 'VERSION': 'MotoBot Version ' + __VERSION__, 'FINGER': 'Oh you dirty man!', 'TIME': strftime('%a %b %d %H:%M:%S', localtime()), 'PING': message } try: ctcp_req = match.group(1) reply = ctcp_response[ctcp_req] return reply, Notice(context.nick), Eat except KeyError: return None
Fix CTCP import and naming bug
## Code Before: from motobot import match, Notice, Eat, __VERSION__ from time import strftime, localtime @match(r'\x01(.+)\x01', priority=Priority.max) def ctcp_match(bot, context, message, match): mapping = { 'VERSION': 'MotoBot Version ' + __VERSION__, 'FINGER': 'Oh you dirty man!', 'TIME': strftime('%a %b %d %H:%M:%S', localtime()), 'PING': message } try: ctcp_req = match.group(1) reply = ctcp_response[ctcp_req] return reply, Notice(context.nick), Eat except KeyError: return None ## Instruction: Fix CTCP import and naming bug ## Code After: from motobot import match, Notice, Eat, Priority, __VERSION__ from time import strftime, localtime @match(r'\x01(.+)\x01', priority=Priority.max) def ctcp_match(bot, context, message, match): ctcp_response = { 'VERSION': 'MotoBot Version ' + __VERSION__, 'FINGER': 'Oh you dirty man!', 'TIME': strftime('%a %b %d %H:%M:%S', localtime()), 'PING': message } try: ctcp_req = match.group(1) reply = ctcp_response[ctcp_req] return reply, Notice(context.nick), Eat except KeyError: return None
- from motobot import match, Notice, Eat, __VERSION__ + from motobot import match, Notice, Eat, Priority, __VERSION__ ? ++++++++++ from time import strftime, localtime @match(r'\x01(.+)\x01', priority=Priority.max) def ctcp_match(bot, context, message, match): - mapping = { + ctcp_response = { 'VERSION': 'MotoBot Version ' + __VERSION__, 'FINGER': 'Oh you dirty man!', 'TIME': strftime('%a %b %d %H:%M:%S', localtime()), 'PING': message } try: ctcp_req = match.group(1) reply = ctcp_response[ctcp_req] return reply, Notice(context.nick), Eat except KeyError: return None
238d031651cb74d0ca9bed9d38cda836049c9c37
src/sentry/api/serializers/models/grouptagkey.py
src/sentry/api/serializers/models/grouptagkey.py
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import GroupTagKey, TagKey @register(GroupTagKey) class GroupTagKeySerializer(Serializer): def get_attrs(self, item_list, user): tag_labels = { t.key: t.get_label() for t in TagKey.objects.filter( project=item_list[0].project, key__in=[i.key for i in item_list] ) } result = {} for item in item_list: try: label = tag_labels[item.key] except KeyError: label = item.value result[item] = { 'name': label, } return result def serialize(self, obj, attrs, user): if obj.key.startswith('sentry:'): key = obj.key.split('sentry:', 1)[-1] else: key = obj.key return { 'name': attrs['name'], 'key': key, 'uniqueValues': obj.values_seen, }
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import GroupTagKey, TagKey @register(GroupTagKey) class GroupTagKeySerializer(Serializer): def get_attrs(self, item_list, user): tag_labels = { t.key: t.get_label() for t in TagKey.objects.filter( project=item_list[0].project, key__in=[i.key for i in item_list] ) } result = {} for item in item_list: try: label = tag_labels[item.key] except KeyError: if item.key.startswith('sentry:'): label = item.key.split('sentry:', 1)[-1] else: label = item.key result[item] = { 'name': label, } return result def serialize(self, obj, attrs, user): if obj.key.startswith('sentry:'): key = obj.key.split('sentry:', 1)[-1] else: key = obj.key return { 'name': attrs['name'], 'key': key, 'uniqueValues': obj.values_seen, }
Correct fallback for tag name
Correct fallback for tag name
Python
bsd-3-clause
daevaorn/sentry,gencer/sentry,zenefits/sentry,beeftornado/sentry,imankulov/sentry,BuildingLink/sentry,looker/sentry,looker/sentry,fotinakis/sentry,JamesMura/sentry,mvaled/sentry,alexm92/sentry,ifduyue/sentry,jean/sentry,beeftornado/sentry,fotinakis/sentry,BuildingLink/sentry,ifduyue/sentry,alexm92/sentry,BuildingLink/sentry,fotinakis/sentry,nicholasserra/sentry,BuildingLink/sentry,JackDanger/sentry,JamesMura/sentry,imankulov/sentry,jean/sentry,nicholasserra/sentry,zenefits/sentry,zenefits/sentry,beeftornado/sentry,ifduyue/sentry,mvaled/sentry,zenefits/sentry,gencer/sentry,looker/sentry,ifduyue/sentry,daevaorn/sentry,gencer/sentry,mvaled/sentry,mvaled/sentry,daevaorn/sentry,JackDanger/sentry,JamesMura/sentry,mvaled/sentry,BuildingLink/sentry,zenefits/sentry,mitsuhiko/sentry,imankulov/sentry,daevaorn/sentry,jean/sentry,JamesMura/sentry,gencer/sentry,mitsuhiko/sentry,mvaled/sentry,jean/sentry,fotinakis/sentry,ifduyue/sentry,nicholasserra/sentry,jean/sentry,JackDanger/sentry,looker/sentry,looker/sentry,alexm92/sentry,JamesMura/sentry,gencer/sentry
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import GroupTagKey, TagKey @register(GroupTagKey) class GroupTagKeySerializer(Serializer): def get_attrs(self, item_list, user): tag_labels = { t.key: t.get_label() for t in TagKey.objects.filter( project=item_list[0].project, key__in=[i.key for i in item_list] ) } result = {} for item in item_list: try: label = tag_labels[item.key] except KeyError: + if item.key.startswith('sentry:'): + label = item.key.split('sentry:', 1)[-1] + else: - label = item.value + label = item.key result[item] = { 'name': label, } return result def serialize(self, obj, attrs, user): if obj.key.startswith('sentry:'): key = obj.key.split('sentry:', 1)[-1] else: key = obj.key return { 'name': attrs['name'], 'key': key, 'uniqueValues': obj.values_seen, }
Correct fallback for tag name
## Code Before: from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import GroupTagKey, TagKey @register(GroupTagKey) class GroupTagKeySerializer(Serializer): def get_attrs(self, item_list, user): tag_labels = { t.key: t.get_label() for t in TagKey.objects.filter( project=item_list[0].project, key__in=[i.key for i in item_list] ) } result = {} for item in item_list: try: label = tag_labels[item.key] except KeyError: label = item.value result[item] = { 'name': label, } return result def serialize(self, obj, attrs, user): if obj.key.startswith('sentry:'): key = obj.key.split('sentry:', 1)[-1] else: key = obj.key return { 'name': attrs['name'], 'key': key, 'uniqueValues': obj.values_seen, } ## Instruction: Correct fallback for tag name ## Code After: from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import GroupTagKey, TagKey @register(GroupTagKey) class GroupTagKeySerializer(Serializer): def get_attrs(self, item_list, user): tag_labels = { t.key: t.get_label() for t in TagKey.objects.filter( project=item_list[0].project, key__in=[i.key for i in item_list] ) } result = {} for item in item_list: try: label = tag_labels[item.key] except KeyError: if item.key.startswith('sentry:'): label = item.key.split('sentry:', 1)[-1] else: label = item.key result[item] = { 'name': label, } return result def serialize(self, obj, attrs, user): if obj.key.startswith('sentry:'): key = obj.key.split('sentry:', 1)[-1] else: key = obj.key return { 'name': attrs['name'], 'key': key, 'uniqueValues': obj.values_seen, }
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import GroupTagKey, TagKey @register(GroupTagKey) class GroupTagKeySerializer(Serializer): def get_attrs(self, item_list, user): tag_labels = { t.key: t.get_label() for t in TagKey.objects.filter( project=item_list[0].project, key__in=[i.key for i in item_list] ) } result = {} for item in item_list: try: label = tag_labels[item.key] except KeyError: + if item.key.startswith('sentry:'): + label = item.key.split('sentry:', 1)[-1] + else: - label = item.value ? ^^^^ + label = item.key ? ++++ ^ + result[item] = { 'name': label, } return result def serialize(self, obj, attrs, user): if obj.key.startswith('sentry:'): key = obj.key.split('sentry:', 1)[-1] else: key = obj.key return { 'name': attrs['name'], 'key': key, 'uniqueValues': obj.values_seen, }
b9b095a2a66f79e36bbad1affaeb57b38e20803b
cwod_site/cwod/models.py
cwod_site/cwod/models.py
from django.db import models # Create your models here. class CongressionalRecordVolume(models.Model): congress = models.IntegerField(db_index=True) session = models.CharField(max_length=10, db_index=True) volume = models.IntegerField()
from django.db import models # Create your models here. class CongressionalRecordVolume(models.Model): congress = models.IntegerField(db_index=True) session = models.CharField(max_length=10, db_index=True) volume = models.IntegerField() class NgramDateCount(models.Model): """Storing the total number of ngrams per date allows us to show the percentage of a given ngram on a given date, mainly for graphing purposes. """ n = models.IntegerField(db_index=True) date = models.DateField(db_index=True) count = models.IntegerField() class Meta: unique_together = (('n', 'date', ), )
Create model for storing total n-gram counts by date
Create model for storing total n-gram counts by date
Python
bsd-3-clause
sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,propublica/Capitol-Words,propublica/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,propublica/Capitol-Words,propublica/Capitol-Words
from django.db import models # Create your models here. class CongressionalRecordVolume(models.Model): congress = models.IntegerField(db_index=True) session = models.CharField(max_length=10, db_index=True) volume = models.IntegerField() + + class NgramDateCount(models.Model): + """Storing the total number of ngrams per date + allows us to show the percentage of a given ngram + on a given date, mainly for graphing purposes. + """ + n = models.IntegerField(db_index=True) + date = models.DateField(db_index=True) + count = models.IntegerField() + + class Meta: + unique_together = (('n', 'date', ), ) +
Create model for storing total n-gram counts by date
## Code Before: from django.db import models # Create your models here. class CongressionalRecordVolume(models.Model): congress = models.IntegerField(db_index=True) session = models.CharField(max_length=10, db_index=True) volume = models.IntegerField() ## Instruction: Create model for storing total n-gram counts by date ## Code After: from django.db import models # Create your models here. class CongressionalRecordVolume(models.Model): congress = models.IntegerField(db_index=True) session = models.CharField(max_length=10, db_index=True) volume = models.IntegerField() class NgramDateCount(models.Model): """Storing the total number of ngrams per date allows us to show the percentage of a given ngram on a given date, mainly for graphing purposes. """ n = models.IntegerField(db_index=True) date = models.DateField(db_index=True) count = models.IntegerField() class Meta: unique_together = (('n', 'date', ), )
from django.db import models # Create your models here. class CongressionalRecordVolume(models.Model): congress = models.IntegerField(db_index=True) session = models.CharField(max_length=10, db_index=True) volume = models.IntegerField() + + + class NgramDateCount(models.Model): + """Storing the total number of ngrams per date + allows us to show the percentage of a given ngram + on a given date, mainly for graphing purposes. + """ + n = models.IntegerField(db_index=True) + date = models.DateField(db_index=True) + count = models.IntegerField() + + class Meta: + unique_together = (('n', 'date', ), )
1d1fec3287abbddfb376ff1fcbcc85bbcf0b44a2
pyoanda/tests/test_client.py
pyoanda/tests/test_client.py
import unittest from ..client import Client class TestClient(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_connect(self): pass
import unittest from unittest.mock import patch from ..client import Client from ..exceptions import BadCredentials class TestClient(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_connect_pass(self): with patch.object(Client, '_Client__get_credentials', return_value=True) as mock_method: c = Client( "http://mydomain.com", "http://mystreamingdomain.com", "my_account", "my_token" ) def test_connect_fail(self): with patch.object(Client, '_Client__get_credentials', return_value=False) as mock_method: with self.assertRaises(BadCredentials): c = Client( "http://mydomain.com", "http://mystreamingdomain.com", "my_account", "my_token" )
Add very simple client creator validator
Add very simple client creator validator
Python
mit
MonoCloud/pyoanda,toloco/pyoanda,elyobo/pyoanda
import unittest + from unittest.mock import patch + from ..client import Client + from ..exceptions import BadCredentials + class TestClient(unittest.TestCase): - def setUp(self): + def setUp(self): - pass + pass - def tearDown(self): + def tearDown(self): - pass + pass - def test_connect(self): + def test_connect_pass(self): - pass + with patch.object(Client, '_Client__get_credentials', return_value=True) as mock_method: + c = Client( + "http://mydomain.com", + "http://mystreamingdomain.com", + "my_account", + "my_token" + ) + def test_connect_fail(self): + with patch.object(Client, '_Client__get_credentials', return_value=False) as mock_method: + with self.assertRaises(BadCredentials): + c = Client( + "http://mydomain.com", + "http://mystreamingdomain.com", + "my_account", + "my_token" + )
Add very simple client creator validator
## Code Before: import unittest from ..client import Client class TestClient(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_connect(self): pass ## Instruction: Add very simple client creator validator ## Code After: import unittest from unittest.mock import patch from ..client import Client from ..exceptions import BadCredentials class TestClient(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_connect_pass(self): with patch.object(Client, '_Client__get_credentials', return_value=True) as mock_method: c = Client( "http://mydomain.com", "http://mystreamingdomain.com", "my_account", "my_token" ) def test_connect_fail(self): with patch.object(Client, '_Client__get_credentials', return_value=False) as mock_method: with self.assertRaises(BadCredentials): c = Client( "http://mydomain.com", "http://mystreamingdomain.com", "my_account", "my_token" )
import unittest + from unittest.mock import patch + from ..client import Client + from ..exceptions import BadCredentials + class TestClient(unittest.TestCase): - def setUp(self): ? ^ + def setUp(self): ? ^^^^ - pass + pass - def tearDown(self): ? ^ + def tearDown(self): ? ^^^^ - pass + pass - def test_connect(self): ? ^ + def test_connect_pass(self): ? ^^^^ +++++ - pass + with patch.object(Client, '_Client__get_credentials', return_value=True) as mock_method: + c = Client( + "http://mydomain.com", + "http://mystreamingdomain.com", + "my_account", + "my_token" + ) + def test_connect_fail(self): + with patch.object(Client, '_Client__get_credentials', return_value=False) as mock_method: + with self.assertRaises(BadCredentials): + c = Client( + "http://mydomain.com", + "http://mystreamingdomain.com", + "my_account", + "my_token" + )
350e8bdcb9c6f3eace7839e5dc7270bfeb51e50f
tests/grafana_dashboards/test_config.py
tests/grafana_dashboards/test_config.py
import os from grafana_dashboards.config import Config __author__ = 'Jakub Plichta <[email protected]>' def test_dict(): config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.yaml') config = Config(config_file) assert config.get_config('context') == {'component': 'frontend'} assert config.get_config('unknown') == {}
import os from grafana_dashboards.config import Config __author__ = 'Jakub Plichta <[email protected]>' def test_existent_config_file(): config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.yaml') config = Config(config_file) assert config.get_config('context') == {'component': 'frontend'} assert config.get_config('unknown') == {} def test_nonexistent_config_file(): config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'no_file.yaml') config = Config(config_file) assert config.get_config('context') == {} assert config.get_config('unknown') == {}
Add more tests for Config
Add more tests for Config
Python
apache-2.0
jakubplichta/grafana-dashboard-builder
import os from grafana_dashboards.config import Config __author__ = 'Jakub Plichta <[email protected]>' - def test_dict(): + def test_existent_config_file(): config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.yaml') config = Config(config_file) assert config.get_config('context') == {'component': 'frontend'} assert config.get_config('unknown') == {} + + def test_nonexistent_config_file(): + config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'no_file.yaml') + config = Config(config_file) + + assert config.get_config('context') == {} + assert config.get_config('unknown') == {} +
Add more tests for Config
## Code Before: import os from grafana_dashboards.config import Config __author__ = 'Jakub Plichta <[email protected]>' def test_dict(): config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.yaml') config = Config(config_file) assert config.get_config('context') == {'component': 'frontend'} assert config.get_config('unknown') == {} ## Instruction: Add more tests for Config ## Code After: import os from grafana_dashboards.config import Config __author__ = 'Jakub Plichta <[email protected]>' def test_existent_config_file(): config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.yaml') config = Config(config_file) assert config.get_config('context') == {'component': 'frontend'} assert config.get_config('unknown') == {} def test_nonexistent_config_file(): config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'no_file.yaml') config = Config(config_file) assert config.get_config('context') == {} assert config.get_config('unknown') == {}
import os from grafana_dashboards.config import Config __author__ = 'Jakub Plichta <[email protected]>' - def test_dict(): + def test_existent_config_file(): config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.yaml') config = Config(config_file) assert config.get_config('context') == {'component': 'frontend'} assert config.get_config('unknown') == {} + + + def test_nonexistent_config_file(): + config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'no_file.yaml') + config = Config(config_file) + + assert config.get_config('context') == {} + assert config.get_config('unknown') == {}
92031812b77479fe9a3dbd3ca512ba97e700384e
fusion_index/test/test_lookup.py
fusion_index/test/test_lookup.py
from axiom.store import Store from hypothesis import given from hypothesis.strategies import binary, lists, text, tuples, characters from testtools import TestCase from testtools.matchers import Equals from fusion_index.lookup import LookupEntry def axiom_text(): return text( alphabet=characters( blacklist_categories={'Cs'}, blacklist_characters={u'\x00'}), average_size=5) class LookupTests(TestCase): @given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary()))) def test_inserts(self, values): """ Test inserting and retrieving arbitrary entries. """ s = Store() def _tx(): d = {} for e, t, k, v in values: LookupEntry.set(s, e, t, k, v) d[(e, t, k)] = v self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) for (e, t, k), v in d.iteritems(): self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) s.transact(_tx)
import string from axiom.store import Store from hypothesis import given from hypothesis.strategies import binary, characters, lists, text, tuples from testtools import TestCase from testtools.matchers import Equals from fusion_index.lookup import LookupEntry def axiom_text(): return text( alphabet=characters( blacklist_categories={'Cs'}, blacklist_characters={u'\x00'}), average_size=5) _lower_table = dict( zip(map(ord, string.uppercase.decode('ascii')), map(ord, string.lowercase.decode('ascii')))) def _lower(s): """ Lowercase only ASCII characters, like SQLite NOCASE. """ return s.translate(_lower_table) class LookupTests(TestCase): @given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary()))) def test_inserts(self, values): """ Test inserting and retrieving arbitrary entries. """ s = Store() def _tx(): d = {} for e, t, k, v in values: LookupEntry.set(s, e, t, k, v) d[(_lower(e), _lower(t), _lower(k))] = v self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) for (e, t, k), v in d.iteritems(): self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) s.transact(_tx)
Fix test model to be case-insensitive.
Fix test model to be case-insensitive.
Python
mit
fusionapp/fusion-index
+ import string + from axiom.store import Store from hypothesis import given - from hypothesis.strategies import binary, lists, text, tuples, characters + from hypothesis.strategies import binary, characters, lists, text, tuples from testtools import TestCase from testtools.matchers import Equals from fusion_index.lookup import LookupEntry def axiom_text(): return text( alphabet=characters( blacklist_categories={'Cs'}, blacklist_characters={u'\x00'}), average_size=5) + _lower_table = dict( + zip(map(ord, string.uppercase.decode('ascii')), + map(ord, string.lowercase.decode('ascii')))) + + + def _lower(s): + """ + Lowercase only ASCII characters, like SQLite NOCASE. + """ + return s.translate(_lower_table) + + class LookupTests(TestCase): @given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary()))) def test_inserts(self, values): """ Test inserting and retrieving arbitrary entries. """ s = Store() def _tx(): d = {} for e, t, k, v in values: LookupEntry.set(s, e, t, k, v) - d[(e, t, k)] = v + d[(_lower(e), _lower(t), _lower(k))] = v self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) for (e, t, k), v in d.iteritems(): self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) s.transact(_tx)
Fix test model to be case-insensitive.
## Code Before: from axiom.store import Store from hypothesis import given from hypothesis.strategies import binary, lists, text, tuples, characters from testtools import TestCase from testtools.matchers import Equals from fusion_index.lookup import LookupEntry def axiom_text(): return text( alphabet=characters( blacklist_categories={'Cs'}, blacklist_characters={u'\x00'}), average_size=5) class LookupTests(TestCase): @given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary()))) def test_inserts(self, values): """ Test inserting and retrieving arbitrary entries. """ s = Store() def _tx(): d = {} for e, t, k, v in values: LookupEntry.set(s, e, t, k, v) d[(e, t, k)] = v self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) for (e, t, k), v in d.iteritems(): self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) s.transact(_tx) ## Instruction: Fix test model to be case-insensitive. ## Code After: import string from axiom.store import Store from hypothesis import given from hypothesis.strategies import binary, characters, lists, text, tuples from testtools import TestCase from testtools.matchers import Equals from fusion_index.lookup import LookupEntry def axiom_text(): return text( alphabet=characters( blacklist_categories={'Cs'}, blacklist_characters={u'\x00'}), average_size=5) _lower_table = dict( zip(map(ord, string.uppercase.decode('ascii')), map(ord, string.lowercase.decode('ascii')))) def _lower(s): """ Lowercase only ASCII characters, like SQLite NOCASE. """ return s.translate(_lower_table) class LookupTests(TestCase): @given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary()))) def test_inserts(self, values): """ Test inserting and retrieving arbitrary entries. """ s = Store() def _tx(): d = {} for e, t, k, v in values: LookupEntry.set(s, e, t, k, v) d[(_lower(e), _lower(t), _lower(k))] = v self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) for (e, t, k), v in d.iteritems(): self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) s.transact(_tx)
+ import string + from axiom.store import Store from hypothesis import given - from hypothesis.strategies import binary, lists, text, tuples, characters ? ------------ + from hypothesis.strategies import binary, characters, lists, text, tuples ? ++++++++++++ from testtools import TestCase from testtools.matchers import Equals from fusion_index.lookup import LookupEntry def axiom_text(): return text( alphabet=characters( blacklist_categories={'Cs'}, blacklist_characters={u'\x00'}), average_size=5) + _lower_table = dict( + zip(map(ord, string.uppercase.decode('ascii')), + map(ord, string.lowercase.decode('ascii')))) + + + def _lower(s): + """ + Lowercase only ASCII characters, like SQLite NOCASE. + """ + return s.translate(_lower_table) + + class LookupTests(TestCase): @given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary()))) def test_inserts(self, values): """ Test inserting and retrieving arbitrary entries. """ s = Store() def _tx(): d = {} for e, t, k, v in values: LookupEntry.set(s, e, t, k, v) - d[(e, t, k)] = v + d[(_lower(e), _lower(t), _lower(k))] = v self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) for (e, t, k), v in d.iteritems(): self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) s.transact(_tx)
c244f074615765ba26874c2dba820a95984686bb
os_tasklib/neutron/__init__.py
os_tasklib/neutron/__init__.py
from create_port import CreatePort # noqa from delete_ports import DeletePorts # noqa from show_network import ShowNetwork # noqa
from os_tasklib.neutron.create_port import CreatePort # noqa from os_tasklib.neutron.delete_ports import DeletePorts # noqa from os_tasklib.neutron.show_network import ShowNetwork # noqa
Fix imports on Python 3
Fix imports on Python 3 On Python 3, imports are absolute by default. Because of these invalid imports, tests don't run anymore on Python 3, since tests cannot be loaded. Change-Id: Ib11a09432939df959568de400f60dfe981d0a403
Python
apache-2.0
stackforge/cue,stackforge/cue,openstack/cue,stackforge/cue,openstack/cue,openstack/cue
- from create_port import CreatePort # noqa + from os_tasklib.neutron.create_port import CreatePort # noqa - from delete_ports import DeletePorts # noqa + from os_tasklib.neutron.delete_ports import DeletePorts # noqa - from show_network import ShowNetwork # noqa + from os_tasklib.neutron.show_network import ShowNetwork # noqa
Fix imports on Python 3
## Code Before: from create_port import CreatePort # noqa from delete_ports import DeletePorts # noqa from show_network import ShowNetwork # noqa ## Instruction: Fix imports on Python 3 ## Code After: from os_tasklib.neutron.create_port import CreatePort # noqa from os_tasklib.neutron.delete_ports import DeletePorts # noqa from os_tasklib.neutron.show_network import ShowNetwork # noqa
- from create_port import CreatePort # noqa + from os_tasklib.neutron.create_port import CreatePort # noqa ? +++++++++++++++++++ - from delete_ports import DeletePorts # noqa + from os_tasklib.neutron.delete_ports import DeletePorts # noqa ? +++++++++++++++++++ - from show_network import ShowNetwork # noqa + from os_tasklib.neutron.show_network import ShowNetwork # noqa ? +++++++++++++++++++
139e6acc19040d89f304875c533513c9651f2906
budget_proj/budget_app/filters.py
budget_proj/budget_app/filters.py
from django.db.models import CharField from django_filters import rest_framework as filters from . import models class DefaultFilterMeta: """ Set our default Filter configurations to DRY up the FilterSet Meta classes. """ # Let us filter by all fields except id exclude = ('id',) # We prefer case insensitive matching on CharFields filter_overrides = { CharField: { 'filter_class': filters.CharFilter, 'extra': lambda f: { 'lookup_expr': 'iexact', }, }, } class OcrbFilter(filters.FilterSet): class Meta(DefaultFilterMeta): model = models.OCRB class KpmFilter(filters.FilterSet): class Meta(DefaultFilterMeta): model = models.KPM class BudgetHistoryFilter(filters.FilterSet): class Meta(DefaultFilterMeta): model = models.BudgetHistory class LookupCodeFilter(filters.FilterSet): class Meta(DefaultFilterMeta): model = models.LookupCode
from django.db.models import CharField from django_filters import rest_framework as filters from . import models class CustomFilterBase(filters.FilterSet): """ Extends Filterset to populate help_text from the associated model field. Works with swagger but not the builtin docs. """ @classmethod def filter_for_field(cls, f, name, lookup_expr): result = super().filter_for_field(f, name, lookup_expr) if 'help_text' not in result.extra: result.extra['help_text'] = f.help_text return result class DefaultFilterMeta: """ Defaults for: - enable filtering by all model fields except `id` - ignoring upper/lowercase when on CharFields """ # Let us filter by all fields except id exclude = ('id',) # We prefer case insensitive matching on CharFields filter_overrides = { CharField: { 'filter_class': filters.CharFilter, 'extra': lambda f: { 'lookup_expr': 'iexact', }, }, } class OcrbFilter(CustomFilterBase): class Meta(DefaultFilterMeta): model = models.OCRB class KpmFilter(CustomFilterBase): class Meta(DefaultFilterMeta): model = models.KPM class BudgetHistoryFilter(CustomFilterBase): class Meta(DefaultFilterMeta): model = models.BudgetHistory class LookupCodeFilter(CustomFilterBase): class Meta(DefaultFilterMeta): model = models.LookupCode
Upgrade Filters fields to use docs from model fields
Upgrade Filters fields to use docs from model fields
Python
mit
jimtyhurst/team-budget,hackoregon/team-budget,hackoregon/team-budget,hackoregon/team-budget,jimtyhurst/team-budget,jimtyhurst/team-budget
from django.db.models import CharField from django_filters import rest_framework as filters from . import models + class CustomFilterBase(filters.FilterSet): + """ + Extends Filterset to populate help_text from the associated model field. + Works with swagger but not the builtin docs. + """ + + @classmethod + def filter_for_field(cls, f, name, lookup_expr): + result = super().filter_for_field(f, name, lookup_expr) + + if 'help_text' not in result.extra: + result.extra['help_text'] = f.help_text + return result + class DefaultFilterMeta: """ - Set our default Filter configurations to DRY up the FilterSet Meta classes. + Defaults for: + - enable filtering by all model fields except `id` + - ignoring upper/lowercase when on CharFields """ # Let us filter by all fields except id exclude = ('id',) # We prefer case insensitive matching on CharFields filter_overrides = { CharField: { 'filter_class': filters.CharFilter, 'extra': lambda f: { 'lookup_expr': 'iexact', }, }, } - class OcrbFilter(filters.FilterSet): + class OcrbFilter(CustomFilterBase): class Meta(DefaultFilterMeta): model = models.OCRB - class KpmFilter(filters.FilterSet): + class KpmFilter(CustomFilterBase): class Meta(DefaultFilterMeta): model = models.KPM - class BudgetHistoryFilter(filters.FilterSet): + class BudgetHistoryFilter(CustomFilterBase): class Meta(DefaultFilterMeta): model = models.BudgetHistory - class LookupCodeFilter(filters.FilterSet): + class LookupCodeFilter(CustomFilterBase): class Meta(DefaultFilterMeta): model = models.LookupCode
Upgrade Filters fields to use docs from model fields
## Code Before: from django.db.models import CharField from django_filters import rest_framework as filters from . import models class DefaultFilterMeta: """ Set our default Filter configurations to DRY up the FilterSet Meta classes. """ # Let us filter by all fields except id exclude = ('id',) # We prefer case insensitive matching on CharFields filter_overrides = { CharField: { 'filter_class': filters.CharFilter, 'extra': lambda f: { 'lookup_expr': 'iexact', }, }, } class OcrbFilter(filters.FilterSet): class Meta(DefaultFilterMeta): model = models.OCRB class KpmFilter(filters.FilterSet): class Meta(DefaultFilterMeta): model = models.KPM class BudgetHistoryFilter(filters.FilterSet): class Meta(DefaultFilterMeta): model = models.BudgetHistory class LookupCodeFilter(filters.FilterSet): class Meta(DefaultFilterMeta): model = models.LookupCode ## Instruction: Upgrade Filters fields to use docs from model fields ## Code After: from django.db.models import CharField from django_filters import rest_framework as filters from . import models class CustomFilterBase(filters.FilterSet): """ Extends Filterset to populate help_text from the associated model field. Works with swagger but not the builtin docs. """ @classmethod def filter_for_field(cls, f, name, lookup_expr): result = super().filter_for_field(f, name, lookup_expr) if 'help_text' not in result.extra: result.extra['help_text'] = f.help_text return result class DefaultFilterMeta: """ Defaults for: - enable filtering by all model fields except `id` - ignoring upper/lowercase when on CharFields """ # Let us filter by all fields except id exclude = ('id',) # We prefer case insensitive matching on CharFields filter_overrides = { CharField: { 'filter_class': filters.CharFilter, 'extra': lambda f: { 'lookup_expr': 'iexact', }, }, } class OcrbFilter(CustomFilterBase): class Meta(DefaultFilterMeta): model = models.OCRB class KpmFilter(CustomFilterBase): class Meta(DefaultFilterMeta): model = models.KPM class BudgetHistoryFilter(CustomFilterBase): class Meta(DefaultFilterMeta): model = models.BudgetHistory class LookupCodeFilter(CustomFilterBase): class Meta(DefaultFilterMeta): model = models.LookupCode
from django.db.models import CharField from django_filters import rest_framework as filters from . import models + class CustomFilterBase(filters.FilterSet): + """ + Extends Filterset to populate help_text from the associated model field. + Works with swagger but not the builtin docs. + """ + + @classmethod + def filter_for_field(cls, f, name, lookup_expr): + result = super().filter_for_field(f, name, lookup_expr) + + if 'help_text' not in result.extra: + result.extra['help_text'] = f.help_text + return result + class DefaultFilterMeta: """ - Set our default Filter configurations to DRY up the FilterSet Meta classes. + Defaults for: + - enable filtering by all model fields except `id` + - ignoring upper/lowercase when on CharFields """ # Let us filter by all fields except id exclude = ('id',) # We prefer case insensitive matching on CharFields filter_overrides = { CharField: { 'filter_class': filters.CharFilter, 'extra': lambda f: { 'lookup_expr': 'iexact', }, }, } - class OcrbFilter(filters.FilterSet): ? ^^^ ^^^^ ^ - + class OcrbFilter(CustomFilterBase): ? ^^^ ^^ ^^^ class Meta(DefaultFilterMeta): model = models.OCRB - class KpmFilter(filters.FilterSet): ? ^^^ ^^^^ ^ - + class KpmFilter(CustomFilterBase): ? ^^^ ^^ ^^^ class Meta(DefaultFilterMeta): model = models.KPM - class BudgetHistoryFilter(filters.FilterSet): ? ^^^ ^^^^ ^ - + class BudgetHistoryFilter(CustomFilterBase): ? ^^^ ^^ ^^^ class Meta(DefaultFilterMeta): model = models.BudgetHistory - class LookupCodeFilter(filters.FilterSet): ? ^^^ ^^^^ ^ - + class LookupCodeFilter(CustomFilterBase): ? ^^^ ^^ ^^^ class Meta(DefaultFilterMeta): model = models.LookupCode
116d3837aa817dee6e15bdc24f20eac1e56066dd
buildtools/__init__.py
buildtools/__init__.py
__all__ = ['Config', 'Chdir', 'cmd', 'log','Properties','replace_vars','cmd'] from buildtools.config import Config, Properties, replace_vars from buildtools.os_utils import Chdir, cmd, ENV, BuildEnv from buildtools.bt_logging import log
__all__ = ['Config', 'Chdir', 'cmd', 'log','Properties','replace_vars','cmd','ENV','BuildEnv'] from buildtools.config import Config, Properties, replace_vars from buildtools.os_utils import Chdir, cmd, ENV, BuildEnv from buildtools.bt_logging import log
Add BuildEnv and ENV to __all__
Add BuildEnv and ENV to __all__
Python
mit
N3X15/python-build-tools,N3X15/python-build-tools,N3X15/python-build-tools
- __all__ = ['Config', 'Chdir', 'cmd', 'log','Properties','replace_vars','cmd'] + __all__ = ['Config', 'Chdir', 'cmd', 'log','Properties','replace_vars','cmd','ENV','BuildEnv'] from buildtools.config import Config, Properties, replace_vars from buildtools.os_utils import Chdir, cmd, ENV, BuildEnv from buildtools.bt_logging import log
Add BuildEnv and ENV to __all__
## Code Before: __all__ = ['Config', 'Chdir', 'cmd', 'log','Properties','replace_vars','cmd'] from buildtools.config import Config, Properties, replace_vars from buildtools.os_utils import Chdir, cmd, ENV, BuildEnv from buildtools.bt_logging import log ## Instruction: Add BuildEnv and ENV to __all__ ## Code After: __all__ = ['Config', 'Chdir', 'cmd', 'log','Properties','replace_vars','cmd','ENV','BuildEnv'] from buildtools.config import Config, Properties, replace_vars from buildtools.os_utils import Chdir, cmd, ENV, BuildEnv from buildtools.bt_logging import log
- __all__ = ['Config', 'Chdir', 'cmd', 'log','Properties','replace_vars','cmd'] + __all__ = ['Config', 'Chdir', 'cmd', 'log','Properties','replace_vars','cmd','ENV','BuildEnv'] ? +++++++++++++++++ from buildtools.config import Config, Properties, replace_vars from buildtools.os_utils import Chdir, cmd, ENV, BuildEnv from buildtools.bt_logging import log
f33bf5a99b9bb814fe6da6b7713e87014aae5fdf
src/journal/migrations/0035_journal_xsl.py
src/journal/migrations/0035_journal_xsl.py
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import journal.models class Migration(migrations.Migration): dependencies = [ ('journal', '0034_migrate_issue_types'), ] operations = [ migrations.AddField( model_name='journal', name='xsl', field=models.ForeignKey(default=journal.models.default_xsl, on_delete=django.db.models.deletion.SET_DEFAULT, to='core.XSLFile'), preserve_default=False, ), ]
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import journal.models class Migration(migrations.Migration): dependencies = [ ('journal', '0034_migrate_issue_types'), ('core', '0037_journal_xsl_files'), ] operations = [ migrations.AddField( model_name='journal', name='xsl', field=models.ForeignKey(default=journal.models.default_xsl, on_delete=django.db.models.deletion.SET_DEFAULT, to='core.XSLFile'), preserve_default=False, ), ]
Fix migration tree for journal 0035
Fix migration tree for journal 0035
Python
agpl-3.0
BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import journal.models class Migration(migrations.Migration): dependencies = [ ('journal', '0034_migrate_issue_types'), + ('core', '0037_journal_xsl_files'), + + ] operations = [ migrations.AddField( model_name='journal', name='xsl', field=models.ForeignKey(default=journal.models.default_xsl, on_delete=django.db.models.deletion.SET_DEFAULT, to='core.XSLFile'), preserve_default=False, ), ]
Fix migration tree for journal 0035
## Code Before: from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import journal.models class Migration(migrations.Migration): dependencies = [ ('journal', '0034_migrate_issue_types'), ] operations = [ migrations.AddField( model_name='journal', name='xsl', field=models.ForeignKey(default=journal.models.default_xsl, on_delete=django.db.models.deletion.SET_DEFAULT, to='core.XSLFile'), preserve_default=False, ), ] ## Instruction: Fix migration tree for journal 0035 ## Code After: from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import journal.models class Migration(migrations.Migration): dependencies = [ ('journal', '0034_migrate_issue_types'), ('core', '0037_journal_xsl_files'), ] operations = [ migrations.AddField( model_name='journal', name='xsl', field=models.ForeignKey(default=journal.models.default_xsl, on_delete=django.db.models.deletion.SET_DEFAULT, to='core.XSLFile'), preserve_default=False, ), ]
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import journal.models class Migration(migrations.Migration): dependencies = [ ('journal', '0034_migrate_issue_types'), + ('core', '0037_journal_xsl_files'), + + ] operations = [ migrations.AddField( model_name='journal', name='xsl', field=models.ForeignKey(default=journal.models.default_xsl, on_delete=django.db.models.deletion.SET_DEFAULT, to='core.XSLFile'), preserve_default=False, ), ]
e9aef2b63b1a6036703aa73bc0a6c30bb9425eb6
io_helpers.py
io_helpers.py
import subprocess def speak(say_wa): echo_string = "'{0}'".format(say_wa.replace("'", "'\''")) echo = subprocess.Popen(['echo', echo_string], stdout=subprocess.PIPE) espeak = subprocess.Popen(["espeak", "-v", "english", "--stdout"], stdin=echo.stdout, stdout=subprocess.PIPE) echo.stdout.close() subprocess.Popen(['aplay'], stdin=espeak.stdout) espeak.stdout.close()
import subprocess import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) class Button(object): def __init__(self, button_gpio, callback): self._button_gpio = button_gpio self._callback = callback GPIO.setup(self._button_gpio, GPIO.IN, pull_up_down=GPIO.PUD_UP) def is_pressed(self): return not GPIO.input(self._button_gpio) def listen(self): if self.is_pressed(): self._callback() class LED(object): def __init__(self, led_gpio): self._led_gpio = led_gpio GPIO.setup(self._led_gpio, GPIO.OUT) self.off() # start with it off def on(self): GPIO.output(self._led_gpio, True) def off(self): GPIO.output(self._led_gpio, False) def speak(say_wa): echo_string = "'{0}'".format(say_wa.replace("'", "'\''")) echo = subprocess.Popen(['echo', echo_string], stdout=subprocess.PIPE) espeak = subprocess.Popen(["espeak", "-v", "english", "--stdout"], stdin=echo.stdout, stdout=subprocess.PIPE) echo.stdout.close() subprocess.Popen(['aplay'], stdin=espeak.stdout) espeak.stdout.close()
Add LED and Button classes
Add LED and Button classes
Python
mit
jessstringham/raspberrypi
import subprocess + + import RPi.GPIO as GPIO + + + GPIO.setmode(GPIO.BOARD) + + + class Button(object): + + def __init__(self, button_gpio, callback): + self._button_gpio = button_gpio + self._callback = callback + GPIO.setup(self._button_gpio, GPIO.IN, pull_up_down=GPIO.PUD_UP) + + def is_pressed(self): + return not GPIO.input(self._button_gpio) + + def listen(self): + if self.is_pressed(): + self._callback() + + + class LED(object): + + def __init__(self, led_gpio): + self._led_gpio = led_gpio + GPIO.setup(self._led_gpio, GPIO.OUT) + self.off() # start with it off + + def on(self): + GPIO.output(self._led_gpio, True) + + def off(self): + GPIO.output(self._led_gpio, False) def speak(say_wa): echo_string = "'{0}'".format(say_wa.replace("'", "'\''")) echo = subprocess.Popen(['echo', echo_string], stdout=subprocess.PIPE) espeak = subprocess.Popen(["espeak", "-v", "english", "--stdout"], stdin=echo.stdout, stdout=subprocess.PIPE) echo.stdout.close() subprocess.Popen(['aplay'], stdin=espeak.stdout) espeak.stdout.close()
Add LED and Button classes
## Code Before: import subprocess def speak(say_wa): echo_string = "'{0}'".format(say_wa.replace("'", "'\''")) echo = subprocess.Popen(['echo', echo_string], stdout=subprocess.PIPE) espeak = subprocess.Popen(["espeak", "-v", "english", "--stdout"], stdin=echo.stdout, stdout=subprocess.PIPE) echo.stdout.close() subprocess.Popen(['aplay'], stdin=espeak.stdout) espeak.stdout.close() ## Instruction: Add LED and Button classes ## Code After: import subprocess import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) class Button(object): def __init__(self, button_gpio, callback): self._button_gpio = button_gpio self._callback = callback GPIO.setup(self._button_gpio, GPIO.IN, pull_up_down=GPIO.PUD_UP) def is_pressed(self): return not GPIO.input(self._button_gpio) def listen(self): if self.is_pressed(): self._callback() class LED(object): def __init__(self, led_gpio): self._led_gpio = led_gpio GPIO.setup(self._led_gpio, GPIO.OUT) self.off() # start with it off def on(self): GPIO.output(self._led_gpio, True) def off(self): GPIO.output(self._led_gpio, False) def speak(say_wa): echo_string = "'{0}'".format(say_wa.replace("'", "'\''")) echo = subprocess.Popen(['echo', echo_string], stdout=subprocess.PIPE) espeak = subprocess.Popen(["espeak", "-v", "english", "--stdout"], stdin=echo.stdout, stdout=subprocess.PIPE) echo.stdout.close() subprocess.Popen(['aplay'], stdin=espeak.stdout) espeak.stdout.close()
import subprocess + + import RPi.GPIO as GPIO + + + GPIO.setmode(GPIO.BOARD) + + + class Button(object): + + def __init__(self, button_gpio, callback): + self._button_gpio = button_gpio + self._callback = callback + GPIO.setup(self._button_gpio, GPIO.IN, pull_up_down=GPIO.PUD_UP) + + def is_pressed(self): + return not GPIO.input(self._button_gpio) + + def listen(self): + if self.is_pressed(): + self._callback() + + + class LED(object): + + def __init__(self, led_gpio): + self._led_gpio = led_gpio + GPIO.setup(self._led_gpio, GPIO.OUT) + self.off() # start with it off + + def on(self): + GPIO.output(self._led_gpio, True) + + def off(self): + GPIO.output(self._led_gpio, False) def speak(say_wa): echo_string = "'{0}'".format(say_wa.replace("'", "'\''")) echo = subprocess.Popen(['echo', echo_string], stdout=subprocess.PIPE) espeak = subprocess.Popen(["espeak", "-v", "english", "--stdout"], stdin=echo.stdout, stdout=subprocess.PIPE) echo.stdout.close() subprocess.Popen(['aplay'], stdin=espeak.stdout) espeak.stdout.close()
b077df615eb4354f416877cc2857fb9848e158eb
saleor/core/templatetags/shop.py
saleor/core/templatetags/shop.py
from __future__ import unicode_literals try: from itertools import zip_longest except ImportError: from itertools import izip_longest as zip_longest from django.template import Library from django.utils.http import urlencode register = Library() @register.filter def slice(items, group_size=1): args = [iter(items)] * group_size return (filter(None, group) for group in zip_longest(*args, fillvalue=None)) @register.simple_tag(takes_context=True) def get_sort_by_url(context, field, descending=False): request = context['request'] request_get = request.GET.dict() if descending: request_get['sort_by'] = '-' + field else: request_get['sort_by'] = field return '%s?%s' % (request.path, urlencode(request_get)) @register.simple_tag(takes_context=True) def get_sort_by_url_toggle(context, field): request = context['request'] request_get = request.GET.dict() if field == request_get.get('sort_by'): new_sort_by = '-%s' % field # descending sort else: new_sort_by = field # ascending sort request_get['sort_by'] = new_sort_by return '%s?%s' % (request.path, urlencode(request_get))
from __future__ import unicode_literals try: from itertools import zip_longest except ImportError: from itertools import izip_longest as zip_longest from django.template import Library from django.utils.http import urlencode register = Library() @register.filter def slice(items, group_size=1): args = [iter(items)] * group_size return (filter(None, group) for group in zip_longest(*args, fillvalue=None)) @register.simple_tag(takes_context=True) def get_sort_by_url(context, field, descending=False): request = context['request'] request_get = request.GET.dict() if descending: request_get['sort_by'] = '-' + field else: request_get['sort_by'] = field return '%s?%s' % (request.path, urlencode(request_get)) @register.simple_tag(takes_context=True) def get_sort_by_url_toggle(context, field): request = context['request'] request_get = request.GET.copy() if field == request_get.get('sort_by'): new_sort_by = u'-%s' % field # descending sort else: new_sort_by = field # ascending sort request_get['sort_by'] = new_sort_by return '%s?%s' % (request.path, request_get.urlencode())
Fix get_sort_by_toggle to work with QueryDicts with multiple values
Fix get_sort_by_toggle to work with QueryDicts with multiple values
Python
bsd-3-clause
UITools/saleor,mociepka/saleor,mociepka/saleor,UITools/saleor,maferelo/saleor,maferelo/saleor,UITools/saleor,UITools/saleor,mociepka/saleor,maferelo/saleor,UITools/saleor
from __future__ import unicode_literals try: from itertools import zip_longest except ImportError: from itertools import izip_longest as zip_longest from django.template import Library from django.utils.http import urlencode register = Library() @register.filter def slice(items, group_size=1): args = [iter(items)] * group_size return (filter(None, group) for group in zip_longest(*args, fillvalue=None)) @register.simple_tag(takes_context=True) def get_sort_by_url(context, field, descending=False): request = context['request'] request_get = request.GET.dict() if descending: request_get['sort_by'] = '-' + field else: request_get['sort_by'] = field return '%s?%s' % (request.path, urlencode(request_get)) @register.simple_tag(takes_context=True) def get_sort_by_url_toggle(context, field): request = context['request'] - request_get = request.GET.dict() + request_get = request.GET.copy() if field == request_get.get('sort_by'): - new_sort_by = '-%s' % field # descending sort + new_sort_by = u'-%s' % field # descending sort else: new_sort_by = field # ascending sort request_get['sort_by'] = new_sort_by - return '%s?%s' % (request.path, urlencode(request_get)) + return '%s?%s' % (request.path, request_get.urlencode())
Fix get_sort_by_toggle to work with QueryDicts with multiple values
## Code Before: from __future__ import unicode_literals try: from itertools import zip_longest except ImportError: from itertools import izip_longest as zip_longest from django.template import Library from django.utils.http import urlencode register = Library() @register.filter def slice(items, group_size=1): args = [iter(items)] * group_size return (filter(None, group) for group in zip_longest(*args, fillvalue=None)) @register.simple_tag(takes_context=True) def get_sort_by_url(context, field, descending=False): request = context['request'] request_get = request.GET.dict() if descending: request_get['sort_by'] = '-' + field else: request_get['sort_by'] = field return '%s?%s' % (request.path, urlencode(request_get)) @register.simple_tag(takes_context=True) def get_sort_by_url_toggle(context, field): request = context['request'] request_get = request.GET.dict() if field == request_get.get('sort_by'): new_sort_by = '-%s' % field # descending sort else: new_sort_by = field # ascending sort request_get['sort_by'] = new_sort_by return '%s?%s' % (request.path, urlencode(request_get)) ## Instruction: Fix get_sort_by_toggle to work with QueryDicts with multiple values ## Code After: from __future__ import unicode_literals try: from itertools import zip_longest except ImportError: from itertools import izip_longest as zip_longest from django.template import Library from django.utils.http import urlencode register = Library() @register.filter def slice(items, group_size=1): args = [iter(items)] * group_size return (filter(None, group) for group in zip_longest(*args, fillvalue=None)) @register.simple_tag(takes_context=True) def get_sort_by_url(context, field, descending=False): request = context['request'] request_get = request.GET.dict() if descending: request_get['sort_by'] = '-' + field else: request_get['sort_by'] = field return '%s?%s' % (request.path, urlencode(request_get)) @register.simple_tag(takes_context=True) def get_sort_by_url_toggle(context, field): request = context['request'] request_get = request.GET.copy() if field == request_get.get('sort_by'): new_sort_by = u'-%s' % field # descending sort else: new_sort_by = field # ascending sort request_get['sort_by'] = new_sort_by return '%s?%s' % (request.path, request_get.urlencode())
from __future__ import unicode_literals try: from itertools import zip_longest except ImportError: from itertools import izip_longest as zip_longest from django.template import Library from django.utils.http import urlencode register = Library() @register.filter def slice(items, group_size=1): args = [iter(items)] * group_size return (filter(None, group) for group in zip_longest(*args, fillvalue=None)) @register.simple_tag(takes_context=True) def get_sort_by_url(context, field, descending=False): request = context['request'] request_get = request.GET.dict() if descending: request_get['sort_by'] = '-' + field else: request_get['sort_by'] = field return '%s?%s' % (request.path, urlencode(request_get)) @register.simple_tag(takes_context=True) def get_sort_by_url_toggle(context, field): request = context['request'] - request_get = request.GET.dict() ? -- ^ + request_get = request.GET.copy() ? ^^^ if field == request_get.get('sort_by'): - new_sort_by = '-%s' % field # descending sort + new_sort_by = u'-%s' % field # descending sort ? + else: new_sort_by = field # ascending sort request_get['sort_by'] = new_sort_by - return '%s?%s' % (request.path, urlencode(request_get)) ? ---------- + return '%s?%s' % (request.path, request_get.urlencode()) ? +++++++++++
09225071761ae059c46393d41180b6c37d1b3edc
portal/models/locale.py
portal/models/locale.py
from .coding import Coding from .lazy import lazyprop from ..system_uri import IETF_LANGUAGE_TAG class LocaleConstants(object): """Attributes for built in locales Additions may be defined in persistence files, base values defined within for easy access and testing """ def __iter__(self): for attr in dir(self): if attr.startswith('_'): continue yield getattr(self, attr) @lazyprop def AmericanEnglish(self): Coding( system=IETF_LANGUAGE_TAG, code='en_US', display='American English').add_if_not_found(True) @lazyprop def AustralianEnglish(self): Coding( system=IETF_LANGUAGE_TAG, code='en_AU', display='Australian English').add_if_not_found(True)
from .coding import Coding from .lazy import lazyprop from ..system_uri import IETF_LANGUAGE_TAG class LocaleConstants(object): """Attributes for built in locales Additions may be defined in persistence files, base values defined within for easy access and testing """ def __iter__(self): for attr in dir(self): if attr.startswith('_'): continue yield getattr(self, attr) @lazyprop def AmericanEnglish(self): return Coding( system=IETF_LANGUAGE_TAG, code='en_US', display='American English').add_if_not_found(True) @lazyprop def AustralianEnglish(self): return Coding( system=IETF_LANGUAGE_TAG, code='en_AU', display='Australian English').add_if_not_found(True)
Correct coding error - need to return coding from property function or it'll cache None.
Correct coding error - need to return coding from property function or it'll cache None.
Python
bsd-3-clause
uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal
from .coding import Coding from .lazy import lazyprop from ..system_uri import IETF_LANGUAGE_TAG class LocaleConstants(object): """Attributes for built in locales Additions may be defined in persistence files, base values defined within for easy access and testing """ - def __iter__(self): for attr in dir(self): if attr.startswith('_'): continue yield getattr(self, attr) @lazyprop def AmericanEnglish(self): - Coding( + return Coding( system=IETF_LANGUAGE_TAG, code='en_US', display='American English').add_if_not_found(True) @lazyprop def AustralianEnglish(self): - Coding( + return Coding( system=IETF_LANGUAGE_TAG, code='en_AU', display='Australian English').add_if_not_found(True)
Correct coding error - need to return coding from property function or it'll cache None.
## Code Before: from .coding import Coding from .lazy import lazyprop from ..system_uri import IETF_LANGUAGE_TAG class LocaleConstants(object): """Attributes for built in locales Additions may be defined in persistence files, base values defined within for easy access and testing """ def __iter__(self): for attr in dir(self): if attr.startswith('_'): continue yield getattr(self, attr) @lazyprop def AmericanEnglish(self): Coding( system=IETF_LANGUAGE_TAG, code='en_US', display='American English').add_if_not_found(True) @lazyprop def AustralianEnglish(self): Coding( system=IETF_LANGUAGE_TAG, code='en_AU', display='Australian English').add_if_not_found(True) ## Instruction: Correct coding error - need to return coding from property function or it'll cache None. ## Code After: from .coding import Coding from .lazy import lazyprop from ..system_uri import IETF_LANGUAGE_TAG class LocaleConstants(object): """Attributes for built in locales Additions may be defined in persistence files, base values defined within for easy access and testing """ def __iter__(self): for attr in dir(self): if attr.startswith('_'): continue yield getattr(self, attr) @lazyprop def AmericanEnglish(self): return Coding( system=IETF_LANGUAGE_TAG, code='en_US', display='American English').add_if_not_found(True) @lazyprop def AustralianEnglish(self): return Coding( system=IETF_LANGUAGE_TAG, code='en_AU', display='Australian English').add_if_not_found(True)
from .coding import Coding from .lazy import lazyprop from ..system_uri import IETF_LANGUAGE_TAG class LocaleConstants(object): """Attributes for built in locales Additions may be defined in persistence files, base values defined within for easy access and testing """ - def __iter__(self): for attr in dir(self): if attr.startswith('_'): continue yield getattr(self, attr) @lazyprop def AmericanEnglish(self): - Coding( + return Coding( ? +++++++ system=IETF_LANGUAGE_TAG, code='en_US', display='American English').add_if_not_found(True) @lazyprop def AustralianEnglish(self): - Coding( + return Coding( ? +++++++ system=IETF_LANGUAGE_TAG, code='en_AU', display='Australian English').add_if_not_found(True)
417196332246474b306e81c8d7d2f3a7a5065eb5
senic_hub/backend/subprocess_run.py
senic_hub/backend/subprocess_run.py
"""Provides `subprocess.run()` from Python 3.5+ if available. Otherwise falls back to `subprocess.check_output()`.""" try: from subprocess import run except ImportError: from collections import namedtuple from subprocess import check_output def run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, encoding=None, errors=None): stdout_bytes = check_output(args, stdin=stdin, stderr=stderr, shell=shell, timeout=timeout) Output = namedtuple('Output', ['stdout']) return Output(stdout=stdout_bytes)
"""Provides `subprocess.run()` from Python 3.5+ if available. Otherwise falls back to `subprocess.check_output()`.""" try: from subprocess import run except ImportError: from collections import namedtuple from subprocess import check_output, CalledProcessError def run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, encoding=None, errors=None): try: stdout_bytes = check_output(args, stdin=stdin, stderr=stderr, shell=shell, timeout=timeout) except CalledProcessError as e: if check: raise else: stdout_bytes = e.output Output = namedtuple('Output', ['stdout']) return Output(stdout=stdout_bytes)
Fix throwing error although check arg is false
Fix throwing error although check arg is false
Python
mit
grunskis/senic-hub,grunskis/nuimo-hub-backend,grunskis/senic-hub,grunskis/senic-hub,grunskis/senic-hub,grunskis/senic-hub,grunskis/nuimo-hub-backend,getsenic/senic-hub,grunskis/nuimo-hub-backend,grunskis/nuimo-hub-backend,grunskis/senic-hub,getsenic/senic-hub,grunskis/nuimo-hub-backend
"""Provides `subprocess.run()` from Python 3.5+ if available. Otherwise falls back to `subprocess.check_output()`.""" try: from subprocess import run except ImportError: from collections import namedtuple - from subprocess import check_output + from subprocess import check_output, CalledProcessError def run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, encoding=None, errors=None): + try: - stdout_bytes = check_output(args, stdin=stdin, stderr=stderr, shell=shell, timeout=timeout) + stdout_bytes = check_output(args, stdin=stdin, stderr=stderr, shell=shell, timeout=timeout) + except CalledProcessError as e: + if check: + raise + else: + stdout_bytes = e.output Output = namedtuple('Output', ['stdout']) return Output(stdout=stdout_bytes)
Fix throwing error although check arg is false
## Code Before: """Provides `subprocess.run()` from Python 3.5+ if available. Otherwise falls back to `subprocess.check_output()`.""" try: from subprocess import run except ImportError: from collections import namedtuple from subprocess import check_output def run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, encoding=None, errors=None): stdout_bytes = check_output(args, stdin=stdin, stderr=stderr, shell=shell, timeout=timeout) Output = namedtuple('Output', ['stdout']) return Output(stdout=stdout_bytes) ## Instruction: Fix throwing error although check arg is false ## Code After: """Provides `subprocess.run()` from Python 3.5+ if available. Otherwise falls back to `subprocess.check_output()`.""" try: from subprocess import run except ImportError: from collections import namedtuple from subprocess import check_output, CalledProcessError def run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, encoding=None, errors=None): try: stdout_bytes = check_output(args, stdin=stdin, stderr=stderr, shell=shell, timeout=timeout) except CalledProcessError as e: if check: raise else: stdout_bytes = e.output Output = namedtuple('Output', ['stdout']) return Output(stdout=stdout_bytes)
"""Provides `subprocess.run()` from Python 3.5+ if available. Otherwise falls back to `subprocess.check_output()`.""" try: from subprocess import run except ImportError: from collections import namedtuple - from subprocess import check_output + from subprocess import check_output, CalledProcessError ? ++++++++++++++++++++ def run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, encoding=None, errors=None): + try: - stdout_bytes = check_output(args, stdin=stdin, stderr=stderr, shell=shell, timeout=timeout) + stdout_bytes = check_output(args, stdin=stdin, stderr=stderr, shell=shell, timeout=timeout) ? ++++ + except CalledProcessError as e: + if check: + raise + else: + stdout_bytes = e.output Output = namedtuple('Output', ['stdout']) return Output(stdout=stdout_bytes)
52cb80dd92ceabd7d2efe67c0a89f76cd701283b
statirator/main.py
statirator/main.py
import os import sys def main(): # init is a special case, cause we want to add statirator.core to # INSTALLED_APPS, and have the command picked up. we'll handle it in here if 'init' in sys.argv: from django.conf import settings settings.configure(INSTALLED_APPS=('statirator.core', )) elif 'test' in sys.argv: os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "statirator.test_settings") from django.core import management management.execute_from_command_line() if __name__ == '__main__': main()
import os import sys def main(): if 'test' in sys.argv: os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "statirator.test_settings") else: from django.conf import settings settings.configure(INSTALLED_APPS=('statirator.core', )) from django.core import management management.execute_from_command_line() if __name__ == '__main__': main()
Add statirator.core for all commands except test
Add statirator.core for all commands except test
Python
mit
MeirKriheli/statirator,MeirKriheli/statirator,MeirKriheli/statirator
import os import sys def main(): - # init is a special case, cause we want to add statirator.core to - # INSTALLED_APPS, and have the command picked up. we'll handle it in here - - if 'init' in sys.argv: + if 'test' in sys.argv: + os.environ.setdefault( + "DJANGO_SETTINGS_MODULE", "statirator.test_settings") + else: from django.conf import settings settings.configure(INSTALLED_APPS=('statirator.core', )) - elif 'test' in sys.argv: - os.environ.setdefault( - "DJANGO_SETTINGS_MODULE", "statirator.test_settings") from django.core import management management.execute_from_command_line() if __name__ == '__main__': main()
Add statirator.core for all commands except test
## Code Before: import os import sys def main(): # init is a special case, cause we want to add statirator.core to # INSTALLED_APPS, and have the command picked up. we'll handle it in here if 'init' in sys.argv: from django.conf import settings settings.configure(INSTALLED_APPS=('statirator.core', )) elif 'test' in sys.argv: os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "statirator.test_settings") from django.core import management management.execute_from_command_line() if __name__ == '__main__': main() ## Instruction: Add statirator.core for all commands except test ## Code After: import os import sys def main(): if 'test' in sys.argv: os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "statirator.test_settings") else: from django.conf import settings settings.configure(INSTALLED_APPS=('statirator.core', )) from django.core import management management.execute_from_command_line() if __name__ == '__main__': main()
import os import sys def main(): - # init is a special case, cause we want to add statirator.core to - # INSTALLED_APPS, and have the command picked up. we'll handle it in here - - if 'init' in sys.argv: ? ^^^ + if 'test' in sys.argv: ? ^^^ + os.environ.setdefault( + "DJANGO_SETTINGS_MODULE", "statirator.test_settings") + else: from django.conf import settings settings.configure(INSTALLED_APPS=('statirator.core', )) - elif 'test' in sys.argv: - os.environ.setdefault( - "DJANGO_SETTINGS_MODULE", "statirator.test_settings") from django.core import management management.execute_from_command_line() if __name__ == '__main__': main()
e27088976467dd95ad2672123cb39dd54b78f413
blog/models.py
blog/models.py
from django.db import models from django.template.defaultfilters import slugify from django.core.urlresolvers import reverse_lazy class Category(models.Model): title = models.CharField(max_length=80) class Meta: verbose_name_plural = 'categories' def __unicode__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(editable=False, unique=True) image = models.ImageField(upload_to='posts', blank=True, null=False) created_on = models.DateTimeField(auto_now_add=True) content = models.TextField() categories = models.ManyToManyField(Category) class Meta: ordering = ('created_on',) def __unicode__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return reverse_lazy('blog:show_post', kwargs={'slug': self.slug})
from django.db import models from django.core.exceptions import ValidationError from django.template.defaultfilters import slugify from django.core.urlresolvers import reverse_lazy def validate_no_commas(value): if ',' in value: raise ValidationError('%s contains commas' % value) class Category(models.Model): title = models.CharField(max_length=80, validators=[validate_no_commas]) class Meta: verbose_name_plural = 'categories' def __unicode__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(editable=False, unique=True) image = models.ImageField(upload_to='posts', blank=True, null=False) created_on = models.DateTimeField(auto_now_add=True) content = models.TextField() categories = models.ManyToManyField(Category) class Meta: ordering = ('created_on',) def __unicode__(self): return self.title def save(self, *args, **kwargs): self.slug = self.get_slug() super(Post, self).save(*args, **kwargs) def get_slug(self): return self.slug or slugify(self.title) def get_absolute_url(self): return reverse_lazy('blog:show_post', kwargs={'slug': self.slug})
Add validation in category and get_slug in post
Add validation in category and get_slug in post
Python
mit
jmcomets/jmcomets.github.io
from django.db import models + from django.core.exceptions import ValidationError from django.template.defaultfilters import slugify from django.core.urlresolvers import reverse_lazy + def validate_no_commas(value): + if ',' in value: + raise ValidationError('%s contains commas' % value) + class Category(models.Model): - title = models.CharField(max_length=80) + title = models.CharField(max_length=80, validators=[validate_no_commas]) class Meta: verbose_name_plural = 'categories' def __unicode__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(editable=False, unique=True) image = models.ImageField(upload_to='posts', blank=True, null=False) created_on = models.DateTimeField(auto_now_add=True) content = models.TextField() categories = models.ManyToManyField(Category) class Meta: ordering = ('created_on',) def __unicode__(self): return self.title def save(self, *args, **kwargs): - self.slug = slugify(self.title) + self.slug = self.get_slug() super(Post, self).save(*args, **kwargs) + + def get_slug(self): + return self.slug or slugify(self.title) def get_absolute_url(self): return reverse_lazy('blog:show_post', kwargs={'slug': self.slug})
Add validation in category and get_slug in post
## Code Before: from django.db import models from django.template.defaultfilters import slugify from django.core.urlresolvers import reverse_lazy class Category(models.Model): title = models.CharField(max_length=80) class Meta: verbose_name_plural = 'categories' def __unicode__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(editable=False, unique=True) image = models.ImageField(upload_to='posts', blank=True, null=False) created_on = models.DateTimeField(auto_now_add=True) content = models.TextField() categories = models.ManyToManyField(Category) class Meta: ordering = ('created_on',) def __unicode__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return reverse_lazy('blog:show_post', kwargs={'slug': self.slug}) ## Instruction: Add validation in category and get_slug in post ## Code After: from django.db import models from django.core.exceptions import ValidationError from django.template.defaultfilters import slugify from django.core.urlresolvers import reverse_lazy def validate_no_commas(value): if ',' in value: raise ValidationError('%s contains commas' % value) class Category(models.Model): title = models.CharField(max_length=80, validators=[validate_no_commas]) class Meta: verbose_name_plural = 'categories' def __unicode__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(editable=False, unique=True) image = models.ImageField(upload_to='posts', blank=True, null=False) created_on = models.DateTimeField(auto_now_add=True) content = models.TextField() categories = models.ManyToManyField(Category) class Meta: ordering = ('created_on',) def __unicode__(self): return self.title def save(self, *args, **kwargs): self.slug = self.get_slug() super(Post, self).save(*args, **kwargs) def get_slug(self): return self.slug or slugify(self.title) def get_absolute_url(self): return reverse_lazy('blog:show_post', kwargs={'slug': self.slug})
from django.db import models + from django.core.exceptions import ValidationError from django.template.defaultfilters import slugify from django.core.urlresolvers import reverse_lazy + def validate_no_commas(value): + if ',' in value: + raise ValidationError('%s contains commas' % value) + class Category(models.Model): - title = models.CharField(max_length=80) + title = models.CharField(max_length=80, validators=[validate_no_commas]) class Meta: verbose_name_plural = 'categories' def __unicode__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(editable=False, unique=True) image = models.ImageField(upload_to='posts', blank=True, null=False) created_on = models.DateTimeField(auto_now_add=True) content = models.TextField() categories = models.ManyToManyField(Category) class Meta: ordering = ('created_on',) def __unicode__(self): return self.title def save(self, *args, **kwargs): - self.slug = slugify(self.title) ? -------- ^^ ^ + self.slug = self.get_slug() ? ++ ^^ ^^^ super(Post, self).save(*args, **kwargs) + + def get_slug(self): + return self.slug or slugify(self.title) def get_absolute_url(self): return reverse_lazy('blog:show_post', kwargs={'slug': self.slug})
90ca5fdd66d11cb0d746fb4ab006445ded860d69
modoboa_webmail/__init__.py
modoboa_webmail/__init__.py
"""DMARC related tools for Modoboa.""" from __future__ import unicode_literals from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution(__name__).version except DistributionNotFound: # package is not installed pass default_app_config = "modoboa_webmail.apps.WebmailConfig"
"""DMARC related tools for Modoboa.""" from __future__ import unicode_literals from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution(__name__).version except DistributionNotFound: # package is not installed __version__ = '9.9.9' default_app_config = "modoboa_webmail.apps.WebmailConfig"
Fix crash in development mode with python 3
Fix crash in development mode with python 3
Python
mit
modoboa/modoboa-webmail,modoboa/modoboa-webmail,modoboa/modoboa-webmail
"""DMARC related tools for Modoboa.""" from __future__ import unicode_literals from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution(__name__).version except DistributionNotFound: # package is not installed - pass + __version__ = '9.9.9' default_app_config = "modoboa_webmail.apps.WebmailConfig"
Fix crash in development mode with python 3
## Code Before: """DMARC related tools for Modoboa.""" from __future__ import unicode_literals from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution(__name__).version except DistributionNotFound: # package is not installed pass default_app_config = "modoboa_webmail.apps.WebmailConfig" ## Instruction: Fix crash in development mode with python 3 ## Code After: """DMARC related tools for Modoboa.""" from __future__ import unicode_literals from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution(__name__).version except DistributionNotFound: # package is not installed __version__ = '9.9.9' default_app_config = "modoboa_webmail.apps.WebmailConfig"
"""DMARC related tools for Modoboa.""" from __future__ import unicode_literals from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution(__name__).version except DistributionNotFound: # package is not installed - pass + __version__ = '9.9.9' default_app_config = "modoboa_webmail.apps.WebmailConfig"
842cfc631949831053f4310f586e7b2a83ff7cde
notifications_utils/timezones.py
notifications_utils/timezones.py
from datetime import datetime import pytz from dateutil import parser local_timezone = pytz.timezone("Europe/London") def utc_string_to_aware_gmt_datetime(date): """ Date can either be a string or a naive datetime """ if not isinstance(date, datetime): date = parser.parse(date) forced_utc = date.replace(tzinfo=pytz.utc) return forced_utc.astimezone(local_timezone) def convert_utc_to_bst(utc_dt): return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None) def convert_bst_to_utc(date): return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
from datetime import datetime import pytz from dateutil import parser local_timezone = pytz.timezone("Europe/London") def utc_string_to_aware_gmt_datetime(date): """ Date can either be a string, naive UTC datetime or an aware UTC datetime Returns an aware London datetime, essentially the time you'd see on your clock """ if not isinstance(date, datetime): date = parser.parse(date) forced_utc = date.replace(tzinfo=pytz.utc) return forced_utc.astimezone(local_timezone) def convert_utc_to_bst(utc_dt): """ Takes a naive UTC datetime and returns a naive London datetime """ return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None) def convert_bst_to_utc(date): """ Takes a naive London datetime and returns a naive UTC datetime """ return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
Add descriptions to timezone functions
Add descriptions to timezone functions These are quite complex things and benefit from having better descriptions. Note, we weren't quite happy with the names of the functions. `aware_gmt_datetime` should really be `aware_london_datetime` and the other two functions could have more verbose names (mentioning that they convert from naive to naive) but we decided not to change these as will involve lots of changes around the codebase.
Python
mit
alphagov/notifications-utils
from datetime import datetime import pytz from dateutil import parser local_timezone = pytz.timezone("Europe/London") def utc_string_to_aware_gmt_datetime(date): """ - Date can either be a string or a naive datetime + Date can either be a string, naive UTC datetime or an aware UTC datetime + Returns an aware London datetime, essentially the time you'd see on your clock """ if not isinstance(date, datetime): date = parser.parse(date) forced_utc = date.replace(tzinfo=pytz.utc) return forced_utc.astimezone(local_timezone) def convert_utc_to_bst(utc_dt): + """ + Takes a naive UTC datetime and returns a naive London datetime + """ return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None) def convert_bst_to_utc(date): + """ + Takes a naive London datetime and returns a naive UTC datetime + """ return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
Add descriptions to timezone functions
## Code Before: from datetime import datetime import pytz from dateutil import parser local_timezone = pytz.timezone("Europe/London") def utc_string_to_aware_gmt_datetime(date): """ Date can either be a string or a naive datetime """ if not isinstance(date, datetime): date = parser.parse(date) forced_utc = date.replace(tzinfo=pytz.utc) return forced_utc.astimezone(local_timezone) def convert_utc_to_bst(utc_dt): return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None) def convert_bst_to_utc(date): return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None) ## Instruction: Add descriptions to timezone functions ## Code After: from datetime import datetime import pytz from dateutil import parser local_timezone = pytz.timezone("Europe/London") def utc_string_to_aware_gmt_datetime(date): """ Date can either be a string, naive UTC datetime or an aware UTC datetime Returns an aware London datetime, essentially the time you'd see on your clock """ if not isinstance(date, datetime): date = parser.parse(date) forced_utc = date.replace(tzinfo=pytz.utc) return forced_utc.astimezone(local_timezone) def convert_utc_to_bst(utc_dt): """ Takes a naive UTC datetime and returns a naive London datetime """ return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None) def convert_bst_to_utc(date): """ Takes a naive London datetime and returns a naive UTC datetime """ return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
from datetime import datetime import pytz from dateutil import parser local_timezone = pytz.timezone("Europe/London") def utc_string_to_aware_gmt_datetime(date): """ - Date can either be a string or a naive datetime + Date can either be a string, naive UTC datetime or an aware UTC datetime + Returns an aware London datetime, essentially the time you'd see on your clock """ if not isinstance(date, datetime): date = parser.parse(date) forced_utc = date.replace(tzinfo=pytz.utc) return forced_utc.astimezone(local_timezone) def convert_utc_to_bst(utc_dt): + """ + Takes a naive UTC datetime and returns a naive London datetime + """ return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None) def convert_bst_to_utc(date): + """ + Takes a naive London datetime and returns a naive UTC datetime + """ return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
13ec50a7e2187edb03174ed4a9dbf8767f4c6ad4
version.py
version.py
major = 0 minor=0 patch=0 branch="dev" timestamp=1376412824.91
major = 0 minor=0 patch=8 branch="master" timestamp=1376412892.53
Tag commit for v0.0.8-master generated by gitmake.py
Tag commit for v0.0.8-master generated by gitmake.py
Python
mit
ryansturmer/gitmake
major = 0 minor=0 - patch=0 + patch=8 - branch="dev" + branch="master" - timestamp=1376412824.91 + timestamp=1376412892.53
Tag commit for v0.0.8-master generated by gitmake.py
## Code Before: major = 0 minor=0 patch=0 branch="dev" timestamp=1376412824.91 ## Instruction: Tag commit for v0.0.8-master generated by gitmake.py ## Code After: major = 0 minor=0 patch=8 branch="master" timestamp=1376412892.53
major = 0 minor=0 - patch=0 ? ^ + patch=8 ? ^ - branch="dev" + branch="master" - timestamp=1376412824.91 ? - ^^ + timestamp=1376412892.53 ? + ^^
e0f4135b90a3f920db3a14b14b70e0e57df3d717
setup.py
setup.py
from distutils.core import setup, Extension import sys import commands setup ( name = "kerberos", version = "1.0", description = "Kerberos high-level interface", ext_modules = [ Extension( "kerberos", extra_link_args = commands.getoutput("krb5-config --libs gssapi").split(), extra_compile_args = commands.getoutput("krb5-config --cflags gssapi").split(), sources = [ "src/kerberos.c", "src/kerberosbasic.c", "src/kerberosgss.c", "src/base64.c" ], ), ], )
from distutils.core import setup, Extension import sys if sys.version_info < (3,0): import commands as subprocess else: import subprocess setup ( name = "kerberos", version = "1.0", description = "Kerberos high-level interface", ext_modules = [ Extension( "kerberos", extra_link_args = subprocess.getoutput("krb5-config --libs gssapi").split(), extra_compile_args = subprocess.getoutput("krb5-config --cflags gssapi").split(), sources = [ "src/kerberos.c", "src/kerberosbasic.c", "src/kerberosgss.c", "src/base64.c" ], ), ], )
Build for either python 2 or python 3
Build for either python 2 or python 3
Python
apache-2.0
admiyo/PyKerberos,admiyo/PyKerberos,admiyo/PyKerberos
from distutils.core import setup, Extension import sys - import commands + + if sys.version_info < (3,0): + import commands as subprocess + else: + import subprocess setup ( name = "kerberos", version = "1.0", description = "Kerberos high-level interface", ext_modules = [ Extension( "kerberos", - extra_link_args = commands.getoutput("krb5-config --libs gssapi").split(), + extra_link_args = subprocess.getoutput("krb5-config --libs gssapi").split(), - extra_compile_args = commands.getoutput("krb5-config --cflags gssapi").split(), + extra_compile_args = subprocess.getoutput("krb5-config --cflags gssapi").split(), sources = [ "src/kerberos.c", "src/kerberosbasic.c", "src/kerberosgss.c", "src/base64.c" ], ), ], )
Build for either python 2 or python 3
## Code Before: from distutils.core import setup, Extension import sys import commands setup ( name = "kerberos", version = "1.0", description = "Kerberos high-level interface", ext_modules = [ Extension( "kerberos", extra_link_args = commands.getoutput("krb5-config --libs gssapi").split(), extra_compile_args = commands.getoutput("krb5-config --cflags gssapi").split(), sources = [ "src/kerberos.c", "src/kerberosbasic.c", "src/kerberosgss.c", "src/base64.c" ], ), ], ) ## Instruction: Build for either python 2 or python 3 ## Code After: from distutils.core import setup, Extension import sys if sys.version_info < (3,0): import commands as subprocess else: import subprocess setup ( name = "kerberos", version = "1.0", description = "Kerberos high-level interface", ext_modules = [ Extension( "kerberos", extra_link_args = subprocess.getoutput("krb5-config --libs gssapi").split(), extra_compile_args = subprocess.getoutput("krb5-config --cflags gssapi").split(), sources = [ "src/kerberos.c", "src/kerberosbasic.c", "src/kerberosgss.c", "src/base64.c" ], ), ], )
from distutils.core import setup, Extension import sys - import commands + + if sys.version_info < (3,0): + import commands as subprocess + else: + import subprocess setup ( name = "kerberos", version = "1.0", description = "Kerberos high-level interface", ext_modules = [ Extension( "kerberos", - extra_link_args = commands.getoutput("krb5-config --libs gssapi").split(), ? ^^^^^^ + extra_link_args = subprocess.getoutput("krb5-config --libs gssapi").split(), ? ++++++ ^^ - extra_compile_args = commands.getoutput("krb5-config --cflags gssapi").split(), ? ^^^^^^ + extra_compile_args = subprocess.getoutput("krb5-config --cflags gssapi").split(), ? ++++++ ^^ sources = [ "src/kerberos.c", "src/kerberosbasic.c", "src/kerberosgss.c", "src/base64.c" ], ), ], )
902e4500b57d54a80a586b0843ff3a68706a5c58
setup.py
setup.py
from distutils.core import setup from Cython.Build import cythonize #from Cython.Compiler.Options import directive_defaults #directive_defaults['profile'] = True setup( name = "Pentacular", ext_modules = cythonize( [ 'board_strip.pyx', 'length_lookup_table.pyx', 'priority_filter.py', 'budget_searcher.py', 'utility_calculator.py', 'utility_stats.py', 'direction_strips.py', 'alpha_beta.py', 'ab_state.py', 'game_state.py', 'board.py', 'ai_player.py', ], # extra_compile_args=["-O3"], # Is this doing anything? ) )
from distutils.core import setup from Cython.Build import cythonize #from Cython.Compiler.Options import directive_defaults #directive_defaults['profile'] = True cy_modules = [ 'board_strip.pyx', 'length_lookup_table.pyx', ] if False: cy_modules.extend([ 'priority_filter.py', 'budget_searcher.py', 'utility_calculator.py', 'utility_stats.py', 'direction_strips.py', 'alpha_beta.py', 'ab_state.py', 'game_state.py', 'board.py', 'ai_player.py', ]) setup( name = "Pentacular", ext_modules = cythonize( [ 'board_strip.pyx', 'length_lookup_table.pyx', ], # extra_compile_args=["-O3"], # Is this doing anything? ) )
Remove py modules causing GUI lag
Remove py modules causing GUI lag
Python
mit
cropleyb/pentai,cropleyb/pentai,cropleyb/pentai
from distutils.core import setup from Cython.Build import cythonize #from Cython.Compiler.Options import directive_defaults #directive_defaults['profile'] = True + cy_modules = [ + 'board_strip.pyx', + 'length_lookup_table.pyx', + ] + if False: + cy_modules.extend([ + 'priority_filter.py', + 'budget_searcher.py', + 'utility_calculator.py', + 'utility_stats.py', + 'direction_strips.py', + 'alpha_beta.py', + 'ab_state.py', + 'game_state.py', + 'board.py', + 'ai_player.py', + ]) setup( name = "Pentacular", ext_modules = cythonize( [ 'board_strip.pyx', 'length_lookup_table.pyx', - 'priority_filter.py', - 'budget_searcher.py', - 'utility_calculator.py', - 'utility_stats.py', - 'direction_strips.py', - 'alpha_beta.py', - 'ab_state.py', - 'game_state.py', - 'board.py', - 'ai_player.py', ], # extra_compile_args=["-O3"], # Is this doing anything? ) )
Remove py modules causing GUI lag
## Code Before: from distutils.core import setup from Cython.Build import cythonize #from Cython.Compiler.Options import directive_defaults #directive_defaults['profile'] = True setup( name = "Pentacular", ext_modules = cythonize( [ 'board_strip.pyx', 'length_lookup_table.pyx', 'priority_filter.py', 'budget_searcher.py', 'utility_calculator.py', 'utility_stats.py', 'direction_strips.py', 'alpha_beta.py', 'ab_state.py', 'game_state.py', 'board.py', 'ai_player.py', ], # extra_compile_args=["-O3"], # Is this doing anything? ) ) ## Instruction: Remove py modules causing GUI lag ## Code After: from distutils.core import setup from Cython.Build import cythonize #from Cython.Compiler.Options import directive_defaults #directive_defaults['profile'] = True cy_modules = [ 'board_strip.pyx', 'length_lookup_table.pyx', ] if False: cy_modules.extend([ 'priority_filter.py', 'budget_searcher.py', 'utility_calculator.py', 'utility_stats.py', 'direction_strips.py', 'alpha_beta.py', 'ab_state.py', 'game_state.py', 'board.py', 'ai_player.py', ]) setup( name = "Pentacular", ext_modules = cythonize( [ 'board_strip.pyx', 'length_lookup_table.pyx', ], # extra_compile_args=["-O3"], # Is this doing anything? ) )
from distutils.core import setup from Cython.Build import cythonize #from Cython.Compiler.Options import directive_defaults #directive_defaults['profile'] = True + cy_modules = [ + 'board_strip.pyx', + 'length_lookup_table.pyx', + ] + if False: + cy_modules.extend([ + 'priority_filter.py', + 'budget_searcher.py', + 'utility_calculator.py', + 'utility_stats.py', + 'direction_strips.py', + 'alpha_beta.py', + 'ab_state.py', + 'game_state.py', + 'board.py', + 'ai_player.py', + ]) setup( name = "Pentacular", ext_modules = cythonize( [ 'board_strip.pyx', 'length_lookup_table.pyx', - 'priority_filter.py', - 'budget_searcher.py', - 'utility_calculator.py', - 'utility_stats.py', - 'direction_strips.py', - 'alpha_beta.py', - 'ab_state.py', - 'game_state.py', - 'board.py', - 'ai_player.py', ], # extra_compile_args=["-O3"], # Is this doing anything? ) )
1270c31dcf35c17a26a282605d2e04ffd2e8d985
tests/test_ftp.py
tests/test_ftp.py
from wex.url import URL expected_lines = [ b"FTP/1.0 200 OK\r\n", b"X-wex-url: ftp://anonymous:[email protected]/pub/site/README\r\n", b"\r\n", b"This directory contains files related to the operation of the\n", ] expected_content = b''.join(expected_lines) url = 'ftp://anonymous:[email protected]/pub/site/README' def test_ftp_read(): readables = list(URL(url).get()) assert len(readables) == 1 r0 = readables[0] chunk = r0.read(2**16) content = chunk chunk = r0.read(2**16) assert not chunk assert content.startswith(expected_content) def test_ftp_readline(): readables = list(URL(url).get()) assert len(readables) == 1 r0 = readables[0] first_four_lines = [r0.readline() for i in range(4)] assert first_four_lines == expected_lines[:4]
from wex.url import URL url = 'ftp://anonymous:[email protected]/1KB.zip' expected_lines = [ b"FTP/1.0 200 OK\r\n", b"X-wex-url: " + url + "\r\n", b"\r\n", ] expected_content = b''.join(expected_lines) def test_ftp_read(): readables = list(URL(url).get()) assert len(readables) == 1 r0 = readables[0] chunk = r0.read(2**16) content = chunk chunk = r0.read(2**16) assert not chunk assert content.startswith(expected_content) def test_ftp_readline(): readables = list(URL(url).get()) assert len(readables) == 1 n = 3 r0 = readables[0] first_few_lines = [r0.readline() for i in range(n)] assert first_few_lines == expected_lines[:n]
Switch ftp server now ftp.kernel.org closed
Switch ftp server now ftp.kernel.org closed
Python
bsd-3-clause
eBay/wextracto,gilessbrown/wextracto,gilessbrown/wextracto,eBay/wextracto
from wex.url import URL + + url = 'ftp://anonymous:[email protected]/1KB.zip' expected_lines = [ b"FTP/1.0 200 OK\r\n", - b"X-wex-url: ftp://anonymous:[email protected]/pub/site/README\r\n", + b"X-wex-url: " + url + "\r\n", b"\r\n", - b"This directory contains files related to the operation of the\n", ] expected_content = b''.join(expected_lines) - - url = 'ftp://anonymous:[email protected]/pub/site/README' def test_ftp_read(): readables = list(URL(url).get()) assert len(readables) == 1 r0 = readables[0] chunk = r0.read(2**16) content = chunk chunk = r0.read(2**16) assert not chunk assert content.startswith(expected_content) def test_ftp_readline(): readables = list(URL(url).get()) assert len(readables) == 1 + n = 3 r0 = readables[0] - first_four_lines = [r0.readline() for i in range(4)] + first_few_lines = [r0.readline() for i in range(n)] - assert first_four_lines == expected_lines[:4] + assert first_few_lines == expected_lines[:n]
Switch ftp server now ftp.kernel.org closed
## Code Before: from wex.url import URL expected_lines = [ b"FTP/1.0 200 OK\r\n", b"X-wex-url: ftp://anonymous:[email protected]/pub/site/README\r\n", b"\r\n", b"This directory contains files related to the operation of the\n", ] expected_content = b''.join(expected_lines) url = 'ftp://anonymous:[email protected]/pub/site/README' def test_ftp_read(): readables = list(URL(url).get()) assert len(readables) == 1 r0 = readables[0] chunk = r0.read(2**16) content = chunk chunk = r0.read(2**16) assert not chunk assert content.startswith(expected_content) def test_ftp_readline(): readables = list(URL(url).get()) assert len(readables) == 1 r0 = readables[0] first_four_lines = [r0.readline() for i in range(4)] assert first_four_lines == expected_lines[:4] ## Instruction: Switch ftp server now ftp.kernel.org closed ## Code After: from wex.url import URL url = 'ftp://anonymous:[email protected]/1KB.zip' expected_lines = [ b"FTP/1.0 200 OK\r\n", b"X-wex-url: " + url + "\r\n", b"\r\n", ] expected_content = b''.join(expected_lines) def test_ftp_read(): readables = list(URL(url).get()) assert len(readables) == 1 r0 = readables[0] chunk = r0.read(2**16) content = chunk chunk = r0.read(2**16) assert not chunk assert content.startswith(expected_content) def test_ftp_readline(): readables = list(URL(url).get()) assert len(readables) == 1 n = 3 r0 = readables[0] first_few_lines = [r0.readline() for i in range(n)] assert first_few_lines == expected_lines[:n]
from wex.url import URL + + url = 'ftp://anonymous:[email protected]/1KB.zip' expected_lines = [ b"FTP/1.0 200 OK\r\n", - b"X-wex-url: ftp://anonymous:[email protected]/pub/site/README\r\n", + b"X-wex-url: " + url + "\r\n", b"\r\n", - b"This directory contains files related to the operation of the\n", ] expected_content = b''.join(expected_lines) - - url = 'ftp://anonymous:[email protected]/pub/site/README' def test_ftp_read(): readables = list(URL(url).get()) assert len(readables) == 1 r0 = readables[0] chunk = r0.read(2**16) content = chunk chunk = r0.read(2**16) assert not chunk assert content.startswith(expected_content) def test_ftp_readline(): readables = list(URL(url).get()) assert len(readables) == 1 + n = 3 r0 = readables[0] - first_four_lines = [r0.readline() for i in range(4)] ? ^^^ ^ + first_few_lines = [r0.readline() for i in range(n)] ? ^^ ^ - assert first_four_lines == expected_lines[:4] ? ^^^ ^ + assert first_few_lines == expected_lines[:n] ? ^^ ^
bcaf887ccad40adf2cb09627c12f2a3e1b4b006d
redis_cache/client/__init__.py
redis_cache/client/__init__.py
from .default import DefaultClient from .sharded import ShardClient from .herd import HerdClient from .experimental import SimpleFailoverClient from .sentinel import SentinelClient __all__ = ['DefaultClient', 'ShardClient', 'HerdClient', 'SimpleFailoverClient', 'SentinelClient']
import warnings from .default import DefaultClient from .sharded import ShardClient from .herd import HerdClient from .experimental import SimpleFailoverClient __all__ = ['DefaultClient', 'ShardClient', 'HerdClient', 'SimpleFailoverClient',] try: from .sentinel import SentinelClient __all__.append("SentinelClient") except ImportError: warnings.warn("sentinel client is unsuported with redis-py<2.9", RuntimeWarning)
Disable Sentinel client with redis-py < 2.9
Disable Sentinel client with redis-py < 2.9
Python
bsd-3-clause
zl352773277/django-redis,smahs/django-redis,yanheng/django-redis,lucius-feng/django-redis,GetAmbassador/django-redis
+ + import warnings from .default import DefaultClient from .sharded import ShardClient from .herd import HerdClient from .experimental import SimpleFailoverClient - from .sentinel import SentinelClient + __all__ = ['DefaultClient', 'ShardClient', - 'HerdClient', 'SimpleFailoverClient', + 'HerdClient', 'SimpleFailoverClient',] - 'SentinelClient'] + try: + from .sentinel import SentinelClient + __all__.append("SentinelClient") + except ImportError: + warnings.warn("sentinel client is unsuported with redis-py<2.9", + RuntimeWarning) + +
Disable Sentinel client with redis-py < 2.9
## Code Before: from .default import DefaultClient from .sharded import ShardClient from .herd import HerdClient from .experimental import SimpleFailoverClient from .sentinel import SentinelClient __all__ = ['DefaultClient', 'ShardClient', 'HerdClient', 'SimpleFailoverClient', 'SentinelClient'] ## Instruction: Disable Sentinel client with redis-py < 2.9 ## Code After: import warnings from .default import DefaultClient from .sharded import ShardClient from .herd import HerdClient from .experimental import SimpleFailoverClient __all__ = ['DefaultClient', 'ShardClient', 'HerdClient', 'SimpleFailoverClient',] try: from .sentinel import SentinelClient __all__.append("SentinelClient") except ImportError: warnings.warn("sentinel client is unsuported with redis-py<2.9", RuntimeWarning)
+ + import warnings from .default import DefaultClient from .sharded import ShardClient from .herd import HerdClient from .experimental import SimpleFailoverClient - from .sentinel import SentinelClient + __all__ = ['DefaultClient', 'ShardClient', - 'HerdClient', 'SimpleFailoverClient', + 'HerdClient', 'SimpleFailoverClient',] ? + - 'SentinelClient'] + + try: + from .sentinel import SentinelClient + __all__.append("SentinelClient") + except ImportError: + warnings.warn("sentinel client is unsuported with redis-py<2.9", + RuntimeWarning) +
34072121b9fc6d1b0ec740cb3d22034971ef0141
comics/search/urls.py
comics/search/urls.py
from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^', include('haystack.urls')), )
from django.conf.urls.defaults import * from haystack.views import SearchView from haystack.forms import SearchForm urlpatterns = patterns('', url(r'^$', SearchView(form_class=SearchForm), name='haystack_search'), )
Convert to simpler search form
Convert to simpler search form
Python
agpl-3.0
datagutten/comics,klette/comics,jodal/comics,datagutten/comics,jodal/comics,klette/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,klette/comics
from django.conf.urls.defaults import * + from haystack.views import SearchView + from haystack.forms import SearchForm urlpatterns = patterns('', - (r'^', include('haystack.urls')), + url(r'^$', SearchView(form_class=SearchForm), name='haystack_search'), )
Convert to simpler search form
## Code Before: from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^', include('haystack.urls')), ) ## Instruction: Convert to simpler search form ## Code After: from django.conf.urls.defaults import * from haystack.views import SearchView from haystack.forms import SearchForm urlpatterns = patterns('', url(r'^$', SearchView(form_class=SearchForm), name='haystack_search'), )
from django.conf.urls.defaults import * + from haystack.views import SearchView + from haystack.forms import SearchForm urlpatterns = patterns('', - (r'^', include('haystack.urls')), + url(r'^$', SearchView(form_class=SearchForm), name='haystack_search'), )
9eafc01ef8260a313f2e214924cfd5bda706c1c0
cactusbot/handler.py
cactusbot/handler.py
"""Handle handlers.""" import logging class Handlers(object): """Handlers.""" def __init__(self, *handlers): self.handlers = handlers def handle(self, event, packet): """Handle incoming data.""" for handler in self.handlers: if hasattr(handler, "on_" + event): response = "" try: response = getattr(handler, "on_" + event)(packet) except Exception as e: print("Uh oh!") print(e) else: if response is StopIteration: break yield response class Handler(object): """Handler.""" def __init__(self): self.logger = logging.getLogger(__name__)
"""Handle handlers.""" import logging class Handlers(object): """Handlers.""" def __init__(self, *handlers): self.logger = logging.getLogger(__name__) self.handlers = handlers def handle(self, event, packet): """Handle incoming data.""" for handler in self.handlers: if hasattr(handler, "on_" + event): response = "" try: response = getattr(handler, "on_" + event)(packet) except Exception as e: self.logger.warning(e) else: if response is StopIteration: break yield response class Handler(object): """Handler.""" def __init__(self): self.logger = logging.getLogger(__name__)
Add exception logging to Handlers
Add exception logging to Handlers
Python
mit
CactusDev/CactusBot
"""Handle handlers.""" import logging + class Handlers(object): """Handlers.""" def __init__(self, *handlers): + + self.logger = logging.getLogger(__name__) + self.handlers = handlers def handle(self, event, packet): """Handle incoming data.""" for handler in self.handlers: if hasattr(handler, "on_" + event): response = "" try: response = getattr(handler, "on_" + event)(packet) except Exception as e: + self.logger.warning(e) - print("Uh oh!") - print(e) else: if response is StopIteration: break yield response class Handler(object): """Handler.""" - + def __init__(self): self.logger = logging.getLogger(__name__)
Add exception logging to Handlers
## Code Before: """Handle handlers.""" import logging class Handlers(object): """Handlers.""" def __init__(self, *handlers): self.handlers = handlers def handle(self, event, packet): """Handle incoming data.""" for handler in self.handlers: if hasattr(handler, "on_" + event): response = "" try: response = getattr(handler, "on_" + event)(packet) except Exception as e: print("Uh oh!") print(e) else: if response is StopIteration: break yield response class Handler(object): """Handler.""" def __init__(self): self.logger = logging.getLogger(__name__) ## Instruction: Add exception logging to Handlers ## Code After: """Handle handlers.""" import logging class Handlers(object): """Handlers.""" def __init__(self, *handlers): self.logger = logging.getLogger(__name__) self.handlers = handlers def handle(self, event, packet): """Handle incoming data.""" for handler in self.handlers: if hasattr(handler, "on_" + event): response = "" try: response = getattr(handler, "on_" + event)(packet) except Exception as e: self.logger.warning(e) else: if response is StopIteration: break yield response class Handler(object): """Handler.""" def __init__(self): self.logger = logging.getLogger(__name__)
"""Handle handlers.""" import logging + class Handlers(object): """Handlers.""" def __init__(self, *handlers): + + self.logger = logging.getLogger(__name__) + self.handlers = handlers def handle(self, event, packet): """Handle incoming data.""" for handler in self.handlers: if hasattr(handler, "on_" + event): response = "" try: response = getattr(handler, "on_" + event)(packet) except Exception as e: + self.logger.warning(e) - print("Uh oh!") - print(e) else: if response is StopIteration: break yield response class Handler(object): """Handler.""" - + def __init__(self): self.logger = logging.getLogger(__name__)
4ee409a5635b1d027f5d3c68fb2a62f554c9c801
ib_insync/__init__.py
ib_insync/__init__.py
import sys import importlib from .version import __version__, __version_info__ # noqa from . import util if sys.version_info < (3, 6, 0): raise RuntimeError('ib_insync requires Python 3.6 or higher') try: import ibapi except ImportError: raise RuntimeError( 'IB API from http://interactivebrokers.github.io is required') if util.ibapiVersionInfo() < (9, 73, 6): raise RuntimeError( f'Old version ({ibapi.__version__}) of ibapi package detected. ' 'The newest version from http://interactivebrokers.github.io ' 'is required') from .version import __version__, __version_info__ # noqa from .objects import * # noqa from .event import * # noqa from .contract import * # noqa from .order import * # noqa from .ticker import * # noqa from .ib import * # noqa from .client import * # noqa from .wrapper import * # noqa from .flexreport import * # noqa from .ibcontroller import * # noqa from . import util # noqa __all__ = ['util'] for _m in ( objects, event, contract, order, ticker, ib, # noqa client, wrapper, flexreport, ibcontroller): # noqa __all__ += _m.__all__ del sys del importlib del ibapi
import sys import importlib if sys.version_info < (3, 6, 0): raise RuntimeError('ib_insync requires Python 3.6 or higher') try: import ibapi except ImportError: raise RuntimeError( 'IB API from http://interactivebrokers.github.io is required') from . import util # noqa if util.ibapiVersionInfo() < (9, 73, 6): raise RuntimeError( f'Old version ({ibapi.__version__}) of ibapi package detected. ' 'The newest version from http://interactivebrokers.github.io ' 'is required') from .version import __version__, __version_info__ # noqa from .objects import * # noqa from .event import * # noqa from .contract import * # noqa from .order import * # noqa from .ticker import * # noqa from .ib import * # noqa from .client import * # noqa from .wrapper import * # noqa from .flexreport import * # noqa from .ibcontroller import * # noqa __all__ = ['util'] for _m in ( objects, event, contract, order, ticker, ib, # noqa client, wrapper, flexreport, ibcontroller): # noqa __all__ += _m.__all__ del sys del importlib del ibapi
Fix explicit check for presence of ibapi package
Fix explicit check for presence of ibapi package
Python
bsd-2-clause
erdewit/ib_insync,erdewit/ib_insync
import sys import importlib - - from .version import __version__, __version_info__ # noqa - from . import util - if sys.version_info < (3, 6, 0): raise RuntimeError('ib_insync requires Python 3.6 or higher') try: import ibapi except ImportError: raise RuntimeError( 'IB API from http://interactivebrokers.github.io is required') + from . import util # noqa if util.ibapiVersionInfo() < (9, 73, 6): raise RuntimeError( f'Old version ({ibapi.__version__}) of ibapi package detected. ' 'The newest version from http://interactivebrokers.github.io ' 'is required') - from .version import __version__, __version_info__ # noqa from .objects import * # noqa from .event import * # noqa from .contract import * # noqa from .order import * # noqa from .ticker import * # noqa from .ib import * # noqa from .client import * # noqa from .wrapper import * # noqa from .flexreport import * # noqa from .ibcontroller import * # noqa - from . import util # noqa __all__ = ['util'] for _m in ( objects, event, contract, order, ticker, ib, # noqa client, wrapper, flexreport, ibcontroller): # noqa __all__ += _m.__all__ del sys del importlib del ibapi
Fix explicit check for presence of ibapi package
## Code Before: import sys import importlib from .version import __version__, __version_info__ # noqa from . import util if sys.version_info < (3, 6, 0): raise RuntimeError('ib_insync requires Python 3.6 or higher') try: import ibapi except ImportError: raise RuntimeError( 'IB API from http://interactivebrokers.github.io is required') if util.ibapiVersionInfo() < (9, 73, 6): raise RuntimeError( f'Old version ({ibapi.__version__}) of ibapi package detected. ' 'The newest version from http://interactivebrokers.github.io ' 'is required') from .version import __version__, __version_info__ # noqa from .objects import * # noqa from .event import * # noqa from .contract import * # noqa from .order import * # noqa from .ticker import * # noqa from .ib import * # noqa from .client import * # noqa from .wrapper import * # noqa from .flexreport import * # noqa from .ibcontroller import * # noqa from . import util # noqa __all__ = ['util'] for _m in ( objects, event, contract, order, ticker, ib, # noqa client, wrapper, flexreport, ibcontroller): # noqa __all__ += _m.__all__ del sys del importlib del ibapi ## Instruction: Fix explicit check for presence of ibapi package ## Code After: import sys import importlib if sys.version_info < (3, 6, 0): raise RuntimeError('ib_insync requires Python 3.6 or higher') try: import ibapi except ImportError: raise RuntimeError( 'IB API from http://interactivebrokers.github.io is required') from . import util # noqa if util.ibapiVersionInfo() < (9, 73, 6): raise RuntimeError( f'Old version ({ibapi.__version__}) of ibapi package detected. ' 'The newest version from http://interactivebrokers.github.io ' 'is required') from .version import __version__, __version_info__ # noqa from .objects import * # noqa from .event import * # noqa from .contract import * # noqa from .order import * # noqa from .ticker import * # noqa from .ib import * # noqa from .client import * # noqa from .wrapper import * # noqa from .flexreport import * # noqa from .ibcontroller import * # noqa __all__ = ['util'] for _m in ( objects, event, contract, order, ticker, ib, # noqa client, wrapper, flexreport, ibcontroller): # noqa __all__ += _m.__all__ del sys del importlib del ibapi
import sys import importlib - - from .version import __version__, __version_info__ # noqa - from . import util - if sys.version_info < (3, 6, 0): raise RuntimeError('ib_insync requires Python 3.6 or higher') try: import ibapi except ImportError: raise RuntimeError( 'IB API from http://interactivebrokers.github.io is required') + from . import util # noqa if util.ibapiVersionInfo() < (9, 73, 6): raise RuntimeError( f'Old version ({ibapi.__version__}) of ibapi package detected. ' 'The newest version from http://interactivebrokers.github.io ' 'is required') - from .version import __version__, __version_info__ # noqa from .objects import * # noqa from .event import * # noqa from .contract import * # noqa from .order import * # noqa from .ticker import * # noqa from .ib import * # noqa from .client import * # noqa from .wrapper import * # noqa from .flexreport import * # noqa from .ibcontroller import * # noqa - from . import util # noqa __all__ = ['util'] for _m in ( objects, event, contract, order, ticker, ib, # noqa client, wrapper, flexreport, ibcontroller): # noqa __all__ += _m.__all__ del sys del importlib del ibapi
f0d629ae8b4568b2aceaf38779c8b07832e860b0
teamspeak_web_utils.py
teamspeak_web_utils.py
import re from bs4 import BeautifulSoup import cfscrape def nplstatus(): scraper = cfscrape.create_scraper() data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content soup = BeautifulSoup(data, 'html.parser') raw_status = soup.find_all(class_='register_linklabel')[2].span return not raw_status def latest_version(): scraper = cfscrape.create_scraper() data = scraper.get('http://teamspeak.com/downloads').content soup = BeautifulSoup(data, 'html.parser') def search(search_string): return soup.find_all(text=re.compile(search_string))[0].parent.\ find(class_='version').text return search(r'Client\ 64\-bit'), search(r'Server\ 64\-bit')
import re from bs4 import BeautifulSoup import cfscrape def nplstatus(): scraper = cfscrape.create_scraper() data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content soup = BeautifulSoup(data, 'html.parser') raw_status = soup.find_all(class_='register_linklabel')[2].span return not raw_status def latest_version(): scraper = cfscrape.create_scraper() data = scraper.get('http://teamspeak.com/downloads').content soup = BeautifulSoup(data, 'html.parser') def search(search_string): return soup.find_all(text=re.compile(search_string))[0].parent.\ find(class_='version').text def clean(s): return s.replace('\n', '').strip() return clean(search(r'Client\ 64\-bit')), \ clean(search(r'Server\ 64\-bit'))
Clean string returned by website
Clean string returned by website => remove newline-characters and strip
Python
mit
Thor77/TeamspeakIRC
import re from bs4 import BeautifulSoup import cfscrape def nplstatus(): scraper = cfscrape.create_scraper() data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content soup = BeautifulSoup(data, 'html.parser') raw_status = soup.find_all(class_='register_linklabel')[2].span return not raw_status def latest_version(): scraper = cfscrape.create_scraper() data = scraper.get('http://teamspeak.com/downloads').content soup = BeautifulSoup(data, 'html.parser') def search(search_string): return soup.find_all(text=re.compile(search_string))[0].parent.\ find(class_='version').text - return search(r'Client\ 64\-bit'), search(r'Server\ 64\-bit') + def clean(s): + return s.replace('\n', '').strip() + return clean(search(r'Client\ 64\-bit')), \ + clean(search(r'Server\ 64\-bit')) +
Clean string returned by website
## Code Before: import re from bs4 import BeautifulSoup import cfscrape def nplstatus(): scraper = cfscrape.create_scraper() data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content soup = BeautifulSoup(data, 'html.parser') raw_status = soup.find_all(class_='register_linklabel')[2].span return not raw_status def latest_version(): scraper = cfscrape.create_scraper() data = scraper.get('http://teamspeak.com/downloads').content soup = BeautifulSoup(data, 'html.parser') def search(search_string): return soup.find_all(text=re.compile(search_string))[0].parent.\ find(class_='version').text return search(r'Client\ 64\-bit'), search(r'Server\ 64\-bit') ## Instruction: Clean string returned by website ## Code After: import re from bs4 import BeautifulSoup import cfscrape def nplstatus(): scraper = cfscrape.create_scraper() data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content soup = BeautifulSoup(data, 'html.parser') raw_status = soup.find_all(class_='register_linklabel')[2].span return not raw_status def latest_version(): scraper = cfscrape.create_scraper() data = scraper.get('http://teamspeak.com/downloads').content soup = BeautifulSoup(data, 'html.parser') def search(search_string): return soup.find_all(text=re.compile(search_string))[0].parent.\ find(class_='version').text def clean(s): return s.replace('\n', '').strip() return clean(search(r'Client\ 64\-bit')), \ clean(search(r'Server\ 64\-bit'))
import re from bs4 import BeautifulSoup import cfscrape def nplstatus(): scraper = cfscrape.create_scraper() data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content soup = BeautifulSoup(data, 'html.parser') raw_status = soup.find_all(class_='register_linklabel')[2].span return not raw_status def latest_version(): scraper = cfscrape.create_scraper() data = scraper.get('http://teamspeak.com/downloads').content soup = BeautifulSoup(data, 'html.parser') def search(search_string): return soup.find_all(text=re.compile(search_string))[0].parent.\ find(class_='version').text - return search(r'Client\ 64\-bit'), search(r'Server\ 64\-bit') + + def clean(s): + return s.replace('\n', '').strip() + return clean(search(r'Client\ 64\-bit')), \ + clean(search(r'Server\ 64\-bit'))
97eabe6697e58f3b4dd8cced9a2c3bf05f3444c2
accounting/apps/books/context_processors.py
accounting/apps/books/context_processors.py
from .utils import organization_manager from .models import Organization def organizations(request): """ Add some generally useful metadata to the template context """ # selected organization orga = organization_manager.get_selected_organization(request) # all user authorized organizations if not request.user or not request.user.is_authenticated(): user_organizations = None else: user_organizations = request.user.organizations.all() return { 'user_organizations': user_organizations, 'selected_organization': orga, }
from django.db.models import Q from .utils import organization_manager from .models import Organization def organizations(request): """ Add some generally useful metadata to the template context """ # selected organization orga = organization_manager.get_selected_organization(request) # all user authorized organizations if not request.user or not request.user.is_authenticated(): user_organizations = None else: user = request.user user_organizations = (Organization.objects .filter(Q(members=user) | Q(owner=user))) return { 'user_organizations': user_organizations, 'selected_organization': orga, }
Use owner or member filter for the dropdown
Use owner or member filter for the dropdown
Python
mit
kenjhim/django-accounting,dulaccc/django-accounting,dulaccc/django-accounting,dulaccc/django-accounting,kenjhim/django-accounting,kenjhim/django-accounting,dulaccc/django-accounting,kenjhim/django-accounting
+ from django.db.models import Q + from .utils import organization_manager from .models import Organization def organizations(request): """ Add some generally useful metadata to the template context """ # selected organization orga = organization_manager.get_selected_organization(request) # all user authorized organizations if not request.user or not request.user.is_authenticated(): user_organizations = None else: - user_organizations = request.user.organizations.all() + user = request.user + user_organizations = (Organization.objects + .filter(Q(members=user) | Q(owner=user))) return { 'user_organizations': user_organizations, 'selected_organization': orga, }
Use owner or member filter for the dropdown
## Code Before: from .utils import organization_manager from .models import Organization def organizations(request): """ Add some generally useful metadata to the template context """ # selected organization orga = organization_manager.get_selected_organization(request) # all user authorized organizations if not request.user or not request.user.is_authenticated(): user_organizations = None else: user_organizations = request.user.organizations.all() return { 'user_organizations': user_organizations, 'selected_organization': orga, } ## Instruction: Use owner or member filter for the dropdown ## Code After: from django.db.models import Q from .utils import organization_manager from .models import Organization def organizations(request): """ Add some generally useful metadata to the template context """ # selected organization orga = organization_manager.get_selected_organization(request) # all user authorized organizations if not request.user or not request.user.is_authenticated(): user_organizations = None else: user = request.user user_organizations = (Organization.objects .filter(Q(members=user) | Q(owner=user))) return { 'user_organizations': user_organizations, 'selected_organization': orga, }
+ from django.db.models import Q + from .utils import organization_manager from .models import Organization def organizations(request): """ Add some generally useful metadata to the template context """ # selected organization orga = organization_manager.get_selected_organization(request) # all user authorized organizations if not request.user or not request.user.is_authenticated(): user_organizations = None else: - user_organizations = request.user.organizations.all() + user = request.user + user_organizations = (Organization.objects + .filter(Q(members=user) | Q(owner=user))) return { 'user_organizations': user_organizations, 'selected_organization': orga, }
d153696d44220523d072653b9ff0f0d01eef325f
django_enum_js/__init__.py
django_enum_js/__init__.py
import json class EnumWrapper: def __init__(self): self.registered_enums = {} def register_enum(self, enum_class): self.registered_enums[enum_class.__name__] = enum_class def _enum_to_dict(self, enum_class): return dict([(k,v) for k,v in enum_class.__dict__.items() if not k[:2] == '__']) def _json_dump_enum(self, enum_class): return json.dumps(self._enum_to_dict(enum_class)) def get_json_formatted_enums(self): data = {} for identifier, enum_content in self.registered_enums.items(): data[identifier] = self._enum_to_dict(enum_content) return json.dumps(data) enum_wrapper = EnumWrapper()
import json class EnumWrapper: def __init__(self): self.registered_enums = {} def register_enum(self, enum_class): self.registered_enums[enum_class.__name__] = enum_class return enum_class def _enum_to_dict(self, enum_class): return dict([(k,v) for k,v in enum_class.__dict__.items() if not k[:2] == '__']) def _json_dump_enum(self, enum_class): return json.dumps(self._enum_to_dict(enum_class)) def get_json_formatted_enums(self): data = {} for identifier, enum_content in self.registered_enums.items(): data[identifier] = self._enum_to_dict(enum_content) return json.dumps(data) enum_wrapper = EnumWrapper()
Allow using register_enum as a decorator
Allow using register_enum as a decorator By returning the original class instance, it'd be possible to use `enum_wrapper.register_enum` as a decorator, making the usage cleaner while staying backwards compatible: ```python @enum_wrapper.register_enum class MyAwesomeClass: pass ```
Python
mit
leifdenby/django_enum_js
import json class EnumWrapper: def __init__(self): self.registered_enums = {} def register_enum(self, enum_class): self.registered_enums[enum_class.__name__] = enum_class + return enum_class def _enum_to_dict(self, enum_class): return dict([(k,v) for k,v in enum_class.__dict__.items() if not k[:2] == '__']) def _json_dump_enum(self, enum_class): return json.dumps(self._enum_to_dict(enum_class)) def get_json_formatted_enums(self): data = {} for identifier, enum_content in self.registered_enums.items(): data[identifier] = self._enum_to_dict(enum_content) return json.dumps(data) enum_wrapper = EnumWrapper()
Allow using register_enum as a decorator
## Code Before: import json class EnumWrapper: def __init__(self): self.registered_enums = {} def register_enum(self, enum_class): self.registered_enums[enum_class.__name__] = enum_class def _enum_to_dict(self, enum_class): return dict([(k,v) for k,v in enum_class.__dict__.items() if not k[:2] == '__']) def _json_dump_enum(self, enum_class): return json.dumps(self._enum_to_dict(enum_class)) def get_json_formatted_enums(self): data = {} for identifier, enum_content in self.registered_enums.items(): data[identifier] = self._enum_to_dict(enum_content) return json.dumps(data) enum_wrapper = EnumWrapper() ## Instruction: Allow using register_enum as a decorator ## Code After: import json class EnumWrapper: def __init__(self): self.registered_enums = {} def register_enum(self, enum_class): self.registered_enums[enum_class.__name__] = enum_class return enum_class def _enum_to_dict(self, enum_class): return dict([(k,v) for k,v in enum_class.__dict__.items() if not k[:2] == '__']) def _json_dump_enum(self, enum_class): return json.dumps(self._enum_to_dict(enum_class)) def get_json_formatted_enums(self): data = {} for identifier, enum_content in self.registered_enums.items(): data[identifier] = self._enum_to_dict(enum_content) return json.dumps(data) enum_wrapper = EnumWrapper()
import json class EnumWrapper: def __init__(self): self.registered_enums = {} def register_enum(self, enum_class): self.registered_enums[enum_class.__name__] = enum_class + return enum_class def _enum_to_dict(self, enum_class): return dict([(k,v) for k,v in enum_class.__dict__.items() if not k[:2] == '__']) def _json_dump_enum(self, enum_class): return json.dumps(self._enum_to_dict(enum_class)) def get_json_formatted_enums(self): data = {} for identifier, enum_content in self.registered_enums.items(): data[identifier] = self._enum_to_dict(enum_content) return json.dumps(data) enum_wrapper = EnumWrapper()
19fb86f8b3a2307489f926d9d5d78bd84c6b05a1
Sketches/MH/TimerMixIn.py
Sketches/MH/TimerMixIn.py
from Axon.Component import component from threading import Timer class TimerMixIn(object): def __init__(self, *argl, **argd): super(TimerMixIn,self).__init__(*argl,**argd) self.timer = None self.timerSuccess = True def startTimer(self, secs): self.timer = Timer(secs, self.__handleTimerDone) self.timerSuccess = False self.timer.start() def cancelTimer(self): if self.timer is not None and self.timer: self.timer.cancel() self.timer = None self.timerSuccess = False def timerRunning(self): return self.timer is not None def timerWasCancelled(self): return not self.timerSuccess def __handleTimerDone(self): self.scheduler.wakeThread(self) self.timer = None self.timerSuccess = True if __name__ == "__main__": from Kamaelia.Chassis.Pipeline import Pipeline from Kamaelia.Util.Console import ConsoleEchoer class TestComponent(TimerMixIn,component): def __init__(self): super(TestComponent,self).__init__() def main(self): count = 0 while True: self.startTimer(0.5) while self.timerRunning(): self.pause() yield 1 self.send(count, "outbox") count=count+1 Pipeline(TestComponent(),ConsoleEchoer()).run()
from Axon.Component import component from threading import Timer class TimerMixIn(object): def __init__(self, *argl, **argd): super(TimerMixIn,self).__init__(*argl,**argd) self.timer = None self.timerSuccess = True def startTimer(self, secs): if self.timer is not None: self.cancelTimer() self.timer = Timer(secs, self.__handleTimerDone) self.timerSuccess = False self.timer.start() def cancelTimer(self): if self.timer is not None and self.timer: self.timer.cancel() self.timer = None self.timerSuccess = False def timerRunning(self): return self.timer is not None def timerWasCancelled(self): return not self.timerSuccess def __handleTimerDone(self): self.scheduler.wakeThread(self) self.timer = None self.timerSuccess = True if __name__ == "__main__": from Kamaelia.Chassis.Pipeline import Pipeline from Kamaelia.Util.Console import ConsoleEchoer class TestComponent(TimerMixIn,component): def __init__(self): super(TestComponent,self).__init__() def main(self): count = 0 while True: self.startTimer(0.5) while self.timerRunning(): self.pause() yield 1 self.send(count, "outbox") count=count+1 Pipeline(TestComponent(),ConsoleEchoer()).run()
Handle situation if timer is already running.
Handle situation if timer is already running.
Python
apache-2.0
sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia
from Axon.Component import component from threading import Timer class TimerMixIn(object): def __init__(self, *argl, **argd): super(TimerMixIn,self).__init__(*argl,**argd) self.timer = None self.timerSuccess = True def startTimer(self, secs): + if self.timer is not None: + self.cancelTimer() self.timer = Timer(secs, self.__handleTimerDone) self.timerSuccess = False self.timer.start() def cancelTimer(self): if self.timer is not None and self.timer: self.timer.cancel() self.timer = None self.timerSuccess = False def timerRunning(self): return self.timer is not None def timerWasCancelled(self): return not self.timerSuccess def __handleTimerDone(self): self.scheduler.wakeThread(self) self.timer = None self.timerSuccess = True if __name__ == "__main__": from Kamaelia.Chassis.Pipeline import Pipeline from Kamaelia.Util.Console import ConsoleEchoer class TestComponent(TimerMixIn,component): def __init__(self): super(TestComponent,self).__init__() def main(self): count = 0 while True: self.startTimer(0.5) while self.timerRunning(): self.pause() yield 1 self.send(count, "outbox") count=count+1 Pipeline(TestComponent(),ConsoleEchoer()).run()
Handle situation if timer is already running.
## Code Before: from Axon.Component import component from threading import Timer class TimerMixIn(object): def __init__(self, *argl, **argd): super(TimerMixIn,self).__init__(*argl,**argd) self.timer = None self.timerSuccess = True def startTimer(self, secs): self.timer = Timer(secs, self.__handleTimerDone) self.timerSuccess = False self.timer.start() def cancelTimer(self): if self.timer is not None and self.timer: self.timer.cancel() self.timer = None self.timerSuccess = False def timerRunning(self): return self.timer is not None def timerWasCancelled(self): return not self.timerSuccess def __handleTimerDone(self): self.scheduler.wakeThread(self) self.timer = None self.timerSuccess = True if __name__ == "__main__": from Kamaelia.Chassis.Pipeline import Pipeline from Kamaelia.Util.Console import ConsoleEchoer class TestComponent(TimerMixIn,component): def __init__(self): super(TestComponent,self).__init__() def main(self): count = 0 while True: self.startTimer(0.5) while self.timerRunning(): self.pause() yield 1 self.send(count, "outbox") count=count+1 Pipeline(TestComponent(),ConsoleEchoer()).run() ## Instruction: Handle situation if timer is already running. ## Code After: from Axon.Component import component from threading import Timer class TimerMixIn(object): def __init__(self, *argl, **argd): super(TimerMixIn,self).__init__(*argl,**argd) self.timer = None self.timerSuccess = True def startTimer(self, secs): if self.timer is not None: self.cancelTimer() self.timer = Timer(secs, self.__handleTimerDone) self.timerSuccess = False self.timer.start() def cancelTimer(self): if self.timer is not None and self.timer: self.timer.cancel() self.timer = None self.timerSuccess = False def timerRunning(self): return self.timer is not None def timerWasCancelled(self): return not self.timerSuccess def __handleTimerDone(self): self.scheduler.wakeThread(self) self.timer = None self.timerSuccess = True if __name__ == "__main__": from Kamaelia.Chassis.Pipeline import Pipeline from Kamaelia.Util.Console import ConsoleEchoer class TestComponent(TimerMixIn,component): def __init__(self): super(TestComponent,self).__init__() def main(self): count = 0 while True: self.startTimer(0.5) while self.timerRunning(): self.pause() yield 1 self.send(count, "outbox") count=count+1 Pipeline(TestComponent(),ConsoleEchoer()).run()
from Axon.Component import component from threading import Timer class TimerMixIn(object): def __init__(self, *argl, **argd): super(TimerMixIn,self).__init__(*argl,**argd) self.timer = None self.timerSuccess = True def startTimer(self, secs): + if self.timer is not None: + self.cancelTimer() self.timer = Timer(secs, self.__handleTimerDone) self.timerSuccess = False self.timer.start() def cancelTimer(self): if self.timer is not None and self.timer: self.timer.cancel() self.timer = None self.timerSuccess = False def timerRunning(self): return self.timer is not None def timerWasCancelled(self): return not self.timerSuccess def __handleTimerDone(self): self.scheduler.wakeThread(self) self.timer = None self.timerSuccess = True if __name__ == "__main__": from Kamaelia.Chassis.Pipeline import Pipeline from Kamaelia.Util.Console import ConsoleEchoer class TestComponent(TimerMixIn,component): def __init__(self): super(TestComponent,self).__init__() def main(self): count = 0 while True: self.startTimer(0.5) while self.timerRunning(): self.pause() yield 1 self.send(count, "outbox") count=count+1 Pipeline(TestComponent(),ConsoleEchoer()).run()
e8afa1408618d7dc4e39b84963199dd87c217ef9
app/main/views/buyers.py
app/main/views/buyers.py
from flask import render_template, request, flash from flask_login import login_required from .. import main from ... import data_api_client from ..auth import role_required @main.route('/buyers', methods=['GET']) @login_required @role_required('admin') def find_buyer_by_brief_id(): brief_id = request.args.get('brief_id') try: brief = data_api_client.get_brief(brief_id).get('briefs') except: flash('no_brief', 'error') return render_template( "view_buyers.html", users=list(), title=None, brief_id=brief_id ), 404 users = brief.get('users') title = brief.get('title') return render_template( "view_buyers.html", users=users, title=title, brief_id=brief_id )
from flask import render_template, request, flash from flask_login import login_required from .. import main from ... import data_api_client from ..auth import role_required @main.route('/buyers', methods=['GET']) @login_required @role_required('admin') def find_buyer_by_brief_id(): brief_id = request.args.get('brief_id') try: brief = data_api_client.get_brief(brief_id).get('briefs') except: flash('no_brief', 'error') return render_template( "view_buyers.html", users=list(), brief_id=brief_id ), 404 users = brief.get('users') title = brief.get('title') return render_template( "view_buyers.html", users=users, title=title, brief_id=brief_id )
Remove unnecessary variable from route
Remove unnecessary variable from route Jinja will set any variable it can't find to None, so the title variable is unnecessary.
Python
mit
alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend
from flask import render_template, request, flash from flask_login import login_required from .. import main from ... import data_api_client from ..auth import role_required @main.route('/buyers', methods=['GET']) @login_required @role_required('admin') def find_buyer_by_brief_id(): brief_id = request.args.get('brief_id') try: brief = data_api_client.get_brief(brief_id).get('briefs') except: flash('no_brief', 'error') return render_template( "view_buyers.html", users=list(), - title=None, brief_id=brief_id ), 404 users = brief.get('users') title = brief.get('title') return render_template( "view_buyers.html", users=users, title=title, brief_id=brief_id )
Remove unnecessary variable from route
## Code Before: from flask import render_template, request, flash from flask_login import login_required from .. import main from ... import data_api_client from ..auth import role_required @main.route('/buyers', methods=['GET']) @login_required @role_required('admin') def find_buyer_by_brief_id(): brief_id = request.args.get('brief_id') try: brief = data_api_client.get_brief(brief_id).get('briefs') except: flash('no_brief', 'error') return render_template( "view_buyers.html", users=list(), title=None, brief_id=brief_id ), 404 users = brief.get('users') title = brief.get('title') return render_template( "view_buyers.html", users=users, title=title, brief_id=brief_id ) ## Instruction: Remove unnecessary variable from route ## Code After: from flask import render_template, request, flash from flask_login import login_required from .. import main from ... import data_api_client from ..auth import role_required @main.route('/buyers', methods=['GET']) @login_required @role_required('admin') def find_buyer_by_brief_id(): brief_id = request.args.get('brief_id') try: brief = data_api_client.get_brief(brief_id).get('briefs') except: flash('no_brief', 'error') return render_template( "view_buyers.html", users=list(), brief_id=brief_id ), 404 users = brief.get('users') title = brief.get('title') return render_template( "view_buyers.html", users=users, title=title, brief_id=brief_id )
from flask import render_template, request, flash from flask_login import login_required from .. import main from ... import data_api_client from ..auth import role_required @main.route('/buyers', methods=['GET']) @login_required @role_required('admin') def find_buyer_by_brief_id(): brief_id = request.args.get('brief_id') try: brief = data_api_client.get_brief(brief_id).get('briefs') except: flash('no_brief', 'error') return render_template( "view_buyers.html", users=list(), - title=None, brief_id=brief_id ), 404 users = brief.get('users') title = brief.get('title') return render_template( "view_buyers.html", users=users, title=title, brief_id=brief_id )
991973e554758e7a9881453d7668925902e610b9
tests.py
tests.py
import unittest import git_mnemonic as gm class GitMnemonicTests(unittest.TestCase): def test_encode(self): self.assertTrue(gm.encode("master")) def test_decode(self): self.assertTrue(gm.decode("bis alo ama aha")) def test_invertible(self): once = gm.encode("master") self.assertEquals(gm.encode(gm.decode(once)), once) if __name__ == '__main__': unittest.main(verbosity=2)
import unittest import git_mnemonic as gm class GitMnemonicTests(unittest.TestCase): def test_encode(self): self.assertTrue(gm.encode("master")) def test_decode(self): self.assertTrue(gm.decode("bis alo ama aha")) def test_invertible(self): once = gm.encode("master") self.assertEquals(gm.encode(gm.decode(once)), once) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(GitMnemonicTests) results = unittest.TextTestRunner(verbosity=2).run(suite) if not results.wasSuccessful(): import sys sys.exit(1)
Make unittest test runner work in older pythons
Make unittest test runner work in older pythons
Python
mit
glenjamin/git-mnemonic
import unittest import git_mnemonic as gm class GitMnemonicTests(unittest.TestCase): def test_encode(self): self.assertTrue(gm.encode("master")) def test_decode(self): self.assertTrue(gm.decode("bis alo ama aha")) def test_invertible(self): once = gm.encode("master") self.assertEquals(gm.encode(gm.decode(once)), once) if __name__ == '__main__': - unittest.main(verbosity=2) + suite = unittest.TestLoader().loadTestsFromTestCase(GitMnemonicTests) + results = unittest.TextTestRunner(verbosity=2).run(suite) + if not results.wasSuccessful(): + import sys + sys.exit(1)
Make unittest test runner work in older pythons
## Code Before: import unittest import git_mnemonic as gm class GitMnemonicTests(unittest.TestCase): def test_encode(self): self.assertTrue(gm.encode("master")) def test_decode(self): self.assertTrue(gm.decode("bis alo ama aha")) def test_invertible(self): once = gm.encode("master") self.assertEquals(gm.encode(gm.decode(once)), once) if __name__ == '__main__': unittest.main(verbosity=2) ## Instruction: Make unittest test runner work in older pythons ## Code After: import unittest import git_mnemonic as gm class GitMnemonicTests(unittest.TestCase): def test_encode(self): self.assertTrue(gm.encode("master")) def test_decode(self): self.assertTrue(gm.decode("bis alo ama aha")) def test_invertible(self): once = gm.encode("master") self.assertEquals(gm.encode(gm.decode(once)), once) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(GitMnemonicTests) results = unittest.TextTestRunner(verbosity=2).run(suite) if not results.wasSuccessful(): import sys sys.exit(1)
import unittest import git_mnemonic as gm class GitMnemonicTests(unittest.TestCase): def test_encode(self): self.assertTrue(gm.encode("master")) def test_decode(self): self.assertTrue(gm.decode("bis alo ama aha")) def test_invertible(self): once = gm.encode("master") self.assertEquals(gm.encode(gm.decode(once)), once) if __name__ == '__main__': - unittest.main(verbosity=2) + suite = unittest.TestLoader().loadTestsFromTestCase(GitMnemonicTests) + results = unittest.TextTestRunner(verbosity=2).run(suite) + if not results.wasSuccessful(): + import sys + sys.exit(1)
f60fe11653d71f278aa04e71a522a89fc86c284a
bse/api.py
bse/api.py
''' Main interface to BSE functionality ''' from . import io def get_basis_set(name): '''Reads a json basis set file given only the name The path to the basis set file is taken to be the 'data' directory in this project ''' return io.read_table_basis_by_name(name) def get_metadata(keys=None, key_filter=None): if key_filter: raise RuntimeError("key_filter not implemented") avail_names = io.get_available_names() metadata = {} for n in avail_names: bs = io.read_table_basis_by_name(n) common_name = bs['basisSetName'] defined_elements = list(bs['basisSetElements'].keys()) function_types = set() for e in bs['basisSetElements'].values(): for s in e['elementElectronShells']: function_types.add(s['shellFunctionType']) metadata[common_name] = { 'mangled_name': n, 'elements': defined_elements, 'functiontypes': list(function_types), } return metadata
''' Main interface to BSE functionality ''' from . import io def get_basis_set(name): '''Reads a json basis set file given only the name The path to the basis set file is taken to be the 'data' directory in this project ''' return io.read_table_basis_by_name(name) def get_metadata(keys=None, key_filter=None): if key_filter: raise RuntimeError("key_filter not implemented") avail_names = io.get_available_names() metadata = {} for n in avail_names: bs = io.read_table_basis_by_name(n) displayname = bs['basisSetName'] defined_elements = list(bs['basisSetElements'].keys()) function_types = set() for e in bs['basisSetElements'].values(): for s in e['elementElectronShells']: function_types.add(s['shellFunctionType']) metadata[n] = { 'displayname': displayname, 'elements': defined_elements, 'functiontypes': list(function_types), } return metadata
Switch which name is used as a metadata key
Switch which name is used as a metadata key
Python
bsd-3-clause
MOLSSI-BSE/basis_set_exchange
''' Main interface to BSE functionality ''' from . import io def get_basis_set(name): '''Reads a json basis set file given only the name The path to the basis set file is taken to be the 'data' directory in this project ''' return io.read_table_basis_by_name(name) def get_metadata(keys=None, key_filter=None): if key_filter: raise RuntimeError("key_filter not implemented") avail_names = io.get_available_names() metadata = {} for n in avail_names: bs = io.read_table_basis_by_name(n) - common_name = bs['basisSetName'] + displayname = bs['basisSetName'] defined_elements = list(bs['basisSetElements'].keys()) function_types = set() for e in bs['basisSetElements'].values(): for s in e['elementElectronShells']: function_types.add(s['shellFunctionType']) - metadata[common_name] = { + metadata[n] = { - 'mangled_name': n, + 'displayname': displayname, 'elements': defined_elements, 'functiontypes': list(function_types), } return metadata
Switch which name is used as a metadata key
## Code Before: ''' Main interface to BSE functionality ''' from . import io def get_basis_set(name): '''Reads a json basis set file given only the name The path to the basis set file is taken to be the 'data' directory in this project ''' return io.read_table_basis_by_name(name) def get_metadata(keys=None, key_filter=None): if key_filter: raise RuntimeError("key_filter not implemented") avail_names = io.get_available_names() metadata = {} for n in avail_names: bs = io.read_table_basis_by_name(n) common_name = bs['basisSetName'] defined_elements = list(bs['basisSetElements'].keys()) function_types = set() for e in bs['basisSetElements'].values(): for s in e['elementElectronShells']: function_types.add(s['shellFunctionType']) metadata[common_name] = { 'mangled_name': n, 'elements': defined_elements, 'functiontypes': list(function_types), } return metadata ## Instruction: Switch which name is used as a metadata key ## Code After: ''' Main interface to BSE functionality ''' from . import io def get_basis_set(name): '''Reads a json basis set file given only the name The path to the basis set file is taken to be the 'data' directory in this project ''' return io.read_table_basis_by_name(name) def get_metadata(keys=None, key_filter=None): if key_filter: raise RuntimeError("key_filter not implemented") avail_names = io.get_available_names() metadata = {} for n in avail_names: bs = io.read_table_basis_by_name(n) displayname = bs['basisSetName'] defined_elements = list(bs['basisSetElements'].keys()) function_types = set() for e in bs['basisSetElements'].values(): for s in e['elementElectronShells']: function_types.add(s['shellFunctionType']) metadata[n] = { 'displayname': displayname, 'elements': defined_elements, 'functiontypes': list(function_types), } return metadata
''' Main interface to BSE functionality ''' from . import io def get_basis_set(name): '''Reads a json basis set file given only the name The path to the basis set file is taken to be the 'data' directory in this project ''' return io.read_table_basis_by_name(name) def get_metadata(keys=None, key_filter=None): if key_filter: raise RuntimeError("key_filter not implemented") avail_names = io.get_available_names() metadata = {} for n in avail_names: bs = io.read_table_basis_by_name(n) - common_name = bs['basisSetName'] ? ^^^^^^^ + displayname = bs['basisSetName'] ? ^^^^^^^ defined_elements = list(bs['basisSetElements'].keys()) function_types = set() for e in bs['basisSetElements'].values(): for s in e['elementElectronShells']: function_types.add(s['shellFunctionType']) - metadata[common_name] = { ? ----- ----- + metadata[n] = { - 'mangled_name': n, + 'displayname': displayname, 'elements': defined_elements, 'functiontypes': list(function_types), } return metadata
3aaf18dc43ee81bf2669eb597444d713d1577ebe
Motor/src/main/python/vehicles.py
Motor/src/main/python/vehicles.py
from Adafruit_MotorHAT import Adafruit_MotorHAT class Vehicle: def __init__(self, motor_hat=Adafruit_MotorHAT()): self.motor_hat = motor_hat self.motors = [] def release(self): self.motor_hat.getMotor(1).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(2).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(3).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(4).run(Adafruit_MotorHAT.RELEASE) def update_motor(self, index, command, speed): motor = self.motor_hat.getMotor(index + 1) motor.run(command + 1) motor.setSpeed(speed) print("Set %d motor to %d command with %d speed" % (index + 1, command + 1, speed)) motor_state = {"location": index, "command": command, "speed": speed} n = len(self.motors) if index < n: self.motors[index] = motor_state elif index == n: self.motors.append(motor_state) else: raise IndexError() def dict(self): return {"motors": self.motors}
from Adafruit_MotorHAT import Adafruit_MotorHAT class Vehicle: def __init__(self, motor_hat=Adafruit_MotorHAT()): self.motor_hat = motor_hat self.motors = [] def release(self): self.motor_hat.getMotor(1).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(2).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(3).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(4).run(Adafruit_MotorHAT.RELEASE) def update_motor(self, index, command, speed): motor = self.motor_hat.getMotor(index + 1) motor.run(command + 1) motor.setSpeed(speed) motor_state = {"location": index, "command": command, "speed": speed} n = len(self.motors) if index < n: self.motors[index] = motor_state elif index == n: self.motors.append(motor_state) else: raise IndexError() def dict(self): return {"motors": self.motors}
Update motor API with new data model
Update motor API with new data model
Python
mit
misalcedo/RapBot,misalcedo/RapBot,misalcedo/RapBot,misalcedo/RapBot
from Adafruit_MotorHAT import Adafruit_MotorHAT class Vehicle: def __init__(self, motor_hat=Adafruit_MotorHAT()): self.motor_hat = motor_hat self.motors = [] def release(self): self.motor_hat.getMotor(1).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(2).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(3).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(4).run(Adafruit_MotorHAT.RELEASE) def update_motor(self, index, command, speed): motor = self.motor_hat.getMotor(index + 1) motor.run(command + 1) motor.setSpeed(speed) - print("Set %d motor to %d command with %d speed" % (index + 1, command + 1, speed)) - motor_state = {"location": index, "command": command, "speed": speed} n = len(self.motors) if index < n: self.motors[index] = motor_state elif index == n: self.motors.append(motor_state) else: raise IndexError() def dict(self): return {"motors": self.motors}
Update motor API with new data model
## Code Before: from Adafruit_MotorHAT import Adafruit_MotorHAT class Vehicle: def __init__(self, motor_hat=Adafruit_MotorHAT()): self.motor_hat = motor_hat self.motors = [] def release(self): self.motor_hat.getMotor(1).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(2).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(3).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(4).run(Adafruit_MotorHAT.RELEASE) def update_motor(self, index, command, speed): motor = self.motor_hat.getMotor(index + 1) motor.run(command + 1) motor.setSpeed(speed) print("Set %d motor to %d command with %d speed" % (index + 1, command + 1, speed)) motor_state = {"location": index, "command": command, "speed": speed} n = len(self.motors) if index < n: self.motors[index] = motor_state elif index == n: self.motors.append(motor_state) else: raise IndexError() def dict(self): return {"motors": self.motors} ## Instruction: Update motor API with new data model ## Code After: from Adafruit_MotorHAT import Adafruit_MotorHAT class Vehicle: def __init__(self, motor_hat=Adafruit_MotorHAT()): self.motor_hat = motor_hat self.motors = [] def release(self): self.motor_hat.getMotor(1).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(2).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(3).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(4).run(Adafruit_MotorHAT.RELEASE) def update_motor(self, index, command, speed): motor = self.motor_hat.getMotor(index + 1) motor.run(command + 1) motor.setSpeed(speed) motor_state = {"location": index, "command": command, "speed": speed} n = len(self.motors) if index < n: self.motors[index] = motor_state elif index == n: self.motors.append(motor_state) else: raise IndexError() def dict(self): return {"motors": self.motors}
from Adafruit_MotorHAT import Adafruit_MotorHAT class Vehicle: def __init__(self, motor_hat=Adafruit_MotorHAT()): self.motor_hat = motor_hat self.motors = [] def release(self): self.motor_hat.getMotor(1).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(2).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(3).run(Adafruit_MotorHAT.RELEASE) self.motor_hat.getMotor(4).run(Adafruit_MotorHAT.RELEASE) def update_motor(self, index, command, speed): motor = self.motor_hat.getMotor(index + 1) motor.run(command + 1) motor.setSpeed(speed) - print("Set %d motor to %d command with %d speed" % (index + 1, command + 1, speed)) - motor_state = {"location": index, "command": command, "speed": speed} n = len(self.motors) if index < n: self.motors[index] = motor_state elif index == n: self.motors.append(motor_state) else: raise IndexError() def dict(self): return {"motors": self.motors}
a473b2cb9af95c1296ecae4d2138142f2be397ee
examples/variants.py
examples/variants.py
from __future__ import print_function, unicode_literals from cihai.bootstrap import bootstrap_unihan from cihai.core import Cihai def variant_list(unihan, field): for char in unihan.with_fields(field): print("Character: {}".format(char.char)) for var in char.untagged_vars(field): print(var) def script(unihan_options={}): """Wrapped so we can test in tests/test_examples.py""" print("This example prints variant character data.") c = Cihai() c.add_dataset('cihai.unihan.Unihan', namespace='unihan') if not c.sql.is_bootstrapped: # download and install Unihan to db bootstrap_unihan(c.sql.metadata, options=unihan_options) c.sql.reflect_db() # automap new table created during bootstrap print("## ZVariants") variant_list(c.unihan, "kZVariant") print("## kSemanticVariant") variant_list(c.unihan, "kSemanticVariant") print("## kSpecializedSemanticVariant") variant_list(c.unihan, "kSpecializedSemanticVariant") if __name__ == '__main__': script()
from __future__ import print_function, unicode_literals from cihai.bootstrap import bootstrap_unihan from cihai.core import Cihai def variant_list(unihan, field): for char in unihan.with_fields(field): print("Character: {}".format(char.char)) for var in char.untagged_vars(field): print(var) def script(unihan_options={}): """Wrapped so we can test in tests/test_examples.py""" print("This example prints variant character data.") c = Cihai() c.add_dataset('cihai.unihan.Unihan', namespace='unihan') if not c.sql.is_bootstrapped: # download and install Unihan to db bootstrap_unihan(c.sql.metadata, options=unihan_options) c.sql.reflect_db() # automap new table created during bootstrap c.unihan.add_extension('cihai.unihan.UnihanVariants', namespace='variants') print("## ZVariants") variant_list(c.unihan, "kZVariant") print("## kSemanticVariant") variant_list(c.unihan, "kSemanticVariant") print("## kSpecializedSemanticVariant") variant_list(c.unihan, "kSpecializedSemanticVariant") if __name__ == '__main__': script()
Add variant extension in example script
Add variant extension in example script
Python
mit
cihai/cihai,cihai/cihai-python,cihai/cihai
from __future__ import print_function, unicode_literals from cihai.bootstrap import bootstrap_unihan from cihai.core import Cihai def variant_list(unihan, field): for char in unihan.with_fields(field): print("Character: {}".format(char.char)) for var in char.untagged_vars(field): print(var) def script(unihan_options={}): """Wrapped so we can test in tests/test_examples.py""" print("This example prints variant character data.") c = Cihai() c.add_dataset('cihai.unihan.Unihan', namespace='unihan') if not c.sql.is_bootstrapped: # download and install Unihan to db bootstrap_unihan(c.sql.metadata, options=unihan_options) c.sql.reflect_db() # automap new table created during bootstrap + c.unihan.add_extension('cihai.unihan.UnihanVariants', namespace='variants') + print("## ZVariants") variant_list(c.unihan, "kZVariant") print("## kSemanticVariant") variant_list(c.unihan, "kSemanticVariant") print("## kSpecializedSemanticVariant") variant_list(c.unihan, "kSpecializedSemanticVariant") if __name__ == '__main__': script()
Add variant extension in example script
## Code Before: from __future__ import print_function, unicode_literals from cihai.bootstrap import bootstrap_unihan from cihai.core import Cihai def variant_list(unihan, field): for char in unihan.with_fields(field): print("Character: {}".format(char.char)) for var in char.untagged_vars(field): print(var) def script(unihan_options={}): """Wrapped so we can test in tests/test_examples.py""" print("This example prints variant character data.") c = Cihai() c.add_dataset('cihai.unihan.Unihan', namespace='unihan') if not c.sql.is_bootstrapped: # download and install Unihan to db bootstrap_unihan(c.sql.metadata, options=unihan_options) c.sql.reflect_db() # automap new table created during bootstrap print("## ZVariants") variant_list(c.unihan, "kZVariant") print("## kSemanticVariant") variant_list(c.unihan, "kSemanticVariant") print("## kSpecializedSemanticVariant") variant_list(c.unihan, "kSpecializedSemanticVariant") if __name__ == '__main__': script() ## Instruction: Add variant extension in example script ## Code After: from __future__ import print_function, unicode_literals from cihai.bootstrap import bootstrap_unihan from cihai.core import Cihai def variant_list(unihan, field): for char in unihan.with_fields(field): print("Character: {}".format(char.char)) for var in char.untagged_vars(field): print(var) def script(unihan_options={}): """Wrapped so we can test in tests/test_examples.py""" print("This example prints variant character data.") c = Cihai() c.add_dataset('cihai.unihan.Unihan', namespace='unihan') if not c.sql.is_bootstrapped: # download and install Unihan to db bootstrap_unihan(c.sql.metadata, options=unihan_options) c.sql.reflect_db() # automap new table created during bootstrap c.unihan.add_extension('cihai.unihan.UnihanVariants', namespace='variants') print("## ZVariants") variant_list(c.unihan, "kZVariant") print("## kSemanticVariant") variant_list(c.unihan, "kSemanticVariant") print("## kSpecializedSemanticVariant") variant_list(c.unihan, "kSpecializedSemanticVariant") if __name__ == '__main__': script()
from __future__ import print_function, unicode_literals from cihai.bootstrap import bootstrap_unihan from cihai.core import Cihai def variant_list(unihan, field): for char in unihan.with_fields(field): print("Character: {}".format(char.char)) for var in char.untagged_vars(field): print(var) def script(unihan_options={}): """Wrapped so we can test in tests/test_examples.py""" print("This example prints variant character data.") c = Cihai() c.add_dataset('cihai.unihan.Unihan', namespace='unihan') if not c.sql.is_bootstrapped: # download and install Unihan to db bootstrap_unihan(c.sql.metadata, options=unihan_options) c.sql.reflect_db() # automap new table created during bootstrap + c.unihan.add_extension('cihai.unihan.UnihanVariants', namespace='variants') + print("## ZVariants") variant_list(c.unihan, "kZVariant") print("## kSemanticVariant") variant_list(c.unihan, "kSemanticVariant") print("## kSpecializedSemanticVariant") variant_list(c.unihan, "kSpecializedSemanticVariant") if __name__ == '__main__': script()
1ee442e79df7c7a79076460dea930bbd7d87b00a
setup.py
setup.py
from distutils.core import setup # Keeping all Python code for package in src directory setup(name='quantitation', url='http://www.awblocker.com', version='0.1', description='Absolute quantitation for LC/MSMS proteomics via MCMC', author='Alexander W Blocker', author_email='[email protected]', packages=['quantitation','quantitation.glm'], package_dir = {'': 'lib'} )
from distutils.core import setup # Keeping all Python code for package in src directory setup(name='quantitation', url='http://www.awblocker.com', version='0.1', description='Absolute quantitation for LC/MSMS proteomics via MCMC', author='Alexander W Blocker', author_email='[email protected]', packages=['quantitation','quantitation.glm'], package_dir = {'': 'lib'}, requires=['numpy(>=1.6)','scipy(>=0.9)'] )
Add requires for development use, at least
Add requires for development use, at least
Python
bsd-3-clause
awblocker/quantitation,awblocker/quantitation,awblocker/quantitation
from distutils.core import setup # Keeping all Python code for package in src directory setup(name='quantitation', url='http://www.awblocker.com', version='0.1', description='Absolute quantitation for LC/MSMS proteomics via MCMC', author='Alexander W Blocker', author_email='[email protected]', packages=['quantitation','quantitation.glm'], - package_dir = {'': 'lib'} + package_dir = {'': 'lib'}, + requires=['numpy(>=1.6)','scipy(>=0.9)'] )
Add requires for development use, at least
## Code Before: from distutils.core import setup # Keeping all Python code for package in src directory setup(name='quantitation', url='http://www.awblocker.com', version='0.1', description='Absolute quantitation for LC/MSMS proteomics via MCMC', author='Alexander W Blocker', author_email='[email protected]', packages=['quantitation','quantitation.glm'], package_dir = {'': 'lib'} ) ## Instruction: Add requires for development use, at least ## Code After: from distutils.core import setup # Keeping all Python code for package in src directory setup(name='quantitation', url='http://www.awblocker.com', version='0.1', description='Absolute quantitation for LC/MSMS proteomics via MCMC', author='Alexander W Blocker', author_email='[email protected]', packages=['quantitation','quantitation.glm'], package_dir = {'': 'lib'}, requires=['numpy(>=1.6)','scipy(>=0.9)'] )
from distutils.core import setup # Keeping all Python code for package in src directory setup(name='quantitation', url='http://www.awblocker.com', version='0.1', description='Absolute quantitation for LC/MSMS proteomics via MCMC', author='Alexander W Blocker', author_email='[email protected]', packages=['quantitation','quantitation.glm'], - package_dir = {'': 'lib'} + package_dir = {'': 'lib'}, ? + + requires=['numpy(>=1.6)','scipy(>=0.9)'] )
0d8ce87cda68a0e882cf1108066e2bde6c9cb1fa
shopping_app/forms.py
shopping_app/forms.py
from wtforms import Form, BooleanField, StringField, PasswordField, validators from wtforms.validators import DataRequired, InputRequired class LoginForm(Form): username = StringField('username', validators=[InputRequired(), DataRequired()]) password = PasswordField('password', validators=[InputRequired(), DataRequired()]) class RegistrationForm(Form): username = StringField('Username', [validators.Length(min=4, max=25)]) email = StringField('Email Address', [validators.Length(min=6, max=35)]) password = PasswordField('New Password', [ validators.DataRequired(), validators.EqualTo('confirm', message='Passwords must match') ]) confirm = PasswordField('Repeat Password')
from wtforms import Form, DecimalField, IntegerField, StringField, PasswordField, validators, ValidationError from wtforms.validators import DataRequired, InputRequired from .utils.helpers import check_duplicate_item_name class LoginForm(Form): username = StringField('username', validators=[InputRequired(), DataRequired()]) password = PasswordField('password', validators=[InputRequired(), DataRequired()]) class CreateShoppingItemForm(Form): item_name = StringField('item-name', validators=[InputRequired()]) quantity = IntegerField('quantity', validators=[InputRequired()]) price = DecimalField('price', validators=[InputRequired()]) class RegistrationForm(Form): username = StringField('Username', [validators.Length(min=4, max=25)]) email = StringField('Email Address', [validators.Length(min=6, max=35)]) password = PasswordField('New Password', [ validators.DataRequired(), validators.EqualTo('confirm', message='Passwords must match') ]) confirm = PasswordField('Repeat Password')
Add create shopping item form
Add create shopping item form
Python
mit
gr1d99/shopping-list,gr1d99/shopping-list,gr1d99/shopping-list
- from wtforms import Form, BooleanField, StringField, PasswordField, validators + from wtforms import Form, DecimalField, IntegerField, StringField, PasswordField, validators, ValidationError from wtforms.validators import DataRequired, InputRequired + from .utils.helpers import check_duplicate_item_name class LoginForm(Form): username = StringField('username', validators=[InputRequired(), DataRequired()]) password = PasswordField('password', validators=[InputRequired(), DataRequired()]) + + + class CreateShoppingItemForm(Form): + item_name = StringField('item-name', validators=[InputRequired()]) + quantity = IntegerField('quantity', validators=[InputRequired()]) + price = DecimalField('price', validators=[InputRequired()]) class RegistrationForm(Form): username = StringField('Username', [validators.Length(min=4, max=25)]) email = StringField('Email Address', [validators.Length(min=6, max=35)]) password = PasswordField('New Password', [ validators.DataRequired(), validators.EqualTo('confirm', message='Passwords must match') ]) confirm = PasswordField('Repeat Password')
Add create shopping item form
## Code Before: from wtforms import Form, BooleanField, StringField, PasswordField, validators from wtforms.validators import DataRequired, InputRequired class LoginForm(Form): username = StringField('username', validators=[InputRequired(), DataRequired()]) password = PasswordField('password', validators=[InputRequired(), DataRequired()]) class RegistrationForm(Form): username = StringField('Username', [validators.Length(min=4, max=25)]) email = StringField('Email Address', [validators.Length(min=6, max=35)]) password = PasswordField('New Password', [ validators.DataRequired(), validators.EqualTo('confirm', message='Passwords must match') ]) confirm = PasswordField('Repeat Password') ## Instruction: Add create shopping item form ## Code After: from wtforms import Form, DecimalField, IntegerField, StringField, PasswordField, validators, ValidationError from wtforms.validators import DataRequired, InputRequired from .utils.helpers import check_duplicate_item_name class LoginForm(Form): username = StringField('username', validators=[InputRequired(), DataRequired()]) password = PasswordField('password', validators=[InputRequired(), DataRequired()]) class CreateShoppingItemForm(Form): item_name = StringField('item-name', validators=[InputRequired()]) quantity = IntegerField('quantity', validators=[InputRequired()]) price = DecimalField('price', validators=[InputRequired()]) class RegistrationForm(Form): username = StringField('Username', [validators.Length(min=4, max=25)]) email = StringField('Email Address', [validators.Length(min=6, max=35)]) password = PasswordField('New Password', [ validators.DataRequired(), validators.EqualTo('confirm', message='Passwords must match') ]) confirm = PasswordField('Repeat Password')
- from wtforms import Form, BooleanField, StringField, PasswordField, validators ? ^^^ ^ + from wtforms import Form, DecimalField, IntegerField, StringField, PasswordField, validators, ValidationError ? ^^^^^^ ++ ^^^^^ +++++ +++++++++++++++++ from wtforms.validators import DataRequired, InputRequired + from .utils.helpers import check_duplicate_item_name class LoginForm(Form): username = StringField('username', validators=[InputRequired(), DataRequired()]) password = PasswordField('password', validators=[InputRequired(), DataRequired()]) + + + class CreateShoppingItemForm(Form): + item_name = StringField('item-name', validators=[InputRequired()]) + quantity = IntegerField('quantity', validators=[InputRequired()]) + price = DecimalField('price', validators=[InputRequired()]) class RegistrationForm(Form): username = StringField('Username', [validators.Length(min=4, max=25)]) email = StringField('Email Address', [validators.Length(min=6, max=35)]) password = PasswordField('New Password', [ validators.DataRequired(), validators.EqualTo('confirm', message='Passwords must match') ]) confirm = PasswordField('Repeat Password')
e654cea816be8c4a79da66efbc50a5698a51ba5b
plantcv/plantcv/print_results.py
plantcv/plantcv/print_results.py
import json import os from plantcv.plantcv import outputs def print_results(filename): """Print result table Inputs: filename = filename :param filename: str :return: """ if os.path.isfile(filename): with open(filename, 'r') as f: hierarchical_data = json.load(f) hierarchical_data["observations"] = outputs.observations else: hierarchical_data = {"metadata": {}, "observations": outputs.observations} with open(filename, mode='w') as f: json.dump(hierarchical_data, f)
from plantcv.plantcv import outputs def print_results(filename): """Print result table Inputs: filename = filename :param filename: str :return: """ print("""Deprecation warning: plantcv.print_results will be removed in a future version. Please use plantcv.outputs.save_results instead. """) outputs.save_results(filename=filename, outformat="json")
Add deprecation warning and use new method
Add deprecation warning and use new method
Python
mit
stiphyMT/plantcv,danforthcenter/plantcv,danforthcenter/plantcv,stiphyMT/plantcv,stiphyMT/plantcv,danforthcenter/plantcv
- import json - import os from plantcv.plantcv import outputs def print_results(filename): """Print result table Inputs: filename = filename :param filename: str :return: """ + print("""Deprecation warning: plantcv.print_results will be removed in a future version. + Please use plantcv.outputs.save_results instead. + """) + outputs.save_results(filename=filename, outformat="json") - if os.path.isfile(filename): - with open(filename, 'r') as f: - hierarchical_data = json.load(f) - hierarchical_data["observations"] = outputs.observations - else: - hierarchical_data = {"metadata": {}, "observations": outputs.observations} - - with open(filename, mode='w') as f: - json.dump(hierarchical_data, f) -
Add deprecation warning and use new method
## Code Before: import json import os from plantcv.plantcv import outputs def print_results(filename): """Print result table Inputs: filename = filename :param filename: str :return: """ if os.path.isfile(filename): with open(filename, 'r') as f: hierarchical_data = json.load(f) hierarchical_data["observations"] = outputs.observations else: hierarchical_data = {"metadata": {}, "observations": outputs.observations} with open(filename, mode='w') as f: json.dump(hierarchical_data, f) ## Instruction: Add deprecation warning and use new method ## Code After: from plantcv.plantcv import outputs def print_results(filename): """Print result table Inputs: filename = filename :param filename: str :return: """ print("""Deprecation warning: plantcv.print_results will be removed in a future version. Please use plantcv.outputs.save_results instead. """) outputs.save_results(filename=filename, outformat="json")
- import json - import os from plantcv.plantcv import outputs def print_results(filename): """Print result table Inputs: filename = filename :param filename: str :return: """ + print("""Deprecation warning: plantcv.print_results will be removed in a future version. + Please use plantcv.outputs.save_results instead. + """) + outputs.save_results(filename=filename, outformat="json") - - if os.path.isfile(filename): - with open(filename, 'r') as f: - hierarchical_data = json.load(f) - hierarchical_data["observations"] = outputs.observations - else: - hierarchical_data = {"metadata": {}, "observations": outputs.observations} - - with open(filename, mode='w') as f: - json.dump(hierarchical_data, f)
675c6d78738a56cc556984553216ce92cf0ecd94
test/parseResults.py
test/parseResults.py
import json import sys PREFIXES = [ ["FAIL", "PASS"], ["EXPECTED FAIL", "UNEXPECTED PASS"], ] def parse_expected_failures(): expected_failures = set() with open("expected-failures.txt", "r") as fp: for line in fp: line = line.strip() if not line: continue if line.startswith("#"): continue expected_failures.add(line) return expected_failures def main(filename): expected_failures = parse_expected_failures() with open(filename, "r") as fp: results = json.load(fp) unexpected_results = [] for test in results: expected_failure = test["file"] in expected_failures actual_result = test["result"]["pass"] print("{} {}".format(PREFIXES[expected_failure][actual_result], test["file"])) if actual_result == expected_failure: if not actual_result: print(test["rawResult"]["stderr"]) print(test["rawResult"]["stdout"]) print(test["result"]["message"]) unexpected_results.append(test) if unexpected_results: print("{} unexpected results:".format(len(unexpected_results))) for unexpected in unexpected_results: print("- {}".format(unexpected["file"])) return False print("All results as expected.") return True if __name__ == "__main__": sys.exit(0 if main(sys.argv[1]) else 1)
import json import sys PREFIXES = [ ["FAIL", "PASS"], ["EXPECTED FAIL", "UNEXPECTED PASS"], ] def parse_expected_failures(): expected_failures = set() with open("expected-failures.txt", "r") as fp: for line in fp: line = line.strip() if not line: continue if line.startswith("#"): continue expected_failures.add(line) return expected_failures def main(filename): expected_failures = parse_expected_failures() with open(filename, "r") as fp: results = json.load(fp) unexpected_results = [] for test in results: expected_failure = test["file"] in expected_failures actual_result = test["result"]["pass"] print("{} {} ({})".format(PREFIXES[expected_failure][actual_result], test["file"], test["scenario"])) if actual_result == expected_failure: if not actual_result: print(test["rawResult"]["stderr"]) print(test["rawResult"]["stdout"]) print(test["result"]["message"]) unexpected_results.append(test) if unexpected_results: print("{} unexpected results:".format(len(unexpected_results))) for unexpected in unexpected_results: print("- {}".format(unexpected["file"])) return False print("All results as expected.") return True if __name__ == "__main__": sys.exit(0 if main(sys.argv[1]) else 1)
Print the scenario when running 262-style tests.
Print the scenario when running 262-style tests.
Python
isc
js-temporal/temporal-polyfill,js-temporal/temporal-polyfill,js-temporal/temporal-polyfill
import json import sys PREFIXES = [ ["FAIL", "PASS"], ["EXPECTED FAIL", "UNEXPECTED PASS"], ] def parse_expected_failures(): expected_failures = set() with open("expected-failures.txt", "r") as fp: for line in fp: line = line.strip() if not line: continue if line.startswith("#"): continue expected_failures.add(line) return expected_failures def main(filename): expected_failures = parse_expected_failures() with open(filename, "r") as fp: results = json.load(fp) unexpected_results = [] for test in results: expected_failure = test["file"] in expected_failures actual_result = test["result"]["pass"] - print("{} {}".format(PREFIXES[expected_failure][actual_result], test["file"])) + print("{} {} ({})".format(PREFIXES[expected_failure][actual_result], test["file"], test["scenario"])) if actual_result == expected_failure: if not actual_result: print(test["rawResult"]["stderr"]) print(test["rawResult"]["stdout"]) print(test["result"]["message"]) unexpected_results.append(test) if unexpected_results: print("{} unexpected results:".format(len(unexpected_results))) for unexpected in unexpected_results: print("- {}".format(unexpected["file"])) return False print("All results as expected.") return True if __name__ == "__main__": sys.exit(0 if main(sys.argv[1]) else 1)
Print the scenario when running 262-style tests.
## Code Before: import json import sys PREFIXES = [ ["FAIL", "PASS"], ["EXPECTED FAIL", "UNEXPECTED PASS"], ] def parse_expected_failures(): expected_failures = set() with open("expected-failures.txt", "r") as fp: for line in fp: line = line.strip() if not line: continue if line.startswith("#"): continue expected_failures.add(line) return expected_failures def main(filename): expected_failures = parse_expected_failures() with open(filename, "r") as fp: results = json.load(fp) unexpected_results = [] for test in results: expected_failure = test["file"] in expected_failures actual_result = test["result"]["pass"] print("{} {}".format(PREFIXES[expected_failure][actual_result], test["file"])) if actual_result == expected_failure: if not actual_result: print(test["rawResult"]["stderr"]) print(test["rawResult"]["stdout"]) print(test["result"]["message"]) unexpected_results.append(test) if unexpected_results: print("{} unexpected results:".format(len(unexpected_results))) for unexpected in unexpected_results: print("- {}".format(unexpected["file"])) return False print("All results as expected.") return True if __name__ == "__main__": sys.exit(0 if main(sys.argv[1]) else 1) ## Instruction: Print the scenario when running 262-style tests. ## Code After: import json import sys PREFIXES = [ ["FAIL", "PASS"], ["EXPECTED FAIL", "UNEXPECTED PASS"], ] def parse_expected_failures(): expected_failures = set() with open("expected-failures.txt", "r") as fp: for line in fp: line = line.strip() if not line: continue if line.startswith("#"): continue expected_failures.add(line) return expected_failures def main(filename): expected_failures = parse_expected_failures() with open(filename, "r") as fp: results = json.load(fp) unexpected_results = [] for test in results: expected_failure = test["file"] in expected_failures actual_result = test["result"]["pass"] print("{} {} ({})".format(PREFIXES[expected_failure][actual_result], test["file"], test["scenario"])) if actual_result == expected_failure: if not actual_result: print(test["rawResult"]["stderr"]) print(test["rawResult"]["stdout"]) print(test["result"]["message"]) unexpected_results.append(test) if unexpected_results: print("{} unexpected results:".format(len(unexpected_results))) for unexpected in unexpected_results: print("- {}".format(unexpected["file"])) return False print("All results as expected.") return True if __name__ == "__main__": sys.exit(0 if main(sys.argv[1]) else 1)
import json import sys PREFIXES = [ ["FAIL", "PASS"], ["EXPECTED FAIL", "UNEXPECTED PASS"], ] def parse_expected_failures(): expected_failures = set() with open("expected-failures.txt", "r") as fp: for line in fp: line = line.strip() if not line: continue if line.startswith("#"): continue expected_failures.add(line) return expected_failures def main(filename): expected_failures = parse_expected_failures() with open(filename, "r") as fp: results = json.load(fp) unexpected_results = [] for test in results: expected_failure = test["file"] in expected_failures actual_result = test["result"]["pass"] - print("{} {}".format(PREFIXES[expected_failure][actual_result], test["file"])) + print("{} {} ({})".format(PREFIXES[expected_failure][actual_result], test["file"], test["scenario"])) ? +++++ ++++++++++++++++++ if actual_result == expected_failure: if not actual_result: print(test["rawResult"]["stderr"]) print(test["rawResult"]["stdout"]) print(test["result"]["message"]) unexpected_results.append(test) if unexpected_results: print("{} unexpected results:".format(len(unexpected_results))) for unexpected in unexpected_results: print("- {}".format(unexpected["file"])) return False print("All results as expected.") return True if __name__ == "__main__": sys.exit(0 if main(sys.argv[1]) else 1)
a07ac44d433981b7476ab3b57339797edddb368c
lenet_slim.py
lenet_slim.py
import tensorflow as tf slim = tf.contrib.slim def le_net(images, num_classes=10, scope='LeNet'): with tf.variable_scope(scope, 'LeNet', [images, num_classes]): net = slim.conv2d(images, 32, [5, 5], scope='conv1') net = slim.max_pool2d(net, [2, 2], 2, scope='pool1') net = slim.conv2d(net, 64, [5, 5], scope='conv2') net = slim.max_pool2d(net, [2, 2], 2, scope='pool2') gap = tf.reduce_mean(net, (1, 2)) with tf.variable_scope('GAP'): gap_w = tf.get_variable('W', shape=[64, 10], initializer=tf.random_normal_initializer(0., 0.01)) logits = tf.matmul(gap, gap_w) return logits, net def le_net_arg_scope(weight_decay=0.0): with slim.arg_scope( [slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay), weights_initializer=tf.truncated_normal_initializer(stddev=0.1), activation_fn=tf.nn.relu) as sc: return sc
import tensorflow as tf slim = tf.contrib.slim def le_net(images, num_classes=10, scope='LeNet'): with tf.variable_scope(scope, 'LeNet', [images, num_classes]): net = slim.conv2d(images, 32, [5, 5], scope='conv1') net = slim.max_pool2d(net, [2, 2], 2, scope='pool1') net = slim.conv2d(net, 64, [5, 5], scope='conv2') net = slim.max_pool2d(net, [2, 2], 2, scope='pool2') gap = tf.reduce_mean(net, (1, 2)) with tf.variable_scope('GAP'): gap_w = tf.get_variable('W', shape=[64, num_classes], initializer=tf.random_normal_initializer(0., 0.01)) logits = tf.matmul(gap, gap_w) return logits, net def le_net_arg_scope(weight_decay=0.0): with slim.arg_scope( [slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay), weights_initializer=tf.truncated_normal_initializer(stddev=0.1), activation_fn=tf.nn.relu) as sc: return sc
Fix the shape of gap_w
Fix the shape of gap_w
Python
mit
philipperemy/tensorflow-class-activation-mapping
import tensorflow as tf slim = tf.contrib.slim def le_net(images, num_classes=10, scope='LeNet'): with tf.variable_scope(scope, 'LeNet', [images, num_classes]): net = slim.conv2d(images, 32, [5, 5], scope='conv1') net = slim.max_pool2d(net, [2, 2], 2, scope='pool1') net = slim.conv2d(net, 64, [5, 5], scope='conv2') net = slim.max_pool2d(net, [2, 2], 2, scope='pool2') gap = tf.reduce_mean(net, (1, 2)) with tf.variable_scope('GAP'): - gap_w = tf.get_variable('W', shape=[64, 10], initializer=tf.random_normal_initializer(0., 0.01)) + gap_w = tf.get_variable('W', shape=[64, num_classes], initializer=tf.random_normal_initializer(0., 0.01)) logits = tf.matmul(gap, gap_w) return logits, net def le_net_arg_scope(weight_decay=0.0): with slim.arg_scope( [slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay), weights_initializer=tf.truncated_normal_initializer(stddev=0.1), activation_fn=tf.nn.relu) as sc: return sc
Fix the shape of gap_w
## Code Before: import tensorflow as tf slim = tf.contrib.slim def le_net(images, num_classes=10, scope='LeNet'): with tf.variable_scope(scope, 'LeNet', [images, num_classes]): net = slim.conv2d(images, 32, [5, 5], scope='conv1') net = slim.max_pool2d(net, [2, 2], 2, scope='pool1') net = slim.conv2d(net, 64, [5, 5], scope='conv2') net = slim.max_pool2d(net, [2, 2], 2, scope='pool2') gap = tf.reduce_mean(net, (1, 2)) with tf.variable_scope('GAP'): gap_w = tf.get_variable('W', shape=[64, 10], initializer=tf.random_normal_initializer(0., 0.01)) logits = tf.matmul(gap, gap_w) return logits, net def le_net_arg_scope(weight_decay=0.0): with slim.arg_scope( [slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay), weights_initializer=tf.truncated_normal_initializer(stddev=0.1), activation_fn=tf.nn.relu) as sc: return sc ## Instruction: Fix the shape of gap_w ## Code After: import tensorflow as tf slim = tf.contrib.slim def le_net(images, num_classes=10, scope='LeNet'): with tf.variable_scope(scope, 'LeNet', [images, num_classes]): net = slim.conv2d(images, 32, [5, 5], scope='conv1') net = slim.max_pool2d(net, [2, 2], 2, scope='pool1') net = slim.conv2d(net, 64, [5, 5], scope='conv2') net = slim.max_pool2d(net, [2, 2], 2, scope='pool2') gap = tf.reduce_mean(net, (1, 2)) with tf.variable_scope('GAP'): gap_w = tf.get_variable('W', shape=[64, num_classes], initializer=tf.random_normal_initializer(0., 0.01)) logits = tf.matmul(gap, gap_w) return logits, net def le_net_arg_scope(weight_decay=0.0): with slim.arg_scope( [slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay), weights_initializer=tf.truncated_normal_initializer(stddev=0.1), activation_fn=tf.nn.relu) as sc: return sc
import tensorflow as tf slim = tf.contrib.slim def le_net(images, num_classes=10, scope='LeNet'): with tf.variable_scope(scope, 'LeNet', [images, num_classes]): net = slim.conv2d(images, 32, [5, 5], scope='conv1') net = slim.max_pool2d(net, [2, 2], 2, scope='pool1') net = slim.conv2d(net, 64, [5, 5], scope='conv2') net = slim.max_pool2d(net, [2, 2], 2, scope='pool2') gap = tf.reduce_mean(net, (1, 2)) with tf.variable_scope('GAP'): - gap_w = tf.get_variable('W', shape=[64, 10], initializer=tf.random_normal_initializer(0., 0.01)) ? ^^ + gap_w = tf.get_variable('W', shape=[64, num_classes], initializer=tf.random_normal_initializer(0., 0.01)) ? ^^^^^^^^^^^ logits = tf.matmul(gap, gap_w) return logits, net def le_net_arg_scope(weight_decay=0.0): with slim.arg_scope( [slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay), weights_initializer=tf.truncated_normal_initializer(stddev=0.1), activation_fn=tf.nn.relu) as sc: return sc
dca70886d2535dd843ea995b8d193958997de41b
slack_sdk/oauth/state_store/state_store.py
slack_sdk/oauth/state_store/state_store.py
from logging import Logger class OAuthStateStore: @property def logger(self) -> Logger: raise NotImplementedError() def issue(self) -> str: raise NotImplementedError() def consume(self, state: str) -> bool: raise NotImplementedError()
from logging import Logger class OAuthStateStore: @property def logger(self) -> Logger: raise NotImplementedError() def issue(self, *args, **kwargs) -> str: raise NotImplementedError() def consume(self, state: str) -> bool: raise NotImplementedError()
Enable additional data on state creation
Enable additional data on state creation This should allow for the creation of custom states where the additional data can be used to associate external accounts.
Python
mit
slackhq/python-slackclient,slackapi/python-slackclient,slackapi/python-slackclient,slackapi/python-slackclient
from logging import Logger class OAuthStateStore: @property def logger(self) -> Logger: raise NotImplementedError() - def issue(self) -> str: + def issue(self, *args, **kwargs) -> str: raise NotImplementedError() def consume(self, state: str) -> bool: raise NotImplementedError()
Enable additional data on state creation
## Code Before: from logging import Logger class OAuthStateStore: @property def logger(self) -> Logger: raise NotImplementedError() def issue(self) -> str: raise NotImplementedError() def consume(self, state: str) -> bool: raise NotImplementedError() ## Instruction: Enable additional data on state creation ## Code After: from logging import Logger class OAuthStateStore: @property def logger(self) -> Logger: raise NotImplementedError() def issue(self, *args, **kwargs) -> str: raise NotImplementedError() def consume(self, state: str) -> bool: raise NotImplementedError()
from logging import Logger class OAuthStateStore: @property def logger(self) -> Logger: raise NotImplementedError() - def issue(self) -> str: + def issue(self, *args, **kwargs) -> str: ? +++++++++++++++++ raise NotImplementedError() def consume(self, state: str) -> bool: raise NotImplementedError()
8c6b4396047736d5caf00ec30b4283ee7cdc793e
lighty/wsgi/decorators.py
lighty/wsgi/decorators.py
''' ''' import functools import operator from .. import monads def view(func, **constraints): '''Functions that decorates a view. This function can also checks the argument values ''' func.is_view = True @functools.wraps(func) def wrapper(*args, **kwargs): try: if not functools.reduce(operator.__and__, [constraints[arg](kwargs[arg]) for arg in constraints]): return monads.NoneMonad(ValueError( 'Wrong view argument value')) return monads.ValueMonad(func(*args, **kwargs)) except Exception as e: return monads.NoneMonad(e) return wrapper
''' ''' import functools import operator from .. import monads def view(func, **constraints): '''Functions that decorates a view. This function can also checks the argument values ''' func.is_view = True @functools.wraps(func) @monads.handle_exception def wrapper(*args, **kwargs): if not functools.reduce(operator.__and__, [constraints[arg](kwargs[arg]) for arg in constraints]): return monads.NoneMonad(ValueError('Wrong view argument value')) return monads.ValueMonad(func(*args, **kwargs)) return wrapper
Use exception handling with decorator
Use exception handling with decorator
Python
bsd-3-clause
GrAndSE/lighty
''' ''' import functools import operator from .. import monads def view(func, **constraints): '''Functions that decorates a view. This function can also checks the argument values ''' func.is_view = True @functools.wraps(func) + @monads.handle_exception def wrapper(*args, **kwargs): - try: - if not functools.reduce(operator.__and__, + if not functools.reduce(operator.__and__, - [constraints[arg](kwargs[arg]) + [constraints[arg](kwargs[arg]) - for arg in constraints]): + for arg in constraints]): + return monads.NoneMonad(ValueError('Wrong view argument value')) - return monads.NoneMonad(ValueError( - 'Wrong view argument value')) - return monads.ValueMonad(func(*args, **kwargs)) + return monads.ValueMonad(func(*args, **kwargs)) - except Exception as e: - return monads.NoneMonad(e) return wrapper
Use exception handling with decorator
## Code Before: ''' ''' import functools import operator from .. import monads def view(func, **constraints): '''Functions that decorates a view. This function can also checks the argument values ''' func.is_view = True @functools.wraps(func) def wrapper(*args, **kwargs): try: if not functools.reduce(operator.__and__, [constraints[arg](kwargs[arg]) for arg in constraints]): return monads.NoneMonad(ValueError( 'Wrong view argument value')) return monads.ValueMonad(func(*args, **kwargs)) except Exception as e: return monads.NoneMonad(e) return wrapper ## Instruction: Use exception handling with decorator ## Code After: ''' ''' import functools import operator from .. import monads def view(func, **constraints): '''Functions that decorates a view. This function can also checks the argument values ''' func.is_view = True @functools.wraps(func) @monads.handle_exception def wrapper(*args, **kwargs): if not functools.reduce(operator.__and__, [constraints[arg](kwargs[arg]) for arg in constraints]): return monads.NoneMonad(ValueError('Wrong view argument value')) return monads.ValueMonad(func(*args, **kwargs)) return wrapper
''' ''' import functools import operator from .. import monads def view(func, **constraints): '''Functions that decorates a view. This function can also checks the argument values ''' func.is_view = True @functools.wraps(func) + @monads.handle_exception def wrapper(*args, **kwargs): - try: - if not functools.reduce(operator.__and__, ? ---- + if not functools.reduce(operator.__and__, ? + - [constraints[arg](kwargs[arg]) ? ---- + [constraints[arg](kwargs[arg]) - for arg in constraints]): ? ---- + for arg in constraints]): + return monads.NoneMonad(ValueError('Wrong view argument value')) - return monads.NoneMonad(ValueError( - 'Wrong view argument value')) - return monads.ValueMonad(func(*args, **kwargs)) ? ---- + return monads.ValueMonad(func(*args, **kwargs)) - except Exception as e: - return monads.NoneMonad(e) return wrapper
22db373a8b33b201a8964b3f518434289b2a57af
app/__init__.py
app/__init__.py
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.mail import Mail from flask.ext.moment import Moment from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config bootstrap = Bootstrap() mail = Mail() moment = Moment() db = SQLAlchemy() login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'auth.login' def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') return app
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.mail import Mail from flask.ext.moment import Moment from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config bootstrap = Bootstrap() mail = Mail() moment = Moment() db = SQLAlchemy() login_manager = LoginManager() login_manager.login_view = 'auth.login' def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') return app
Remove duplicate Flask-Login session protection setting
Remove duplicate Flask-Login session protection setting
Python
mit
richgieg/flask-now,richgieg/flask-now
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.mail import Mail from flask.ext.moment import Moment from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config bootstrap = Bootstrap() mail = Mail() moment = Moment() db = SQLAlchemy() login_manager = LoginManager() - login_manager.session_protection = 'strong' login_manager.login_view = 'auth.login' def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') return app
Remove duplicate Flask-Login session protection setting
## Code Before: from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.mail import Mail from flask.ext.moment import Moment from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config bootstrap = Bootstrap() mail = Mail() moment = Moment() db = SQLAlchemy() login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'auth.login' def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') return app ## Instruction: Remove duplicate Flask-Login session protection setting ## Code After: from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.mail import Mail from flask.ext.moment import Moment from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config bootstrap = Bootstrap() mail = Mail() moment = Moment() db = SQLAlchemy() login_manager = LoginManager() login_manager.login_view = 'auth.login' def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') return app
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.mail import Mail from flask.ext.moment import Moment from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config bootstrap = Bootstrap() mail = Mail() moment = Moment() db = SQLAlchemy() login_manager = LoginManager() - login_manager.session_protection = 'strong' login_manager.login_view = 'auth.login' def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') return app