commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
0
2.94k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
444
message
stringlengths
16
3.45k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43.2k
prompt
stringlengths
17
4.58k
response
stringlengths
1
4.43k
prompt_tagged
stringlengths
58
4.62k
response_tagged
stringlengths
1
4.43k
text
stringlengths
132
7.29k
text_tagged
stringlengths
173
7.33k
e560ea4a419e1e61d776245b99ffa0e60b4d0e22
InvenTree/stock/forms.py
InvenTree/stock/forms.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from InvenTree.forms import HelperForm from .models import StockLocation, StockItem class EditStockLocationForm(HelperForm): class Meta: model = StockLocation fields = [ 'name', 'parent', 'description' ] class CreateStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'part', 'supplier_part', 'location', 'belongs_to', 'serial', 'batch', 'quantity', 'status', # 'customer', 'URL', ] class MoveStockItemForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'location', ] class StocktakeForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'quantity', ] class EditStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'quantity', 'batch', 'status', ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from InvenTree.forms import HelperForm from .models import StockLocation, StockItem class EditStockLocationForm(HelperForm): class Meta: model = StockLocation fields = [ 'name', 'parent', 'description' ] class CreateStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'part', 'supplier_part', 'location', 'belongs_to', 'serial', 'batch', 'quantity', 'status', # 'customer', 'URL', ] class MoveStockItemForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'location', ] class StocktakeForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'quantity', ] class EditStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'batch', 'status', 'notes' ]
Update edit form for StockItem
Update edit form for StockItem - Disallow direct quantity editing (must perform stocktake) - Add notes field to allow editing
Python
mit
SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from InvenTree.forms import HelperForm from .models import StockLocation, StockItem class EditStockLocationForm(HelperForm): class Meta: model = StockLocation fields = [ 'name', 'parent', 'description' ] class CreateStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'part', 'supplier_part', 'location', 'belongs_to', 'serial', 'batch', 'quantity', 'status', # 'customer', 'URL', ] class MoveStockItemForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'location', ] class StocktakeForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'quantity', ] class EditStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'quantity', 'batch', 'status', ]Update edit form for StockItem - Disallow direct quantity editing (must perform stocktake) - Add notes field to allow editing
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from InvenTree.forms import HelperForm from .models import StockLocation, StockItem class EditStockLocationForm(HelperForm): class Meta: model = StockLocation fields = [ 'name', 'parent', 'description' ] class CreateStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'part', 'supplier_part', 'location', 'belongs_to', 'serial', 'batch', 'quantity', 'status', # 'customer', 'URL', ] class MoveStockItemForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'location', ] class StocktakeForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'quantity', ] class EditStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'batch', 'status', 'notes' ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from InvenTree.forms import HelperForm from .models import StockLocation, StockItem class EditStockLocationForm(HelperForm): class Meta: model = StockLocation fields = [ 'name', 'parent', 'description' ] class CreateStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'part', 'supplier_part', 'location', 'belongs_to', 'serial', 'batch', 'quantity', 'status', # 'customer', 'URL', ] class MoveStockItemForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'location', ] class StocktakeForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'quantity', ] class EditStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'quantity', 'batch', 'status', ]<commit_msg>Update edit form for StockItem - Disallow direct quantity editing (must perform stocktake) - Add notes field to allow editing<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from InvenTree.forms import HelperForm from .models import StockLocation, StockItem class EditStockLocationForm(HelperForm): class Meta: model = StockLocation fields = [ 'name', 'parent', 'description' ] class CreateStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'part', 'supplier_part', 'location', 'belongs_to', 'serial', 'batch', 'quantity', 'status', # 'customer', 'URL', ] class MoveStockItemForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'location', ] class StocktakeForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'quantity', ] class EditStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'batch', 'status', 'notes' ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from InvenTree.forms import HelperForm from .models import StockLocation, StockItem class EditStockLocationForm(HelperForm): class Meta: model = StockLocation fields = [ 'name', 'parent', 'description' ] class CreateStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'part', 'supplier_part', 'location', 'belongs_to', 'serial', 'batch', 'quantity', 'status', # 'customer', 'URL', ] class MoveStockItemForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'location', ] class StocktakeForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'quantity', ] class EditStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'quantity', 'batch', 'status', ]Update edit form for StockItem - Disallow direct quantity editing (must perform stocktake) - Add notes field to allow editing# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from InvenTree.forms import HelperForm from .models import StockLocation, StockItem class EditStockLocationForm(HelperForm): class Meta: model = StockLocation fields = [ 'name', 'parent', 'description' ] class CreateStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'part', 'supplier_part', 'location', 'belongs_to', 'serial', 'batch', 'quantity', 'status', # 'customer', 'URL', ] class MoveStockItemForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'location', ] class StocktakeForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'quantity', ] class EditStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'batch', 'status', 'notes' ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from InvenTree.forms import HelperForm from .models import StockLocation, StockItem class EditStockLocationForm(HelperForm): class Meta: model = StockLocation fields = [ 'name', 'parent', 'description' ] class CreateStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'part', 'supplier_part', 'location', 'belongs_to', 'serial', 'batch', 'quantity', 'status', # 'customer', 'URL', ] class MoveStockItemForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'location', ] class StocktakeForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'quantity', ] class EditStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'quantity', 'batch', 'status', ]<commit_msg>Update edit form for StockItem - Disallow direct quantity editing (must perform stocktake) - Add notes field to allow editing<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from InvenTree.forms import HelperForm from .models import StockLocation, StockItem class EditStockLocationForm(HelperForm): class Meta: model = StockLocation fields = [ 'name', 'parent', 'description' ] class CreateStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'part', 'supplier_part', 'location', 'belongs_to', 'serial', 'batch', 'quantity', 'status', # 'customer', 'URL', ] class MoveStockItemForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'location', ] class StocktakeForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'quantity', ] class EditStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'batch', 'status', 'notes' ]
f2b4e4758ae60526e8bb5c57e9c45b0a1901fa14
wagtail/wagtailforms/edit_handlers.py
wagtail/wagtailforms/edit_handlers.py
from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model._meta.model_name) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, })
from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model.get_verbose_name()) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, })
Use verbose name for FormSubmissionsPanel heading
Use verbose name for FormSubmissionsPanel heading
Python
bsd-3-clause
rsalmaso/wagtail,takeflight/wagtail,torchbox/wagtail,rsalmaso/wagtail,FlipperPA/wagtail,zerolab/wagtail,jnns/wagtail,nimasmi/wagtail,kaedroho/wagtail,thenewguy/wagtail,zerolab/wagtail,mikedingjan/wagtail,nimasmi/wagtail,wagtail/wagtail,thenewguy/wagtail,nutztherookie/wagtail,takeflight/wagtail,chrxr/wagtail,jnns/wagtail,gasman/wagtail,rsalmaso/wagtail,chrxr/wagtail,kaedroho/wagtail,gasman/wagtail,thenewguy/wagtail,nilnvoid/wagtail,wagtail/wagtail,timorieber/wagtail,torchbox/wagtail,timorieber/wagtail,zerolab/wagtail,thenewguy/wagtail,zerolab/wagtail,nutztherookie/wagtail,chrxr/wagtail,wagtail/wagtail,Toshakins/wagtail,iansprice/wagtail,iansprice/wagtail,rsalmaso/wagtail,gasman/wagtail,zerolab/wagtail,mixxorz/wagtail,nealtodd/wagtail,jnns/wagtail,timorieber/wagtail,kaedroho/wagtail,mikedingjan/wagtail,takeflight/wagtail,FlipperPA/wagtail,kaedroho/wagtail,Toshakins/wagtail,mixxorz/wagtail,nutztherookie/wagtail,nilnvoid/wagtail,nealtodd/wagtail,FlipperPA/wagtail,nutztherookie/wagtail,rsalmaso/wagtail,torchbox/wagtail,gasman/wagtail,Toshakins/wagtail,mixxorz/wagtail,kaedroho/wagtail,thenewguy/wagtail,chrxr/wagtail,nealtodd/wagtail,torchbox/wagtail,nilnvoid/wagtail,mixxorz/wagtail,mikedingjan/wagtail,gasman/wagtail,FlipperPA/wagtail,nimasmi/wagtail,timorieber/wagtail,Toshakins/wagtail,wagtail/wagtail,iansprice/wagtail,mikedingjan/wagtail,nilnvoid/wagtail,mixxorz/wagtail,nealtodd/wagtail,iansprice/wagtail,wagtail/wagtail,jnns/wagtail,nimasmi/wagtail,takeflight/wagtail
from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model._meta.model_name) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, }) Use verbose name for FormSubmissionsPanel heading
from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model.get_verbose_name()) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, })
<commit_before>from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model._meta.model_name) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, }) <commit_msg>Use verbose name for FormSubmissionsPanel heading<commit_after>
from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model.get_verbose_name()) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, })
from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model._meta.model_name) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, }) Use verbose name for FormSubmissionsPanel headingfrom __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model.get_verbose_name()) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, })
<commit_before>from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model._meta.model_name) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, }) <commit_msg>Use verbose name for FormSubmissionsPanel heading<commit_after>from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" def render(self): from .models import FormSubmission submissions = FormSubmission.objects.filter(page=self.instance) if not submissions: return '' return mark_safe(render_to_string(self.template, { 'self': self, 'submissions': submissions })) class FormSubmissionsPanel(object): def __init__(self, heading=None): self.heading = heading def bind_to_model(self, model): heading = _('{} submissions').format(model.get_verbose_name()) return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), { 'model': model, 'heading': self.heading or heading, })
8026b5f309264d4e72c3bc503601468cf1cdfcdd
src/nodeconductor_assembly_waldur/packages/filters.py
src/nodeconductor_assembly_waldur/packages/filters.py
import django_filters from nodeconductor.core.filters import UUIDFilter from . import models class PackageTemplateFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = models.PackageTemplate fields = ('name', 'settings_uuid',) class OpenStackPackageFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = models.OpenStackPackage fields = ('name', 'settings_uuid',)
import django_filters from nodeconductor.core.filters import UUIDFilter from . import models class PackageTemplateFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = models.PackageTemplate fields = ('name', 'settings_uuid',) class OpenStackPackageFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') customer = UUIDFilter(name='tenant__service_project_link__project__customer') project = UUIDFilter(name='tenant__service_project_link__project') class Meta(object): model = models.OpenStackPackage fields = ('name', 'customer', 'project')
Enable filtering OpenStack package by customer and project (WAL-49)
Enable filtering OpenStack package by customer and project (WAL-49)
Python
mit
opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur
import django_filters from nodeconductor.core.filters import UUIDFilter from . import models class PackageTemplateFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = models.PackageTemplate fields = ('name', 'settings_uuid',) class OpenStackPackageFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = models.OpenStackPackage fields = ('name', 'settings_uuid',) Enable filtering OpenStack package by customer and project (WAL-49)
import django_filters from nodeconductor.core.filters import UUIDFilter from . import models class PackageTemplateFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = models.PackageTemplate fields = ('name', 'settings_uuid',) class OpenStackPackageFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') customer = UUIDFilter(name='tenant__service_project_link__project__customer') project = UUIDFilter(name='tenant__service_project_link__project') class Meta(object): model = models.OpenStackPackage fields = ('name', 'customer', 'project')
<commit_before>import django_filters from nodeconductor.core.filters import UUIDFilter from . import models class PackageTemplateFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = models.PackageTemplate fields = ('name', 'settings_uuid',) class OpenStackPackageFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = models.OpenStackPackage fields = ('name', 'settings_uuid',) <commit_msg>Enable filtering OpenStack package by customer and project (WAL-49)<commit_after>
import django_filters from nodeconductor.core.filters import UUIDFilter from . import models class PackageTemplateFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = models.PackageTemplate fields = ('name', 'settings_uuid',) class OpenStackPackageFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') customer = UUIDFilter(name='tenant__service_project_link__project__customer') project = UUIDFilter(name='tenant__service_project_link__project') class Meta(object): model = models.OpenStackPackage fields = ('name', 'customer', 'project')
import django_filters from nodeconductor.core.filters import UUIDFilter from . import models class PackageTemplateFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = models.PackageTemplate fields = ('name', 'settings_uuid',) class OpenStackPackageFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = models.OpenStackPackage fields = ('name', 'settings_uuid',) Enable filtering OpenStack package by customer and project (WAL-49)import django_filters from nodeconductor.core.filters import UUIDFilter from . import models class PackageTemplateFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = models.PackageTemplate fields = ('name', 'settings_uuid',) class OpenStackPackageFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') customer = UUIDFilter(name='tenant__service_project_link__project__customer') project = UUIDFilter(name='tenant__service_project_link__project') class Meta(object): model = models.OpenStackPackage fields = ('name', 'customer', 'project')
<commit_before>import django_filters from nodeconductor.core.filters import UUIDFilter from . import models class PackageTemplateFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = models.PackageTemplate fields = ('name', 'settings_uuid',) class OpenStackPackageFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = models.OpenStackPackage fields = ('name', 'settings_uuid',) <commit_msg>Enable filtering OpenStack package by customer and project (WAL-49)<commit_after>import django_filters from nodeconductor.core.filters import UUIDFilter from . import models class PackageTemplateFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = models.PackageTemplate fields = ('name', 'settings_uuid',) class OpenStackPackageFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') customer = UUIDFilter(name='tenant__service_project_link__project__customer') project = UUIDFilter(name='tenant__service_project_link__project') class Meta(object): model = models.OpenStackPackage fields = ('name', 'customer', 'project')
79614ed2cf4936358a2f7beca703210720883df2
netbox/netbox/graphql/types.py
netbox/netbox/graphql/types.py
import graphene from graphene.types.generic import GenericScalar from graphene_django import DjangoObjectType __all__ = ( 'BaseObjectType', 'ObjectType', 'TaggedObjectType', ) class BaseObjectType(DjangoObjectType): """ Base GraphQL object type for all NetBox objects """ class Meta: abstract = True @classmethod def get_queryset(cls, queryset, info): # Enforce object permissions on the queryset return queryset.restrict(info.context.user, 'view') class ObjectType(BaseObjectType): """ Extends BaseObjectType with support for custom field data. """ # custom_fields = GenericScalar() class Meta: abstract = True # def resolve_custom_fields(self, info): # return self.custom_field_data class TaggedObjectType(ObjectType): """ Extends ObjectType with support for Tags """ tags = graphene.List(graphene.String) class Meta: abstract = True def resolve_tags(self, info): return self.tags.all()
import graphene from django.contrib.contenttypes.models import ContentType from graphene.types.generic import GenericScalar from graphene_django import DjangoObjectType __all__ = ( 'BaseObjectType', 'ObjectType', 'TaggedObjectType', ) # # Base types # class BaseObjectType(DjangoObjectType): """ Base GraphQL object type for all NetBox objects """ class Meta: abstract = True @classmethod def get_queryset(cls, queryset, info): # Enforce object permissions on the queryset return queryset.restrict(info.context.user, 'view') class ObjectType(BaseObjectType): """ Extends BaseObjectType with support for custom field data. """ custom_fields = GenericScalar() class Meta: abstract = True def resolve_custom_fields(self, info): return self.custom_field_data class TaggedObjectType(ObjectType): """ Extends ObjectType with support for Tags """ tags = graphene.List(graphene.String) class Meta: abstract = True def resolve_tags(self, info): return self.tags.all() # # Miscellaneous types # class ContentTypeType(DjangoObjectType): class Meta: model = ContentType fields = ('id', 'app_label', 'model')
Add GraphQL type for ContentType
Add GraphQL type for ContentType
Python
apache-2.0
digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,digitalocean/netbox
import graphene from graphene.types.generic import GenericScalar from graphene_django import DjangoObjectType __all__ = ( 'BaseObjectType', 'ObjectType', 'TaggedObjectType', ) class BaseObjectType(DjangoObjectType): """ Base GraphQL object type for all NetBox objects """ class Meta: abstract = True @classmethod def get_queryset(cls, queryset, info): # Enforce object permissions on the queryset return queryset.restrict(info.context.user, 'view') class ObjectType(BaseObjectType): """ Extends BaseObjectType with support for custom field data. """ # custom_fields = GenericScalar() class Meta: abstract = True # def resolve_custom_fields(self, info): # return self.custom_field_data class TaggedObjectType(ObjectType): """ Extends ObjectType with support for Tags """ tags = graphene.List(graphene.String) class Meta: abstract = True def resolve_tags(self, info): return self.tags.all() Add GraphQL type for ContentType
import graphene from django.contrib.contenttypes.models import ContentType from graphene.types.generic import GenericScalar from graphene_django import DjangoObjectType __all__ = ( 'BaseObjectType', 'ObjectType', 'TaggedObjectType', ) # # Base types # class BaseObjectType(DjangoObjectType): """ Base GraphQL object type for all NetBox objects """ class Meta: abstract = True @classmethod def get_queryset(cls, queryset, info): # Enforce object permissions on the queryset return queryset.restrict(info.context.user, 'view') class ObjectType(BaseObjectType): """ Extends BaseObjectType with support for custom field data. """ custom_fields = GenericScalar() class Meta: abstract = True def resolve_custom_fields(self, info): return self.custom_field_data class TaggedObjectType(ObjectType): """ Extends ObjectType with support for Tags """ tags = graphene.List(graphene.String) class Meta: abstract = True def resolve_tags(self, info): return self.tags.all() # # Miscellaneous types # class ContentTypeType(DjangoObjectType): class Meta: model = ContentType fields = ('id', 'app_label', 'model')
<commit_before>import graphene from graphene.types.generic import GenericScalar from graphene_django import DjangoObjectType __all__ = ( 'BaseObjectType', 'ObjectType', 'TaggedObjectType', ) class BaseObjectType(DjangoObjectType): """ Base GraphQL object type for all NetBox objects """ class Meta: abstract = True @classmethod def get_queryset(cls, queryset, info): # Enforce object permissions on the queryset return queryset.restrict(info.context.user, 'view') class ObjectType(BaseObjectType): """ Extends BaseObjectType with support for custom field data. """ # custom_fields = GenericScalar() class Meta: abstract = True # def resolve_custom_fields(self, info): # return self.custom_field_data class TaggedObjectType(ObjectType): """ Extends ObjectType with support for Tags """ tags = graphene.List(graphene.String) class Meta: abstract = True def resolve_tags(self, info): return self.tags.all() <commit_msg>Add GraphQL type for ContentType<commit_after>
import graphene from django.contrib.contenttypes.models import ContentType from graphene.types.generic import GenericScalar from graphene_django import DjangoObjectType __all__ = ( 'BaseObjectType', 'ObjectType', 'TaggedObjectType', ) # # Base types # class BaseObjectType(DjangoObjectType): """ Base GraphQL object type for all NetBox objects """ class Meta: abstract = True @classmethod def get_queryset(cls, queryset, info): # Enforce object permissions on the queryset return queryset.restrict(info.context.user, 'view') class ObjectType(BaseObjectType): """ Extends BaseObjectType with support for custom field data. """ custom_fields = GenericScalar() class Meta: abstract = True def resolve_custom_fields(self, info): return self.custom_field_data class TaggedObjectType(ObjectType): """ Extends ObjectType with support for Tags """ tags = graphene.List(graphene.String) class Meta: abstract = True def resolve_tags(self, info): return self.tags.all() # # Miscellaneous types # class ContentTypeType(DjangoObjectType): class Meta: model = ContentType fields = ('id', 'app_label', 'model')
import graphene from graphene.types.generic import GenericScalar from graphene_django import DjangoObjectType __all__ = ( 'BaseObjectType', 'ObjectType', 'TaggedObjectType', ) class BaseObjectType(DjangoObjectType): """ Base GraphQL object type for all NetBox objects """ class Meta: abstract = True @classmethod def get_queryset(cls, queryset, info): # Enforce object permissions on the queryset return queryset.restrict(info.context.user, 'view') class ObjectType(BaseObjectType): """ Extends BaseObjectType with support for custom field data. """ # custom_fields = GenericScalar() class Meta: abstract = True # def resolve_custom_fields(self, info): # return self.custom_field_data class TaggedObjectType(ObjectType): """ Extends ObjectType with support for Tags """ tags = graphene.List(graphene.String) class Meta: abstract = True def resolve_tags(self, info): return self.tags.all() Add GraphQL type for ContentTypeimport graphene from django.contrib.contenttypes.models import ContentType from graphene.types.generic import GenericScalar from graphene_django import DjangoObjectType __all__ = ( 'BaseObjectType', 'ObjectType', 'TaggedObjectType', ) # # Base types # class BaseObjectType(DjangoObjectType): """ Base GraphQL object type for all NetBox objects """ class Meta: abstract = True @classmethod def get_queryset(cls, queryset, info): # Enforce object permissions on the queryset return queryset.restrict(info.context.user, 'view') class ObjectType(BaseObjectType): """ Extends BaseObjectType with support for custom field data. """ custom_fields = GenericScalar() class Meta: abstract = True def resolve_custom_fields(self, info): return self.custom_field_data class TaggedObjectType(ObjectType): """ Extends ObjectType with support for Tags """ tags = graphene.List(graphene.String) class Meta: abstract = True def resolve_tags(self, info): return self.tags.all() # # Miscellaneous types # class ContentTypeType(DjangoObjectType): class Meta: model = ContentType fields = ('id', 'app_label', 'model')
<commit_before>import graphene from graphene.types.generic import GenericScalar from graphene_django import DjangoObjectType __all__ = ( 'BaseObjectType', 'ObjectType', 'TaggedObjectType', ) class BaseObjectType(DjangoObjectType): """ Base GraphQL object type for all NetBox objects """ class Meta: abstract = True @classmethod def get_queryset(cls, queryset, info): # Enforce object permissions on the queryset return queryset.restrict(info.context.user, 'view') class ObjectType(BaseObjectType): """ Extends BaseObjectType with support for custom field data. """ # custom_fields = GenericScalar() class Meta: abstract = True # def resolve_custom_fields(self, info): # return self.custom_field_data class TaggedObjectType(ObjectType): """ Extends ObjectType with support for Tags """ tags = graphene.List(graphene.String) class Meta: abstract = True def resolve_tags(self, info): return self.tags.all() <commit_msg>Add GraphQL type for ContentType<commit_after>import graphene from django.contrib.contenttypes.models import ContentType from graphene.types.generic import GenericScalar from graphene_django import DjangoObjectType __all__ = ( 'BaseObjectType', 'ObjectType', 'TaggedObjectType', ) # # Base types # class BaseObjectType(DjangoObjectType): """ Base GraphQL object type for all NetBox objects """ class Meta: abstract = True @classmethod def get_queryset(cls, queryset, info): # Enforce object permissions on the queryset return queryset.restrict(info.context.user, 'view') class ObjectType(BaseObjectType): """ Extends BaseObjectType with support for custom field data. """ custom_fields = GenericScalar() class Meta: abstract = True def resolve_custom_fields(self, info): return self.custom_field_data class TaggedObjectType(ObjectType): """ Extends ObjectType with support for Tags """ tags = graphene.List(graphene.String) class Meta: abstract = True def resolve_tags(self, info): return self.tags.all() # # Miscellaneous types # class ContentTypeType(DjangoObjectType): class Meta: model = ContentType fields = ('id', 'app_label', 'model')
b55812bd94b20a31ba2f9a64eedbcbb811dc4257
camkes/internal/dictutils.py
camkes/internal/dictutils.py
# # Copyright 2014, NICTA # # This software may be distributed and modified according to the terms of # the BSD 2-Clause license. Note that NO WARRANTY is provided. # See "LICENSE_BSD2.txt" for details. # # @TAG(NICTA_BSD) # '''Various helpers for doing advanced things with dictionaries.''' def get_fields(s): '''Return a set of field names referenced as formatting keys in the given string. I thought there would be an easier way to get this, but I can't find one. E.g. get_fields('%(hello)s %(world)s') returns set('hello', 'world').''' class FakeDict(dict): def __init__(self): super(FakeDict, self).__init__() self.referenced = set() def __getitem__(self, key): self.referenced.add(key) return '' f = FakeDict() s % f # Value deliberately discarded return f.referenced class Guard(object): '''Representation of a condition required for some action. See usage in Template.py.''' def __init__(self, guard_fn): self.guard_fn = guard_fn def __call__(self, arg): return self.guard_fn(arg)
# # Copyright 2014, NICTA # # This software may be distributed and modified according to the terms of # the BSD 2-Clause license. Note that NO WARRANTY is provided. # See "LICENSE_BSD2.txt" for details. # # @TAG(NICTA_BSD) # '''Various helpers for doing advanced things with dictionaries.''' import re def get_fields(s): '''Return a set of field names referenced as formatting keys in the given string. I thought there would be an easier way to get this, but I can't find one. E.g. get_fields('%(hello)s %(world)s') returns set('hello', 'world').''' return set(re.findall(r'%\(([^)]+)\)', s)) class Guard(object): '''Representation of a condition required for some action. See usage in Template.py.''' def __init__(self, guard_fn): self.guard_fn = guard_fn def __call__(self, arg): return self.guard_fn(arg)
Support non-string formats in `get_fields`.
Support non-string formats in `get_fields`. This commit rewrites the `get_fields` function to be simpler and more general. The previous implementation relied on ad hoc dict mocking and only supported format strings involving string-valued formats ('%(name)s'). From this commit other formats (e.g. '%(name)04d') are supported. The motivation for this is upcoming changes to how the DMA pool frames are named.
Python
bsd-2-clause
smaccm/camkes-tool,smaccm/camkes-tool,smaccm/camkes-tool,smaccm/camkes-tool
# # Copyright 2014, NICTA # # This software may be distributed and modified according to the terms of # the BSD 2-Clause license. Note that NO WARRANTY is provided. # See "LICENSE_BSD2.txt" for details. # # @TAG(NICTA_BSD) # '''Various helpers for doing advanced things with dictionaries.''' def get_fields(s): '''Return a set of field names referenced as formatting keys in the given string. I thought there would be an easier way to get this, but I can't find one. E.g. get_fields('%(hello)s %(world)s') returns set('hello', 'world').''' class FakeDict(dict): def __init__(self): super(FakeDict, self).__init__() self.referenced = set() def __getitem__(self, key): self.referenced.add(key) return '' f = FakeDict() s % f # Value deliberately discarded return f.referenced class Guard(object): '''Representation of a condition required for some action. See usage in Template.py.''' def __init__(self, guard_fn): self.guard_fn = guard_fn def __call__(self, arg): return self.guard_fn(arg) Support non-string formats in `get_fields`. This commit rewrites the `get_fields` function to be simpler and more general. The previous implementation relied on ad hoc dict mocking and only supported format strings involving string-valued formats ('%(name)s'). From this commit other formats (e.g. '%(name)04d') are supported. The motivation for this is upcoming changes to how the DMA pool frames are named.
# # Copyright 2014, NICTA # # This software may be distributed and modified according to the terms of # the BSD 2-Clause license. Note that NO WARRANTY is provided. # See "LICENSE_BSD2.txt" for details. # # @TAG(NICTA_BSD) # '''Various helpers for doing advanced things with dictionaries.''' import re def get_fields(s): '''Return a set of field names referenced as formatting keys in the given string. I thought there would be an easier way to get this, but I can't find one. E.g. get_fields('%(hello)s %(world)s') returns set('hello', 'world').''' return set(re.findall(r'%\(([^)]+)\)', s)) class Guard(object): '''Representation of a condition required for some action. See usage in Template.py.''' def __init__(self, guard_fn): self.guard_fn = guard_fn def __call__(self, arg): return self.guard_fn(arg)
<commit_before># # Copyright 2014, NICTA # # This software may be distributed and modified according to the terms of # the BSD 2-Clause license. Note that NO WARRANTY is provided. # See "LICENSE_BSD2.txt" for details. # # @TAG(NICTA_BSD) # '''Various helpers for doing advanced things with dictionaries.''' def get_fields(s): '''Return a set of field names referenced as formatting keys in the given string. I thought there would be an easier way to get this, but I can't find one. E.g. get_fields('%(hello)s %(world)s') returns set('hello', 'world').''' class FakeDict(dict): def __init__(self): super(FakeDict, self).__init__() self.referenced = set() def __getitem__(self, key): self.referenced.add(key) return '' f = FakeDict() s % f # Value deliberately discarded return f.referenced class Guard(object): '''Representation of a condition required for some action. See usage in Template.py.''' def __init__(self, guard_fn): self.guard_fn = guard_fn def __call__(self, arg): return self.guard_fn(arg) <commit_msg>Support non-string formats in `get_fields`. This commit rewrites the `get_fields` function to be simpler and more general. The previous implementation relied on ad hoc dict mocking and only supported format strings involving string-valued formats ('%(name)s'). From this commit other formats (e.g. '%(name)04d') are supported. The motivation for this is upcoming changes to how the DMA pool frames are named.<commit_after>
# # Copyright 2014, NICTA # # This software may be distributed and modified according to the terms of # the BSD 2-Clause license. Note that NO WARRANTY is provided. # See "LICENSE_BSD2.txt" for details. # # @TAG(NICTA_BSD) # '''Various helpers for doing advanced things with dictionaries.''' import re def get_fields(s): '''Return a set of field names referenced as formatting keys in the given string. I thought there would be an easier way to get this, but I can't find one. E.g. get_fields('%(hello)s %(world)s') returns set('hello', 'world').''' return set(re.findall(r'%\(([^)]+)\)', s)) class Guard(object): '''Representation of a condition required for some action. See usage in Template.py.''' def __init__(self, guard_fn): self.guard_fn = guard_fn def __call__(self, arg): return self.guard_fn(arg)
# # Copyright 2014, NICTA # # This software may be distributed and modified according to the terms of # the BSD 2-Clause license. Note that NO WARRANTY is provided. # See "LICENSE_BSD2.txt" for details. # # @TAG(NICTA_BSD) # '''Various helpers for doing advanced things with dictionaries.''' def get_fields(s): '''Return a set of field names referenced as formatting keys in the given string. I thought there would be an easier way to get this, but I can't find one. E.g. get_fields('%(hello)s %(world)s') returns set('hello', 'world').''' class FakeDict(dict): def __init__(self): super(FakeDict, self).__init__() self.referenced = set() def __getitem__(self, key): self.referenced.add(key) return '' f = FakeDict() s % f # Value deliberately discarded return f.referenced class Guard(object): '''Representation of a condition required for some action. See usage in Template.py.''' def __init__(self, guard_fn): self.guard_fn = guard_fn def __call__(self, arg): return self.guard_fn(arg) Support non-string formats in `get_fields`. This commit rewrites the `get_fields` function to be simpler and more general. The previous implementation relied on ad hoc dict mocking and only supported format strings involving string-valued formats ('%(name)s'). From this commit other formats (e.g. '%(name)04d') are supported. The motivation for this is upcoming changes to how the DMA pool frames are named.# # Copyright 2014, NICTA # # This software may be distributed and modified according to the terms of # the BSD 2-Clause license. Note that NO WARRANTY is provided. # See "LICENSE_BSD2.txt" for details. # # @TAG(NICTA_BSD) # '''Various helpers for doing advanced things with dictionaries.''' import re def get_fields(s): '''Return a set of field names referenced as formatting keys in the given string. I thought there would be an easier way to get this, but I can't find one. E.g. get_fields('%(hello)s %(world)s') returns set('hello', 'world').''' return set(re.findall(r'%\(([^)]+)\)', s)) class Guard(object): '''Representation of a condition required for some action. See usage in Template.py.''' def __init__(self, guard_fn): self.guard_fn = guard_fn def __call__(self, arg): return self.guard_fn(arg)
<commit_before># # Copyright 2014, NICTA # # This software may be distributed and modified according to the terms of # the BSD 2-Clause license. Note that NO WARRANTY is provided. # See "LICENSE_BSD2.txt" for details. # # @TAG(NICTA_BSD) # '''Various helpers for doing advanced things with dictionaries.''' def get_fields(s): '''Return a set of field names referenced as formatting keys in the given string. I thought there would be an easier way to get this, but I can't find one. E.g. get_fields('%(hello)s %(world)s') returns set('hello', 'world').''' class FakeDict(dict): def __init__(self): super(FakeDict, self).__init__() self.referenced = set() def __getitem__(self, key): self.referenced.add(key) return '' f = FakeDict() s % f # Value deliberately discarded return f.referenced class Guard(object): '''Representation of a condition required for some action. See usage in Template.py.''' def __init__(self, guard_fn): self.guard_fn = guard_fn def __call__(self, arg): return self.guard_fn(arg) <commit_msg>Support non-string formats in `get_fields`. This commit rewrites the `get_fields` function to be simpler and more general. The previous implementation relied on ad hoc dict mocking and only supported format strings involving string-valued formats ('%(name)s'). From this commit other formats (e.g. '%(name)04d') are supported. The motivation for this is upcoming changes to how the DMA pool frames are named.<commit_after># # Copyright 2014, NICTA # # This software may be distributed and modified according to the terms of # the BSD 2-Clause license. Note that NO WARRANTY is provided. # See "LICENSE_BSD2.txt" for details. # # @TAG(NICTA_BSD) # '''Various helpers for doing advanced things with dictionaries.''' import re def get_fields(s): '''Return a set of field names referenced as formatting keys in the given string. I thought there would be an easier way to get this, but I can't find one. E.g. get_fields('%(hello)s %(world)s') returns set('hello', 'world').''' return set(re.findall(r'%\(([^)]+)\)', s)) class Guard(object): '''Representation of a condition required for some action. See usage in Template.py.''' def __init__(self, guard_fn): self.guard_fn = guard_fn def __call__(self, arg): return self.guard_fn(arg)
d852356e932a5112308a8c65c1ff6f14019a6835
factory/tools/cat_StarterLog.py
factory/tools/cat_StarterLog.py
#!/bin/env python # # cat_StarterLog.py # # Print out the StarterLog for a glidein output file # # Usage: cat_StarterLog.py logname # import os.path import sys STARTUP_DIR=sys.path[0] sys.path.append(os.path.join(STARTUP_DIR,"lib")) import gWftLogParser USAGE="Usage: cat_StarterLog.py <logname>" def main(): try: print gWftLogParser.get_CondorLog(sys.argv[1],"((StarterLog)|(StarterLog.vm2))") except: sys.stderr.write("%s\n"%USAGE) sys.exit(1) if __name__ == '__main__': main()
#!/bin/env python # # cat_StarterLog.py # # Print out the StarterLog for a glidein output file # # Usage: cat_StarterLog.py logname # import os.path import sys STARTUP_DIR=sys.path[0] sys.path.append(os.path.join(STARTUP_DIR,"lib")) import gWftLogParser USAGE="Usage: cat_StarterLog.py [-monitor] <logname>" def main(): if sys.argv[1]=='-monitor': fname=sys.argv[2] condor_log_id="((StarterLog.monitor)|(StarterLog.vm1))" else: fname=sys.argv[1] condor_log_id="((StarterLog)|(StarterLog.vm2))" try: print gWftLogParser.get_CondorLog(sys.argv[1],"((StarterLog)|(StarterLog.vm2))") except: sys.stderr.write("%s\n"%USAGE) sys.exit(1) if __name__ == '__main__': main()
Add support for monitor starterlog
Add support for monitor starterlog
Python
bsd-3-clause
holzman/glideinwms-old,holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS,bbockelm/glideinWMS,holzman/glideinwms-old,bbockelm/glideinWMS
#!/bin/env python # # cat_StarterLog.py # # Print out the StarterLog for a glidein output file # # Usage: cat_StarterLog.py logname # import os.path import sys STARTUP_DIR=sys.path[0] sys.path.append(os.path.join(STARTUP_DIR,"lib")) import gWftLogParser USAGE="Usage: cat_StarterLog.py <logname>" def main(): try: print gWftLogParser.get_CondorLog(sys.argv[1],"((StarterLog)|(StarterLog.vm2))") except: sys.stderr.write("%s\n"%USAGE) sys.exit(1) if __name__ == '__main__': main() Add support for monitor starterlog
#!/bin/env python # # cat_StarterLog.py # # Print out the StarterLog for a glidein output file # # Usage: cat_StarterLog.py logname # import os.path import sys STARTUP_DIR=sys.path[0] sys.path.append(os.path.join(STARTUP_DIR,"lib")) import gWftLogParser USAGE="Usage: cat_StarterLog.py [-monitor] <logname>" def main(): if sys.argv[1]=='-monitor': fname=sys.argv[2] condor_log_id="((StarterLog.monitor)|(StarterLog.vm1))" else: fname=sys.argv[1] condor_log_id="((StarterLog)|(StarterLog.vm2))" try: print gWftLogParser.get_CondorLog(sys.argv[1],"((StarterLog)|(StarterLog.vm2))") except: sys.stderr.write("%s\n"%USAGE) sys.exit(1) if __name__ == '__main__': main()
<commit_before>#!/bin/env python # # cat_StarterLog.py # # Print out the StarterLog for a glidein output file # # Usage: cat_StarterLog.py logname # import os.path import sys STARTUP_DIR=sys.path[0] sys.path.append(os.path.join(STARTUP_DIR,"lib")) import gWftLogParser USAGE="Usage: cat_StarterLog.py <logname>" def main(): try: print gWftLogParser.get_CondorLog(sys.argv[1],"((StarterLog)|(StarterLog.vm2))") except: sys.stderr.write("%s\n"%USAGE) sys.exit(1) if __name__ == '__main__': main() <commit_msg>Add support for monitor starterlog<commit_after>
#!/bin/env python # # cat_StarterLog.py # # Print out the StarterLog for a glidein output file # # Usage: cat_StarterLog.py logname # import os.path import sys STARTUP_DIR=sys.path[0] sys.path.append(os.path.join(STARTUP_DIR,"lib")) import gWftLogParser USAGE="Usage: cat_StarterLog.py [-monitor] <logname>" def main(): if sys.argv[1]=='-monitor': fname=sys.argv[2] condor_log_id="((StarterLog.monitor)|(StarterLog.vm1))" else: fname=sys.argv[1] condor_log_id="((StarterLog)|(StarterLog.vm2))" try: print gWftLogParser.get_CondorLog(sys.argv[1],"((StarterLog)|(StarterLog.vm2))") except: sys.stderr.write("%s\n"%USAGE) sys.exit(1) if __name__ == '__main__': main()
#!/bin/env python # # cat_StarterLog.py # # Print out the StarterLog for a glidein output file # # Usage: cat_StarterLog.py logname # import os.path import sys STARTUP_DIR=sys.path[0] sys.path.append(os.path.join(STARTUP_DIR,"lib")) import gWftLogParser USAGE="Usage: cat_StarterLog.py <logname>" def main(): try: print gWftLogParser.get_CondorLog(sys.argv[1],"((StarterLog)|(StarterLog.vm2))") except: sys.stderr.write("%s\n"%USAGE) sys.exit(1) if __name__ == '__main__': main() Add support for monitor starterlog#!/bin/env python # # cat_StarterLog.py # # Print out the StarterLog for a glidein output file # # Usage: cat_StarterLog.py logname # import os.path import sys STARTUP_DIR=sys.path[0] sys.path.append(os.path.join(STARTUP_DIR,"lib")) import gWftLogParser USAGE="Usage: cat_StarterLog.py [-monitor] <logname>" def main(): if sys.argv[1]=='-monitor': fname=sys.argv[2] condor_log_id="((StarterLog.monitor)|(StarterLog.vm1))" else: fname=sys.argv[1] condor_log_id="((StarterLog)|(StarterLog.vm2))" try: print gWftLogParser.get_CondorLog(sys.argv[1],"((StarterLog)|(StarterLog.vm2))") except: sys.stderr.write("%s\n"%USAGE) sys.exit(1) if __name__ == '__main__': main()
<commit_before>#!/bin/env python # # cat_StarterLog.py # # Print out the StarterLog for a glidein output file # # Usage: cat_StarterLog.py logname # import os.path import sys STARTUP_DIR=sys.path[0] sys.path.append(os.path.join(STARTUP_DIR,"lib")) import gWftLogParser USAGE="Usage: cat_StarterLog.py <logname>" def main(): try: print gWftLogParser.get_CondorLog(sys.argv[1],"((StarterLog)|(StarterLog.vm2))") except: sys.stderr.write("%s\n"%USAGE) sys.exit(1) if __name__ == '__main__': main() <commit_msg>Add support for monitor starterlog<commit_after>#!/bin/env python # # cat_StarterLog.py # # Print out the StarterLog for a glidein output file # # Usage: cat_StarterLog.py logname # import os.path import sys STARTUP_DIR=sys.path[0] sys.path.append(os.path.join(STARTUP_DIR,"lib")) import gWftLogParser USAGE="Usage: cat_StarterLog.py [-monitor] <logname>" def main(): if sys.argv[1]=='-monitor': fname=sys.argv[2] condor_log_id="((StarterLog.monitor)|(StarterLog.vm1))" else: fname=sys.argv[1] condor_log_id="((StarterLog)|(StarterLog.vm2))" try: print gWftLogParser.get_CondorLog(sys.argv[1],"((StarterLog)|(StarterLog.vm2))") except: sys.stderr.write("%s\n"%USAGE) sys.exit(1) if __name__ == '__main__': main()
def129e32bf731351253e210b53c44cf8c57c302
planetstack/openstack_observer/steps/sync_images.py
planetstack/openstack_observer/steps/sync_images.py
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} for f in os.listdir(images_path): if os.path.isfile(os.path.join(images_path ,f)): available_images[f] = os.path.join(images_path ,f) images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save()
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} if os.path.exists(images_path): for f in os.listdir(images_path): filename = os.path.join(images_path, f) if os.path.isfile(filename): available_images[f] = filename images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save()
Check the existence of the images_path
Check the existence of the images_path ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' BEG TRACEBACK Traceback (most recent call last): File "/opt/xos/observer/event_loop.py", line 349, in sync failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion) File "/opt/xos/observer/openstacksyncstep.py", line 14, in __call__ return self.call(**args) File "/opt/xos/observer/syncstep.py", line 97, in call pending = self.fetch_pending(deletion) File "/opt/xos/observer/steps/sync_images.py", line 22, in fetch_pending for f in os.listdir(images_path): OSError: [Errno 2] No such file or directory: '/opt/xos/images' ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' END TRACEBACK Signed-off-by: S.Çağlar Onur <acf5ae661bb0a9f738c88a741b1d35ac69ab5408@10ur.org>
Python
apache-2.0
wathsalav/xos,wathsalav/xos,wathsalav/xos,wathsalav/xos
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} for f in os.listdir(images_path): if os.path.isfile(os.path.join(images_path ,f)): available_images[f] = os.path.join(images_path ,f) images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save() Check the existence of the images_path ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' BEG TRACEBACK Traceback (most recent call last): File "/opt/xos/observer/event_loop.py", line 349, in sync failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion) File "/opt/xos/observer/openstacksyncstep.py", line 14, in __call__ return self.call(**args) File "/opt/xos/observer/syncstep.py", line 97, in call pending = self.fetch_pending(deletion) File "/opt/xos/observer/steps/sync_images.py", line 22, in fetch_pending for f in os.listdir(images_path): OSError: [Errno 2] No such file or directory: '/opt/xos/images' ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' END TRACEBACK Signed-off-by: S.Çağlar Onur <acf5ae661bb0a9f738c88a741b1d35ac69ab5408@10ur.org>
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} if os.path.exists(images_path): for f in os.listdir(images_path): filename = os.path.join(images_path, f) if os.path.isfile(filename): available_images[f] = filename images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save()
<commit_before>import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} for f in os.listdir(images_path): if os.path.isfile(os.path.join(images_path ,f)): available_images[f] = os.path.join(images_path ,f) images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save() <commit_msg>Check the existence of the images_path ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' BEG TRACEBACK Traceback (most recent call last): File "/opt/xos/observer/event_loop.py", line 349, in sync failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion) File "/opt/xos/observer/openstacksyncstep.py", line 14, in __call__ return self.call(**args) File "/opt/xos/observer/syncstep.py", line 97, in call pending = self.fetch_pending(deletion) File "/opt/xos/observer/steps/sync_images.py", line 22, in fetch_pending for f in os.listdir(images_path): OSError: [Errno 2] No such file or directory: '/opt/xos/images' ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' END TRACEBACK Signed-off-by: S.Çağlar Onur <acf5ae661bb0a9f738c88a741b1d35ac69ab5408@10ur.org><commit_after>
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} if os.path.exists(images_path): for f in os.listdir(images_path): filename = os.path.join(images_path, f) if os.path.isfile(filename): available_images[f] = filename images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save()
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} for f in os.listdir(images_path): if os.path.isfile(os.path.join(images_path ,f)): available_images[f] = os.path.join(images_path ,f) images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save() Check the existence of the images_path ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' BEG TRACEBACK Traceback (most recent call last): File "/opt/xos/observer/event_loop.py", line 349, in sync failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion) File "/opt/xos/observer/openstacksyncstep.py", line 14, in __call__ return self.call(**args) File "/opt/xos/observer/syncstep.py", line 97, in call pending = self.fetch_pending(deletion) File "/opt/xos/observer/steps/sync_images.py", line 22, in fetch_pending for f in os.listdir(images_path): OSError: [Errno 2] No such file or directory: '/opt/xos/images' ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' END TRACEBACK Signed-off-by: S.Çağlar Onur <acf5ae661bb0a9f738c88a741b1d35ac69ab5408@10ur.org>import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} if os.path.exists(images_path): for f in os.listdir(images_path): filename = os.path.join(images_path, f) if os.path.isfile(filename): available_images[f] = filename images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save()
<commit_before>import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} for f in os.listdir(images_path): if os.path.isfile(os.path.join(images_path ,f)): available_images[f] = os.path.join(images_path ,f) images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save() <commit_msg>Check the existence of the images_path ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' BEG TRACEBACK Traceback (most recent call last): File "/opt/xos/observer/event_loop.py", line 349, in sync failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion) File "/opt/xos/observer/openstacksyncstep.py", line 14, in __call__ return self.call(**args) File "/opt/xos/observer/syncstep.py", line 97, in call pending = self.fetch_pending(deletion) File "/opt/xos/observer/steps/sync_images.py", line 22, in fetch_pending for f in os.listdir(images_path): OSError: [Errno 2] No such file or directory: '/opt/xos/images' ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' END TRACEBACK Signed-off-by: S.Çağlar Onur <acf5ae661bb0a9f738c88a741b1d35ac69ab5408@10ur.org><commit_after>import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} if os.path.exists(images_path): for f in os.listdir(images_path): filename = os.path.join(images_path, f) if os.path.isfile(filename): available_images[f] = filename images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save()
541c5d55fd083877a10c63b071bf0176f628a5cb
src/utils/management/commands/dump_file_text_to_db.py
src/utils/management/commands/dump_file_text_to_db.py
from django.core.management.base import BaseCommand from submission.models import Article from core.models import File class Command(BaseCommand): """Dumps the text of files to the database using FileText Model""" help = """ Dumps the text of galley files into the database, which populates the full-text searching indexes """ def add_arguments(self, parser): parser.add_argument('--journal-code', type=int) parser.add_argument('--article-id', type=int) parser.add_argument('--file-id', type=int) parser.add_argument('--all', action="store_true", default=False) def handle(self, *args, **options): if options["file_id"]: file_ = File.objects.get(id=options["file_id"]) file_.index_full_text() elif options["article_id"] or options["journal_code"] or options["all"]: articles = Article.objects.all() if options["journal_code"]: articles = articles.filter(journal__code=options["journal_code"]) if options["article_id"]: articles = articles.filter(id=options["article_id"]) for article in articles: print(f"Processing Article {article.pk}") article.index_full_text() else: self.stderr.write("At least one filtering flag must be provided") self.print_help("manage.py", "dump_file_text_to_db.py")
from django.core.management.base import BaseCommand from submission.models import Article from core.models import File class Command(BaseCommand): """Dumps the text of files to the database using FileText Model""" help = """ Dumps the text of galley files into the database, which populates the full-text searching indexes """ def add_arguments(self, parser): parser.add_argument('--journal-code', type=str) parser.add_argument('--article-id', type=int) parser.add_argument('--file-id', type=int) parser.add_argument('--all', action="store_true", default=False) def handle(self, *args, **options): if options["file_id"]: file_ = File.objects.get(id=options["file_id"]) file_.index_full_text() elif options["article_id"] or options["journal_code"] or options["all"]: articles = Article.objects.all() if options["journal_code"]: articles = articles.filter(journal__code=options["journal_code"]) if options["article_id"]: articles = articles.filter(id=options["article_id"]) for article in articles: print(f"Processing Article {article.pk}") article.index_full_text() else: self.stderr.write("At least one filtering flag must be provided") self.print_help("manage.py", "dump_file_text_to_db.py")
Fix wrong CLI argument type
Fix wrong CLI argument type
Python
agpl-3.0
BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway
from django.core.management.base import BaseCommand from submission.models import Article from core.models import File class Command(BaseCommand): """Dumps the text of files to the database using FileText Model""" help = """ Dumps the text of galley files into the database, which populates the full-text searching indexes """ def add_arguments(self, parser): parser.add_argument('--journal-code', type=int) parser.add_argument('--article-id', type=int) parser.add_argument('--file-id', type=int) parser.add_argument('--all', action="store_true", default=False) def handle(self, *args, **options): if options["file_id"]: file_ = File.objects.get(id=options["file_id"]) file_.index_full_text() elif options["article_id"] or options["journal_code"] or options["all"]: articles = Article.objects.all() if options["journal_code"]: articles = articles.filter(journal__code=options["journal_code"]) if options["article_id"]: articles = articles.filter(id=options["article_id"]) for article in articles: print(f"Processing Article {article.pk}") article.index_full_text() else: self.stderr.write("At least one filtering flag must be provided") self.print_help("manage.py", "dump_file_text_to_db.py") Fix wrong CLI argument type
from django.core.management.base import BaseCommand from submission.models import Article from core.models import File class Command(BaseCommand): """Dumps the text of files to the database using FileText Model""" help = """ Dumps the text of galley files into the database, which populates the full-text searching indexes """ def add_arguments(self, parser): parser.add_argument('--journal-code', type=str) parser.add_argument('--article-id', type=int) parser.add_argument('--file-id', type=int) parser.add_argument('--all', action="store_true", default=False) def handle(self, *args, **options): if options["file_id"]: file_ = File.objects.get(id=options["file_id"]) file_.index_full_text() elif options["article_id"] or options["journal_code"] or options["all"]: articles = Article.objects.all() if options["journal_code"]: articles = articles.filter(journal__code=options["journal_code"]) if options["article_id"]: articles = articles.filter(id=options["article_id"]) for article in articles: print(f"Processing Article {article.pk}") article.index_full_text() else: self.stderr.write("At least one filtering flag must be provided") self.print_help("manage.py", "dump_file_text_to_db.py")
<commit_before>from django.core.management.base import BaseCommand from submission.models import Article from core.models import File class Command(BaseCommand): """Dumps the text of files to the database using FileText Model""" help = """ Dumps the text of galley files into the database, which populates the full-text searching indexes """ def add_arguments(self, parser): parser.add_argument('--journal-code', type=int) parser.add_argument('--article-id', type=int) parser.add_argument('--file-id', type=int) parser.add_argument('--all', action="store_true", default=False) def handle(self, *args, **options): if options["file_id"]: file_ = File.objects.get(id=options["file_id"]) file_.index_full_text() elif options["article_id"] or options["journal_code"] or options["all"]: articles = Article.objects.all() if options["journal_code"]: articles = articles.filter(journal__code=options["journal_code"]) if options["article_id"]: articles = articles.filter(id=options["article_id"]) for article in articles: print(f"Processing Article {article.pk}") article.index_full_text() else: self.stderr.write("At least one filtering flag must be provided") self.print_help("manage.py", "dump_file_text_to_db.py") <commit_msg>Fix wrong CLI argument type<commit_after>
from django.core.management.base import BaseCommand from submission.models import Article from core.models import File class Command(BaseCommand): """Dumps the text of files to the database using FileText Model""" help = """ Dumps the text of galley files into the database, which populates the full-text searching indexes """ def add_arguments(self, parser): parser.add_argument('--journal-code', type=str) parser.add_argument('--article-id', type=int) parser.add_argument('--file-id', type=int) parser.add_argument('--all', action="store_true", default=False) def handle(self, *args, **options): if options["file_id"]: file_ = File.objects.get(id=options["file_id"]) file_.index_full_text() elif options["article_id"] or options["journal_code"] or options["all"]: articles = Article.objects.all() if options["journal_code"]: articles = articles.filter(journal__code=options["journal_code"]) if options["article_id"]: articles = articles.filter(id=options["article_id"]) for article in articles: print(f"Processing Article {article.pk}") article.index_full_text() else: self.stderr.write("At least one filtering flag must be provided") self.print_help("manage.py", "dump_file_text_to_db.py")
from django.core.management.base import BaseCommand from submission.models import Article from core.models import File class Command(BaseCommand): """Dumps the text of files to the database using FileText Model""" help = """ Dumps the text of galley files into the database, which populates the full-text searching indexes """ def add_arguments(self, parser): parser.add_argument('--journal-code', type=int) parser.add_argument('--article-id', type=int) parser.add_argument('--file-id', type=int) parser.add_argument('--all', action="store_true", default=False) def handle(self, *args, **options): if options["file_id"]: file_ = File.objects.get(id=options["file_id"]) file_.index_full_text() elif options["article_id"] or options["journal_code"] or options["all"]: articles = Article.objects.all() if options["journal_code"]: articles = articles.filter(journal__code=options["journal_code"]) if options["article_id"]: articles = articles.filter(id=options["article_id"]) for article in articles: print(f"Processing Article {article.pk}") article.index_full_text() else: self.stderr.write("At least one filtering flag must be provided") self.print_help("manage.py", "dump_file_text_to_db.py") Fix wrong CLI argument typefrom django.core.management.base import BaseCommand from submission.models import Article from core.models import File class Command(BaseCommand): """Dumps the text of files to the database using FileText Model""" help = """ Dumps the text of galley files into the database, which populates the full-text searching indexes """ def add_arguments(self, parser): parser.add_argument('--journal-code', type=str) parser.add_argument('--article-id', type=int) parser.add_argument('--file-id', type=int) parser.add_argument('--all', action="store_true", default=False) def handle(self, *args, **options): if options["file_id"]: file_ = File.objects.get(id=options["file_id"]) file_.index_full_text() elif options["article_id"] or options["journal_code"] or options["all"]: articles = Article.objects.all() if options["journal_code"]: articles = articles.filter(journal__code=options["journal_code"]) if options["article_id"]: articles = articles.filter(id=options["article_id"]) for article in articles: print(f"Processing Article {article.pk}") article.index_full_text() else: self.stderr.write("At least one filtering flag must be provided") self.print_help("manage.py", "dump_file_text_to_db.py")
<commit_before>from django.core.management.base import BaseCommand from submission.models import Article from core.models import File class Command(BaseCommand): """Dumps the text of files to the database using FileText Model""" help = """ Dumps the text of galley files into the database, which populates the full-text searching indexes """ def add_arguments(self, parser): parser.add_argument('--journal-code', type=int) parser.add_argument('--article-id', type=int) parser.add_argument('--file-id', type=int) parser.add_argument('--all', action="store_true", default=False) def handle(self, *args, **options): if options["file_id"]: file_ = File.objects.get(id=options["file_id"]) file_.index_full_text() elif options["article_id"] or options["journal_code"] or options["all"]: articles = Article.objects.all() if options["journal_code"]: articles = articles.filter(journal__code=options["journal_code"]) if options["article_id"]: articles = articles.filter(id=options["article_id"]) for article in articles: print(f"Processing Article {article.pk}") article.index_full_text() else: self.stderr.write("At least one filtering flag must be provided") self.print_help("manage.py", "dump_file_text_to_db.py") <commit_msg>Fix wrong CLI argument type<commit_after>from django.core.management.base import BaseCommand from submission.models import Article from core.models import File class Command(BaseCommand): """Dumps the text of files to the database using FileText Model""" help = """ Dumps the text of galley files into the database, which populates the full-text searching indexes """ def add_arguments(self, parser): parser.add_argument('--journal-code', type=str) parser.add_argument('--article-id', type=int) parser.add_argument('--file-id', type=int) parser.add_argument('--all', action="store_true", default=False) def handle(self, *args, **options): if options["file_id"]: file_ = File.objects.get(id=options["file_id"]) file_.index_full_text() elif options["article_id"] or options["journal_code"] or options["all"]: articles = Article.objects.all() if options["journal_code"]: articles = articles.filter(journal__code=options["journal_code"]) if options["article_id"]: articles = articles.filter(id=options["article_id"]) for article in articles: print(f"Processing Article {article.pk}") article.index_full_text() else: self.stderr.write("At least one filtering flag must be provided") self.print_help("manage.py", "dump_file_text_to_db.py")
5968e99eb8e040686d345c6d77c71bb5975e5f29
simple-cipher/simple_cipher.py
simple-cipher/simple_cipher.py
import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = Cipher._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key = key self._key = [ord(k)-97 for k in key] def encode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(Cipher._shift(c, k) for c, k in zip(chars, key)) def decode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(Cipher._shift(c, -k) for c, k in zip(chars, key)) @staticmethod def _shift(char, key): return chr(97 + ((ord(char) - 97 + key) % 26)) @staticmethod def _random_key(length=256): return "".join(secrets.choice(ascii_lowercase) for _ in range(length)) class Caesar(Cipher): def __init__(self): Cipher.__init__(self, "d")
import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = self._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key = key self._key = [ord(k)-97 for k in key] def encode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(self._shift(c, k) for c, k in zip(chars, key)) def decode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(self._shift(c, -k) for c, k in zip(chars, key)) @staticmethod def _shift(char, key): return chr(97 + ((ord(char) - 97 + key) % 26)) @staticmethod def _random_key(length=256): return "".join(secrets.choice(ascii_lowercase) for _ in range(length)) class Caesar(Cipher): def __init__(self): super().__init__("d")
Use super() and self within the Cipher and Caesar classes
Use super() and self within the Cipher and Caesar classes
Python
agpl-3.0
CubicComet/exercism-python-solutions
import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = Cipher._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key = key self._key = [ord(k)-97 for k in key] def encode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(Cipher._shift(c, k) for c, k in zip(chars, key)) def decode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(Cipher._shift(c, -k) for c, k in zip(chars, key)) @staticmethod def _shift(char, key): return chr(97 + ((ord(char) - 97 + key) % 26)) @staticmethod def _random_key(length=256): return "".join(secrets.choice(ascii_lowercase) for _ in range(length)) class Caesar(Cipher): def __init__(self): Cipher.__init__(self, "d") Use super() and self within the Cipher and Caesar classes
import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = self._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key = key self._key = [ord(k)-97 for k in key] def encode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(self._shift(c, k) for c, k in zip(chars, key)) def decode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(self._shift(c, -k) for c, k in zip(chars, key)) @staticmethod def _shift(char, key): return chr(97 + ((ord(char) - 97 + key) % 26)) @staticmethod def _random_key(length=256): return "".join(secrets.choice(ascii_lowercase) for _ in range(length)) class Caesar(Cipher): def __init__(self): super().__init__("d")
<commit_before>import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = Cipher._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key = key self._key = [ord(k)-97 for k in key] def encode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(Cipher._shift(c, k) for c, k in zip(chars, key)) def decode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(Cipher._shift(c, -k) for c, k in zip(chars, key)) @staticmethod def _shift(char, key): return chr(97 + ((ord(char) - 97 + key) % 26)) @staticmethod def _random_key(length=256): return "".join(secrets.choice(ascii_lowercase) for _ in range(length)) class Caesar(Cipher): def __init__(self): Cipher.__init__(self, "d") <commit_msg>Use super() and self within the Cipher and Caesar classes<commit_after>
import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = self._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key = key self._key = [ord(k)-97 for k in key] def encode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(self._shift(c, k) for c, k in zip(chars, key)) def decode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(self._shift(c, -k) for c, k in zip(chars, key)) @staticmethod def _shift(char, key): return chr(97 + ((ord(char) - 97 + key) % 26)) @staticmethod def _random_key(length=256): return "".join(secrets.choice(ascii_lowercase) for _ in range(length)) class Caesar(Cipher): def __init__(self): super().__init__("d")
import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = Cipher._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key = key self._key = [ord(k)-97 for k in key] def encode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(Cipher._shift(c, k) for c, k in zip(chars, key)) def decode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(Cipher._shift(c, -k) for c, k in zip(chars, key)) @staticmethod def _shift(char, key): return chr(97 + ((ord(char) - 97 + key) % 26)) @staticmethod def _random_key(length=256): return "".join(secrets.choice(ascii_lowercase) for _ in range(length)) class Caesar(Cipher): def __init__(self): Cipher.__init__(self, "d") Use super() and self within the Cipher and Caesar classesimport math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = self._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key = key self._key = [ord(k)-97 for k in key] def encode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(self._shift(c, k) for c, k in zip(chars, key)) def decode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(self._shift(c, -k) for c, k in zip(chars, key)) @staticmethod def _shift(char, key): return chr(97 + ((ord(char) - 97 + key) % 26)) @staticmethod def _random_key(length=256): return "".join(secrets.choice(ascii_lowercase) for _ in range(length)) class Caesar(Cipher): def __init__(self): super().__init__("d")
<commit_before>import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = Cipher._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key = key self._key = [ord(k)-97 for k in key] def encode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(Cipher._shift(c, k) for c, k in zip(chars, key)) def decode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(Cipher._shift(c, -k) for c, k in zip(chars, key)) @staticmethod def _shift(char, key): return chr(97 + ((ord(char) - 97 + key) % 26)) @staticmethod def _random_key(length=256): return "".join(secrets.choice(ascii_lowercase) for _ in range(length)) class Caesar(Cipher): def __init__(self): Cipher.__init__(self, "d") <commit_msg>Use super() and self within the Cipher and Caesar classes<commit_after>import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = self._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key = key self._key = [ord(k)-97 for k in key] def encode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(self._shift(c, k) for c, k in zip(chars, key)) def decode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(self._shift(c, -k) for c, k in zip(chars, key)) @staticmethod def _shift(char, key): return chr(97 + ((ord(char) - 97 + key) % 26)) @staticmethod def _random_key(length=256): return "".join(secrets.choice(ascii_lowercase) for _ in range(length)) class Caesar(Cipher): def __init__(self): super().__init__("d")
6cae50cd400fec3a99f72fd9b60cf3a2cce0db24
skimage/morphology/__init__.py
skimage/morphology/__init__.py
from .binary import (binary_erosion, binary_dilation, binary_opening, binary_closing) from .grey import * from .selem import * from .ccomp import label from .watershed import watershed, is_local_maximum from ._skeletonize import skeletonize, medial_axis from .convex_hull import convex_hull_image from .greyreconstruct import reconstruction from .misc import remove_small_objects
from .binary import (binary_erosion, binary_dilation, binary_opening, binary_closing) from .grey import (erosion, dilation, opening, closing, white_tophat, black_tophat, greyscale_erode, greyscale_dilate, greyscale_open, greyscale_close, greyscale_white_top_hat, greyscale_black_top_hat) from .selem import square, rectangle, diamond, disk, cube, octahedron, ball from .ccomp import label from .watershed import watershed, is_local_maximum from ._skeletonize import skeletonize, medial_axis from .convex_hull import convex_hull_image from .greyreconstruct import reconstruction from .misc import remove_small_objects __all__ = ['binary_erosion', 'binary_dilation', 'binary_opening', 'binary_closing', 'erosion', 'dilation', 'opening', 'closing', 'white_tophat', 'black_tophat', 'greyscale_erode', 'greyscale_dilate', 'greyscale_open', 'greyscale_close', 'greyscale_white_top_hat', 'greyscale_black_top_hat', 'square', 'rectangle', 'diamond', 'disk', 'cube', 'octahedron', 'ball', 'label', 'watershed', 'is_local_maximum', 'skeletonize', 'medial_axis', 'convex_hull_image', 'reconstruction', 'remove_small_objects']
Add __all__ to morphology package
Add __all__ to morphology package
Python
bsd-3-clause
michaelaye/scikit-image,vighneshbirodkar/scikit-image,paalge/scikit-image,blink1073/scikit-image,oew1v07/scikit-image,SamHames/scikit-image,chintak/scikit-image,vighneshbirodkar/scikit-image,oew1v07/scikit-image,chriscrosscutler/scikit-image,rjeli/scikit-image,michaelpacer/scikit-image,michaelpacer/scikit-image,michaelaye/scikit-image,dpshelio/scikit-image,warmspringwinds/scikit-image,SamHames/scikit-image,Hiyorimi/scikit-image,paalge/scikit-image,chintak/scikit-image,almarklein/scikit-image,juliusbierk/scikit-image,bennlich/scikit-image,vighneshbirodkar/scikit-image,rjeli/scikit-image,youprofit/scikit-image,ajaybhat/scikit-image,rjeli/scikit-image,ClinicalGraphics/scikit-image,chintak/scikit-image,newville/scikit-image,newville/scikit-image,almarklein/scikit-image,WarrenWeckesser/scikits-image,dpshelio/scikit-image,SamHames/scikit-image,bsipocz/scikit-image,bsipocz/scikit-image,emon10005/scikit-image,ofgulban/scikit-image,robintw/scikit-image,Britefury/scikit-image,pratapvardhan/scikit-image,almarklein/scikit-image,ofgulban/scikit-image,keflavich/scikit-image,emon10005/scikit-image,ajaybhat/scikit-image,paalge/scikit-image,keflavich/scikit-image,warmspringwinds/scikit-image,ClinicalGraphics/scikit-image,Britefury/scikit-image,GaZ3ll3/scikit-image,jwiggins/scikit-image,chintak/scikit-image,jwiggins/scikit-image,Hiyorimi/scikit-image,almarklein/scikit-image,bennlich/scikit-image,ofgulban/scikit-image,Midafi/scikit-image,pratapvardhan/scikit-image,youprofit/scikit-image,robintw/scikit-image,GaZ3ll3/scikit-image,Midafi/scikit-image,juliusbierk/scikit-image,chriscrosscutler/scikit-image,blink1073/scikit-image,WarrenWeckesser/scikits-image,SamHames/scikit-image
from .binary import (binary_erosion, binary_dilation, binary_opening, binary_closing) from .grey import * from .selem import * from .ccomp import label from .watershed import watershed, is_local_maximum from ._skeletonize import skeletonize, medial_axis from .convex_hull import convex_hull_image from .greyreconstruct import reconstruction from .misc import remove_small_objects Add __all__ to morphology package
from .binary import (binary_erosion, binary_dilation, binary_opening, binary_closing) from .grey import (erosion, dilation, opening, closing, white_tophat, black_tophat, greyscale_erode, greyscale_dilate, greyscale_open, greyscale_close, greyscale_white_top_hat, greyscale_black_top_hat) from .selem import square, rectangle, diamond, disk, cube, octahedron, ball from .ccomp import label from .watershed import watershed, is_local_maximum from ._skeletonize import skeletonize, medial_axis from .convex_hull import convex_hull_image from .greyreconstruct import reconstruction from .misc import remove_small_objects __all__ = ['binary_erosion', 'binary_dilation', 'binary_opening', 'binary_closing', 'erosion', 'dilation', 'opening', 'closing', 'white_tophat', 'black_tophat', 'greyscale_erode', 'greyscale_dilate', 'greyscale_open', 'greyscale_close', 'greyscale_white_top_hat', 'greyscale_black_top_hat', 'square', 'rectangle', 'diamond', 'disk', 'cube', 'octahedron', 'ball', 'label', 'watershed', 'is_local_maximum', 'skeletonize', 'medial_axis', 'convex_hull_image', 'reconstruction', 'remove_small_objects']
<commit_before>from .binary import (binary_erosion, binary_dilation, binary_opening, binary_closing) from .grey import * from .selem import * from .ccomp import label from .watershed import watershed, is_local_maximum from ._skeletonize import skeletonize, medial_axis from .convex_hull import convex_hull_image from .greyreconstruct import reconstruction from .misc import remove_small_objects <commit_msg>Add __all__ to morphology package<commit_after>
from .binary import (binary_erosion, binary_dilation, binary_opening, binary_closing) from .grey import (erosion, dilation, opening, closing, white_tophat, black_tophat, greyscale_erode, greyscale_dilate, greyscale_open, greyscale_close, greyscale_white_top_hat, greyscale_black_top_hat) from .selem import square, rectangle, diamond, disk, cube, octahedron, ball from .ccomp import label from .watershed import watershed, is_local_maximum from ._skeletonize import skeletonize, medial_axis from .convex_hull import convex_hull_image from .greyreconstruct import reconstruction from .misc import remove_small_objects __all__ = ['binary_erosion', 'binary_dilation', 'binary_opening', 'binary_closing', 'erosion', 'dilation', 'opening', 'closing', 'white_tophat', 'black_tophat', 'greyscale_erode', 'greyscale_dilate', 'greyscale_open', 'greyscale_close', 'greyscale_white_top_hat', 'greyscale_black_top_hat', 'square', 'rectangle', 'diamond', 'disk', 'cube', 'octahedron', 'ball', 'label', 'watershed', 'is_local_maximum', 'skeletonize', 'medial_axis', 'convex_hull_image', 'reconstruction', 'remove_small_objects']
from .binary import (binary_erosion, binary_dilation, binary_opening, binary_closing) from .grey import * from .selem import * from .ccomp import label from .watershed import watershed, is_local_maximum from ._skeletonize import skeletonize, medial_axis from .convex_hull import convex_hull_image from .greyreconstruct import reconstruction from .misc import remove_small_objects Add __all__ to morphology packagefrom .binary import (binary_erosion, binary_dilation, binary_opening, binary_closing) from .grey import (erosion, dilation, opening, closing, white_tophat, black_tophat, greyscale_erode, greyscale_dilate, greyscale_open, greyscale_close, greyscale_white_top_hat, greyscale_black_top_hat) from .selem import square, rectangle, diamond, disk, cube, octahedron, ball from .ccomp import label from .watershed import watershed, is_local_maximum from ._skeletonize import skeletonize, medial_axis from .convex_hull import convex_hull_image from .greyreconstruct import reconstruction from .misc import remove_small_objects __all__ = ['binary_erosion', 'binary_dilation', 'binary_opening', 'binary_closing', 'erosion', 'dilation', 'opening', 'closing', 'white_tophat', 'black_tophat', 'greyscale_erode', 'greyscale_dilate', 'greyscale_open', 'greyscale_close', 'greyscale_white_top_hat', 'greyscale_black_top_hat', 'square', 'rectangle', 'diamond', 'disk', 'cube', 'octahedron', 'ball', 'label', 'watershed', 'is_local_maximum', 'skeletonize', 'medial_axis', 'convex_hull_image', 'reconstruction', 'remove_small_objects']
<commit_before>from .binary import (binary_erosion, binary_dilation, binary_opening, binary_closing) from .grey import * from .selem import * from .ccomp import label from .watershed import watershed, is_local_maximum from ._skeletonize import skeletonize, medial_axis from .convex_hull import convex_hull_image from .greyreconstruct import reconstruction from .misc import remove_small_objects <commit_msg>Add __all__ to morphology package<commit_after>from .binary import (binary_erosion, binary_dilation, binary_opening, binary_closing) from .grey import (erosion, dilation, opening, closing, white_tophat, black_tophat, greyscale_erode, greyscale_dilate, greyscale_open, greyscale_close, greyscale_white_top_hat, greyscale_black_top_hat) from .selem import square, rectangle, diamond, disk, cube, octahedron, ball from .ccomp import label from .watershed import watershed, is_local_maximum from ._skeletonize import skeletonize, medial_axis from .convex_hull import convex_hull_image from .greyreconstruct import reconstruction from .misc import remove_small_objects __all__ = ['binary_erosion', 'binary_dilation', 'binary_opening', 'binary_closing', 'erosion', 'dilation', 'opening', 'closing', 'white_tophat', 'black_tophat', 'greyscale_erode', 'greyscale_dilate', 'greyscale_open', 'greyscale_close', 'greyscale_white_top_hat', 'greyscale_black_top_hat', 'square', 'rectangle', 'diamond', 'disk', 'cube', 'octahedron', 'ball', 'label', 'watershed', 'is_local_maximum', 'skeletonize', 'medial_axis', 'convex_hull_image', 'reconstruction', 'remove_small_objects']
3e1d59b91cfe84dd57558047a2d841fe5cc9bd6b
bdp/platform/frontend/setup.py
bdp/platform/frontend/setup.py
""" Created on 21/03/2012 @author: losa, sortega """ import os from setuptools import setup, find_packages def find_files(path): files = [] for dirname, subdirnames, filenames in os.walk(path): for subdirname in subdirnames: files.extend(find_files(os.path.join(dirname, subdirname))) for filename in filenames: files.append(os.path.join(dirname, filename)) return files setup( name = "bdp_fe", version = "0.1.0", description = "Big Data Platform Frontend", long_description = ("This package is a web interface for the Big Data " "Platform. Through this frontend, a user can lauch " "Haddop jobs, read and interpret its results."), author = "Telefonica Digital", author_email = "cosmos@tid.es", package_dir = {'': 'src'}, packages = find_packages('src'), package_data = {'': ['templates/*']}, data_files = [('share/bdp_fe/static', find_files('src/bdp_fe/jobconf/static/'))], install_requires = [ 'setuptools', 'pymongo', 'django', 'coverage', 'django-jenkins', 'thrift', 'flup', 'MySQL-python', ], classifiers = [ "Development Status :: 3 - Alpha", ], )
""" Created on 21/03/2012 @author: losa, sortega """ import os from setuptools import setup, find_packages def find_files(path): files = [] for dirname, subdirnames, filenames in os.walk(path): for subdirname in subdirnames: files.extend(find_files(os.path.join(dirname, subdirname))) for filename in filenames: files.append(os.path.join(dirname, filename)) return files setup( name = "bdp_fe", version = "0.1.0", description = "Big Data Platform Frontend", long_description = ("This package is a web interface for the Big Data " "Platform. Through this frontend, a user can lauch " "Haddop jobs, read and interpret its results."), author = "Telefonica Digital", author_email = "cosmos@tid.es", package_dir = {'': 'src'}, packages = find_packages('src'), package_data = {'': ['templates/*']}, data_files = [('share/bdp_fe/static', find_files('src/bdp_fe/jobconf/static/'))], install_requires = [ 'setuptools', 'pymongo', 'django', 'coverage', 'pylint', 'django-jenkins', 'thrift', 'flup', 'MySQL-python', ], classifiers = [ "Development Status :: 3 - Alpha", ], )
Add pylint to installation requirements
Add pylint to installation requirements
Python
apache-2.0
telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform
""" Created on 21/03/2012 @author: losa, sortega """ import os from setuptools import setup, find_packages def find_files(path): files = [] for dirname, subdirnames, filenames in os.walk(path): for subdirname in subdirnames: files.extend(find_files(os.path.join(dirname, subdirname))) for filename in filenames: files.append(os.path.join(dirname, filename)) return files setup( name = "bdp_fe", version = "0.1.0", description = "Big Data Platform Frontend", long_description = ("This package is a web interface for the Big Data " "Platform. Through this frontend, a user can lauch " "Haddop jobs, read and interpret its results."), author = "Telefonica Digital", author_email = "cosmos@tid.es", package_dir = {'': 'src'}, packages = find_packages('src'), package_data = {'': ['templates/*']}, data_files = [('share/bdp_fe/static', find_files('src/bdp_fe/jobconf/static/'))], install_requires = [ 'setuptools', 'pymongo', 'django', 'coverage', 'django-jenkins', 'thrift', 'flup', 'MySQL-python', ], classifiers = [ "Development Status :: 3 - Alpha", ], ) Add pylint to installation requirements
""" Created on 21/03/2012 @author: losa, sortega """ import os from setuptools import setup, find_packages def find_files(path): files = [] for dirname, subdirnames, filenames in os.walk(path): for subdirname in subdirnames: files.extend(find_files(os.path.join(dirname, subdirname))) for filename in filenames: files.append(os.path.join(dirname, filename)) return files setup( name = "bdp_fe", version = "0.1.0", description = "Big Data Platform Frontend", long_description = ("This package is a web interface for the Big Data " "Platform. Through this frontend, a user can lauch " "Haddop jobs, read and interpret its results."), author = "Telefonica Digital", author_email = "cosmos@tid.es", package_dir = {'': 'src'}, packages = find_packages('src'), package_data = {'': ['templates/*']}, data_files = [('share/bdp_fe/static', find_files('src/bdp_fe/jobconf/static/'))], install_requires = [ 'setuptools', 'pymongo', 'django', 'coverage', 'pylint', 'django-jenkins', 'thrift', 'flup', 'MySQL-python', ], classifiers = [ "Development Status :: 3 - Alpha", ], )
<commit_before>""" Created on 21/03/2012 @author: losa, sortega """ import os from setuptools import setup, find_packages def find_files(path): files = [] for dirname, subdirnames, filenames in os.walk(path): for subdirname in subdirnames: files.extend(find_files(os.path.join(dirname, subdirname))) for filename in filenames: files.append(os.path.join(dirname, filename)) return files setup( name = "bdp_fe", version = "0.1.0", description = "Big Data Platform Frontend", long_description = ("This package is a web interface for the Big Data " "Platform. Through this frontend, a user can lauch " "Haddop jobs, read and interpret its results."), author = "Telefonica Digital", author_email = "cosmos@tid.es", package_dir = {'': 'src'}, packages = find_packages('src'), package_data = {'': ['templates/*']}, data_files = [('share/bdp_fe/static', find_files('src/bdp_fe/jobconf/static/'))], install_requires = [ 'setuptools', 'pymongo', 'django', 'coverage', 'django-jenkins', 'thrift', 'flup', 'MySQL-python', ], classifiers = [ "Development Status :: 3 - Alpha", ], ) <commit_msg>Add pylint to installation requirements<commit_after>
""" Created on 21/03/2012 @author: losa, sortega """ import os from setuptools import setup, find_packages def find_files(path): files = [] for dirname, subdirnames, filenames in os.walk(path): for subdirname in subdirnames: files.extend(find_files(os.path.join(dirname, subdirname))) for filename in filenames: files.append(os.path.join(dirname, filename)) return files setup( name = "bdp_fe", version = "0.1.0", description = "Big Data Platform Frontend", long_description = ("This package is a web interface for the Big Data " "Platform. Through this frontend, a user can lauch " "Haddop jobs, read and interpret its results."), author = "Telefonica Digital", author_email = "cosmos@tid.es", package_dir = {'': 'src'}, packages = find_packages('src'), package_data = {'': ['templates/*']}, data_files = [('share/bdp_fe/static', find_files('src/bdp_fe/jobconf/static/'))], install_requires = [ 'setuptools', 'pymongo', 'django', 'coverage', 'pylint', 'django-jenkins', 'thrift', 'flup', 'MySQL-python', ], classifiers = [ "Development Status :: 3 - Alpha", ], )
""" Created on 21/03/2012 @author: losa, sortega """ import os from setuptools import setup, find_packages def find_files(path): files = [] for dirname, subdirnames, filenames in os.walk(path): for subdirname in subdirnames: files.extend(find_files(os.path.join(dirname, subdirname))) for filename in filenames: files.append(os.path.join(dirname, filename)) return files setup( name = "bdp_fe", version = "0.1.0", description = "Big Data Platform Frontend", long_description = ("This package is a web interface for the Big Data " "Platform. Through this frontend, a user can lauch " "Haddop jobs, read and interpret its results."), author = "Telefonica Digital", author_email = "cosmos@tid.es", package_dir = {'': 'src'}, packages = find_packages('src'), package_data = {'': ['templates/*']}, data_files = [('share/bdp_fe/static', find_files('src/bdp_fe/jobconf/static/'))], install_requires = [ 'setuptools', 'pymongo', 'django', 'coverage', 'django-jenkins', 'thrift', 'flup', 'MySQL-python', ], classifiers = [ "Development Status :: 3 - Alpha", ], ) Add pylint to installation requirements""" Created on 21/03/2012 @author: losa, sortega """ import os from setuptools import setup, find_packages def find_files(path): files = [] for dirname, subdirnames, filenames in os.walk(path): for subdirname in subdirnames: files.extend(find_files(os.path.join(dirname, subdirname))) for filename in filenames: files.append(os.path.join(dirname, filename)) return files setup( name = "bdp_fe", version = "0.1.0", description = "Big Data Platform Frontend", long_description = ("This package is a web interface for the Big Data " "Platform. Through this frontend, a user can lauch " "Haddop jobs, read and interpret its results."), author = "Telefonica Digital", author_email = "cosmos@tid.es", package_dir = {'': 'src'}, packages = find_packages('src'), package_data = {'': ['templates/*']}, data_files = [('share/bdp_fe/static', find_files('src/bdp_fe/jobconf/static/'))], install_requires = [ 'setuptools', 'pymongo', 'django', 'coverage', 'pylint', 'django-jenkins', 'thrift', 'flup', 'MySQL-python', ], classifiers = [ "Development Status :: 3 - Alpha", ], )
<commit_before>""" Created on 21/03/2012 @author: losa, sortega """ import os from setuptools import setup, find_packages def find_files(path): files = [] for dirname, subdirnames, filenames in os.walk(path): for subdirname in subdirnames: files.extend(find_files(os.path.join(dirname, subdirname))) for filename in filenames: files.append(os.path.join(dirname, filename)) return files setup( name = "bdp_fe", version = "0.1.0", description = "Big Data Platform Frontend", long_description = ("This package is a web interface for the Big Data " "Platform. Through this frontend, a user can lauch " "Haddop jobs, read and interpret its results."), author = "Telefonica Digital", author_email = "cosmos@tid.es", package_dir = {'': 'src'}, packages = find_packages('src'), package_data = {'': ['templates/*']}, data_files = [('share/bdp_fe/static', find_files('src/bdp_fe/jobconf/static/'))], install_requires = [ 'setuptools', 'pymongo', 'django', 'coverage', 'django-jenkins', 'thrift', 'flup', 'MySQL-python', ], classifiers = [ "Development Status :: 3 - Alpha", ], ) <commit_msg>Add pylint to installation requirements<commit_after>""" Created on 21/03/2012 @author: losa, sortega """ import os from setuptools import setup, find_packages def find_files(path): files = [] for dirname, subdirnames, filenames in os.walk(path): for subdirname in subdirnames: files.extend(find_files(os.path.join(dirname, subdirname))) for filename in filenames: files.append(os.path.join(dirname, filename)) return files setup( name = "bdp_fe", version = "0.1.0", description = "Big Data Platform Frontend", long_description = ("This package is a web interface for the Big Data " "Platform. Through this frontend, a user can lauch " "Haddop jobs, read and interpret its results."), author = "Telefonica Digital", author_email = "cosmos@tid.es", package_dir = {'': 'src'}, packages = find_packages('src'), package_data = {'': ['templates/*']}, data_files = [('share/bdp_fe/static', find_files('src/bdp_fe/jobconf/static/'))], install_requires = [ 'setuptools', 'pymongo', 'django', 'coverage', 'pylint', 'django-jenkins', 'thrift', 'flup', 'MySQL-python', ], classifiers = [ "Development Status :: 3 - Alpha", ], )
b887bfef4f5070ddea0fd448e6e6bf70cf994070
roulier/carriers/gls_fr/rest/carrier_action.py
roulier/carriers/gls_fr/rest/carrier_action.py
"""Implementation for Laposte.""" from roulier.carrier_action import CarrierGetLabel from roulier.roulier import factory from .api import GlsEuApiParcel from .encoder import GlsEuEncoder from .decoder import GlsEuDecoderGetLabel from .transport import GlsEuTransport class GlsEuGetabel(CarrierGetLabel): """Implementation for GLS via it's REST WebService.""" ws_url = "https://api.gls-group.eu/public/v1/shipments" ws_test_url = "https://api-qs.gls-group.eu/public/v1/shipments" encoder = GlsEuEncoder decoder = GlsEuDecoderGetLabel transport = GlsEuTransport api = GlsEuApiParcel manage_multi_label = True factory.register_builder("gls_fr_rest", "get_label", GlsEuGetabel)
"""Implementation for Laposte.""" from roulier.carrier_action import CarrierGetLabel from roulier.roulier import factory from .api import GlsEuApiParcel from .encoder import GlsEuEncoder from .decoder import GlsEuDecoderGetLabel from .transport import GlsEuTransport class GlsEuGetabel(CarrierGetLabel): """Implementation for GLS via it's REST WebService.""" ws_url = "https://api.gls-group.eu/public/v1/shipments" ws_test_url = "https://api-qs1.gls-group.eu/public/v1/shipments" encoder = GlsEuEncoder decoder = GlsEuDecoderGetLabel transport = GlsEuTransport api = GlsEuApiParcel manage_multi_label = True factory.register_builder("gls_fr_rest", "get_label", GlsEuGetabel)
Update test url for gls web api v1
[FIX] Update test url for gls web api v1
Python
agpl-3.0
akretion/roulier
"""Implementation for Laposte.""" from roulier.carrier_action import CarrierGetLabel from roulier.roulier import factory from .api import GlsEuApiParcel from .encoder import GlsEuEncoder from .decoder import GlsEuDecoderGetLabel from .transport import GlsEuTransport class GlsEuGetabel(CarrierGetLabel): """Implementation for GLS via it's REST WebService.""" ws_url = "https://api.gls-group.eu/public/v1/shipments" ws_test_url = "https://api-qs.gls-group.eu/public/v1/shipments" encoder = GlsEuEncoder decoder = GlsEuDecoderGetLabel transport = GlsEuTransport api = GlsEuApiParcel manage_multi_label = True factory.register_builder("gls_fr_rest", "get_label", GlsEuGetabel) [FIX] Update test url for gls web api v1
"""Implementation for Laposte.""" from roulier.carrier_action import CarrierGetLabel from roulier.roulier import factory from .api import GlsEuApiParcel from .encoder import GlsEuEncoder from .decoder import GlsEuDecoderGetLabel from .transport import GlsEuTransport class GlsEuGetabel(CarrierGetLabel): """Implementation for GLS via it's REST WebService.""" ws_url = "https://api.gls-group.eu/public/v1/shipments" ws_test_url = "https://api-qs1.gls-group.eu/public/v1/shipments" encoder = GlsEuEncoder decoder = GlsEuDecoderGetLabel transport = GlsEuTransport api = GlsEuApiParcel manage_multi_label = True factory.register_builder("gls_fr_rest", "get_label", GlsEuGetabel)
<commit_before>"""Implementation for Laposte.""" from roulier.carrier_action import CarrierGetLabel from roulier.roulier import factory from .api import GlsEuApiParcel from .encoder import GlsEuEncoder from .decoder import GlsEuDecoderGetLabel from .transport import GlsEuTransport class GlsEuGetabel(CarrierGetLabel): """Implementation for GLS via it's REST WebService.""" ws_url = "https://api.gls-group.eu/public/v1/shipments" ws_test_url = "https://api-qs.gls-group.eu/public/v1/shipments" encoder = GlsEuEncoder decoder = GlsEuDecoderGetLabel transport = GlsEuTransport api = GlsEuApiParcel manage_multi_label = True factory.register_builder("gls_fr_rest", "get_label", GlsEuGetabel) <commit_msg>[FIX] Update test url for gls web api v1<commit_after>
"""Implementation for Laposte.""" from roulier.carrier_action import CarrierGetLabel from roulier.roulier import factory from .api import GlsEuApiParcel from .encoder import GlsEuEncoder from .decoder import GlsEuDecoderGetLabel from .transport import GlsEuTransport class GlsEuGetabel(CarrierGetLabel): """Implementation for GLS via it's REST WebService.""" ws_url = "https://api.gls-group.eu/public/v1/shipments" ws_test_url = "https://api-qs1.gls-group.eu/public/v1/shipments" encoder = GlsEuEncoder decoder = GlsEuDecoderGetLabel transport = GlsEuTransport api = GlsEuApiParcel manage_multi_label = True factory.register_builder("gls_fr_rest", "get_label", GlsEuGetabel)
"""Implementation for Laposte.""" from roulier.carrier_action import CarrierGetLabel from roulier.roulier import factory from .api import GlsEuApiParcel from .encoder import GlsEuEncoder from .decoder import GlsEuDecoderGetLabel from .transport import GlsEuTransport class GlsEuGetabel(CarrierGetLabel): """Implementation for GLS via it's REST WebService.""" ws_url = "https://api.gls-group.eu/public/v1/shipments" ws_test_url = "https://api-qs.gls-group.eu/public/v1/shipments" encoder = GlsEuEncoder decoder = GlsEuDecoderGetLabel transport = GlsEuTransport api = GlsEuApiParcel manage_multi_label = True factory.register_builder("gls_fr_rest", "get_label", GlsEuGetabel) [FIX] Update test url for gls web api v1"""Implementation for Laposte.""" from roulier.carrier_action import CarrierGetLabel from roulier.roulier import factory from .api import GlsEuApiParcel from .encoder import GlsEuEncoder from .decoder import GlsEuDecoderGetLabel from .transport import GlsEuTransport class GlsEuGetabel(CarrierGetLabel): """Implementation for GLS via it's REST WebService.""" ws_url = "https://api.gls-group.eu/public/v1/shipments" ws_test_url = "https://api-qs1.gls-group.eu/public/v1/shipments" encoder = GlsEuEncoder decoder = GlsEuDecoderGetLabel transport = GlsEuTransport api = GlsEuApiParcel manage_multi_label = True factory.register_builder("gls_fr_rest", "get_label", GlsEuGetabel)
<commit_before>"""Implementation for Laposte.""" from roulier.carrier_action import CarrierGetLabel from roulier.roulier import factory from .api import GlsEuApiParcel from .encoder import GlsEuEncoder from .decoder import GlsEuDecoderGetLabel from .transport import GlsEuTransport class GlsEuGetabel(CarrierGetLabel): """Implementation for GLS via it's REST WebService.""" ws_url = "https://api.gls-group.eu/public/v1/shipments" ws_test_url = "https://api-qs.gls-group.eu/public/v1/shipments" encoder = GlsEuEncoder decoder = GlsEuDecoderGetLabel transport = GlsEuTransport api = GlsEuApiParcel manage_multi_label = True factory.register_builder("gls_fr_rest", "get_label", GlsEuGetabel) <commit_msg>[FIX] Update test url for gls web api v1<commit_after>"""Implementation for Laposte.""" from roulier.carrier_action import CarrierGetLabel from roulier.roulier import factory from .api import GlsEuApiParcel from .encoder import GlsEuEncoder from .decoder import GlsEuDecoderGetLabel from .transport import GlsEuTransport class GlsEuGetabel(CarrierGetLabel): """Implementation for GLS via it's REST WebService.""" ws_url = "https://api.gls-group.eu/public/v1/shipments" ws_test_url = "https://api-qs1.gls-group.eu/public/v1/shipments" encoder = GlsEuEncoder decoder = GlsEuDecoderGetLabel transport = GlsEuTransport api = GlsEuApiParcel manage_multi_label = True factory.register_builder("gls_fr_rest", "get_label", GlsEuGetabel)
052228bb3ba3c8ec13452f5a8328ed77c30e565d
images/hub/canvasauthenticator/canvasauthenticator/__init__.py
images/hub/canvasauthenticator/canvasauthenticator/__init__.py
from traitlets import List, Unicode from oauthenticator.generic import GenericOAuthenticator from tornado import gen canvas_site = 'https://ucberkeley.test.instructure.com/' class CanvasAuthenticator(GenericOAuthenticator): allowed_email_domains = List( [], config=True, help=""" List of domains whose users are authorized to log in. This relies on the primary email id set in canvas for the user """ ) canvas_url = Unicode( '', config=True, help=""" URL to canvas installation to use for authentication. Must have a trailing slash """ ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.canvas_url: raise ValueError('c.CanvasAuthenticator.canvas_url must be set') # canvas_url must have a trailing slash if self.canvas_url[-1] != '/': raise ValueError('c.CanvasAuthenticator.canvas_url must have a trailing slash') self.token_url = f'{self.canvas_url}login/oauth2/token' self.userdata_url = f'{self.canvas_url}api/v1/users/self/profile' self.extra_params = { 'client_id': self.client_id, 'client_secret': self.client_secret } def normalize_username(self,username): username = username.lower() # FIXME: allow username = username.split('@')[0] return username
from traitlets import List, Unicode from oauthenticator.generic import GenericOAuthenticator from tornado import gen canvas_site = 'https://ucberkeley.test.instructure.com/' class CanvasAuthenticator(GenericOAuthenticator): allowed_email_domains = List( [], config=True, help=""" List of domains whose users are authorized to log in. This relies on the primary email id set in canvas for the user """ ) canvas_url = Unicode( '', config=True, help=""" URL to canvas installation to use for authentication. Must have a trailing slash """ ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.canvas_url: raise ValueError('c.CanvasAuthenticator.canvas_url must be set') # canvas_url must have a trailing slash if self.canvas_url[-1] != '/': raise ValueError('c.CanvasAuthenticator.canvas_url must have a trailing slash') self.token_url = f'{self.canvas_url}login/oauth2/token' self.userdata_url = f'{self.canvas_url}api/v1/users/self/profile' self.extra_params = { 'client_id': self.client_id, 'client_secret': self.client_secret } def normalize_username(self,username): username = username.lower() # To make life easier & match usernames with existing users who were # created with google auth, we want to strip the domain name. If not, # we use the full email as the official user name if username.endswith('@berkeley.edu'): return username.split('@')[0] return username
Normalize usernames properly to prevent clashes from guest accounts
Normalize usernames properly to prevent clashes from guest accounts Guest accounts can have non berkeley.edu emails, and might get access to a berkeley.edu user's home directory. This will prevent that.
Python
bsd-3-clause
ryanlovett/datahub,berkeley-dsep-infra/datahub,ryanlovett/datahub,ryanlovett/datahub,berkeley-dsep-infra/datahub,berkeley-dsep-infra/datahub
from traitlets import List, Unicode from oauthenticator.generic import GenericOAuthenticator from tornado import gen canvas_site = 'https://ucberkeley.test.instructure.com/' class CanvasAuthenticator(GenericOAuthenticator): allowed_email_domains = List( [], config=True, help=""" List of domains whose users are authorized to log in. This relies on the primary email id set in canvas for the user """ ) canvas_url = Unicode( '', config=True, help=""" URL to canvas installation to use for authentication. Must have a trailing slash """ ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.canvas_url: raise ValueError('c.CanvasAuthenticator.canvas_url must be set') # canvas_url must have a trailing slash if self.canvas_url[-1] != '/': raise ValueError('c.CanvasAuthenticator.canvas_url must have a trailing slash') self.token_url = f'{self.canvas_url}login/oauth2/token' self.userdata_url = f'{self.canvas_url}api/v1/users/self/profile' self.extra_params = { 'client_id': self.client_id, 'client_secret': self.client_secret } def normalize_username(self,username): username = username.lower() # FIXME: allow username = username.split('@')[0] return usernameNormalize usernames properly to prevent clashes from guest accounts Guest accounts can have non berkeley.edu emails, and might get access to a berkeley.edu user's home directory. This will prevent that.
from traitlets import List, Unicode from oauthenticator.generic import GenericOAuthenticator from tornado import gen canvas_site = 'https://ucberkeley.test.instructure.com/' class CanvasAuthenticator(GenericOAuthenticator): allowed_email_domains = List( [], config=True, help=""" List of domains whose users are authorized to log in. This relies on the primary email id set in canvas for the user """ ) canvas_url = Unicode( '', config=True, help=""" URL to canvas installation to use for authentication. Must have a trailing slash """ ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.canvas_url: raise ValueError('c.CanvasAuthenticator.canvas_url must be set') # canvas_url must have a trailing slash if self.canvas_url[-1] != '/': raise ValueError('c.CanvasAuthenticator.canvas_url must have a trailing slash') self.token_url = f'{self.canvas_url}login/oauth2/token' self.userdata_url = f'{self.canvas_url}api/v1/users/self/profile' self.extra_params = { 'client_id': self.client_id, 'client_secret': self.client_secret } def normalize_username(self,username): username = username.lower() # To make life easier & match usernames with existing users who were # created with google auth, we want to strip the domain name. If not, # we use the full email as the official user name if username.endswith('@berkeley.edu'): return username.split('@')[0] return username
<commit_before>from traitlets import List, Unicode from oauthenticator.generic import GenericOAuthenticator from tornado import gen canvas_site = 'https://ucberkeley.test.instructure.com/' class CanvasAuthenticator(GenericOAuthenticator): allowed_email_domains = List( [], config=True, help=""" List of domains whose users are authorized to log in. This relies on the primary email id set in canvas for the user """ ) canvas_url = Unicode( '', config=True, help=""" URL to canvas installation to use for authentication. Must have a trailing slash """ ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.canvas_url: raise ValueError('c.CanvasAuthenticator.canvas_url must be set') # canvas_url must have a trailing slash if self.canvas_url[-1] != '/': raise ValueError('c.CanvasAuthenticator.canvas_url must have a trailing slash') self.token_url = f'{self.canvas_url}login/oauth2/token' self.userdata_url = f'{self.canvas_url}api/v1/users/self/profile' self.extra_params = { 'client_id': self.client_id, 'client_secret': self.client_secret } def normalize_username(self,username): username = username.lower() # FIXME: allow username = username.split('@')[0] return username<commit_msg>Normalize usernames properly to prevent clashes from guest accounts Guest accounts can have non berkeley.edu emails, and might get access to a berkeley.edu user's home directory. This will prevent that.<commit_after>
from traitlets import List, Unicode from oauthenticator.generic import GenericOAuthenticator from tornado import gen canvas_site = 'https://ucberkeley.test.instructure.com/' class CanvasAuthenticator(GenericOAuthenticator): allowed_email_domains = List( [], config=True, help=""" List of domains whose users are authorized to log in. This relies on the primary email id set in canvas for the user """ ) canvas_url = Unicode( '', config=True, help=""" URL to canvas installation to use for authentication. Must have a trailing slash """ ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.canvas_url: raise ValueError('c.CanvasAuthenticator.canvas_url must be set') # canvas_url must have a trailing slash if self.canvas_url[-1] != '/': raise ValueError('c.CanvasAuthenticator.canvas_url must have a trailing slash') self.token_url = f'{self.canvas_url}login/oauth2/token' self.userdata_url = f'{self.canvas_url}api/v1/users/self/profile' self.extra_params = { 'client_id': self.client_id, 'client_secret': self.client_secret } def normalize_username(self,username): username = username.lower() # To make life easier & match usernames with existing users who were # created with google auth, we want to strip the domain name. If not, # we use the full email as the official user name if username.endswith('@berkeley.edu'): return username.split('@')[0] return username
from traitlets import List, Unicode from oauthenticator.generic import GenericOAuthenticator from tornado import gen canvas_site = 'https://ucberkeley.test.instructure.com/' class CanvasAuthenticator(GenericOAuthenticator): allowed_email_domains = List( [], config=True, help=""" List of domains whose users are authorized to log in. This relies on the primary email id set in canvas for the user """ ) canvas_url = Unicode( '', config=True, help=""" URL to canvas installation to use for authentication. Must have a trailing slash """ ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.canvas_url: raise ValueError('c.CanvasAuthenticator.canvas_url must be set') # canvas_url must have a trailing slash if self.canvas_url[-1] != '/': raise ValueError('c.CanvasAuthenticator.canvas_url must have a trailing slash') self.token_url = f'{self.canvas_url}login/oauth2/token' self.userdata_url = f'{self.canvas_url}api/v1/users/self/profile' self.extra_params = { 'client_id': self.client_id, 'client_secret': self.client_secret } def normalize_username(self,username): username = username.lower() # FIXME: allow username = username.split('@')[0] return usernameNormalize usernames properly to prevent clashes from guest accounts Guest accounts can have non berkeley.edu emails, and might get access to a berkeley.edu user's home directory. This will prevent that.from traitlets import List, Unicode from oauthenticator.generic import GenericOAuthenticator from tornado import gen canvas_site = 'https://ucberkeley.test.instructure.com/' class CanvasAuthenticator(GenericOAuthenticator): allowed_email_domains = List( [], config=True, help=""" List of domains whose users are authorized to log in. This relies on the primary email id set in canvas for the user """ ) canvas_url = Unicode( '', config=True, help=""" URL to canvas installation to use for authentication. Must have a trailing slash """ ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.canvas_url: raise ValueError('c.CanvasAuthenticator.canvas_url must be set') # canvas_url must have a trailing slash if self.canvas_url[-1] != '/': raise ValueError('c.CanvasAuthenticator.canvas_url must have a trailing slash') self.token_url = f'{self.canvas_url}login/oauth2/token' self.userdata_url = f'{self.canvas_url}api/v1/users/self/profile' self.extra_params = { 'client_id': self.client_id, 'client_secret': self.client_secret } def normalize_username(self,username): username = username.lower() # To make life easier & match usernames with existing users who were # created with google auth, we want to strip the domain name. If not, # we use the full email as the official user name if username.endswith('@berkeley.edu'): return username.split('@')[0] return username
<commit_before>from traitlets import List, Unicode from oauthenticator.generic import GenericOAuthenticator from tornado import gen canvas_site = 'https://ucberkeley.test.instructure.com/' class CanvasAuthenticator(GenericOAuthenticator): allowed_email_domains = List( [], config=True, help=""" List of domains whose users are authorized to log in. This relies on the primary email id set in canvas for the user """ ) canvas_url = Unicode( '', config=True, help=""" URL to canvas installation to use for authentication. Must have a trailing slash """ ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.canvas_url: raise ValueError('c.CanvasAuthenticator.canvas_url must be set') # canvas_url must have a trailing slash if self.canvas_url[-1] != '/': raise ValueError('c.CanvasAuthenticator.canvas_url must have a trailing slash') self.token_url = f'{self.canvas_url}login/oauth2/token' self.userdata_url = f'{self.canvas_url}api/v1/users/self/profile' self.extra_params = { 'client_id': self.client_id, 'client_secret': self.client_secret } def normalize_username(self,username): username = username.lower() # FIXME: allow username = username.split('@')[0] return username<commit_msg>Normalize usernames properly to prevent clashes from guest accounts Guest accounts can have non berkeley.edu emails, and might get access to a berkeley.edu user's home directory. This will prevent that.<commit_after>from traitlets import List, Unicode from oauthenticator.generic import GenericOAuthenticator from tornado import gen canvas_site = 'https://ucberkeley.test.instructure.com/' class CanvasAuthenticator(GenericOAuthenticator): allowed_email_domains = List( [], config=True, help=""" List of domains whose users are authorized to log in. This relies on the primary email id set in canvas for the user """ ) canvas_url = Unicode( '', config=True, help=""" URL to canvas installation to use for authentication. Must have a trailing slash """ ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.canvas_url: raise ValueError('c.CanvasAuthenticator.canvas_url must be set') # canvas_url must have a trailing slash if self.canvas_url[-1] != '/': raise ValueError('c.CanvasAuthenticator.canvas_url must have a trailing slash') self.token_url = f'{self.canvas_url}login/oauth2/token' self.userdata_url = f'{self.canvas_url}api/v1/users/self/profile' self.extra_params = { 'client_id': self.client_id, 'client_secret': self.client_secret } def normalize_username(self,username): username = username.lower() # To make life easier & match usernames with existing users who were # created with google auth, we want to strip the domain name. If not, # we use the full email as the official user name if username.endswith('@berkeley.edu'): return username.split('@')[0] return username
c3aad1ab31b84cce97555c56ec44986addca5ee8
create_schemas_and_tables.py
create_schemas_and_tables.py
#! /usr/bin/env python3 import os import subprocess ODIE_DIR = os.path.dirname(__file__) subprocess.call([os.path.join(ODIE_DIR, 'create_garfield_models.py')]) subprocess.call([os.path.join(ODIE_DIR, 'create_fsmi_models.py')])
#! /usr/bin/env python3 import os import subprocess ODIE_DIR = os.path.dirname(__file__) # due to Flask-SQLA only using a single MetaData object even when handling multiple # databases, we can't create let it create all our models at once (otherwise it # tries to create Enums in all databases, which will fail due to missing schemas) # We therefor create them db by db, only letting Flask-SQLA know about one db at a time. # Hence subprocesses instead of simple imports subprocess.call([os.path.join(ODIE_DIR, 'create_garfield_models.py')]) subprocess.call([os.path.join(ODIE_DIR, 'create_fsmi_models.py')])
Add comment explaining unconventional model creation
Add comment explaining unconventional model creation
Python
mit
fjalir/odie-server,Kha/odie-server,Kha/odie-server,fjalir/odie-server,fjalir/odie-server,Kha/odie-server,fsmi/odie-server,fsmi/odie-server,fsmi/odie-server
#! /usr/bin/env python3 import os import subprocess ODIE_DIR = os.path.dirname(__file__) subprocess.call([os.path.join(ODIE_DIR, 'create_garfield_models.py')]) subprocess.call([os.path.join(ODIE_DIR, 'create_fsmi_models.py')]) Add comment explaining unconventional model creation
#! /usr/bin/env python3 import os import subprocess ODIE_DIR = os.path.dirname(__file__) # due to Flask-SQLA only using a single MetaData object even when handling multiple # databases, we can't create let it create all our models at once (otherwise it # tries to create Enums in all databases, which will fail due to missing schemas) # We therefor create them db by db, only letting Flask-SQLA know about one db at a time. # Hence subprocesses instead of simple imports subprocess.call([os.path.join(ODIE_DIR, 'create_garfield_models.py')]) subprocess.call([os.path.join(ODIE_DIR, 'create_fsmi_models.py')])
<commit_before>#! /usr/bin/env python3 import os import subprocess ODIE_DIR = os.path.dirname(__file__) subprocess.call([os.path.join(ODIE_DIR, 'create_garfield_models.py')]) subprocess.call([os.path.join(ODIE_DIR, 'create_fsmi_models.py')]) <commit_msg>Add comment explaining unconventional model creation<commit_after>
#! /usr/bin/env python3 import os import subprocess ODIE_DIR = os.path.dirname(__file__) # due to Flask-SQLA only using a single MetaData object even when handling multiple # databases, we can't create let it create all our models at once (otherwise it # tries to create Enums in all databases, which will fail due to missing schemas) # We therefor create them db by db, only letting Flask-SQLA know about one db at a time. # Hence subprocesses instead of simple imports subprocess.call([os.path.join(ODIE_DIR, 'create_garfield_models.py')]) subprocess.call([os.path.join(ODIE_DIR, 'create_fsmi_models.py')])
#! /usr/bin/env python3 import os import subprocess ODIE_DIR = os.path.dirname(__file__) subprocess.call([os.path.join(ODIE_DIR, 'create_garfield_models.py')]) subprocess.call([os.path.join(ODIE_DIR, 'create_fsmi_models.py')]) Add comment explaining unconventional model creation#! /usr/bin/env python3 import os import subprocess ODIE_DIR = os.path.dirname(__file__) # due to Flask-SQLA only using a single MetaData object even when handling multiple # databases, we can't create let it create all our models at once (otherwise it # tries to create Enums in all databases, which will fail due to missing schemas) # We therefor create them db by db, only letting Flask-SQLA know about one db at a time. # Hence subprocesses instead of simple imports subprocess.call([os.path.join(ODIE_DIR, 'create_garfield_models.py')]) subprocess.call([os.path.join(ODIE_DIR, 'create_fsmi_models.py')])
<commit_before>#! /usr/bin/env python3 import os import subprocess ODIE_DIR = os.path.dirname(__file__) subprocess.call([os.path.join(ODIE_DIR, 'create_garfield_models.py')]) subprocess.call([os.path.join(ODIE_DIR, 'create_fsmi_models.py')]) <commit_msg>Add comment explaining unconventional model creation<commit_after>#! /usr/bin/env python3 import os import subprocess ODIE_DIR = os.path.dirname(__file__) # due to Flask-SQLA only using a single MetaData object even when handling multiple # databases, we can't create let it create all our models at once (otherwise it # tries to create Enums in all databases, which will fail due to missing schemas) # We therefor create them db by db, only letting Flask-SQLA know about one db at a time. # Hence subprocesses instead of simple imports subprocess.call([os.path.join(ODIE_DIR, 'create_garfield_models.py')]) subprocess.call([os.path.join(ODIE_DIR, 'create_fsmi_models.py')])
94db336d4006af775542b5adaf6853b3d88b912c
jacquard/directory/__init__.py
jacquard/directory/__init__.py
import pkg_resources def open_directory(engine, kwargs): entry_point = None for candidate_entry_point in pkg_resources.iter_entry_points( 'jacquard.directory_engines', name=engine, ): entry_point = candidate_entry_point if entry_point is None: raise RuntimeError("Cannot find directory engine '%s'" % engine) cls = entry_point.load() return cls(**kwargs)
Add open directory utility function
Add open directory utility function
Python
mit
prophile/jacquard,prophile/jacquard
Add open directory utility function
import pkg_resources def open_directory(engine, kwargs): entry_point = None for candidate_entry_point in pkg_resources.iter_entry_points( 'jacquard.directory_engines', name=engine, ): entry_point = candidate_entry_point if entry_point is None: raise RuntimeError("Cannot find directory engine '%s'" % engine) cls = entry_point.load() return cls(**kwargs)
<commit_before><commit_msg>Add open directory utility function<commit_after>
import pkg_resources def open_directory(engine, kwargs): entry_point = None for candidate_entry_point in pkg_resources.iter_entry_points( 'jacquard.directory_engines', name=engine, ): entry_point = candidate_entry_point if entry_point is None: raise RuntimeError("Cannot find directory engine '%s'" % engine) cls = entry_point.load() return cls(**kwargs)
Add open directory utility functionimport pkg_resources def open_directory(engine, kwargs): entry_point = None for candidate_entry_point in pkg_resources.iter_entry_points( 'jacquard.directory_engines', name=engine, ): entry_point = candidate_entry_point if entry_point is None: raise RuntimeError("Cannot find directory engine '%s'" % engine) cls = entry_point.load() return cls(**kwargs)
<commit_before><commit_msg>Add open directory utility function<commit_after>import pkg_resources def open_directory(engine, kwargs): entry_point = None for candidate_entry_point in pkg_resources.iter_entry_points( 'jacquard.directory_engines', name=engine, ): entry_point = candidate_entry_point if entry_point is None: raise RuntimeError("Cannot find directory engine '%s'" % engine) cls = entry_point.load() return cls(**kwargs)
3934ed699cdb0b472c09ad238ee4284b0050869c
prime-factors/prime_factors.py
prime-factors/prime_factors.py
def prime_factors(n): factors = [] factor = 2 while n != 1: while n % factor == 0: factors += [factor] n //= factor factor += 1 return factors
def prime_factors(n): factors = [] while n % 2 == 0: factors += [2] n //= 2 factor = 3 while n != 1: while n % factor == 0: factors += [factor] n //= factor factor += 2 return factors
Make solution more efficient by only testing odd numbers
Make solution more efficient by only testing odd numbers
Python
agpl-3.0
CubicComet/exercism-python-solutions
def prime_factors(n): factors = [] factor = 2 while n != 1: while n % factor == 0: factors += [factor] n //= factor factor += 1 return factors Make solution more efficient by only testing odd numbers
def prime_factors(n): factors = [] while n % 2 == 0: factors += [2] n //= 2 factor = 3 while n != 1: while n % factor == 0: factors += [factor] n //= factor factor += 2 return factors
<commit_before>def prime_factors(n): factors = [] factor = 2 while n != 1: while n % factor == 0: factors += [factor] n //= factor factor += 1 return factors <commit_msg>Make solution more efficient by only testing odd numbers<commit_after>
def prime_factors(n): factors = [] while n % 2 == 0: factors += [2] n //= 2 factor = 3 while n != 1: while n % factor == 0: factors += [factor] n //= factor factor += 2 return factors
def prime_factors(n): factors = [] factor = 2 while n != 1: while n % factor == 0: factors += [factor] n //= factor factor += 1 return factors Make solution more efficient by only testing odd numbersdef prime_factors(n): factors = [] while n % 2 == 0: factors += [2] n //= 2 factor = 3 while n != 1: while n % factor == 0: factors += [factor] n //= factor factor += 2 return factors
<commit_before>def prime_factors(n): factors = [] factor = 2 while n != 1: while n % factor == 0: factors += [factor] n //= factor factor += 1 return factors <commit_msg>Make solution more efficient by only testing odd numbers<commit_after>def prime_factors(n): factors = [] while n % 2 == 0: factors += [2] n //= 2 factor = 3 while n != 1: while n % factor == 0: factors += [factor] n //= factor factor += 2 return factors
a5d6793758de7badcc84bd377ea2dddc472d9a6b
imgcat/ipython_magic.py
imgcat/ipython_magic.py
from IPython.core.magic import (Magics, magics_class, line_magic) from IPython.display import display as ipython_display from IPython.display import Markdown import io import PIL.Image def _is_ipython_notebook(): try: # pylint: disable=undefined-variable return 'IPKernelApp' in get_ipython().config # pylint: enable=undefined-variable except: return False IS_NOTEBOOK = _is_ipython_notebook() @magics_class class ImgcatMagics(Magics): @line_magic def imgcat(self, line=''): '''%imgcat magic, equivalent to imgcat(<expression>). Usage: %imgcat <expression> ''' if not line: ipython_display(Markdown("Usage: `%imgcat [python code]`")) return global_ns = self.shell.user_global_ns local_ns = self.shell.user_ns ret = eval(line, global_ns, local_ns) # pylint: disable=eval-used if IS_NOTEBOOK: from .imgcat import to_content_buf buf = io.BytesIO(to_content_buf(ret)) im = PIL.Image.open(buf) ipython_display(im) buf.close() else: from .imgcat import imgcat imgcat(ret)
from IPython.core.magic import (Magics, magics_class, line_magic) from IPython.display import display as ipython_display from IPython.display import Markdown import io import os import PIL.Image def _is_ipython_notebook(): try: # pylint: disable=undefined-variable return 'IPKernelApp' in get_ipython().config # pylint: enable=undefined-variable except: return False IS_NOTEBOOK = _is_ipython_notebook() @magics_class class ImgcatMagics(Magics): # TODO: Add tests for ipython magic. @line_magic def imgcat(self, line=''): '''%imgcat magic, equivalent to imgcat(<expression>). Usage: %imgcat <expression> ''' if not line: ipython_display(Markdown("Usage: `%imgcat [python code]`")) return if os.path.isfile(line): with open(line, mode='rb') as fp: ret = fp.read() else: global_ns = self.shell.user_global_ns local_ns = self.shell.user_ns ret = eval(line, global_ns, local_ns) # pylint: disable=eval-used if IS_NOTEBOOK: from .imgcat import to_content_buf buf = io.BytesIO(to_content_buf(ret)) im = PIL.Image.open(buf) ipython_display(im) buf.close() else: from .imgcat import imgcat imgcat(ret)
Support `%imgcat <filename>` for the ipython magic
Support `%imgcat <filename>` for the ipython magic If <filename> is an existing path, do not evaluate it as a code but display the image file itself. Otherwise, evaluate the expression.
Python
mit
wookayin/python-imgcat
from IPython.core.magic import (Magics, magics_class, line_magic) from IPython.display import display as ipython_display from IPython.display import Markdown import io import PIL.Image def _is_ipython_notebook(): try: # pylint: disable=undefined-variable return 'IPKernelApp' in get_ipython().config # pylint: enable=undefined-variable except: return False IS_NOTEBOOK = _is_ipython_notebook() @magics_class class ImgcatMagics(Magics): @line_magic def imgcat(self, line=''): '''%imgcat magic, equivalent to imgcat(<expression>). Usage: %imgcat <expression> ''' if not line: ipython_display(Markdown("Usage: `%imgcat [python code]`")) return global_ns = self.shell.user_global_ns local_ns = self.shell.user_ns ret = eval(line, global_ns, local_ns) # pylint: disable=eval-used if IS_NOTEBOOK: from .imgcat import to_content_buf buf = io.BytesIO(to_content_buf(ret)) im = PIL.Image.open(buf) ipython_display(im) buf.close() else: from .imgcat import imgcat imgcat(ret) Support `%imgcat <filename>` for the ipython magic If <filename> is an existing path, do not evaluate it as a code but display the image file itself. Otherwise, evaluate the expression.
from IPython.core.magic import (Magics, magics_class, line_magic) from IPython.display import display as ipython_display from IPython.display import Markdown import io import os import PIL.Image def _is_ipython_notebook(): try: # pylint: disable=undefined-variable return 'IPKernelApp' in get_ipython().config # pylint: enable=undefined-variable except: return False IS_NOTEBOOK = _is_ipython_notebook() @magics_class class ImgcatMagics(Magics): # TODO: Add tests for ipython magic. @line_magic def imgcat(self, line=''): '''%imgcat magic, equivalent to imgcat(<expression>). Usage: %imgcat <expression> ''' if not line: ipython_display(Markdown("Usage: `%imgcat [python code]`")) return if os.path.isfile(line): with open(line, mode='rb') as fp: ret = fp.read() else: global_ns = self.shell.user_global_ns local_ns = self.shell.user_ns ret = eval(line, global_ns, local_ns) # pylint: disable=eval-used if IS_NOTEBOOK: from .imgcat import to_content_buf buf = io.BytesIO(to_content_buf(ret)) im = PIL.Image.open(buf) ipython_display(im) buf.close() else: from .imgcat import imgcat imgcat(ret)
<commit_before>from IPython.core.magic import (Magics, magics_class, line_magic) from IPython.display import display as ipython_display from IPython.display import Markdown import io import PIL.Image def _is_ipython_notebook(): try: # pylint: disable=undefined-variable return 'IPKernelApp' in get_ipython().config # pylint: enable=undefined-variable except: return False IS_NOTEBOOK = _is_ipython_notebook() @magics_class class ImgcatMagics(Magics): @line_magic def imgcat(self, line=''): '''%imgcat magic, equivalent to imgcat(<expression>). Usage: %imgcat <expression> ''' if not line: ipython_display(Markdown("Usage: `%imgcat [python code]`")) return global_ns = self.shell.user_global_ns local_ns = self.shell.user_ns ret = eval(line, global_ns, local_ns) # pylint: disable=eval-used if IS_NOTEBOOK: from .imgcat import to_content_buf buf = io.BytesIO(to_content_buf(ret)) im = PIL.Image.open(buf) ipython_display(im) buf.close() else: from .imgcat import imgcat imgcat(ret) <commit_msg>Support `%imgcat <filename>` for the ipython magic If <filename> is an existing path, do not evaluate it as a code but display the image file itself. Otherwise, evaluate the expression.<commit_after>
from IPython.core.magic import (Magics, magics_class, line_magic) from IPython.display import display as ipython_display from IPython.display import Markdown import io import os import PIL.Image def _is_ipython_notebook(): try: # pylint: disable=undefined-variable return 'IPKernelApp' in get_ipython().config # pylint: enable=undefined-variable except: return False IS_NOTEBOOK = _is_ipython_notebook() @magics_class class ImgcatMagics(Magics): # TODO: Add tests for ipython magic. @line_magic def imgcat(self, line=''): '''%imgcat magic, equivalent to imgcat(<expression>). Usage: %imgcat <expression> ''' if not line: ipython_display(Markdown("Usage: `%imgcat [python code]`")) return if os.path.isfile(line): with open(line, mode='rb') as fp: ret = fp.read() else: global_ns = self.shell.user_global_ns local_ns = self.shell.user_ns ret = eval(line, global_ns, local_ns) # pylint: disable=eval-used if IS_NOTEBOOK: from .imgcat import to_content_buf buf = io.BytesIO(to_content_buf(ret)) im = PIL.Image.open(buf) ipython_display(im) buf.close() else: from .imgcat import imgcat imgcat(ret)
from IPython.core.magic import (Magics, magics_class, line_magic) from IPython.display import display as ipython_display from IPython.display import Markdown import io import PIL.Image def _is_ipython_notebook(): try: # pylint: disable=undefined-variable return 'IPKernelApp' in get_ipython().config # pylint: enable=undefined-variable except: return False IS_NOTEBOOK = _is_ipython_notebook() @magics_class class ImgcatMagics(Magics): @line_magic def imgcat(self, line=''): '''%imgcat magic, equivalent to imgcat(<expression>). Usage: %imgcat <expression> ''' if not line: ipython_display(Markdown("Usage: `%imgcat [python code]`")) return global_ns = self.shell.user_global_ns local_ns = self.shell.user_ns ret = eval(line, global_ns, local_ns) # pylint: disable=eval-used if IS_NOTEBOOK: from .imgcat import to_content_buf buf = io.BytesIO(to_content_buf(ret)) im = PIL.Image.open(buf) ipython_display(im) buf.close() else: from .imgcat import imgcat imgcat(ret) Support `%imgcat <filename>` for the ipython magic If <filename> is an existing path, do not evaluate it as a code but display the image file itself. Otherwise, evaluate the expression.from IPython.core.magic import (Magics, magics_class, line_magic) from IPython.display import display as ipython_display from IPython.display import Markdown import io import os import PIL.Image def _is_ipython_notebook(): try: # pylint: disable=undefined-variable return 'IPKernelApp' in get_ipython().config # pylint: enable=undefined-variable except: return False IS_NOTEBOOK = _is_ipython_notebook() @magics_class class ImgcatMagics(Magics): # TODO: Add tests for ipython magic. @line_magic def imgcat(self, line=''): '''%imgcat magic, equivalent to imgcat(<expression>). Usage: %imgcat <expression> ''' if not line: ipython_display(Markdown("Usage: `%imgcat [python code]`")) return if os.path.isfile(line): with open(line, mode='rb') as fp: ret = fp.read() else: global_ns = self.shell.user_global_ns local_ns = self.shell.user_ns ret = eval(line, global_ns, local_ns) # pylint: disable=eval-used if IS_NOTEBOOK: from .imgcat import to_content_buf buf = io.BytesIO(to_content_buf(ret)) im = PIL.Image.open(buf) ipython_display(im) buf.close() else: from .imgcat import imgcat imgcat(ret)
<commit_before>from IPython.core.magic import (Magics, magics_class, line_magic) from IPython.display import display as ipython_display from IPython.display import Markdown import io import PIL.Image def _is_ipython_notebook(): try: # pylint: disable=undefined-variable return 'IPKernelApp' in get_ipython().config # pylint: enable=undefined-variable except: return False IS_NOTEBOOK = _is_ipython_notebook() @magics_class class ImgcatMagics(Magics): @line_magic def imgcat(self, line=''): '''%imgcat magic, equivalent to imgcat(<expression>). Usage: %imgcat <expression> ''' if not line: ipython_display(Markdown("Usage: `%imgcat [python code]`")) return global_ns = self.shell.user_global_ns local_ns = self.shell.user_ns ret = eval(line, global_ns, local_ns) # pylint: disable=eval-used if IS_NOTEBOOK: from .imgcat import to_content_buf buf = io.BytesIO(to_content_buf(ret)) im = PIL.Image.open(buf) ipython_display(im) buf.close() else: from .imgcat import imgcat imgcat(ret) <commit_msg>Support `%imgcat <filename>` for the ipython magic If <filename> is an existing path, do not evaluate it as a code but display the image file itself. Otherwise, evaluate the expression.<commit_after>from IPython.core.magic import (Magics, magics_class, line_magic) from IPython.display import display as ipython_display from IPython.display import Markdown import io import os import PIL.Image def _is_ipython_notebook(): try: # pylint: disable=undefined-variable return 'IPKernelApp' in get_ipython().config # pylint: enable=undefined-variable except: return False IS_NOTEBOOK = _is_ipython_notebook() @magics_class class ImgcatMagics(Magics): # TODO: Add tests for ipython magic. @line_magic def imgcat(self, line=''): '''%imgcat magic, equivalent to imgcat(<expression>). Usage: %imgcat <expression> ''' if not line: ipython_display(Markdown("Usage: `%imgcat [python code]`")) return if os.path.isfile(line): with open(line, mode='rb') as fp: ret = fp.read() else: global_ns = self.shell.user_global_ns local_ns = self.shell.user_ns ret = eval(line, global_ns, local_ns) # pylint: disable=eval-used if IS_NOTEBOOK: from .imgcat import to_content_buf buf = io.BytesIO(to_content_buf(ret)) im = PIL.Image.open(buf) ipython_display(im) buf.close() else: from .imgcat import imgcat imgcat(ret)
7961fe22b76b8dd75172a848c645b26d87dc2776
tests/training_tests/test_chatterbot_corpus_training.py
tests/training_tests/test_chatterbot_corpus_training.py
from tests.base_case import ChatBotTestCase from chatterbot.trainers import ChatterBotCorpusTrainer class ChatterBotCorpusTrainingTestCase(ChatBotTestCase): """ Test case for training with data from the ChatterBot Corpus. """ def setUp(self): super(ChatterBotCorpusTrainingTestCase, self).setUp() self.chatbot.set_trainer(ChatterBotCorpusTrainer) def test_train_with_english_greeting_corpus(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_greeting_corpus_tags(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertIn('greetings', statement.get_tags()) def test_train_with_multiple_corpora(self): self.chatbot.train( 'chatterbot.corpus.english.greetings', 'chatterbot.corpus.english.conversations', ) statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_corpus(self): self.chatbot.train('chatterbot.corpus.english') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement)
from tests.base_case import ChatBotTestCase from chatterbot.trainers import ChatterBotCorpusTrainer class ChatterBotCorpusTrainingTestCase(ChatBotTestCase): """ Test case for training with data from the ChatterBot Corpus. """ def setUp(self): super(ChatterBotCorpusTrainingTestCase, self).setUp() self.chatbot.set_trainer(ChatterBotCorpusTrainer) def test_train_with_english_greeting_corpus(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_greeting_corpus_tags(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertEqual(['greetings'], statement.get_tags()) def test_train_with_multiple_corpora(self): self.chatbot.train( 'chatterbot.corpus.english.greetings', 'chatterbot.corpus.english.conversations', ) statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_corpus(self): self.chatbot.train('chatterbot.corpus.english') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement)
Switch to list equality check
Switch to list equality check
Python
bsd-3-clause
vkosuri/ChatterBot,gunthercox/ChatterBot
from tests.base_case import ChatBotTestCase from chatterbot.trainers import ChatterBotCorpusTrainer class ChatterBotCorpusTrainingTestCase(ChatBotTestCase): """ Test case for training with data from the ChatterBot Corpus. """ def setUp(self): super(ChatterBotCorpusTrainingTestCase, self).setUp() self.chatbot.set_trainer(ChatterBotCorpusTrainer) def test_train_with_english_greeting_corpus(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_greeting_corpus_tags(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertIn('greetings', statement.get_tags()) def test_train_with_multiple_corpora(self): self.chatbot.train( 'chatterbot.corpus.english.greetings', 'chatterbot.corpus.english.conversations', ) statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_corpus(self): self.chatbot.train('chatterbot.corpus.english') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) Switch to list equality check
from tests.base_case import ChatBotTestCase from chatterbot.trainers import ChatterBotCorpusTrainer class ChatterBotCorpusTrainingTestCase(ChatBotTestCase): """ Test case for training with data from the ChatterBot Corpus. """ def setUp(self): super(ChatterBotCorpusTrainingTestCase, self).setUp() self.chatbot.set_trainer(ChatterBotCorpusTrainer) def test_train_with_english_greeting_corpus(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_greeting_corpus_tags(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertEqual(['greetings'], statement.get_tags()) def test_train_with_multiple_corpora(self): self.chatbot.train( 'chatterbot.corpus.english.greetings', 'chatterbot.corpus.english.conversations', ) statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_corpus(self): self.chatbot.train('chatterbot.corpus.english') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement)
<commit_before>from tests.base_case import ChatBotTestCase from chatterbot.trainers import ChatterBotCorpusTrainer class ChatterBotCorpusTrainingTestCase(ChatBotTestCase): """ Test case for training with data from the ChatterBot Corpus. """ def setUp(self): super(ChatterBotCorpusTrainingTestCase, self).setUp() self.chatbot.set_trainer(ChatterBotCorpusTrainer) def test_train_with_english_greeting_corpus(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_greeting_corpus_tags(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertIn('greetings', statement.get_tags()) def test_train_with_multiple_corpora(self): self.chatbot.train( 'chatterbot.corpus.english.greetings', 'chatterbot.corpus.english.conversations', ) statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_corpus(self): self.chatbot.train('chatterbot.corpus.english') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) <commit_msg>Switch to list equality check<commit_after>
from tests.base_case import ChatBotTestCase from chatterbot.trainers import ChatterBotCorpusTrainer class ChatterBotCorpusTrainingTestCase(ChatBotTestCase): """ Test case for training with data from the ChatterBot Corpus. """ def setUp(self): super(ChatterBotCorpusTrainingTestCase, self).setUp() self.chatbot.set_trainer(ChatterBotCorpusTrainer) def test_train_with_english_greeting_corpus(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_greeting_corpus_tags(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertEqual(['greetings'], statement.get_tags()) def test_train_with_multiple_corpora(self): self.chatbot.train( 'chatterbot.corpus.english.greetings', 'chatterbot.corpus.english.conversations', ) statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_corpus(self): self.chatbot.train('chatterbot.corpus.english') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement)
from tests.base_case import ChatBotTestCase from chatterbot.trainers import ChatterBotCorpusTrainer class ChatterBotCorpusTrainingTestCase(ChatBotTestCase): """ Test case for training with data from the ChatterBot Corpus. """ def setUp(self): super(ChatterBotCorpusTrainingTestCase, self).setUp() self.chatbot.set_trainer(ChatterBotCorpusTrainer) def test_train_with_english_greeting_corpus(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_greeting_corpus_tags(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertIn('greetings', statement.get_tags()) def test_train_with_multiple_corpora(self): self.chatbot.train( 'chatterbot.corpus.english.greetings', 'chatterbot.corpus.english.conversations', ) statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_corpus(self): self.chatbot.train('chatterbot.corpus.english') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) Switch to list equality checkfrom tests.base_case import ChatBotTestCase from chatterbot.trainers import ChatterBotCorpusTrainer class ChatterBotCorpusTrainingTestCase(ChatBotTestCase): """ Test case for training with data from the ChatterBot Corpus. """ def setUp(self): super(ChatterBotCorpusTrainingTestCase, self).setUp() self.chatbot.set_trainer(ChatterBotCorpusTrainer) def test_train_with_english_greeting_corpus(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_greeting_corpus_tags(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertEqual(['greetings'], statement.get_tags()) def test_train_with_multiple_corpora(self): self.chatbot.train( 'chatterbot.corpus.english.greetings', 'chatterbot.corpus.english.conversations', ) statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_corpus(self): self.chatbot.train('chatterbot.corpus.english') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement)
<commit_before>from tests.base_case import ChatBotTestCase from chatterbot.trainers import ChatterBotCorpusTrainer class ChatterBotCorpusTrainingTestCase(ChatBotTestCase): """ Test case for training with data from the ChatterBot Corpus. """ def setUp(self): super(ChatterBotCorpusTrainingTestCase, self).setUp() self.chatbot.set_trainer(ChatterBotCorpusTrainer) def test_train_with_english_greeting_corpus(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_greeting_corpus_tags(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertIn('greetings', statement.get_tags()) def test_train_with_multiple_corpora(self): self.chatbot.train( 'chatterbot.corpus.english.greetings', 'chatterbot.corpus.english.conversations', ) statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_corpus(self): self.chatbot.train('chatterbot.corpus.english') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) <commit_msg>Switch to list equality check<commit_after>from tests.base_case import ChatBotTestCase from chatterbot.trainers import ChatterBotCorpusTrainer class ChatterBotCorpusTrainingTestCase(ChatBotTestCase): """ Test case for training with data from the ChatterBot Corpus. """ def setUp(self): super(ChatterBotCorpusTrainingTestCase, self).setUp() self.chatbot.set_trainer(ChatterBotCorpusTrainer) def test_train_with_english_greeting_corpus(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_greeting_corpus_tags(self): self.chatbot.train('chatterbot.corpus.english.greetings') statement = self.chatbot.storage.find('Hello') self.assertEqual(['greetings'], statement.get_tags()) def test_train_with_multiple_corpora(self): self.chatbot.train( 'chatterbot.corpus.english.greetings', 'chatterbot.corpus.english.conversations', ) statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement) def test_train_with_english_corpus(self): self.chatbot.train('chatterbot.corpus.english') statement = self.chatbot.storage.find('Hello') self.assertIsNotNone(statement)
3beffa750d68c2104b740193f0386be464829a1a
libpb/__init__.py
libpb/__init__.py
"""FreeBSD port building infrastructure.""" from __future__ import absolute_import from . import event def stop(kill=False, kill_clean=False): """Stop building ports and cleanup.""" from os import killpg from signal import SIGTERM, SIGKILL from .builder import builders from .env import cpus, flags from .queue import attr_queue, clean_queue, queues from .subprocess import children if flags["no_op"]: exit(254) flags["mode"] = "clean" if kill_clean: cleaning = () else: cleaning = set(i.pid for i in clean_queue.active) # Kill all active children for pid in children(): if pid not in cleaning: try: killpg(pid, SIGKILL if kill else SIGTERM) except OSError: pass # Stop all queues attr_queue.load = 0 for queue in queues: queue.load = 0 # Make cleaning go a bit faster if kill_clean: clean_queue.load = 0 return else: clean_queue.load = cpus # Wait for all active ports to finish so that they may be cleaned active = set() for queue in queues: for job in queue.active: port = job.port active.add(port) port.stage_completed.connect(lambda x: x.clean()) # Clean all other outstanding ports for builder in builders: for port in builder.ports: if port not in active: port.clean()
"""FreeBSD port building infrastructure.""" from __future__ import absolute_import from . import event def stop(kill=False, kill_clean=False): """Stop building ports and cleanup.""" from os import killpg from signal import SIGTERM, SIGKILL from .builder import builders from .env import cpus, flags from .queue import attr_queue, clean_queue, queues from .subprocess import children if flags["no_op"]: raise SystemExit(254) flags["mode"] = "clean" if kill_clean: cleaning = () else: cleaning = set(i.pid for i in clean_queue.active) # Kill all active children for pid in children(): if pid not in cleaning: try: killpg(pid, SIGKILL if kill else SIGTERM) except OSError: pass # Stop all queues attr_queue.load = 0 for queue in queues: queue.load = 0 # Make cleaning go a bit faster if kill_clean: clean_queue.load = 0 return else: clean_queue.load = cpus # Wait for all active ports to finish so that they may be cleaned active = set() for queue in queues: for job in queue.active: port = job.port active.add(port) port.stage_completed.connect(lambda x: x.clean()) # Clean all other outstanding ports for builder in builders: for port in builder.ports: if port not in active: port.clean()
Use SystemExit, not exit() to initiate a shutdown.
Use SystemExit, not exit() to initiate a shutdown. exit() has unintented side affects, such as closing stdin, that are undesired as stdin is assumed to be writable while libpb/event/run unwinds (i.e. Top monitor).
Python
bsd-2-clause
DragonSA/portbuilder,DragonSA/portbuilder
"""FreeBSD port building infrastructure.""" from __future__ import absolute_import from . import event def stop(kill=False, kill_clean=False): """Stop building ports and cleanup.""" from os import killpg from signal import SIGTERM, SIGKILL from .builder import builders from .env import cpus, flags from .queue import attr_queue, clean_queue, queues from .subprocess import children if flags["no_op"]: exit(254) flags["mode"] = "clean" if kill_clean: cleaning = () else: cleaning = set(i.pid for i in clean_queue.active) # Kill all active children for pid in children(): if pid not in cleaning: try: killpg(pid, SIGKILL if kill else SIGTERM) except OSError: pass # Stop all queues attr_queue.load = 0 for queue in queues: queue.load = 0 # Make cleaning go a bit faster if kill_clean: clean_queue.load = 0 return else: clean_queue.load = cpus # Wait for all active ports to finish so that they may be cleaned active = set() for queue in queues: for job in queue.active: port = job.port active.add(port) port.stage_completed.connect(lambda x: x.clean()) # Clean all other outstanding ports for builder in builders: for port in builder.ports: if port not in active: port.clean() Use SystemExit, not exit() to initiate a shutdown. exit() has unintented side affects, such as closing stdin, that are undesired as stdin is assumed to be writable while libpb/event/run unwinds (i.e. Top monitor).
"""FreeBSD port building infrastructure.""" from __future__ import absolute_import from . import event def stop(kill=False, kill_clean=False): """Stop building ports and cleanup.""" from os import killpg from signal import SIGTERM, SIGKILL from .builder import builders from .env import cpus, flags from .queue import attr_queue, clean_queue, queues from .subprocess import children if flags["no_op"]: raise SystemExit(254) flags["mode"] = "clean" if kill_clean: cleaning = () else: cleaning = set(i.pid for i in clean_queue.active) # Kill all active children for pid in children(): if pid not in cleaning: try: killpg(pid, SIGKILL if kill else SIGTERM) except OSError: pass # Stop all queues attr_queue.load = 0 for queue in queues: queue.load = 0 # Make cleaning go a bit faster if kill_clean: clean_queue.load = 0 return else: clean_queue.load = cpus # Wait for all active ports to finish so that they may be cleaned active = set() for queue in queues: for job in queue.active: port = job.port active.add(port) port.stage_completed.connect(lambda x: x.clean()) # Clean all other outstanding ports for builder in builders: for port in builder.ports: if port not in active: port.clean()
<commit_before>"""FreeBSD port building infrastructure.""" from __future__ import absolute_import from . import event def stop(kill=False, kill_clean=False): """Stop building ports and cleanup.""" from os import killpg from signal import SIGTERM, SIGKILL from .builder import builders from .env import cpus, flags from .queue import attr_queue, clean_queue, queues from .subprocess import children if flags["no_op"]: exit(254) flags["mode"] = "clean" if kill_clean: cleaning = () else: cleaning = set(i.pid for i in clean_queue.active) # Kill all active children for pid in children(): if pid not in cleaning: try: killpg(pid, SIGKILL if kill else SIGTERM) except OSError: pass # Stop all queues attr_queue.load = 0 for queue in queues: queue.load = 0 # Make cleaning go a bit faster if kill_clean: clean_queue.load = 0 return else: clean_queue.load = cpus # Wait for all active ports to finish so that they may be cleaned active = set() for queue in queues: for job in queue.active: port = job.port active.add(port) port.stage_completed.connect(lambda x: x.clean()) # Clean all other outstanding ports for builder in builders: for port in builder.ports: if port not in active: port.clean() <commit_msg>Use SystemExit, not exit() to initiate a shutdown. exit() has unintented side affects, such as closing stdin, that are undesired as stdin is assumed to be writable while libpb/event/run unwinds (i.e. Top monitor).<commit_after>
"""FreeBSD port building infrastructure.""" from __future__ import absolute_import from . import event def stop(kill=False, kill_clean=False): """Stop building ports and cleanup.""" from os import killpg from signal import SIGTERM, SIGKILL from .builder import builders from .env import cpus, flags from .queue import attr_queue, clean_queue, queues from .subprocess import children if flags["no_op"]: raise SystemExit(254) flags["mode"] = "clean" if kill_clean: cleaning = () else: cleaning = set(i.pid for i in clean_queue.active) # Kill all active children for pid in children(): if pid not in cleaning: try: killpg(pid, SIGKILL if kill else SIGTERM) except OSError: pass # Stop all queues attr_queue.load = 0 for queue in queues: queue.load = 0 # Make cleaning go a bit faster if kill_clean: clean_queue.load = 0 return else: clean_queue.load = cpus # Wait for all active ports to finish so that they may be cleaned active = set() for queue in queues: for job in queue.active: port = job.port active.add(port) port.stage_completed.connect(lambda x: x.clean()) # Clean all other outstanding ports for builder in builders: for port in builder.ports: if port not in active: port.clean()
"""FreeBSD port building infrastructure.""" from __future__ import absolute_import from . import event def stop(kill=False, kill_clean=False): """Stop building ports and cleanup.""" from os import killpg from signal import SIGTERM, SIGKILL from .builder import builders from .env import cpus, flags from .queue import attr_queue, clean_queue, queues from .subprocess import children if flags["no_op"]: exit(254) flags["mode"] = "clean" if kill_clean: cleaning = () else: cleaning = set(i.pid for i in clean_queue.active) # Kill all active children for pid in children(): if pid not in cleaning: try: killpg(pid, SIGKILL if kill else SIGTERM) except OSError: pass # Stop all queues attr_queue.load = 0 for queue in queues: queue.load = 0 # Make cleaning go a bit faster if kill_clean: clean_queue.load = 0 return else: clean_queue.load = cpus # Wait for all active ports to finish so that they may be cleaned active = set() for queue in queues: for job in queue.active: port = job.port active.add(port) port.stage_completed.connect(lambda x: x.clean()) # Clean all other outstanding ports for builder in builders: for port in builder.ports: if port not in active: port.clean() Use SystemExit, not exit() to initiate a shutdown. exit() has unintented side affects, such as closing stdin, that are undesired as stdin is assumed to be writable while libpb/event/run unwinds (i.e. Top monitor)."""FreeBSD port building infrastructure.""" from __future__ import absolute_import from . import event def stop(kill=False, kill_clean=False): """Stop building ports and cleanup.""" from os import killpg from signal import SIGTERM, SIGKILL from .builder import builders from .env import cpus, flags from .queue import attr_queue, clean_queue, queues from .subprocess import children if flags["no_op"]: raise SystemExit(254) flags["mode"] = "clean" if kill_clean: cleaning = () else: cleaning = set(i.pid for i in clean_queue.active) # Kill all active children for pid in children(): if pid not in cleaning: try: killpg(pid, SIGKILL if kill else SIGTERM) except OSError: pass # Stop all queues attr_queue.load = 0 for queue in queues: queue.load = 0 # Make cleaning go a bit faster if kill_clean: clean_queue.load = 0 return else: clean_queue.load = cpus # Wait for all active ports to finish so that they may be cleaned active = set() for queue in queues: for job in queue.active: port = job.port active.add(port) port.stage_completed.connect(lambda x: x.clean()) # Clean all other outstanding ports for builder in builders: for port in builder.ports: if port not in active: port.clean()
<commit_before>"""FreeBSD port building infrastructure.""" from __future__ import absolute_import from . import event def stop(kill=False, kill_clean=False): """Stop building ports and cleanup.""" from os import killpg from signal import SIGTERM, SIGKILL from .builder import builders from .env import cpus, flags from .queue import attr_queue, clean_queue, queues from .subprocess import children if flags["no_op"]: exit(254) flags["mode"] = "clean" if kill_clean: cleaning = () else: cleaning = set(i.pid for i in clean_queue.active) # Kill all active children for pid in children(): if pid not in cleaning: try: killpg(pid, SIGKILL if kill else SIGTERM) except OSError: pass # Stop all queues attr_queue.load = 0 for queue in queues: queue.load = 0 # Make cleaning go a bit faster if kill_clean: clean_queue.load = 0 return else: clean_queue.load = cpus # Wait for all active ports to finish so that they may be cleaned active = set() for queue in queues: for job in queue.active: port = job.port active.add(port) port.stage_completed.connect(lambda x: x.clean()) # Clean all other outstanding ports for builder in builders: for port in builder.ports: if port not in active: port.clean() <commit_msg>Use SystemExit, not exit() to initiate a shutdown. exit() has unintented side affects, such as closing stdin, that are undesired as stdin is assumed to be writable while libpb/event/run unwinds (i.e. Top monitor).<commit_after>"""FreeBSD port building infrastructure.""" from __future__ import absolute_import from . import event def stop(kill=False, kill_clean=False): """Stop building ports and cleanup.""" from os import killpg from signal import SIGTERM, SIGKILL from .builder import builders from .env import cpus, flags from .queue import attr_queue, clean_queue, queues from .subprocess import children if flags["no_op"]: raise SystemExit(254) flags["mode"] = "clean" if kill_clean: cleaning = () else: cleaning = set(i.pid for i in clean_queue.active) # Kill all active children for pid in children(): if pid not in cleaning: try: killpg(pid, SIGKILL if kill else SIGTERM) except OSError: pass # Stop all queues attr_queue.load = 0 for queue in queues: queue.load = 0 # Make cleaning go a bit faster if kill_clean: clean_queue.load = 0 return else: clean_queue.load = cpus # Wait for all active ports to finish so that they may be cleaned active = set() for queue in queues: for job in queue.active: port = job.port active.add(port) port.stage_completed.connect(lambda x: x.clean()) # Clean all other outstanding ports for builder in builders: for port in builder.ports: if port not in active: port.clean()
7c1a630057ce78f36c1d2406bb7109e72dee4ee3
storm/src/py/resources/index.py
storm/src/py/resources/index.py
# -*- coding: utf-8 -*- from elasticsearch import Elasticsearch from elasticsearch.exceptions import NotFoundError from storm import Bolt, log class ESIndexBolt(Bolt): def initialize(self, conf, context): log('bolt initializing') # TODO: Make connection params configurable. self.es = Elasticsearch(hosts={'host': 'localhost', 'port': 9200}) def process(self, tup): event = dict( timestamp=int(tup.values[0]) * 1000, path=tup.values[1] ) params = dict( index='observations', id=tup.values[2], doc_type='user' ) try: events = self.es.get(**params)['_source']['history'] params['body'] = {'history': events + [event]} except NotFoundError: params['body'] = {'history': [event]} params['op_type'] = 'create' self.es.index(**params) ESIndexBolt().run()
# -*- coding: utf-8 -*- from elasticsearch import Elasticsearch from elasticsearch.client import IndicesClient from elasticsearch.exceptions import NotFoundError from elasticsearch.exceptions import TransportError from storm import Bolt, log class ESIndexBolt(Bolt): def initialize(self, conf, context): log('Bolt id-%s is initializing.' % id(self)) # TODO: Make connection params configurable. self.es = Elasticsearch(hosts=[{'host': 'localhost', 'port': 9200}]) ic = IndicesClient(self.es) try: ic.get_mapping( index='observations', doc_type='user' ) except NotFoundError: doc_type = { 'user': { 'properties': { 'events': { 'type': 'nested' } } } } ic.put_mapping( index='observations', ignore_conflicts=True, doc_type='user', body=doc_type ) def process(self, tup): event = dict( timestamp=tup.values[0], path=tup.values[1] ) params = dict( index='observations', id=tup.values[2], doc_type='user' ) try: events = self.es.get(**params)['_source']['events'] params['body'] = {'events': events + [event]} except NotFoundError: params['body'] = {'events': [event]} params['op_type'] = 'create' except TransportError, e: # TODO: What is going wrong here? log('[TransportError] %s' % e) self.es.index(**params) ESIndexBolt().run()
Add dynamic mapping creation with nested type
Add dynamic mapping creation with nested type
Python
bsd-2-clause
cutoffthetop/recommender,cutoffthetop/recommender,cutoffthetop/recommender
# -*- coding: utf-8 -*- from elasticsearch import Elasticsearch from elasticsearch.exceptions import NotFoundError from storm import Bolt, log class ESIndexBolt(Bolt): def initialize(self, conf, context): log('bolt initializing') # TODO: Make connection params configurable. self.es = Elasticsearch(hosts={'host': 'localhost', 'port': 9200}) def process(self, tup): event = dict( timestamp=int(tup.values[0]) * 1000, path=tup.values[1] ) params = dict( index='observations', id=tup.values[2], doc_type='user' ) try: events = self.es.get(**params)['_source']['history'] params['body'] = {'history': events + [event]} except NotFoundError: params['body'] = {'history': [event]} params['op_type'] = 'create' self.es.index(**params) ESIndexBolt().run() Add dynamic mapping creation with nested type
# -*- coding: utf-8 -*- from elasticsearch import Elasticsearch from elasticsearch.client import IndicesClient from elasticsearch.exceptions import NotFoundError from elasticsearch.exceptions import TransportError from storm import Bolt, log class ESIndexBolt(Bolt): def initialize(self, conf, context): log('Bolt id-%s is initializing.' % id(self)) # TODO: Make connection params configurable. self.es = Elasticsearch(hosts=[{'host': 'localhost', 'port': 9200}]) ic = IndicesClient(self.es) try: ic.get_mapping( index='observations', doc_type='user' ) except NotFoundError: doc_type = { 'user': { 'properties': { 'events': { 'type': 'nested' } } } } ic.put_mapping( index='observations', ignore_conflicts=True, doc_type='user', body=doc_type ) def process(self, tup): event = dict( timestamp=tup.values[0], path=tup.values[1] ) params = dict( index='observations', id=tup.values[2], doc_type='user' ) try: events = self.es.get(**params)['_source']['events'] params['body'] = {'events': events + [event]} except NotFoundError: params['body'] = {'events': [event]} params['op_type'] = 'create' except TransportError, e: # TODO: What is going wrong here? log('[TransportError] %s' % e) self.es.index(**params) ESIndexBolt().run()
<commit_before># -*- coding: utf-8 -*- from elasticsearch import Elasticsearch from elasticsearch.exceptions import NotFoundError from storm import Bolt, log class ESIndexBolt(Bolt): def initialize(self, conf, context): log('bolt initializing') # TODO: Make connection params configurable. self.es = Elasticsearch(hosts={'host': 'localhost', 'port': 9200}) def process(self, tup): event = dict( timestamp=int(tup.values[0]) * 1000, path=tup.values[1] ) params = dict( index='observations', id=tup.values[2], doc_type='user' ) try: events = self.es.get(**params)['_source']['history'] params['body'] = {'history': events + [event]} except NotFoundError: params['body'] = {'history': [event]} params['op_type'] = 'create' self.es.index(**params) ESIndexBolt().run() <commit_msg>Add dynamic mapping creation with nested type<commit_after>
# -*- coding: utf-8 -*- from elasticsearch import Elasticsearch from elasticsearch.client import IndicesClient from elasticsearch.exceptions import NotFoundError from elasticsearch.exceptions import TransportError from storm import Bolt, log class ESIndexBolt(Bolt): def initialize(self, conf, context): log('Bolt id-%s is initializing.' % id(self)) # TODO: Make connection params configurable. self.es = Elasticsearch(hosts=[{'host': 'localhost', 'port': 9200}]) ic = IndicesClient(self.es) try: ic.get_mapping( index='observations', doc_type='user' ) except NotFoundError: doc_type = { 'user': { 'properties': { 'events': { 'type': 'nested' } } } } ic.put_mapping( index='observations', ignore_conflicts=True, doc_type='user', body=doc_type ) def process(self, tup): event = dict( timestamp=tup.values[0], path=tup.values[1] ) params = dict( index='observations', id=tup.values[2], doc_type='user' ) try: events = self.es.get(**params)['_source']['events'] params['body'] = {'events': events + [event]} except NotFoundError: params['body'] = {'events': [event]} params['op_type'] = 'create' except TransportError, e: # TODO: What is going wrong here? log('[TransportError] %s' % e) self.es.index(**params) ESIndexBolt().run()
# -*- coding: utf-8 -*- from elasticsearch import Elasticsearch from elasticsearch.exceptions import NotFoundError from storm import Bolt, log class ESIndexBolt(Bolt): def initialize(self, conf, context): log('bolt initializing') # TODO: Make connection params configurable. self.es = Elasticsearch(hosts={'host': 'localhost', 'port': 9200}) def process(self, tup): event = dict( timestamp=int(tup.values[0]) * 1000, path=tup.values[1] ) params = dict( index='observations', id=tup.values[2], doc_type='user' ) try: events = self.es.get(**params)['_source']['history'] params['body'] = {'history': events + [event]} except NotFoundError: params['body'] = {'history': [event]} params['op_type'] = 'create' self.es.index(**params) ESIndexBolt().run() Add dynamic mapping creation with nested type# -*- coding: utf-8 -*- from elasticsearch import Elasticsearch from elasticsearch.client import IndicesClient from elasticsearch.exceptions import NotFoundError from elasticsearch.exceptions import TransportError from storm import Bolt, log class ESIndexBolt(Bolt): def initialize(self, conf, context): log('Bolt id-%s is initializing.' % id(self)) # TODO: Make connection params configurable. self.es = Elasticsearch(hosts=[{'host': 'localhost', 'port': 9200}]) ic = IndicesClient(self.es) try: ic.get_mapping( index='observations', doc_type='user' ) except NotFoundError: doc_type = { 'user': { 'properties': { 'events': { 'type': 'nested' } } } } ic.put_mapping( index='observations', ignore_conflicts=True, doc_type='user', body=doc_type ) def process(self, tup): event = dict( timestamp=tup.values[0], path=tup.values[1] ) params = dict( index='observations', id=tup.values[2], doc_type='user' ) try: events = self.es.get(**params)['_source']['events'] params['body'] = {'events': events + [event]} except NotFoundError: params['body'] = {'events': [event]} params['op_type'] = 'create' except TransportError, e: # TODO: What is going wrong here? log('[TransportError] %s' % e) self.es.index(**params) ESIndexBolt().run()
<commit_before># -*- coding: utf-8 -*- from elasticsearch import Elasticsearch from elasticsearch.exceptions import NotFoundError from storm import Bolt, log class ESIndexBolt(Bolt): def initialize(self, conf, context): log('bolt initializing') # TODO: Make connection params configurable. self.es = Elasticsearch(hosts={'host': 'localhost', 'port': 9200}) def process(self, tup): event = dict( timestamp=int(tup.values[0]) * 1000, path=tup.values[1] ) params = dict( index='observations', id=tup.values[2], doc_type='user' ) try: events = self.es.get(**params)['_source']['history'] params['body'] = {'history': events + [event]} except NotFoundError: params['body'] = {'history': [event]} params['op_type'] = 'create' self.es.index(**params) ESIndexBolt().run() <commit_msg>Add dynamic mapping creation with nested type<commit_after># -*- coding: utf-8 -*- from elasticsearch import Elasticsearch from elasticsearch.client import IndicesClient from elasticsearch.exceptions import NotFoundError from elasticsearch.exceptions import TransportError from storm import Bolt, log class ESIndexBolt(Bolt): def initialize(self, conf, context): log('Bolt id-%s is initializing.' % id(self)) # TODO: Make connection params configurable. self.es = Elasticsearch(hosts=[{'host': 'localhost', 'port': 9200}]) ic = IndicesClient(self.es) try: ic.get_mapping( index='observations', doc_type='user' ) except NotFoundError: doc_type = { 'user': { 'properties': { 'events': { 'type': 'nested' } } } } ic.put_mapping( index='observations', ignore_conflicts=True, doc_type='user', body=doc_type ) def process(self, tup): event = dict( timestamp=tup.values[0], path=tup.values[1] ) params = dict( index='observations', id=tup.values[2], doc_type='user' ) try: events = self.es.get(**params)['_source']['events'] params['body'] = {'events': events + [event]} except NotFoundError: params['body'] = {'events': [event]} params['op_type'] = 'create' except TransportError, e: # TODO: What is going wrong here? log('[TransportError] %s' % e) self.es.index(**params) ESIndexBolt().run()
1ffdbcb9766136b0aee4be4f2f067fabf456e30f
opps/__init__.py
opps/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import pkg_resources pkg_resources.declare_namespace(__name__) VERSION = (0, 1, 6) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS"
#!/usr/bin/env python # -*- coding: utf-8 -*- import pkg_resources pkg_resources.declare_namespace(__name__) VERSION = (0, 1, 7, 'dev') __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS"
Set developer version 0.1.7 start developer version on date 2013.04.16
Set developer version 0.1.7 start developer version on date 2013.04.16
Python
mit
opps/opps,YACOWS/opps,jeanmask/opps,opps/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,williamroot/opps,opps/opps,williamroot/opps,opps/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,YACOWS/opps,jeanmask/opps
#!/usr/bin/env python # -*- coding: utf-8 -*- import pkg_resources pkg_resources.declare_namespace(__name__) VERSION = (0, 1, 6) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS" Set developer version 0.1.7 start developer version on date 2013.04.16
#!/usr/bin/env python # -*- coding: utf-8 -*- import pkg_resources pkg_resources.declare_namespace(__name__) VERSION = (0, 1, 7, 'dev') __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS"
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import pkg_resources pkg_resources.declare_namespace(__name__) VERSION = (0, 1, 6) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS" <commit_msg>Set developer version 0.1.7 start developer version on date 2013.04.16<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- import pkg_resources pkg_resources.declare_namespace(__name__) VERSION = (0, 1, 7, 'dev') __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS"
#!/usr/bin/env python # -*- coding: utf-8 -*- import pkg_resources pkg_resources.declare_namespace(__name__) VERSION = (0, 1, 6) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS" Set developer version 0.1.7 start developer version on date 2013.04.16#!/usr/bin/env python # -*- coding: utf-8 -*- import pkg_resources pkg_resources.declare_namespace(__name__) VERSION = (0, 1, 7, 'dev') __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS"
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import pkg_resources pkg_resources.declare_namespace(__name__) VERSION = (0, 1, 6) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS" <commit_msg>Set developer version 0.1.7 start developer version on date 2013.04.16<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- import pkg_resources pkg_resources.declare_namespace(__name__) VERSION = (0, 1, 7, 'dev') __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS"
aa84c6dccbff76a4e3b081dfb334b64bb3e6664f
test/functional/rpc_deprecated.py
test/functional/rpc_deprecated.py
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_raises_rpc_error class DeprecatedRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True self.extra_args = [[], ["-deprecatedrpc=createmultisig"]] def run_test(self): self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses") assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()]) self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()]) if __name__ == '__main__': DeprecatedRpcTest().main()
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework class DeprecatedRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True self.extra_args = [[], []] def run_test(self): # This test should be used to verify correct behaviour of deprecated # RPC methods with and without the -deprecatedrpc flags. For example: # # self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses") # assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()]) # self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()]) # # There are currently no deprecated RPC methods in master, so this # test is currently empty. pass if __name__ == '__main__': DeprecatedRpcTest().main()
Remove test for deprecated createmultsig option
[tests] Remove test for deprecated createmultsig option
Python
mit
DigitalPandacoin/pandacoin,peercoin/peercoin,DigitalPandacoin/pandacoin,peercoin/peercoin,DigitalPandacoin/pandacoin,DigitalPandacoin/pandacoin,peercoin/peercoin,peercoin/peercoin,DigitalPandacoin/pandacoin,peercoin/peercoin,peercoin/peercoin,DigitalPandacoin/pandacoin
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_raises_rpc_error class DeprecatedRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True self.extra_args = [[], ["-deprecatedrpc=createmultisig"]] def run_test(self): self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses") assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()]) self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()]) if __name__ == '__main__': DeprecatedRpcTest().main() [tests] Remove test for deprecated createmultsig option
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework class DeprecatedRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True self.extra_args = [[], []] def run_test(self): # This test should be used to verify correct behaviour of deprecated # RPC methods with and without the -deprecatedrpc flags. For example: # # self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses") # assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()]) # self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()]) # # There are currently no deprecated RPC methods in master, so this # test is currently empty. pass if __name__ == '__main__': DeprecatedRpcTest().main()
<commit_before>#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_raises_rpc_error class DeprecatedRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True self.extra_args = [[], ["-deprecatedrpc=createmultisig"]] def run_test(self): self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses") assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()]) self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()]) if __name__ == '__main__': DeprecatedRpcTest().main() <commit_msg>[tests] Remove test for deprecated createmultsig option<commit_after>
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework class DeprecatedRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True self.extra_args = [[], []] def run_test(self): # This test should be used to verify correct behaviour of deprecated # RPC methods with and without the -deprecatedrpc flags. For example: # # self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses") # assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()]) # self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()]) # # There are currently no deprecated RPC methods in master, so this # test is currently empty. pass if __name__ == '__main__': DeprecatedRpcTest().main()
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_raises_rpc_error class DeprecatedRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True self.extra_args = [[], ["-deprecatedrpc=createmultisig"]] def run_test(self): self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses") assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()]) self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()]) if __name__ == '__main__': DeprecatedRpcTest().main() [tests] Remove test for deprecated createmultsig option#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework class DeprecatedRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True self.extra_args = [[], []] def run_test(self): # This test should be used to verify correct behaviour of deprecated # RPC methods with and without the -deprecatedrpc flags. For example: # # self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses") # assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()]) # self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()]) # # There are currently no deprecated RPC methods in master, so this # test is currently empty. pass if __name__ == '__main__': DeprecatedRpcTest().main()
<commit_before>#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_raises_rpc_error class DeprecatedRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True self.extra_args = [[], ["-deprecatedrpc=createmultisig"]] def run_test(self): self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses") assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()]) self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()]) if __name__ == '__main__': DeprecatedRpcTest().main() <commit_msg>[tests] Remove test for deprecated createmultsig option<commit_after>#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework class DeprecatedRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True self.extra_args = [[], []] def run_test(self): # This test should be used to verify correct behaviour of deprecated # RPC methods with and without the -deprecatedrpc flags. For example: # # self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses") # assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()]) # self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()]) # # There are currently no deprecated RPC methods in master, so this # test is currently empty. pass if __name__ == '__main__': DeprecatedRpcTest().main()
8798381c93c49d6f7a83320c3ae27c348e95b8ff
testhook/templatetags/testhook.py
testhook/templatetags/testhook.py
import sys from django.template import Library, TemplateSyntaxError from django.conf import settings from django.utils.safestring import mark_safe from django.utils.text import slugify if sys.version_info[0] == 2: str = basestring register = Library() @register.simple_tag def testhook(name, *args): if not getattr(settings, 'TESTHOOK_ENABLED', True): return u'' if not name: raise TemplateSyntaxError( 'Invalid testhook argument for name, expected non empty string' ) elif not isinstance(name, str): raise TemplateSyntaxError( 'Invalid testhook argument for name, expected string' ) # slugify the name by default name = slugify(name) if args: name = '{}-{}'.format(name, '-'.join(filter(None, args))) return mark_safe(u'data-testhook-id="{0}"'.format(name))
import sys from django.template import Library, TemplateSyntaxError from django.conf import settings from django.utils.safestring import mark_safe from django.utils.text import slugify if sys.version_info[0] == 2: str = basestring register = Library() @register.simple_tag def testhook(name, *args): if not getattr(settings, 'TESTHOOK_ENABLED', True): return u'' if not name or not isinstance(name, str): raise TemplateSyntaxError( 'Testhook takes at least one argument (string)' ) # slugify the name by default name = slugify(name) if args: name = '{}-{}'.format(name, '-'.join(filter(None, args))) return mark_safe(u'data-testhook-id="{0}"'.format(name))
Simplify exception handling of required argument
Simplify exception handling of required argument
Python
apache-2.0
jjanssen/django-testhook
import sys from django.template import Library, TemplateSyntaxError from django.conf import settings from django.utils.safestring import mark_safe from django.utils.text import slugify if sys.version_info[0] == 2: str = basestring register = Library() @register.simple_tag def testhook(name, *args): if not getattr(settings, 'TESTHOOK_ENABLED', True): return u'' if not name: raise TemplateSyntaxError( 'Invalid testhook argument for name, expected non empty string' ) elif not isinstance(name, str): raise TemplateSyntaxError( 'Invalid testhook argument for name, expected string' ) # slugify the name by default name = slugify(name) if args: name = '{}-{}'.format(name, '-'.join(filter(None, args))) return mark_safe(u'data-testhook-id="{0}"'.format(name)) Simplify exception handling of required argument
import sys from django.template import Library, TemplateSyntaxError from django.conf import settings from django.utils.safestring import mark_safe from django.utils.text import slugify if sys.version_info[0] == 2: str = basestring register = Library() @register.simple_tag def testhook(name, *args): if not getattr(settings, 'TESTHOOK_ENABLED', True): return u'' if not name or not isinstance(name, str): raise TemplateSyntaxError( 'Testhook takes at least one argument (string)' ) # slugify the name by default name = slugify(name) if args: name = '{}-{}'.format(name, '-'.join(filter(None, args))) return mark_safe(u'data-testhook-id="{0}"'.format(name))
<commit_before>import sys from django.template import Library, TemplateSyntaxError from django.conf import settings from django.utils.safestring import mark_safe from django.utils.text import slugify if sys.version_info[0] == 2: str = basestring register = Library() @register.simple_tag def testhook(name, *args): if not getattr(settings, 'TESTHOOK_ENABLED', True): return u'' if not name: raise TemplateSyntaxError( 'Invalid testhook argument for name, expected non empty string' ) elif not isinstance(name, str): raise TemplateSyntaxError( 'Invalid testhook argument for name, expected string' ) # slugify the name by default name = slugify(name) if args: name = '{}-{}'.format(name, '-'.join(filter(None, args))) return mark_safe(u'data-testhook-id="{0}"'.format(name)) <commit_msg>Simplify exception handling of required argument<commit_after>
import sys from django.template import Library, TemplateSyntaxError from django.conf import settings from django.utils.safestring import mark_safe from django.utils.text import slugify if sys.version_info[0] == 2: str = basestring register = Library() @register.simple_tag def testhook(name, *args): if not getattr(settings, 'TESTHOOK_ENABLED', True): return u'' if not name or not isinstance(name, str): raise TemplateSyntaxError( 'Testhook takes at least one argument (string)' ) # slugify the name by default name = slugify(name) if args: name = '{}-{}'.format(name, '-'.join(filter(None, args))) return mark_safe(u'data-testhook-id="{0}"'.format(name))
import sys from django.template import Library, TemplateSyntaxError from django.conf import settings from django.utils.safestring import mark_safe from django.utils.text import slugify if sys.version_info[0] == 2: str = basestring register = Library() @register.simple_tag def testhook(name, *args): if not getattr(settings, 'TESTHOOK_ENABLED', True): return u'' if not name: raise TemplateSyntaxError( 'Invalid testhook argument for name, expected non empty string' ) elif not isinstance(name, str): raise TemplateSyntaxError( 'Invalid testhook argument for name, expected string' ) # slugify the name by default name = slugify(name) if args: name = '{}-{}'.format(name, '-'.join(filter(None, args))) return mark_safe(u'data-testhook-id="{0}"'.format(name)) Simplify exception handling of required argumentimport sys from django.template import Library, TemplateSyntaxError from django.conf import settings from django.utils.safestring import mark_safe from django.utils.text import slugify if sys.version_info[0] == 2: str = basestring register = Library() @register.simple_tag def testhook(name, *args): if not getattr(settings, 'TESTHOOK_ENABLED', True): return u'' if not name or not isinstance(name, str): raise TemplateSyntaxError( 'Testhook takes at least one argument (string)' ) # slugify the name by default name = slugify(name) if args: name = '{}-{}'.format(name, '-'.join(filter(None, args))) return mark_safe(u'data-testhook-id="{0}"'.format(name))
<commit_before>import sys from django.template import Library, TemplateSyntaxError from django.conf import settings from django.utils.safestring import mark_safe from django.utils.text import slugify if sys.version_info[0] == 2: str = basestring register = Library() @register.simple_tag def testhook(name, *args): if not getattr(settings, 'TESTHOOK_ENABLED', True): return u'' if not name: raise TemplateSyntaxError( 'Invalid testhook argument for name, expected non empty string' ) elif not isinstance(name, str): raise TemplateSyntaxError( 'Invalid testhook argument for name, expected string' ) # slugify the name by default name = slugify(name) if args: name = '{}-{}'.format(name, '-'.join(filter(None, args))) return mark_safe(u'data-testhook-id="{0}"'.format(name)) <commit_msg>Simplify exception handling of required argument<commit_after>import sys from django.template import Library, TemplateSyntaxError from django.conf import settings from django.utils.safestring import mark_safe from django.utils.text import slugify if sys.version_info[0] == 2: str = basestring register = Library() @register.simple_tag def testhook(name, *args): if not getattr(settings, 'TESTHOOK_ENABLED', True): return u'' if not name or not isinstance(name, str): raise TemplateSyntaxError( 'Testhook takes at least one argument (string)' ) # slugify the name by default name = slugify(name) if args: name = '{}-{}'.format(name, '-'.join(filter(None, args))) return mark_safe(u'data-testhook-id="{0}"'.format(name))
790442eb5523f6992e8943ee1db5817cb27abdea
lingvo/jax/base_model_params.py
lingvo/jax/base_model_params.py
# Lint as: python3 # Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """BaseModelParams class definition.""" import abc from typing import List, Type, TypeVar from lingvo.jax import base_input from lingvo.jax import py_utils InstantiableParams = py_utils.InstantiableParams _BaseModelParamsT = TypeVar('_BaseModelParamsT', bound='BaseModelParams') BaseModelParamsT = Type[_BaseModelParamsT] class BaseModelParams(metaclass=abc.ABCMeta): """Encapsulates the parameters for a model.""" @abc.abstractmethod def datasets(self) -> List[base_input.BaseInputParams]: """Returns the list of dataset parameters.""" @abc.abstractmethod def task(self) -> InstantiableParams: """Returns the task parameters."""
# Lint as: python3 # Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """BaseModelParams class definition.""" import abc from typing import List, Type, TypeVar from lingvo.jax import base_input from lingvo.jax import py_utils InstantiableParams = py_utils.InstantiableParams _BaseModelParamsT = TypeVar('_BaseModelParamsT', bound='BaseModelParams') BaseModelParamsT = Type[_BaseModelParamsT] class BaseModelParams(metaclass=abc.ABCMeta): """Encapsulates the parameters for a model.""" # p.is_training on each input param is used to determine whether # the dataset is used for training or eval. @abc.abstractmethod def datasets(self) -> List[base_input.BaseInputParams]: """Returns the list of dataset parameters.""" # Optional. Returns a list of datasets to be decoded. def decoder_datasets(self) -> List[base_input.BaseInputParams]: """Returns the list of dataset parameters for decoder.""" return [] @abc.abstractmethod def task(self) -> InstantiableParams: """Returns the task parameters."""
Add decoder_datasets() to BaseModelParams to indicate which datasets are to be decoded.
Add decoder_datasets() to BaseModelParams to indicate which datasets are to be decoded. PiperOrigin-RevId: 413779472
Python
apache-2.0
tensorflow/lingvo,tensorflow/lingvo,tensorflow/lingvo,tensorflow/lingvo
# Lint as: python3 # Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """BaseModelParams class definition.""" import abc from typing import List, Type, TypeVar from lingvo.jax import base_input from lingvo.jax import py_utils InstantiableParams = py_utils.InstantiableParams _BaseModelParamsT = TypeVar('_BaseModelParamsT', bound='BaseModelParams') BaseModelParamsT = Type[_BaseModelParamsT] class BaseModelParams(metaclass=abc.ABCMeta): """Encapsulates the parameters for a model.""" @abc.abstractmethod def datasets(self) -> List[base_input.BaseInputParams]: """Returns the list of dataset parameters.""" @abc.abstractmethod def task(self) -> InstantiableParams: """Returns the task parameters.""" Add decoder_datasets() to BaseModelParams to indicate which datasets are to be decoded. PiperOrigin-RevId: 413779472
# Lint as: python3 # Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """BaseModelParams class definition.""" import abc from typing import List, Type, TypeVar from lingvo.jax import base_input from lingvo.jax import py_utils InstantiableParams = py_utils.InstantiableParams _BaseModelParamsT = TypeVar('_BaseModelParamsT', bound='BaseModelParams') BaseModelParamsT = Type[_BaseModelParamsT] class BaseModelParams(metaclass=abc.ABCMeta): """Encapsulates the parameters for a model.""" # p.is_training on each input param is used to determine whether # the dataset is used for training or eval. @abc.abstractmethod def datasets(self) -> List[base_input.BaseInputParams]: """Returns the list of dataset parameters.""" # Optional. Returns a list of datasets to be decoded. def decoder_datasets(self) -> List[base_input.BaseInputParams]: """Returns the list of dataset parameters for decoder.""" return [] @abc.abstractmethod def task(self) -> InstantiableParams: """Returns the task parameters."""
<commit_before># Lint as: python3 # Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """BaseModelParams class definition.""" import abc from typing import List, Type, TypeVar from lingvo.jax import base_input from lingvo.jax import py_utils InstantiableParams = py_utils.InstantiableParams _BaseModelParamsT = TypeVar('_BaseModelParamsT', bound='BaseModelParams') BaseModelParamsT = Type[_BaseModelParamsT] class BaseModelParams(metaclass=abc.ABCMeta): """Encapsulates the parameters for a model.""" @abc.abstractmethod def datasets(self) -> List[base_input.BaseInputParams]: """Returns the list of dataset parameters.""" @abc.abstractmethod def task(self) -> InstantiableParams: """Returns the task parameters.""" <commit_msg>Add decoder_datasets() to BaseModelParams to indicate which datasets are to be decoded. PiperOrigin-RevId: 413779472<commit_after>
# Lint as: python3 # Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """BaseModelParams class definition.""" import abc from typing import List, Type, TypeVar from lingvo.jax import base_input from lingvo.jax import py_utils InstantiableParams = py_utils.InstantiableParams _BaseModelParamsT = TypeVar('_BaseModelParamsT', bound='BaseModelParams') BaseModelParamsT = Type[_BaseModelParamsT] class BaseModelParams(metaclass=abc.ABCMeta): """Encapsulates the parameters for a model.""" # p.is_training on each input param is used to determine whether # the dataset is used for training or eval. @abc.abstractmethod def datasets(self) -> List[base_input.BaseInputParams]: """Returns the list of dataset parameters.""" # Optional. Returns a list of datasets to be decoded. def decoder_datasets(self) -> List[base_input.BaseInputParams]: """Returns the list of dataset parameters for decoder.""" return [] @abc.abstractmethod def task(self) -> InstantiableParams: """Returns the task parameters."""
# Lint as: python3 # Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """BaseModelParams class definition.""" import abc from typing import List, Type, TypeVar from lingvo.jax import base_input from lingvo.jax import py_utils InstantiableParams = py_utils.InstantiableParams _BaseModelParamsT = TypeVar('_BaseModelParamsT', bound='BaseModelParams') BaseModelParamsT = Type[_BaseModelParamsT] class BaseModelParams(metaclass=abc.ABCMeta): """Encapsulates the parameters for a model.""" @abc.abstractmethod def datasets(self) -> List[base_input.BaseInputParams]: """Returns the list of dataset parameters.""" @abc.abstractmethod def task(self) -> InstantiableParams: """Returns the task parameters.""" Add decoder_datasets() to BaseModelParams to indicate which datasets are to be decoded. PiperOrigin-RevId: 413779472# Lint as: python3 # Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """BaseModelParams class definition.""" import abc from typing import List, Type, TypeVar from lingvo.jax import base_input from lingvo.jax import py_utils InstantiableParams = py_utils.InstantiableParams _BaseModelParamsT = TypeVar('_BaseModelParamsT', bound='BaseModelParams') BaseModelParamsT = Type[_BaseModelParamsT] class BaseModelParams(metaclass=abc.ABCMeta): """Encapsulates the parameters for a model.""" # p.is_training on each input param is used to determine whether # the dataset is used for training or eval. @abc.abstractmethod def datasets(self) -> List[base_input.BaseInputParams]: """Returns the list of dataset parameters.""" # Optional. Returns a list of datasets to be decoded. def decoder_datasets(self) -> List[base_input.BaseInputParams]: """Returns the list of dataset parameters for decoder.""" return [] @abc.abstractmethod def task(self) -> InstantiableParams: """Returns the task parameters."""
<commit_before># Lint as: python3 # Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """BaseModelParams class definition.""" import abc from typing import List, Type, TypeVar from lingvo.jax import base_input from lingvo.jax import py_utils InstantiableParams = py_utils.InstantiableParams _BaseModelParamsT = TypeVar('_BaseModelParamsT', bound='BaseModelParams') BaseModelParamsT = Type[_BaseModelParamsT] class BaseModelParams(metaclass=abc.ABCMeta): """Encapsulates the parameters for a model.""" @abc.abstractmethod def datasets(self) -> List[base_input.BaseInputParams]: """Returns the list of dataset parameters.""" @abc.abstractmethod def task(self) -> InstantiableParams: """Returns the task parameters.""" <commit_msg>Add decoder_datasets() to BaseModelParams to indicate which datasets are to be decoded. PiperOrigin-RevId: 413779472<commit_after># Lint as: python3 # Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """BaseModelParams class definition.""" import abc from typing import List, Type, TypeVar from lingvo.jax import base_input from lingvo.jax import py_utils InstantiableParams = py_utils.InstantiableParams _BaseModelParamsT = TypeVar('_BaseModelParamsT', bound='BaseModelParams') BaseModelParamsT = Type[_BaseModelParamsT] class BaseModelParams(metaclass=abc.ABCMeta): """Encapsulates the parameters for a model.""" # p.is_training on each input param is used to determine whether # the dataset is used for training or eval. @abc.abstractmethod def datasets(self) -> List[base_input.BaseInputParams]: """Returns the list of dataset parameters.""" # Optional. Returns a list of datasets to be decoded. def decoder_datasets(self) -> List[base_input.BaseInputParams]: """Returns the list of dataset parameters for decoder.""" return [] @abc.abstractmethod def task(self) -> InstantiableParams: """Returns the task parameters."""
8c9d69b16f0c2848865a37b4a30325315f6d6735
longclaw/project_template/products/migrations/0001_initial.py
longclaw/project_template/products/migrations/0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-19 11:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields import modelcluster.fields import wagtail.wagtailcore.fields class Migration(migrations.Migration): initial = True dependencies = [ ('longclawproducts', '0002_auto_20170219_0804'), ] operations = [ migrations.CreateModel( name='ProductVariant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('price', models.DecimalField(decimal_places=2, max_digits=12)), ('ref', models.CharField(max_length=32)), ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')), ('description', wagtail.wagtailcore.fields.RichTextField()), ('stock', models.IntegerField(default=0)), ('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='longclawproducts.Product')), ], options={ 'abstract': False, }, ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-19 11:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields import modelcluster.fields import wagtail.wagtailcore.fields class Migration(migrations.Migration): initial = True dependencies = [ ('longclawproducts', '0002_auto_20170219_0804'), ] operations = [ migrations.CreateModel( name='ProductVariant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('price', models.DecimalField(decimal_places=2, max_digits=12)), ('ref', models.CharField(max_length=32)), ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')), ('description', wagtail.wagtailcore.fields.RichTextField()), ('stock', models.IntegerField(default=0)), ('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='products.Product')), ], options={ 'abstract': False, }, ), ]
Correct migration in project template
Correct migration in project template
Python
mit
JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-19 11:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields import modelcluster.fields import wagtail.wagtailcore.fields class Migration(migrations.Migration): initial = True dependencies = [ ('longclawproducts', '0002_auto_20170219_0804'), ] operations = [ migrations.CreateModel( name='ProductVariant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('price', models.DecimalField(decimal_places=2, max_digits=12)), ('ref', models.CharField(max_length=32)), ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')), ('description', wagtail.wagtailcore.fields.RichTextField()), ('stock', models.IntegerField(default=0)), ('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='longclawproducts.Product')), ], options={ 'abstract': False, }, ), ] Correct migration in project template
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-19 11:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields import modelcluster.fields import wagtail.wagtailcore.fields class Migration(migrations.Migration): initial = True dependencies = [ ('longclawproducts', '0002_auto_20170219_0804'), ] operations = [ migrations.CreateModel( name='ProductVariant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('price', models.DecimalField(decimal_places=2, max_digits=12)), ('ref', models.CharField(max_length=32)), ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')), ('description', wagtail.wagtailcore.fields.RichTextField()), ('stock', models.IntegerField(default=0)), ('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='products.Product')), ], options={ 'abstract': False, }, ), ]
<commit_before># -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-19 11:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields import modelcluster.fields import wagtail.wagtailcore.fields class Migration(migrations.Migration): initial = True dependencies = [ ('longclawproducts', '0002_auto_20170219_0804'), ] operations = [ migrations.CreateModel( name='ProductVariant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('price', models.DecimalField(decimal_places=2, max_digits=12)), ('ref', models.CharField(max_length=32)), ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')), ('description', wagtail.wagtailcore.fields.RichTextField()), ('stock', models.IntegerField(default=0)), ('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='longclawproducts.Product')), ], options={ 'abstract': False, }, ), ] <commit_msg>Correct migration in project template<commit_after>
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-19 11:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields import modelcluster.fields import wagtail.wagtailcore.fields class Migration(migrations.Migration): initial = True dependencies = [ ('longclawproducts', '0002_auto_20170219_0804'), ] operations = [ migrations.CreateModel( name='ProductVariant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('price', models.DecimalField(decimal_places=2, max_digits=12)), ('ref', models.CharField(max_length=32)), ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')), ('description', wagtail.wagtailcore.fields.RichTextField()), ('stock', models.IntegerField(default=0)), ('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='products.Product')), ], options={ 'abstract': False, }, ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-19 11:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields import modelcluster.fields import wagtail.wagtailcore.fields class Migration(migrations.Migration): initial = True dependencies = [ ('longclawproducts', '0002_auto_20170219_0804'), ] operations = [ migrations.CreateModel( name='ProductVariant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('price', models.DecimalField(decimal_places=2, max_digits=12)), ('ref', models.CharField(max_length=32)), ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')), ('description', wagtail.wagtailcore.fields.RichTextField()), ('stock', models.IntegerField(default=0)), ('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='longclawproducts.Product')), ], options={ 'abstract': False, }, ), ] Correct migration in project template# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-19 11:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields import modelcluster.fields import wagtail.wagtailcore.fields class Migration(migrations.Migration): initial = True dependencies = [ ('longclawproducts', '0002_auto_20170219_0804'), ] operations = [ migrations.CreateModel( name='ProductVariant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('price', models.DecimalField(decimal_places=2, max_digits=12)), ('ref', models.CharField(max_length=32)), ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')), ('description', wagtail.wagtailcore.fields.RichTextField()), ('stock', models.IntegerField(default=0)), ('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='products.Product')), ], options={ 'abstract': False, }, ), ]
<commit_before># -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-19 11:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields import modelcluster.fields import wagtail.wagtailcore.fields class Migration(migrations.Migration): initial = True dependencies = [ ('longclawproducts', '0002_auto_20170219_0804'), ] operations = [ migrations.CreateModel( name='ProductVariant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('price', models.DecimalField(decimal_places=2, max_digits=12)), ('ref', models.CharField(max_length=32)), ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')), ('description', wagtail.wagtailcore.fields.RichTextField()), ('stock', models.IntegerField(default=0)), ('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='longclawproducts.Product')), ], options={ 'abstract': False, }, ), ] <commit_msg>Correct migration in project template<commit_after># -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-19 11:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields import modelcluster.fields import wagtail.wagtailcore.fields class Migration(migrations.Migration): initial = True dependencies = [ ('longclawproducts', '0002_auto_20170219_0804'), ] operations = [ migrations.CreateModel( name='ProductVariant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('price', models.DecimalField(decimal_places=2, max_digits=12)), ('ref', models.CharField(max_length=32)), ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')), ('description', wagtail.wagtailcore.fields.RichTextField()), ('stock', models.IntegerField(default=0)), ('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='products.Product')), ], options={ 'abstract': False, }, ), ]
fe6c924532750f646303fe82728795717b830819
piper/version.py
piper/version.py
from piper.abc import DynamicItem from piper.utils import oneshot class Version(DynamicItem): """ Base for versioning classes """ def __str__(self): # pragma: nocover return self.get_version() def get_version(self): raise NotImplementedError() class StaticVersion(Version): """ Static versioning, set inside the piper.yml configuration file """ @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(StaticVersion, self).schema self._schema['required'].append('version') self._schema['properties']['version'] = { 'description': 'Static version to use', 'type': 'string', } return self._schema def get_version(self): return self.config.version class GitVersion(Version): """ Versioning based on the output of `git describe` """ def __init__(self, ns, config): super(GitVersion, self).__init__(ns, config) if 'arguments' not in config: self.config.arguments = None @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(GitVersion, self).schema self._schema['properties']['arguments'] = { 'description': 'Space separated arguments passed directly to the ' '`git describe` call.', 'default': "--tags", 'type': 'string', } return self._schema def get_version(self): cmd = 'git describe' if self.config.arguments: cmd += ' ' + self.config.arguments return oneshot(cmd)
from piper.abc import DynamicItem from piper.utils import oneshot class Version(DynamicItem): """ Base for versioning classes """ def __str__(self): # pragma: nocover return self.get_version() def get_version(self): raise NotImplementedError() class StaticVersion(Version): """ Static versioning, set inside the piper.yml configuration file """ @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(StaticVersion, self).schema self._schema['required'].append('version') self._schema['properties']['version'] = { 'description': 'Static version to use', 'type': 'string', } return self._schema def get_version(self): return self.config.version class GitVersion(Version): """ Versioning based on the output of `git describe` """ @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(GitVersion, self).schema self._schema['properties']['arguments'] = { 'description': 'Space separated arguments passed directly to the ' '`git describe` call.', 'default': "--tags", 'type': 'string', } return self._schema def get_version(self): cmd = 'git describe' if self.config.arguments: cmd += ' ' + self.config.arguments return oneshot(cmd)
Remove argument defaulting from Version()
Remove argument defaulting from Version() It was moved to the ABC and subsequently the check was left behind.
Python
mit
thiderman/piper
from piper.abc import DynamicItem from piper.utils import oneshot class Version(DynamicItem): """ Base for versioning classes """ def __str__(self): # pragma: nocover return self.get_version() def get_version(self): raise NotImplementedError() class StaticVersion(Version): """ Static versioning, set inside the piper.yml configuration file """ @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(StaticVersion, self).schema self._schema['required'].append('version') self._schema['properties']['version'] = { 'description': 'Static version to use', 'type': 'string', } return self._schema def get_version(self): return self.config.version class GitVersion(Version): """ Versioning based on the output of `git describe` """ def __init__(self, ns, config): super(GitVersion, self).__init__(ns, config) if 'arguments' not in config: self.config.arguments = None @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(GitVersion, self).schema self._schema['properties']['arguments'] = { 'description': 'Space separated arguments passed directly to the ' '`git describe` call.', 'default': "--tags", 'type': 'string', } return self._schema def get_version(self): cmd = 'git describe' if self.config.arguments: cmd += ' ' + self.config.arguments return oneshot(cmd) Remove argument defaulting from Version() It was moved to the ABC and subsequently the check was left behind.
from piper.abc import DynamicItem from piper.utils import oneshot class Version(DynamicItem): """ Base for versioning classes """ def __str__(self): # pragma: nocover return self.get_version() def get_version(self): raise NotImplementedError() class StaticVersion(Version): """ Static versioning, set inside the piper.yml configuration file """ @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(StaticVersion, self).schema self._schema['required'].append('version') self._schema['properties']['version'] = { 'description': 'Static version to use', 'type': 'string', } return self._schema def get_version(self): return self.config.version class GitVersion(Version): """ Versioning based on the output of `git describe` """ @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(GitVersion, self).schema self._schema['properties']['arguments'] = { 'description': 'Space separated arguments passed directly to the ' '`git describe` call.', 'default': "--tags", 'type': 'string', } return self._schema def get_version(self): cmd = 'git describe' if self.config.arguments: cmd += ' ' + self.config.arguments return oneshot(cmd)
<commit_before>from piper.abc import DynamicItem from piper.utils import oneshot class Version(DynamicItem): """ Base for versioning classes """ def __str__(self): # pragma: nocover return self.get_version() def get_version(self): raise NotImplementedError() class StaticVersion(Version): """ Static versioning, set inside the piper.yml configuration file """ @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(StaticVersion, self).schema self._schema['required'].append('version') self._schema['properties']['version'] = { 'description': 'Static version to use', 'type': 'string', } return self._schema def get_version(self): return self.config.version class GitVersion(Version): """ Versioning based on the output of `git describe` """ def __init__(self, ns, config): super(GitVersion, self).__init__(ns, config) if 'arguments' not in config: self.config.arguments = None @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(GitVersion, self).schema self._schema['properties']['arguments'] = { 'description': 'Space separated arguments passed directly to the ' '`git describe` call.', 'default': "--tags", 'type': 'string', } return self._schema def get_version(self): cmd = 'git describe' if self.config.arguments: cmd += ' ' + self.config.arguments return oneshot(cmd) <commit_msg>Remove argument defaulting from Version() It was moved to the ABC and subsequently the check was left behind.<commit_after>
from piper.abc import DynamicItem from piper.utils import oneshot class Version(DynamicItem): """ Base for versioning classes """ def __str__(self): # pragma: nocover return self.get_version() def get_version(self): raise NotImplementedError() class StaticVersion(Version): """ Static versioning, set inside the piper.yml configuration file """ @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(StaticVersion, self).schema self._schema['required'].append('version') self._schema['properties']['version'] = { 'description': 'Static version to use', 'type': 'string', } return self._schema def get_version(self): return self.config.version class GitVersion(Version): """ Versioning based on the output of `git describe` """ @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(GitVersion, self).schema self._schema['properties']['arguments'] = { 'description': 'Space separated arguments passed directly to the ' '`git describe` call.', 'default': "--tags", 'type': 'string', } return self._schema def get_version(self): cmd = 'git describe' if self.config.arguments: cmd += ' ' + self.config.arguments return oneshot(cmd)
from piper.abc import DynamicItem from piper.utils import oneshot class Version(DynamicItem): """ Base for versioning classes """ def __str__(self): # pragma: nocover return self.get_version() def get_version(self): raise NotImplementedError() class StaticVersion(Version): """ Static versioning, set inside the piper.yml configuration file """ @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(StaticVersion, self).schema self._schema['required'].append('version') self._schema['properties']['version'] = { 'description': 'Static version to use', 'type': 'string', } return self._schema def get_version(self): return self.config.version class GitVersion(Version): """ Versioning based on the output of `git describe` """ def __init__(self, ns, config): super(GitVersion, self).__init__(ns, config) if 'arguments' not in config: self.config.arguments = None @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(GitVersion, self).schema self._schema['properties']['arguments'] = { 'description': 'Space separated arguments passed directly to the ' '`git describe` call.', 'default': "--tags", 'type': 'string', } return self._schema def get_version(self): cmd = 'git describe' if self.config.arguments: cmd += ' ' + self.config.arguments return oneshot(cmd) Remove argument defaulting from Version() It was moved to the ABC and subsequently the check was left behind.from piper.abc import DynamicItem from piper.utils import oneshot class Version(DynamicItem): """ Base for versioning classes """ def __str__(self): # pragma: nocover return self.get_version() def get_version(self): raise NotImplementedError() class StaticVersion(Version): """ Static versioning, set inside the piper.yml configuration file """ @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(StaticVersion, self).schema self._schema['required'].append('version') self._schema['properties']['version'] = { 'description': 'Static version to use', 'type': 'string', } return self._schema def get_version(self): return self.config.version class GitVersion(Version): """ Versioning based on the output of `git describe` """ @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(GitVersion, self).schema self._schema['properties']['arguments'] = { 'description': 'Space separated arguments passed directly to the ' '`git describe` call.', 'default': "--tags", 'type': 'string', } return self._schema def get_version(self): cmd = 'git describe' if self.config.arguments: cmd += ' ' + self.config.arguments return oneshot(cmd)
<commit_before>from piper.abc import DynamicItem from piper.utils import oneshot class Version(DynamicItem): """ Base for versioning classes """ def __str__(self): # pragma: nocover return self.get_version() def get_version(self): raise NotImplementedError() class StaticVersion(Version): """ Static versioning, set inside the piper.yml configuration file """ @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(StaticVersion, self).schema self._schema['required'].append('version') self._schema['properties']['version'] = { 'description': 'Static version to use', 'type': 'string', } return self._schema def get_version(self): return self.config.version class GitVersion(Version): """ Versioning based on the output of `git describe` """ def __init__(self, ns, config): super(GitVersion, self).__init__(ns, config) if 'arguments' not in config: self.config.arguments = None @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(GitVersion, self).schema self._schema['properties']['arguments'] = { 'description': 'Space separated arguments passed directly to the ' '`git describe` call.', 'default': "--tags", 'type': 'string', } return self._schema def get_version(self): cmd = 'git describe' if self.config.arguments: cmd += ' ' + self.config.arguments return oneshot(cmd) <commit_msg>Remove argument defaulting from Version() It was moved to the ABC and subsequently the check was left behind.<commit_after>from piper.abc import DynamicItem from piper.utils import oneshot class Version(DynamicItem): """ Base for versioning classes """ def __str__(self): # pragma: nocover return self.get_version() def get_version(self): raise NotImplementedError() class StaticVersion(Version): """ Static versioning, set inside the piper.yml configuration file """ @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(StaticVersion, self).schema self._schema['required'].append('version') self._schema['properties']['version'] = { 'description': 'Static version to use', 'type': 'string', } return self._schema def get_version(self): return self.config.version class GitVersion(Version): """ Versioning based on the output of `git describe` """ @property def schema(self): if not hasattr(self, '_schema'): self._schema = super(GitVersion, self).schema self._schema['properties']['arguments'] = { 'description': 'Space separated arguments passed directly to the ' '`git describe` call.', 'default': "--tags", 'type': 'string', } return self._schema def get_version(self): cmd = 'git describe' if self.config.arguments: cmd += ' ' + self.config.arguments return oneshot(cmd)
cd68d5bf444385334841a5ce07058cddb314ff82
lobster/cmssw/data/merge_cfg.py
lobster/cmssw/data/merge_cfg.py
import FWCore.ParameterSet.Config as cms from FWCore.ParameterSet.VarParsing import VarParsing import subprocess import os import sys options = VarParsing('analysis') options.register('chirp', default=None, mytype=VarParsing.varType.string) options.register('inputs', mult=VarParsing.multiplicity.list, mytype=VarParsing.varType.string) options.register('output', mytype=VarParsing.varType.string) options.parseArguments() if options.chirp: for input in options.inputs: status = subprocess.call([os.path.join(os.environ.get("PARROT_PATH", "bin"), "chirp_get"), options.chirp, input, os.path.basename(input)]) if status != 0: sys.exit(500) process = cms.Process("PickEvent") process.source = cms.Source ("PoolSource", fileNames = cms.untracked.vstring(''), ) process.out = cms.OutputModule("PoolOutputModule", fileName = cms.untracked.string(options.output) ) process.end = cms.EndPath(process.out)
import FWCore.ParameterSet.Config as cms from FWCore.ParameterSet.VarParsing import VarParsing import subprocess import os import sys options = VarParsing('analysis') options.register('chirp', default=None, mytype=VarParsing.varType.string) options.register('inputs', mult=VarParsing.multiplicity.list, mytype=VarParsing.varType.string) options.register('output', mytype=VarParsing.varType.string) options.parseArguments() if options.chirp: for input in options.inputs: status = subprocess.call([os.path.join(os.environ.get("PARROT_PATH", "bin"), "chirp_get"), options.chirp, input, os.path.basename(input)]) if status != 0: sys.exit(500) process = cms.Process("PickEvent") process.source = cms.Source ("PoolSource", fileNames = cms.untracked.vstring(''), duplicateCheckMode = cms.untracked.string('noDuplicateCheck') ) process.out = cms.OutputModule("PoolOutputModule", fileName = cms.untracked.string(options.output) ) process.end = cms.EndPath(process.out)
Disable duplicate check mode for merging-- this can cause events to be thrown out for MC data.
Disable duplicate check mode for merging-- this can cause events to be thrown out for MC data.
Python
mit
matz-e/lobster,matz-e/lobster,matz-e/lobster
import FWCore.ParameterSet.Config as cms from FWCore.ParameterSet.VarParsing import VarParsing import subprocess import os import sys options = VarParsing('analysis') options.register('chirp', default=None, mytype=VarParsing.varType.string) options.register('inputs', mult=VarParsing.multiplicity.list, mytype=VarParsing.varType.string) options.register('output', mytype=VarParsing.varType.string) options.parseArguments() if options.chirp: for input in options.inputs: status = subprocess.call([os.path.join(os.environ.get("PARROT_PATH", "bin"), "chirp_get"), options.chirp, input, os.path.basename(input)]) if status != 0: sys.exit(500) process = cms.Process("PickEvent") process.source = cms.Source ("PoolSource", fileNames = cms.untracked.vstring(''), ) process.out = cms.OutputModule("PoolOutputModule", fileName = cms.untracked.string(options.output) ) process.end = cms.EndPath(process.out) Disable duplicate check mode for merging-- this can cause events to be thrown out for MC data.
import FWCore.ParameterSet.Config as cms from FWCore.ParameterSet.VarParsing import VarParsing import subprocess import os import sys options = VarParsing('analysis') options.register('chirp', default=None, mytype=VarParsing.varType.string) options.register('inputs', mult=VarParsing.multiplicity.list, mytype=VarParsing.varType.string) options.register('output', mytype=VarParsing.varType.string) options.parseArguments() if options.chirp: for input in options.inputs: status = subprocess.call([os.path.join(os.environ.get("PARROT_PATH", "bin"), "chirp_get"), options.chirp, input, os.path.basename(input)]) if status != 0: sys.exit(500) process = cms.Process("PickEvent") process.source = cms.Source ("PoolSource", fileNames = cms.untracked.vstring(''), duplicateCheckMode = cms.untracked.string('noDuplicateCheck') ) process.out = cms.OutputModule("PoolOutputModule", fileName = cms.untracked.string(options.output) ) process.end = cms.EndPath(process.out)
<commit_before>import FWCore.ParameterSet.Config as cms from FWCore.ParameterSet.VarParsing import VarParsing import subprocess import os import sys options = VarParsing('analysis') options.register('chirp', default=None, mytype=VarParsing.varType.string) options.register('inputs', mult=VarParsing.multiplicity.list, mytype=VarParsing.varType.string) options.register('output', mytype=VarParsing.varType.string) options.parseArguments() if options.chirp: for input in options.inputs: status = subprocess.call([os.path.join(os.environ.get("PARROT_PATH", "bin"), "chirp_get"), options.chirp, input, os.path.basename(input)]) if status != 0: sys.exit(500) process = cms.Process("PickEvent") process.source = cms.Source ("PoolSource", fileNames = cms.untracked.vstring(''), ) process.out = cms.OutputModule("PoolOutputModule", fileName = cms.untracked.string(options.output) ) process.end = cms.EndPath(process.out) <commit_msg>Disable duplicate check mode for merging-- this can cause events to be thrown out for MC data.<commit_after>
import FWCore.ParameterSet.Config as cms from FWCore.ParameterSet.VarParsing import VarParsing import subprocess import os import sys options = VarParsing('analysis') options.register('chirp', default=None, mytype=VarParsing.varType.string) options.register('inputs', mult=VarParsing.multiplicity.list, mytype=VarParsing.varType.string) options.register('output', mytype=VarParsing.varType.string) options.parseArguments() if options.chirp: for input in options.inputs: status = subprocess.call([os.path.join(os.environ.get("PARROT_PATH", "bin"), "chirp_get"), options.chirp, input, os.path.basename(input)]) if status != 0: sys.exit(500) process = cms.Process("PickEvent") process.source = cms.Source ("PoolSource", fileNames = cms.untracked.vstring(''), duplicateCheckMode = cms.untracked.string('noDuplicateCheck') ) process.out = cms.OutputModule("PoolOutputModule", fileName = cms.untracked.string(options.output) ) process.end = cms.EndPath(process.out)
import FWCore.ParameterSet.Config as cms from FWCore.ParameterSet.VarParsing import VarParsing import subprocess import os import sys options = VarParsing('analysis') options.register('chirp', default=None, mytype=VarParsing.varType.string) options.register('inputs', mult=VarParsing.multiplicity.list, mytype=VarParsing.varType.string) options.register('output', mytype=VarParsing.varType.string) options.parseArguments() if options.chirp: for input in options.inputs: status = subprocess.call([os.path.join(os.environ.get("PARROT_PATH", "bin"), "chirp_get"), options.chirp, input, os.path.basename(input)]) if status != 0: sys.exit(500) process = cms.Process("PickEvent") process.source = cms.Source ("PoolSource", fileNames = cms.untracked.vstring(''), ) process.out = cms.OutputModule("PoolOutputModule", fileName = cms.untracked.string(options.output) ) process.end = cms.EndPath(process.out) Disable duplicate check mode for merging-- this can cause events to be thrown out for MC data.import FWCore.ParameterSet.Config as cms from FWCore.ParameterSet.VarParsing import VarParsing import subprocess import os import sys options = VarParsing('analysis') options.register('chirp', default=None, mytype=VarParsing.varType.string) options.register('inputs', mult=VarParsing.multiplicity.list, mytype=VarParsing.varType.string) options.register('output', mytype=VarParsing.varType.string) options.parseArguments() if options.chirp: for input in options.inputs: status = subprocess.call([os.path.join(os.environ.get("PARROT_PATH", "bin"), "chirp_get"), options.chirp, input, os.path.basename(input)]) if status != 0: sys.exit(500) process = cms.Process("PickEvent") process.source = cms.Source ("PoolSource", fileNames = cms.untracked.vstring(''), duplicateCheckMode = cms.untracked.string('noDuplicateCheck') ) process.out = cms.OutputModule("PoolOutputModule", fileName = cms.untracked.string(options.output) ) process.end = cms.EndPath(process.out)
<commit_before>import FWCore.ParameterSet.Config as cms from FWCore.ParameterSet.VarParsing import VarParsing import subprocess import os import sys options = VarParsing('analysis') options.register('chirp', default=None, mytype=VarParsing.varType.string) options.register('inputs', mult=VarParsing.multiplicity.list, mytype=VarParsing.varType.string) options.register('output', mytype=VarParsing.varType.string) options.parseArguments() if options.chirp: for input in options.inputs: status = subprocess.call([os.path.join(os.environ.get("PARROT_PATH", "bin"), "chirp_get"), options.chirp, input, os.path.basename(input)]) if status != 0: sys.exit(500) process = cms.Process("PickEvent") process.source = cms.Source ("PoolSource", fileNames = cms.untracked.vstring(''), ) process.out = cms.OutputModule("PoolOutputModule", fileName = cms.untracked.string(options.output) ) process.end = cms.EndPath(process.out) <commit_msg>Disable duplicate check mode for merging-- this can cause events to be thrown out for MC data.<commit_after>import FWCore.ParameterSet.Config as cms from FWCore.ParameterSet.VarParsing import VarParsing import subprocess import os import sys options = VarParsing('analysis') options.register('chirp', default=None, mytype=VarParsing.varType.string) options.register('inputs', mult=VarParsing.multiplicity.list, mytype=VarParsing.varType.string) options.register('output', mytype=VarParsing.varType.string) options.parseArguments() if options.chirp: for input in options.inputs: status = subprocess.call([os.path.join(os.environ.get("PARROT_PATH", "bin"), "chirp_get"), options.chirp, input, os.path.basename(input)]) if status != 0: sys.exit(500) process = cms.Process("PickEvent") process.source = cms.Source ("PoolSource", fileNames = cms.untracked.vstring(''), duplicateCheckMode = cms.untracked.string('noDuplicateCheck') ) process.out = cms.OutputModule("PoolOutputModule", fileName = cms.untracked.string(options.output) ) process.end = cms.EndPath(process.out)
5da32c725200d9f3b319be40ae5c2d302dc72249
cloudbridge/cloud/providers/azure/test/test_azure_resource_group.py
cloudbridge/cloud/providers/azure/test/test_azure_resource_group.py
from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase class AzureResourceGroupTestCase(ProviderTestBase): def test_resource_group_create(self): resource_group_params = {'location': self.provider.region_name} rg = self.provider.azure_client. \ create_resource_group(self.provider.resource_group, resource_group_params) print("Create Resource - " + str(rg)) self.assertTrue( rg.name == "cloudbridge", "Resource Group should be Cloudbridge") def test_resource_group_get(self): rg = self.provider.azure_client.get_resource_group('MyGroup') print("Get Resource - " + str(rg)) self.assertTrue( rg.name == "testResourceGroup", "Resource Group should be Cloudbridge")
from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase class AzureResourceGroupTestCase(ProviderTestBase): def test_resource_group_create(self): resource_group_params = {'location': self.provider.region_name} rg = self.provider.azure_client. \ create_resource_group(self.provider.resource_group, resource_group_params) print("Create Resource - " + str(rg)) self.assertTrue( rg.name == self.provider.resource_group, "Resource Group should be {0}".format(rg.name)) def test_resource_group_get(self): rg = self.provider.azure_client.get_resource_group('MyGroup') print("Get Resource - " + str(rg)) self.assertTrue( rg.name == "testResourceGroup", "Resource Group should be {0}".format(rg.name))
Update resource group unit test
Update resource group unit test
Python
mit
gvlproject/libcloudbridge,gvlproject/cloudbridge
from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase class AzureResourceGroupTestCase(ProviderTestBase): def test_resource_group_create(self): resource_group_params = {'location': self.provider.region_name} rg = self.provider.azure_client. \ create_resource_group(self.provider.resource_group, resource_group_params) print("Create Resource - " + str(rg)) self.assertTrue( rg.name == "cloudbridge", "Resource Group should be Cloudbridge") def test_resource_group_get(self): rg = self.provider.azure_client.get_resource_group('MyGroup') print("Get Resource - " + str(rg)) self.assertTrue( rg.name == "testResourceGroup", "Resource Group should be Cloudbridge") Update resource group unit test
from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase class AzureResourceGroupTestCase(ProviderTestBase): def test_resource_group_create(self): resource_group_params = {'location': self.provider.region_name} rg = self.provider.azure_client. \ create_resource_group(self.provider.resource_group, resource_group_params) print("Create Resource - " + str(rg)) self.assertTrue( rg.name == self.provider.resource_group, "Resource Group should be {0}".format(rg.name)) def test_resource_group_get(self): rg = self.provider.azure_client.get_resource_group('MyGroup') print("Get Resource - " + str(rg)) self.assertTrue( rg.name == "testResourceGroup", "Resource Group should be {0}".format(rg.name))
<commit_before>from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase class AzureResourceGroupTestCase(ProviderTestBase): def test_resource_group_create(self): resource_group_params = {'location': self.provider.region_name} rg = self.provider.azure_client. \ create_resource_group(self.provider.resource_group, resource_group_params) print("Create Resource - " + str(rg)) self.assertTrue( rg.name == "cloudbridge", "Resource Group should be Cloudbridge") def test_resource_group_get(self): rg = self.provider.azure_client.get_resource_group('MyGroup') print("Get Resource - " + str(rg)) self.assertTrue( rg.name == "testResourceGroup", "Resource Group should be Cloudbridge") <commit_msg>Update resource group unit test<commit_after>
from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase class AzureResourceGroupTestCase(ProviderTestBase): def test_resource_group_create(self): resource_group_params = {'location': self.provider.region_name} rg = self.provider.azure_client. \ create_resource_group(self.provider.resource_group, resource_group_params) print("Create Resource - " + str(rg)) self.assertTrue( rg.name == self.provider.resource_group, "Resource Group should be {0}".format(rg.name)) def test_resource_group_get(self): rg = self.provider.azure_client.get_resource_group('MyGroup') print("Get Resource - " + str(rg)) self.assertTrue( rg.name == "testResourceGroup", "Resource Group should be {0}".format(rg.name))
from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase class AzureResourceGroupTestCase(ProviderTestBase): def test_resource_group_create(self): resource_group_params = {'location': self.provider.region_name} rg = self.provider.azure_client. \ create_resource_group(self.provider.resource_group, resource_group_params) print("Create Resource - " + str(rg)) self.assertTrue( rg.name == "cloudbridge", "Resource Group should be Cloudbridge") def test_resource_group_get(self): rg = self.provider.azure_client.get_resource_group('MyGroup') print("Get Resource - " + str(rg)) self.assertTrue( rg.name == "testResourceGroup", "Resource Group should be Cloudbridge") Update resource group unit testfrom cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase class AzureResourceGroupTestCase(ProviderTestBase): def test_resource_group_create(self): resource_group_params = {'location': self.provider.region_name} rg = self.provider.azure_client. \ create_resource_group(self.provider.resource_group, resource_group_params) print("Create Resource - " + str(rg)) self.assertTrue( rg.name == self.provider.resource_group, "Resource Group should be {0}".format(rg.name)) def test_resource_group_get(self): rg = self.provider.azure_client.get_resource_group('MyGroup') print("Get Resource - " + str(rg)) self.assertTrue( rg.name == "testResourceGroup", "Resource Group should be {0}".format(rg.name))
<commit_before>from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase class AzureResourceGroupTestCase(ProviderTestBase): def test_resource_group_create(self): resource_group_params = {'location': self.provider.region_name} rg = self.provider.azure_client. \ create_resource_group(self.provider.resource_group, resource_group_params) print("Create Resource - " + str(rg)) self.assertTrue( rg.name == "cloudbridge", "Resource Group should be Cloudbridge") def test_resource_group_get(self): rg = self.provider.azure_client.get_resource_group('MyGroup') print("Get Resource - " + str(rg)) self.assertTrue( rg.name == "testResourceGroup", "Resource Group should be Cloudbridge") <commit_msg>Update resource group unit test<commit_after>from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase class AzureResourceGroupTestCase(ProviderTestBase): def test_resource_group_create(self): resource_group_params = {'location': self.provider.region_name} rg = self.provider.azure_client. \ create_resource_group(self.provider.resource_group, resource_group_params) print("Create Resource - " + str(rg)) self.assertTrue( rg.name == self.provider.resource_group, "Resource Group should be {0}".format(rg.name)) def test_resource_group_get(self): rg = self.provider.azure_client.get_resource_group('MyGroup') print("Get Resource - " + str(rg)) self.assertTrue( rg.name == "testResourceGroup", "Resource Group should be {0}".format(rg.name))
afc18ff91bde4e6e6da554c7f9e520e5cac89fa2
streams.py
streams.py
import praw r = praw.Reddit(user_agent='nba_stream_parser') submissions = r.get_subreddit('nbastreams').get_hot(limit=10) for submission in submissions: print(submission.selftext_html)
from bs4 import BeautifulSoup import html import praw r = praw.Reddit(user_agent='nba_stream_parser') def get_streams_for_team(teams): teams.append('Game Thread') submissions = r.get_subreddit('nbastreams').get_hot(limit=20) streams = [] for submission in submissions: if all(team in submission.title for team in teams): for comment in submission.comments: soup = BeautifulSoup( html.unescape(comment.body_html), 'html.parser') if soup.find('a'): streams.append(soup.find('a')['href']) return streams if __name__ == '__main__': print(get_streams_for_team(['Spurs']))
Add comment parser; get stream links for any (2) team(s)
Add comment parser; get stream links for any (2) team(s)
Python
mit
kshvmdn/NBAScores,kshvmdn/nba.js,kshvmdn/nba-scores
import praw r = praw.Reddit(user_agent='nba_stream_parser') submissions = r.get_subreddit('nbastreams').get_hot(limit=10) for submission in submissions: print(submission.selftext_html) Add comment parser; get stream links for any (2) team(s)
from bs4 import BeautifulSoup import html import praw r = praw.Reddit(user_agent='nba_stream_parser') def get_streams_for_team(teams): teams.append('Game Thread') submissions = r.get_subreddit('nbastreams').get_hot(limit=20) streams = [] for submission in submissions: if all(team in submission.title for team in teams): for comment in submission.comments: soup = BeautifulSoup( html.unescape(comment.body_html), 'html.parser') if soup.find('a'): streams.append(soup.find('a')['href']) return streams if __name__ == '__main__': print(get_streams_for_team(['Spurs']))
<commit_before>import praw r = praw.Reddit(user_agent='nba_stream_parser') submissions = r.get_subreddit('nbastreams').get_hot(limit=10) for submission in submissions: print(submission.selftext_html) <commit_msg>Add comment parser; get stream links for any (2) team(s)<commit_after>
from bs4 import BeautifulSoup import html import praw r = praw.Reddit(user_agent='nba_stream_parser') def get_streams_for_team(teams): teams.append('Game Thread') submissions = r.get_subreddit('nbastreams').get_hot(limit=20) streams = [] for submission in submissions: if all(team in submission.title for team in teams): for comment in submission.comments: soup = BeautifulSoup( html.unescape(comment.body_html), 'html.parser') if soup.find('a'): streams.append(soup.find('a')['href']) return streams if __name__ == '__main__': print(get_streams_for_team(['Spurs']))
import praw r = praw.Reddit(user_agent='nba_stream_parser') submissions = r.get_subreddit('nbastreams').get_hot(limit=10) for submission in submissions: print(submission.selftext_html) Add comment parser; get stream links for any (2) team(s)from bs4 import BeautifulSoup import html import praw r = praw.Reddit(user_agent='nba_stream_parser') def get_streams_for_team(teams): teams.append('Game Thread') submissions = r.get_subreddit('nbastreams').get_hot(limit=20) streams = [] for submission in submissions: if all(team in submission.title for team in teams): for comment in submission.comments: soup = BeautifulSoup( html.unescape(comment.body_html), 'html.parser') if soup.find('a'): streams.append(soup.find('a')['href']) return streams if __name__ == '__main__': print(get_streams_for_team(['Spurs']))
<commit_before>import praw r = praw.Reddit(user_agent='nba_stream_parser') submissions = r.get_subreddit('nbastreams').get_hot(limit=10) for submission in submissions: print(submission.selftext_html) <commit_msg>Add comment parser; get stream links for any (2) team(s)<commit_after>from bs4 import BeautifulSoup import html import praw r = praw.Reddit(user_agent='nba_stream_parser') def get_streams_for_team(teams): teams.append('Game Thread') submissions = r.get_subreddit('nbastreams').get_hot(limit=20) streams = [] for submission in submissions: if all(team in submission.title for team in teams): for comment in submission.comments: soup = BeautifulSoup( html.unescape(comment.body_html), 'html.parser') if soup.find('a'): streams.append(soup.find('a')['href']) return streams if __name__ == '__main__': print(get_streams_for_team(['Spurs']))
46a376698851957813287fcb8deb1e7ebc222914
alfred_listener/__main__.py
alfred_listener/__main__.py
#!/usr/bin/env python import os from argh import arg, ArghParser from functools import wraps def with_app(func): @wraps(func) @arg('--config', help='Path to config file', required=True) def wrapper(*args, **kwargs): config = args[0].config from alfred_listener import create_app app = create_app(config) return func(app, *args, **kwargs) return wrapper @arg('--host', default='127.0.0.1', help='the host') @arg('--port', default=5000, help='the port') @with_app def runserver(app, args): app.run(args.host, args.port) @with_app def shell(app, args): from alfred_listener.helpers import get_shell with app.test_request_context(): sh = get_shell() sh(app=app) def main(): parser = ArghParser() parser.add_commands([runserver, shell]) parser.dispatch() if __name__ == '__main__': main()
#!/usr/bin/env python import os from argh import arg, ArghParser from functools import wraps def with_app(func): @wraps(func) @arg('--config', help='Path to config file', required=True) def wrapper(*args, **kwargs): config = args[0].config from alfred_listener import create_app app = create_app(config) return func(app, *args, **kwargs) return wrapper @arg('--host', default='127.0.0.1', help='the host') @arg('--port', default=5000, help='the port') @arg('--noreload', action='store_true', help='disable code reloader') @with_app def runserver(app, args): app.run(args.host, args.port, use_reloader=not args.noreload) @with_app def shell(app, args): from alfred_listener.helpers import get_shell with app.test_request_context(): sh = get_shell() sh(app=app) def main(): parser = ArghParser() parser.add_commands([runserver, shell]) parser.dispatch() if __name__ == '__main__': main()
Add an option to disable code reloader to runserver command
Add an option to disable code reloader to runserver command
Python
isc
alfredhq/alfred-listener
#!/usr/bin/env python import os from argh import arg, ArghParser from functools import wraps def with_app(func): @wraps(func) @arg('--config', help='Path to config file', required=True) def wrapper(*args, **kwargs): config = args[0].config from alfred_listener import create_app app = create_app(config) return func(app, *args, **kwargs) return wrapper @arg('--host', default='127.0.0.1', help='the host') @arg('--port', default=5000, help='the port') @with_app def runserver(app, args): app.run(args.host, args.port) @with_app def shell(app, args): from alfred_listener.helpers import get_shell with app.test_request_context(): sh = get_shell() sh(app=app) def main(): parser = ArghParser() parser.add_commands([runserver, shell]) parser.dispatch() if __name__ == '__main__': main() Add an option to disable code reloader to runserver command
#!/usr/bin/env python import os from argh import arg, ArghParser from functools import wraps def with_app(func): @wraps(func) @arg('--config', help='Path to config file', required=True) def wrapper(*args, **kwargs): config = args[0].config from alfred_listener import create_app app = create_app(config) return func(app, *args, **kwargs) return wrapper @arg('--host', default='127.0.0.1', help='the host') @arg('--port', default=5000, help='the port') @arg('--noreload', action='store_true', help='disable code reloader') @with_app def runserver(app, args): app.run(args.host, args.port, use_reloader=not args.noreload) @with_app def shell(app, args): from alfred_listener.helpers import get_shell with app.test_request_context(): sh = get_shell() sh(app=app) def main(): parser = ArghParser() parser.add_commands([runserver, shell]) parser.dispatch() if __name__ == '__main__': main()
<commit_before>#!/usr/bin/env python import os from argh import arg, ArghParser from functools import wraps def with_app(func): @wraps(func) @arg('--config', help='Path to config file', required=True) def wrapper(*args, **kwargs): config = args[0].config from alfred_listener import create_app app = create_app(config) return func(app, *args, **kwargs) return wrapper @arg('--host', default='127.0.0.1', help='the host') @arg('--port', default=5000, help='the port') @with_app def runserver(app, args): app.run(args.host, args.port) @with_app def shell(app, args): from alfred_listener.helpers import get_shell with app.test_request_context(): sh = get_shell() sh(app=app) def main(): parser = ArghParser() parser.add_commands([runserver, shell]) parser.dispatch() if __name__ == '__main__': main() <commit_msg>Add an option to disable code reloader to runserver command<commit_after>
#!/usr/bin/env python import os from argh import arg, ArghParser from functools import wraps def with_app(func): @wraps(func) @arg('--config', help='Path to config file', required=True) def wrapper(*args, **kwargs): config = args[0].config from alfred_listener import create_app app = create_app(config) return func(app, *args, **kwargs) return wrapper @arg('--host', default='127.0.0.1', help='the host') @arg('--port', default=5000, help='the port') @arg('--noreload', action='store_true', help='disable code reloader') @with_app def runserver(app, args): app.run(args.host, args.port, use_reloader=not args.noreload) @with_app def shell(app, args): from alfred_listener.helpers import get_shell with app.test_request_context(): sh = get_shell() sh(app=app) def main(): parser = ArghParser() parser.add_commands([runserver, shell]) parser.dispatch() if __name__ == '__main__': main()
#!/usr/bin/env python import os from argh import arg, ArghParser from functools import wraps def with_app(func): @wraps(func) @arg('--config', help='Path to config file', required=True) def wrapper(*args, **kwargs): config = args[0].config from alfred_listener import create_app app = create_app(config) return func(app, *args, **kwargs) return wrapper @arg('--host', default='127.0.0.1', help='the host') @arg('--port', default=5000, help='the port') @with_app def runserver(app, args): app.run(args.host, args.port) @with_app def shell(app, args): from alfred_listener.helpers import get_shell with app.test_request_context(): sh = get_shell() sh(app=app) def main(): parser = ArghParser() parser.add_commands([runserver, shell]) parser.dispatch() if __name__ == '__main__': main() Add an option to disable code reloader to runserver command#!/usr/bin/env python import os from argh import arg, ArghParser from functools import wraps def with_app(func): @wraps(func) @arg('--config', help='Path to config file', required=True) def wrapper(*args, **kwargs): config = args[0].config from alfred_listener import create_app app = create_app(config) return func(app, *args, **kwargs) return wrapper @arg('--host', default='127.0.0.1', help='the host') @arg('--port', default=5000, help='the port') @arg('--noreload', action='store_true', help='disable code reloader') @with_app def runserver(app, args): app.run(args.host, args.port, use_reloader=not args.noreload) @with_app def shell(app, args): from alfred_listener.helpers import get_shell with app.test_request_context(): sh = get_shell() sh(app=app) def main(): parser = ArghParser() parser.add_commands([runserver, shell]) parser.dispatch() if __name__ == '__main__': main()
<commit_before>#!/usr/bin/env python import os from argh import arg, ArghParser from functools import wraps def with_app(func): @wraps(func) @arg('--config', help='Path to config file', required=True) def wrapper(*args, **kwargs): config = args[0].config from alfred_listener import create_app app = create_app(config) return func(app, *args, **kwargs) return wrapper @arg('--host', default='127.0.0.1', help='the host') @arg('--port', default=5000, help='the port') @with_app def runserver(app, args): app.run(args.host, args.port) @with_app def shell(app, args): from alfred_listener.helpers import get_shell with app.test_request_context(): sh = get_shell() sh(app=app) def main(): parser = ArghParser() parser.add_commands([runserver, shell]) parser.dispatch() if __name__ == '__main__': main() <commit_msg>Add an option to disable code reloader to runserver command<commit_after>#!/usr/bin/env python import os from argh import arg, ArghParser from functools import wraps def with_app(func): @wraps(func) @arg('--config', help='Path to config file', required=True) def wrapper(*args, **kwargs): config = args[0].config from alfred_listener import create_app app = create_app(config) return func(app, *args, **kwargs) return wrapper @arg('--host', default='127.0.0.1', help='the host') @arg('--port', default=5000, help='the port') @arg('--noreload', action='store_true', help='disable code reloader') @with_app def runserver(app, args): app.run(args.host, args.port, use_reloader=not args.noreload) @with_app def shell(app, args): from alfred_listener.helpers import get_shell with app.test_request_context(): sh = get_shell() sh(app=app) def main(): parser = ArghParser() parser.add_commands([runserver, shell]) parser.dispatch() if __name__ == '__main__': main()
e0ff626423944ed3b1e08ddeebbfcf60885307a5
tempest/stress/actions/volume_create_delete.py
tempest/stress/actions/volume_create_delete.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tempest.common.utils import data_utils import tempest.stress.stressaction as stressaction class VolumeCreateDeleteTest(stressaction.StressAction): def run(self): name = data_utils.rand_name("volume") self.logger.info("creating %s" % name) volumes_client = self.manager.volumes_client _, volume = volumes_client.create_volume(size=1, display_name=name) vol_id = volume['id'] volumes_client.wait_for_volume_status(vol_id, 'available') self.logger.info("created %s" % volume['id']) self.logger.info("deleting %s" % name) volumes_client.delete_volume(vol_id) volumes_client.wait_for_resource_deletion(vol_id) self.logger.info("deleted %s" % vol_id)
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tempest.common.utils import data_utils import tempest.stress.stressaction as stressaction class VolumeCreateDeleteTest(stressaction.StressAction): def run(self): name = data_utils.rand_name("volume") self.logger.info("creating %s" % name) volumes_client = self.manager.volumes_client volume = volumes_client.create_volume(size=1, display_name=name) vol_id = volume['id'] volumes_client.wait_for_volume_status(vol_id, 'available') self.logger.info("created %s" % volume['id']) self.logger.info("deleting %s" % name) volumes_client.delete_volume(vol_id) volumes_client.wait_for_resource_deletion(vol_id) self.logger.info("deleted %s" % vol_id)
Fix stress test which was not changed to receive one client value
Fix stress test which was not changed to receive one client value Change-Id: I186f2827c91d8b1eabd0769dda4765a973bf42b4 Closes-Bug: 1413980
Python
apache-2.0
tudorvio/tempest,yamt/tempest,jamielennox/tempest,xbezdick/tempest,hpcloud-mon/tempest,tudorvio/tempest,varunarya10/tempest,neerja28/Tempest,danielmellado/tempest,zsoltdudas/lis-tempest,jaspreetw/tempest,FujitsuEnablingSoftwareTechnologyGmbH/tempest,cisco-openstack/tempest,afaheem88/tempest,hpcloud-mon/tempest,vedujoshi/tempest,Vaidyanath/tempest,afaheem88/tempest,manasi24/jiocloud-tempest-qatempest,pczerkas/tempest,rakeshmi/tempest,eggmaster/tempest,LIS/lis-tempest,LIS/lis-tempest,FujitsuEnablingSoftwareTechnologyGmbH/tempest,nunogt/tempest,redhat-cip/tempest,alinbalutoiu/tempest,alinbalutoiu/tempest,jamielennox/tempest,neerja28/Tempest,pczerkas/tempest,xbezdick/tempest,izadorozhna/tempest,Juniper/tempest,CiscoSystems/tempest,izadorozhna/tempest,tonyli71/tempest,manasi24/jiocloud-tempest-qatempest,Tesora/tesora-tempest,yamt/tempest,dkalashnik/tempest,jaspreetw/tempest,openstack/tempest,bigswitch/tempest,JioCloud/tempest,rakeshmi/tempest,JioCloud/tempest,rzarzynski/tempest,manasi24/tempest,rzarzynski/tempest,Juraci/tempest,eggmaster/tempest,pandeyop/tempest,manasi24/tempest,sebrandon1/tempest,flyingfish007/tempest,tonyli71/tempest,danielmellado/tempest,hayderimran7/tempest,dkalashnik/tempest,nunogt/tempest,openstack/tempest,hayderimran7/tempest,roopali8/tempest,varunarya10/tempest,akash1808/tempest,Juniper/tempest,masayukig/tempest,pandeyop/tempest,cisco-openstack/tempest,bigswitch/tempest,flyingfish007/tempest,Juraci/tempest,masayukig/tempest,redhat-cip/tempest,roopali8/tempest,sebrandon1/tempest,Vaidyanath/tempest,NexusIS/tempest,vedujoshi/tempest,CiscoSystems/tempest,akash1808/tempest,zsoltdudas/lis-tempest,NexusIS/tempest,Tesora/tesora-tempest
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tempest.common.utils import data_utils import tempest.stress.stressaction as stressaction class VolumeCreateDeleteTest(stressaction.StressAction): def run(self): name = data_utils.rand_name("volume") self.logger.info("creating %s" % name) volumes_client = self.manager.volumes_client _, volume = volumes_client.create_volume(size=1, display_name=name) vol_id = volume['id'] volumes_client.wait_for_volume_status(vol_id, 'available') self.logger.info("created %s" % volume['id']) self.logger.info("deleting %s" % name) volumes_client.delete_volume(vol_id) volumes_client.wait_for_resource_deletion(vol_id) self.logger.info("deleted %s" % vol_id) Fix stress test which was not changed to receive one client value Change-Id: I186f2827c91d8b1eabd0769dda4765a973bf42b4 Closes-Bug: 1413980
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tempest.common.utils import data_utils import tempest.stress.stressaction as stressaction class VolumeCreateDeleteTest(stressaction.StressAction): def run(self): name = data_utils.rand_name("volume") self.logger.info("creating %s" % name) volumes_client = self.manager.volumes_client volume = volumes_client.create_volume(size=1, display_name=name) vol_id = volume['id'] volumes_client.wait_for_volume_status(vol_id, 'available') self.logger.info("created %s" % volume['id']) self.logger.info("deleting %s" % name) volumes_client.delete_volume(vol_id) volumes_client.wait_for_resource_deletion(vol_id) self.logger.info("deleted %s" % vol_id)
<commit_before># Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tempest.common.utils import data_utils import tempest.stress.stressaction as stressaction class VolumeCreateDeleteTest(stressaction.StressAction): def run(self): name = data_utils.rand_name("volume") self.logger.info("creating %s" % name) volumes_client = self.manager.volumes_client _, volume = volumes_client.create_volume(size=1, display_name=name) vol_id = volume['id'] volumes_client.wait_for_volume_status(vol_id, 'available') self.logger.info("created %s" % volume['id']) self.logger.info("deleting %s" % name) volumes_client.delete_volume(vol_id) volumes_client.wait_for_resource_deletion(vol_id) self.logger.info("deleted %s" % vol_id) <commit_msg>Fix stress test which was not changed to receive one client value Change-Id: I186f2827c91d8b1eabd0769dda4765a973bf42b4 Closes-Bug: 1413980<commit_after>
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tempest.common.utils import data_utils import tempest.stress.stressaction as stressaction class VolumeCreateDeleteTest(stressaction.StressAction): def run(self): name = data_utils.rand_name("volume") self.logger.info("creating %s" % name) volumes_client = self.manager.volumes_client volume = volumes_client.create_volume(size=1, display_name=name) vol_id = volume['id'] volumes_client.wait_for_volume_status(vol_id, 'available') self.logger.info("created %s" % volume['id']) self.logger.info("deleting %s" % name) volumes_client.delete_volume(vol_id) volumes_client.wait_for_resource_deletion(vol_id) self.logger.info("deleted %s" % vol_id)
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tempest.common.utils import data_utils import tempest.stress.stressaction as stressaction class VolumeCreateDeleteTest(stressaction.StressAction): def run(self): name = data_utils.rand_name("volume") self.logger.info("creating %s" % name) volumes_client = self.manager.volumes_client _, volume = volumes_client.create_volume(size=1, display_name=name) vol_id = volume['id'] volumes_client.wait_for_volume_status(vol_id, 'available') self.logger.info("created %s" % volume['id']) self.logger.info("deleting %s" % name) volumes_client.delete_volume(vol_id) volumes_client.wait_for_resource_deletion(vol_id) self.logger.info("deleted %s" % vol_id) Fix stress test which was not changed to receive one client value Change-Id: I186f2827c91d8b1eabd0769dda4765a973bf42b4 Closes-Bug: 1413980# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tempest.common.utils import data_utils import tempest.stress.stressaction as stressaction class VolumeCreateDeleteTest(stressaction.StressAction): def run(self): name = data_utils.rand_name("volume") self.logger.info("creating %s" % name) volumes_client = self.manager.volumes_client volume = volumes_client.create_volume(size=1, display_name=name) vol_id = volume['id'] volumes_client.wait_for_volume_status(vol_id, 'available') self.logger.info("created %s" % volume['id']) self.logger.info("deleting %s" % name) volumes_client.delete_volume(vol_id) volumes_client.wait_for_resource_deletion(vol_id) self.logger.info("deleted %s" % vol_id)
<commit_before># Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tempest.common.utils import data_utils import tempest.stress.stressaction as stressaction class VolumeCreateDeleteTest(stressaction.StressAction): def run(self): name = data_utils.rand_name("volume") self.logger.info("creating %s" % name) volumes_client = self.manager.volumes_client _, volume = volumes_client.create_volume(size=1, display_name=name) vol_id = volume['id'] volumes_client.wait_for_volume_status(vol_id, 'available') self.logger.info("created %s" % volume['id']) self.logger.info("deleting %s" % name) volumes_client.delete_volume(vol_id) volumes_client.wait_for_resource_deletion(vol_id) self.logger.info("deleted %s" % vol_id) <commit_msg>Fix stress test which was not changed to receive one client value Change-Id: I186f2827c91d8b1eabd0769dda4765a973bf42b4 Closes-Bug: 1413980<commit_after># Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tempest.common.utils import data_utils import tempest.stress.stressaction as stressaction class VolumeCreateDeleteTest(stressaction.StressAction): def run(self): name = data_utils.rand_name("volume") self.logger.info("creating %s" % name) volumes_client = self.manager.volumes_client volume = volumes_client.create_volume(size=1, display_name=name) vol_id = volume['id'] volumes_client.wait_for_volume_status(vol_id, 'available') self.logger.info("created %s" % volume['id']) self.logger.info("deleting %s" % name) volumes_client.delete_volume(vol_id) volumes_client.wait_for_resource_deletion(vol_id) self.logger.info("deleted %s" % vol_id)
d37631451ad65588fdd8ab6cb300769deca3d043
modules/roles.py
modules/roles.py
import discord import shlex from modules.botModule import BotModule class Roles(BotModule): name = 'Roles' description = 'Allow for the assignment and removal of roles.' help_text = '' trigger_string = '!role' # String to listen for as trigger async def parse_command(self, message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i, x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is role_to_assign = message.server.roles[role[0]] if len(msg) != 1: try: if role_to_assign in message.author.roles: await client.remove_roles(message.author, role_to_assign) msg = ":ok_hand: Removed you from " + role_to_assign.name + " ." else: await client.add_roles(message.author, role_to_assign) msg = ":ok_hand: Added you to " + role_to_assign.name + " ." except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." await client.send_message(message.channel, msg) else: pass
import discord import shlex from modules.botModule import BotModule class Roles(BotModule): name = 'Roles' description = 'Allow for the assignment and removal of roles.' help_text = 'Usage: `!roles "role_name"`. This will add you to that role if allowed.' ' Executing it when you already have the role assigned will remove you' ' from that role.') trigger_string = '!role' # String to listen for as trigger async def parse_command(self, message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i, x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is role_to_assign = message.server.roles[role[0]] if len(msg) != 1: try: if role_to_assign in message.author.roles: await client.remove_roles(message.author, role_to_assign) msg = ":ok_hand: Removed you from " + role_to_assign.name + " ." else: await client.add_roles(message.author, role_to_assign) msg = ":ok_hand: Added you to " + role_to_assign.name + " ." except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." await client.send_message(message.channel, msg) else: pass
Add help text for Roles module.
Add help text for Roles module.
Python
mit
suclearnub/scubot
import discord import shlex from modules.botModule import BotModule class Roles(BotModule): name = 'Roles' description = 'Allow for the assignment and removal of roles.' help_text = '' trigger_string = '!role' # String to listen for as trigger async def parse_command(self, message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i, x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is role_to_assign = message.server.roles[role[0]] if len(msg) != 1: try: if role_to_assign in message.author.roles: await client.remove_roles(message.author, role_to_assign) msg = ":ok_hand: Removed you from " + role_to_assign.name + " ." else: await client.add_roles(message.author, role_to_assign) msg = ":ok_hand: Added you to " + role_to_assign.name + " ." except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." await client.send_message(message.channel, msg) else: pass Add help text for Roles module.
import discord import shlex from modules.botModule import BotModule class Roles(BotModule): name = 'Roles' description = 'Allow for the assignment and removal of roles.' help_text = 'Usage: `!roles "role_name"`. This will add you to that role if allowed.' ' Executing it when you already have the role assigned will remove you' ' from that role.') trigger_string = '!role' # String to listen for as trigger async def parse_command(self, message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i, x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is role_to_assign = message.server.roles[role[0]] if len(msg) != 1: try: if role_to_assign in message.author.roles: await client.remove_roles(message.author, role_to_assign) msg = ":ok_hand: Removed you from " + role_to_assign.name + " ." else: await client.add_roles(message.author, role_to_assign) msg = ":ok_hand: Added you to " + role_to_assign.name + " ." except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." await client.send_message(message.channel, msg) else: pass
<commit_before>import discord import shlex from modules.botModule import BotModule class Roles(BotModule): name = 'Roles' description = 'Allow for the assignment and removal of roles.' help_text = '' trigger_string = '!role' # String to listen for as trigger async def parse_command(self, message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i, x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is role_to_assign = message.server.roles[role[0]] if len(msg) != 1: try: if role_to_assign in message.author.roles: await client.remove_roles(message.author, role_to_assign) msg = ":ok_hand: Removed you from " + role_to_assign.name + " ." else: await client.add_roles(message.author, role_to_assign) msg = ":ok_hand: Added you to " + role_to_assign.name + " ." except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." await client.send_message(message.channel, msg) else: pass <commit_msg>Add help text for Roles module.<commit_after>
import discord import shlex from modules.botModule import BotModule class Roles(BotModule): name = 'Roles' description = 'Allow for the assignment and removal of roles.' help_text = 'Usage: `!roles "role_name"`. This will add you to that role if allowed.' ' Executing it when you already have the role assigned will remove you' ' from that role.') trigger_string = '!role' # String to listen for as trigger async def parse_command(self, message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i, x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is role_to_assign = message.server.roles[role[0]] if len(msg) != 1: try: if role_to_assign in message.author.roles: await client.remove_roles(message.author, role_to_assign) msg = ":ok_hand: Removed you from " + role_to_assign.name + " ." else: await client.add_roles(message.author, role_to_assign) msg = ":ok_hand: Added you to " + role_to_assign.name + " ." except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." await client.send_message(message.channel, msg) else: pass
import discord import shlex from modules.botModule import BotModule class Roles(BotModule): name = 'Roles' description = 'Allow for the assignment and removal of roles.' help_text = '' trigger_string = '!role' # String to listen for as trigger async def parse_command(self, message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i, x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is role_to_assign = message.server.roles[role[0]] if len(msg) != 1: try: if role_to_assign in message.author.roles: await client.remove_roles(message.author, role_to_assign) msg = ":ok_hand: Removed you from " + role_to_assign.name + " ." else: await client.add_roles(message.author, role_to_assign) msg = ":ok_hand: Added you to " + role_to_assign.name + " ." except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." await client.send_message(message.channel, msg) else: pass Add help text for Roles module.import discord import shlex from modules.botModule import BotModule class Roles(BotModule): name = 'Roles' description = 'Allow for the assignment and removal of roles.' help_text = 'Usage: `!roles "role_name"`. This will add you to that role if allowed.' ' Executing it when you already have the role assigned will remove you' ' from that role.') trigger_string = '!role' # String to listen for as trigger async def parse_command(self, message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i, x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is role_to_assign = message.server.roles[role[0]] if len(msg) != 1: try: if role_to_assign in message.author.roles: await client.remove_roles(message.author, role_to_assign) msg = ":ok_hand: Removed you from " + role_to_assign.name + " ." else: await client.add_roles(message.author, role_to_assign) msg = ":ok_hand: Added you to " + role_to_assign.name + " ." except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." await client.send_message(message.channel, msg) else: pass
<commit_before>import discord import shlex from modules.botModule import BotModule class Roles(BotModule): name = 'Roles' description = 'Allow for the assignment and removal of roles.' help_text = '' trigger_string = '!role' # String to listen for as trigger async def parse_command(self, message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i, x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is role_to_assign = message.server.roles[role[0]] if len(msg) != 1: try: if role_to_assign in message.author.roles: await client.remove_roles(message.author, role_to_assign) msg = ":ok_hand: Removed you from " + role_to_assign.name + " ." else: await client.add_roles(message.author, role_to_assign) msg = ":ok_hand: Added you to " + role_to_assign.name + " ." except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." await client.send_message(message.channel, msg) else: pass <commit_msg>Add help text for Roles module.<commit_after>import discord import shlex from modules.botModule import BotModule class Roles(BotModule): name = 'Roles' description = 'Allow for the assignment and removal of roles.' help_text = 'Usage: `!roles "role_name"`. This will add you to that role if allowed.' ' Executing it when you already have the role assigned will remove you' ' from that role.') trigger_string = '!role' # String to listen for as trigger async def parse_command(self, message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i, x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is role_to_assign = message.server.roles[role[0]] if len(msg) != 1: try: if role_to_assign in message.author.roles: await client.remove_roles(message.author, role_to_assign) msg = ":ok_hand: Removed you from " + role_to_assign.name + " ." else: await client.add_roles(message.author, role_to_assign) msg = ":ok_hand: Added you to " + role_to_assign.name + " ." except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." await client.send_message(message.channel, msg) else: pass
ba42df4296a02396e823ee9692fb84eb0deb8b7c
corehq/messaging/smsbackends/start_enterprise/views.py
corehq/messaging/smsbackends/start_enterprise/views.py
from __future__ import absolute_import from corehq.apps.sms.views import IncomingBackendView from corehq.messaging.smsbackends.start_enterprise.models import ( StartEnterpriseBackend, StartEnterpriseDeliveryReceipt, ) from datetime import datetime from django.http import HttpResponse, HttpResponseBadRequest class StartEnterpriseDeliveryReceiptView(IncomingBackendView): urlname = 'start_enterprise_dlr' @property def backend_class(self): return StartEnterpriseBackend def get(self, request, api_key, *args, **kwargs): message_id = request.GET.get('msgid') if not message_id: return HttpResponseBadRequest("Missing 'msgid'") message_id = message_id.strip() try: dlr = StartEnterpriseDeliveryReceipt.objects.get(message_id=message_id) except StartEnterpriseDeliveryReceipt.DoesNotExist: dlr = None if dlr: dlr.received_on = datetime.utcnow() dlr.info = request.GET.dict() dlr.save() # Based on the documentation, a response of "1" acknowledges receipt of the DLR return HttpResponse("1")
from __future__ import absolute_import import logging from corehq.apps.sms.views import IncomingBackendView from corehq.messaging.smsbackends.start_enterprise.models import ( StartEnterpriseBackend, StartEnterpriseDeliveryReceipt, ) from datetime import datetime from django.http import HttpResponse, HttpResponseBadRequest class StartEnterpriseDeliveryReceiptView(IncomingBackendView): urlname = 'start_enterprise_dlr' @property def backend_class(self): return StartEnterpriseBackend def get(self, request, api_key, *args, **kwargs): logging.info("Received Start Enterprise delivery receipt with items: %s" % request.GET.dict().keys()) message_id = request.GET.get('msgid') if not message_id: return HttpResponseBadRequest("Missing 'msgid'") message_id = message_id.strip() try: dlr = StartEnterpriseDeliveryReceipt.objects.get(message_id=message_id) except StartEnterpriseDeliveryReceipt.DoesNotExist: dlr = None if dlr: dlr.received_on = datetime.utcnow() dlr.info = request.GET.dict() dlr.save() # Based on the documentation, a response of "1" acknowledges receipt of the DLR return HttpResponse("1")
Add logging to delivery receipt view
Add logging to delivery receipt view
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from __future__ import absolute_import from corehq.apps.sms.views import IncomingBackendView from corehq.messaging.smsbackends.start_enterprise.models import ( StartEnterpriseBackend, StartEnterpriseDeliveryReceipt, ) from datetime import datetime from django.http import HttpResponse, HttpResponseBadRequest class StartEnterpriseDeliveryReceiptView(IncomingBackendView): urlname = 'start_enterprise_dlr' @property def backend_class(self): return StartEnterpriseBackend def get(self, request, api_key, *args, **kwargs): message_id = request.GET.get('msgid') if not message_id: return HttpResponseBadRequest("Missing 'msgid'") message_id = message_id.strip() try: dlr = StartEnterpriseDeliveryReceipt.objects.get(message_id=message_id) except StartEnterpriseDeliveryReceipt.DoesNotExist: dlr = None if dlr: dlr.received_on = datetime.utcnow() dlr.info = request.GET.dict() dlr.save() # Based on the documentation, a response of "1" acknowledges receipt of the DLR return HttpResponse("1") Add logging to delivery receipt view
from __future__ import absolute_import import logging from corehq.apps.sms.views import IncomingBackendView from corehq.messaging.smsbackends.start_enterprise.models import ( StartEnterpriseBackend, StartEnterpriseDeliveryReceipt, ) from datetime import datetime from django.http import HttpResponse, HttpResponseBadRequest class StartEnterpriseDeliveryReceiptView(IncomingBackendView): urlname = 'start_enterprise_dlr' @property def backend_class(self): return StartEnterpriseBackend def get(self, request, api_key, *args, **kwargs): logging.info("Received Start Enterprise delivery receipt with items: %s" % request.GET.dict().keys()) message_id = request.GET.get('msgid') if not message_id: return HttpResponseBadRequest("Missing 'msgid'") message_id = message_id.strip() try: dlr = StartEnterpriseDeliveryReceipt.objects.get(message_id=message_id) except StartEnterpriseDeliveryReceipt.DoesNotExist: dlr = None if dlr: dlr.received_on = datetime.utcnow() dlr.info = request.GET.dict() dlr.save() # Based on the documentation, a response of "1" acknowledges receipt of the DLR return HttpResponse("1")
<commit_before>from __future__ import absolute_import from corehq.apps.sms.views import IncomingBackendView from corehq.messaging.smsbackends.start_enterprise.models import ( StartEnterpriseBackend, StartEnterpriseDeliveryReceipt, ) from datetime import datetime from django.http import HttpResponse, HttpResponseBadRequest class StartEnterpriseDeliveryReceiptView(IncomingBackendView): urlname = 'start_enterprise_dlr' @property def backend_class(self): return StartEnterpriseBackend def get(self, request, api_key, *args, **kwargs): message_id = request.GET.get('msgid') if not message_id: return HttpResponseBadRequest("Missing 'msgid'") message_id = message_id.strip() try: dlr = StartEnterpriseDeliveryReceipt.objects.get(message_id=message_id) except StartEnterpriseDeliveryReceipt.DoesNotExist: dlr = None if dlr: dlr.received_on = datetime.utcnow() dlr.info = request.GET.dict() dlr.save() # Based on the documentation, a response of "1" acknowledges receipt of the DLR return HttpResponse("1") <commit_msg>Add logging to delivery receipt view<commit_after>
from __future__ import absolute_import import logging from corehq.apps.sms.views import IncomingBackendView from corehq.messaging.smsbackends.start_enterprise.models import ( StartEnterpriseBackend, StartEnterpriseDeliveryReceipt, ) from datetime import datetime from django.http import HttpResponse, HttpResponseBadRequest class StartEnterpriseDeliveryReceiptView(IncomingBackendView): urlname = 'start_enterprise_dlr' @property def backend_class(self): return StartEnterpriseBackend def get(self, request, api_key, *args, **kwargs): logging.info("Received Start Enterprise delivery receipt with items: %s" % request.GET.dict().keys()) message_id = request.GET.get('msgid') if not message_id: return HttpResponseBadRequest("Missing 'msgid'") message_id = message_id.strip() try: dlr = StartEnterpriseDeliveryReceipt.objects.get(message_id=message_id) except StartEnterpriseDeliveryReceipt.DoesNotExist: dlr = None if dlr: dlr.received_on = datetime.utcnow() dlr.info = request.GET.dict() dlr.save() # Based on the documentation, a response of "1" acknowledges receipt of the DLR return HttpResponse("1")
from __future__ import absolute_import from corehq.apps.sms.views import IncomingBackendView from corehq.messaging.smsbackends.start_enterprise.models import ( StartEnterpriseBackend, StartEnterpriseDeliveryReceipt, ) from datetime import datetime from django.http import HttpResponse, HttpResponseBadRequest class StartEnterpriseDeliveryReceiptView(IncomingBackendView): urlname = 'start_enterprise_dlr' @property def backend_class(self): return StartEnterpriseBackend def get(self, request, api_key, *args, **kwargs): message_id = request.GET.get('msgid') if not message_id: return HttpResponseBadRequest("Missing 'msgid'") message_id = message_id.strip() try: dlr = StartEnterpriseDeliveryReceipt.objects.get(message_id=message_id) except StartEnterpriseDeliveryReceipt.DoesNotExist: dlr = None if dlr: dlr.received_on = datetime.utcnow() dlr.info = request.GET.dict() dlr.save() # Based on the documentation, a response of "1" acknowledges receipt of the DLR return HttpResponse("1") Add logging to delivery receipt viewfrom __future__ import absolute_import import logging from corehq.apps.sms.views import IncomingBackendView from corehq.messaging.smsbackends.start_enterprise.models import ( StartEnterpriseBackend, StartEnterpriseDeliveryReceipt, ) from datetime import datetime from django.http import HttpResponse, HttpResponseBadRequest class StartEnterpriseDeliveryReceiptView(IncomingBackendView): urlname = 'start_enterprise_dlr' @property def backend_class(self): return StartEnterpriseBackend def get(self, request, api_key, *args, **kwargs): logging.info("Received Start Enterprise delivery receipt with items: %s" % request.GET.dict().keys()) message_id = request.GET.get('msgid') if not message_id: return HttpResponseBadRequest("Missing 'msgid'") message_id = message_id.strip() try: dlr = StartEnterpriseDeliveryReceipt.objects.get(message_id=message_id) except StartEnterpriseDeliveryReceipt.DoesNotExist: dlr = None if dlr: dlr.received_on = datetime.utcnow() dlr.info = request.GET.dict() dlr.save() # Based on the documentation, a response of "1" acknowledges receipt of the DLR return HttpResponse("1")
<commit_before>from __future__ import absolute_import from corehq.apps.sms.views import IncomingBackendView from corehq.messaging.smsbackends.start_enterprise.models import ( StartEnterpriseBackend, StartEnterpriseDeliveryReceipt, ) from datetime import datetime from django.http import HttpResponse, HttpResponseBadRequest class StartEnterpriseDeliveryReceiptView(IncomingBackendView): urlname = 'start_enterprise_dlr' @property def backend_class(self): return StartEnterpriseBackend def get(self, request, api_key, *args, **kwargs): message_id = request.GET.get('msgid') if not message_id: return HttpResponseBadRequest("Missing 'msgid'") message_id = message_id.strip() try: dlr = StartEnterpriseDeliveryReceipt.objects.get(message_id=message_id) except StartEnterpriseDeliveryReceipt.DoesNotExist: dlr = None if dlr: dlr.received_on = datetime.utcnow() dlr.info = request.GET.dict() dlr.save() # Based on the documentation, a response of "1" acknowledges receipt of the DLR return HttpResponse("1") <commit_msg>Add logging to delivery receipt view<commit_after>from __future__ import absolute_import import logging from corehq.apps.sms.views import IncomingBackendView from corehq.messaging.smsbackends.start_enterprise.models import ( StartEnterpriseBackend, StartEnterpriseDeliveryReceipt, ) from datetime import datetime from django.http import HttpResponse, HttpResponseBadRequest class StartEnterpriseDeliveryReceiptView(IncomingBackendView): urlname = 'start_enterprise_dlr' @property def backend_class(self): return StartEnterpriseBackend def get(self, request, api_key, *args, **kwargs): logging.info("Received Start Enterprise delivery receipt with items: %s" % request.GET.dict().keys()) message_id = request.GET.get('msgid') if not message_id: return HttpResponseBadRequest("Missing 'msgid'") message_id = message_id.strip() try: dlr = StartEnterpriseDeliveryReceipt.objects.get(message_id=message_id) except StartEnterpriseDeliveryReceipt.DoesNotExist: dlr = None if dlr: dlr.received_on = datetime.utcnow() dlr.info = request.GET.dict() dlr.save() # Based on the documentation, a response of "1" acknowledges receipt of the DLR return HttpResponse("1")
7ca228c6454ae208c8a42cc1d138566cc7d19084
mufg_simulator.py
mufg_simulator.py
#!/usr/bin/pyton from __future__ import division import random initial_items = int(raw_input("how many items do you have at the start?: ") or "50") iteration_days = int(raw_input("how many days do you have to multiple them?: ") or "100") trials = 1000 def iterate_n_days(n, initial_items): current_items = initial_items for x in range(1, n): new_items = 0; for y in range (1,current_items): if (random.random() < 0.01): new_items =new_items +1 current_items=current_items+new_items; print "day=",y," m=",current_items return current_items total_items_accumulated = 0 for y in range(1,trials): total_items_accumulated += iterate_n_days(iteration_days,initial_items) average_items_accumulated = total_items_accumulated / trials print "average items after ", iteration_days, " days over", trials, " trials", average_items_accumulated print "This assumes that you are moving items to new MUFG capsules when the capsule reaches 90 or so items and keeping your inventory from becoming overfull."
#!/usr/bin/pyton from __future__ import division import random initial_items = int(raw_input("how many items do you have at the start?: ") or "50") iteration_days = int(raw_input("how many days do you have to multiple them?: ") or "100") trials = 1000 def iterate_n_days(n, initial_items): current_items = initial_items for x in range(1, n): new_items = 0; for y in range (1,current_items): if (random.random() < 0.01): new_items =new_items +1 current_items=current_items+new_items; print "day=",y," m=",current_items return current_items total_items_accumulated = 0 for y in range(trials): total_items_accumulated += iterate_n_days(iteration_days,initial_items) average_items_accumulated = total_items_accumulated / trials print "average items after ", iteration_days, " days over", trials, " trials", average_items_accumulated print "This assumes that you are moving items to new MUFG capsules when the capsule reaches 90 or so items and keeping your inventory from becoming overfull."
Correct off by one error in trial count
Correct off by one error in trial count
Python
apache-2.0
nikolawannabe/mufg_simulator
#!/usr/bin/pyton from __future__ import division import random initial_items = int(raw_input("how many items do you have at the start?: ") or "50") iteration_days = int(raw_input("how many days do you have to multiple them?: ") or "100") trials = 1000 def iterate_n_days(n, initial_items): current_items = initial_items for x in range(1, n): new_items = 0; for y in range (1,current_items): if (random.random() < 0.01): new_items =new_items +1 current_items=current_items+new_items; print "day=",y," m=",current_items return current_items total_items_accumulated = 0 for y in range(1,trials): total_items_accumulated += iterate_n_days(iteration_days,initial_items) average_items_accumulated = total_items_accumulated / trials print "average items after ", iteration_days, " days over", trials, " trials", average_items_accumulated print "This assumes that you are moving items to new MUFG capsules when the capsule reaches 90 or so items and keeping your inventory from becoming overfull." Correct off by one error in trial count
#!/usr/bin/pyton from __future__ import division import random initial_items = int(raw_input("how many items do you have at the start?: ") or "50") iteration_days = int(raw_input("how many days do you have to multiple them?: ") or "100") trials = 1000 def iterate_n_days(n, initial_items): current_items = initial_items for x in range(1, n): new_items = 0; for y in range (1,current_items): if (random.random() < 0.01): new_items =new_items +1 current_items=current_items+new_items; print "day=",y," m=",current_items return current_items total_items_accumulated = 0 for y in range(trials): total_items_accumulated += iterate_n_days(iteration_days,initial_items) average_items_accumulated = total_items_accumulated / trials print "average items after ", iteration_days, " days over", trials, " trials", average_items_accumulated print "This assumes that you are moving items to new MUFG capsules when the capsule reaches 90 or so items and keeping your inventory from becoming overfull."
<commit_before>#!/usr/bin/pyton from __future__ import division import random initial_items = int(raw_input("how many items do you have at the start?: ") or "50") iteration_days = int(raw_input("how many days do you have to multiple them?: ") or "100") trials = 1000 def iterate_n_days(n, initial_items): current_items = initial_items for x in range(1, n): new_items = 0; for y in range (1,current_items): if (random.random() < 0.01): new_items =new_items +1 current_items=current_items+new_items; print "day=",y," m=",current_items return current_items total_items_accumulated = 0 for y in range(1,trials): total_items_accumulated += iterate_n_days(iteration_days,initial_items) average_items_accumulated = total_items_accumulated / trials print "average items after ", iteration_days, " days over", trials, " trials", average_items_accumulated print "This assumes that you are moving items to new MUFG capsules when the capsule reaches 90 or so items and keeping your inventory from becoming overfull." <commit_msg>Correct off by one error in trial count<commit_after>
#!/usr/bin/pyton from __future__ import division import random initial_items = int(raw_input("how many items do you have at the start?: ") or "50") iteration_days = int(raw_input("how many days do you have to multiple them?: ") or "100") trials = 1000 def iterate_n_days(n, initial_items): current_items = initial_items for x in range(1, n): new_items = 0; for y in range (1,current_items): if (random.random() < 0.01): new_items =new_items +1 current_items=current_items+new_items; print "day=",y," m=",current_items return current_items total_items_accumulated = 0 for y in range(trials): total_items_accumulated += iterate_n_days(iteration_days,initial_items) average_items_accumulated = total_items_accumulated / trials print "average items after ", iteration_days, " days over", trials, " trials", average_items_accumulated print "This assumes that you are moving items to new MUFG capsules when the capsule reaches 90 or so items and keeping your inventory from becoming overfull."
#!/usr/bin/pyton from __future__ import division import random initial_items = int(raw_input("how many items do you have at the start?: ") or "50") iteration_days = int(raw_input("how many days do you have to multiple them?: ") or "100") trials = 1000 def iterate_n_days(n, initial_items): current_items = initial_items for x in range(1, n): new_items = 0; for y in range (1,current_items): if (random.random() < 0.01): new_items =new_items +1 current_items=current_items+new_items; print "day=",y," m=",current_items return current_items total_items_accumulated = 0 for y in range(1,trials): total_items_accumulated += iterate_n_days(iteration_days,initial_items) average_items_accumulated = total_items_accumulated / trials print "average items after ", iteration_days, " days over", trials, " trials", average_items_accumulated print "This assumes that you are moving items to new MUFG capsules when the capsule reaches 90 or so items and keeping your inventory from becoming overfull." Correct off by one error in trial count#!/usr/bin/pyton from __future__ import division import random initial_items = int(raw_input("how many items do you have at the start?: ") or "50") iteration_days = int(raw_input("how many days do you have to multiple them?: ") or "100") trials = 1000 def iterate_n_days(n, initial_items): current_items = initial_items for x in range(1, n): new_items = 0; for y in range (1,current_items): if (random.random() < 0.01): new_items =new_items +1 current_items=current_items+new_items; print "day=",y," m=",current_items return current_items total_items_accumulated = 0 for y in range(trials): total_items_accumulated += iterate_n_days(iteration_days,initial_items) average_items_accumulated = total_items_accumulated / trials print "average items after ", iteration_days, " days over", trials, " trials", average_items_accumulated print "This assumes that you are moving items to new MUFG capsules when the capsule reaches 90 or so items and keeping your inventory from becoming overfull."
<commit_before>#!/usr/bin/pyton from __future__ import division import random initial_items = int(raw_input("how many items do you have at the start?: ") or "50") iteration_days = int(raw_input("how many days do you have to multiple them?: ") or "100") trials = 1000 def iterate_n_days(n, initial_items): current_items = initial_items for x in range(1, n): new_items = 0; for y in range (1,current_items): if (random.random() < 0.01): new_items =new_items +1 current_items=current_items+new_items; print "day=",y," m=",current_items return current_items total_items_accumulated = 0 for y in range(1,trials): total_items_accumulated += iterate_n_days(iteration_days,initial_items) average_items_accumulated = total_items_accumulated / trials print "average items after ", iteration_days, " days over", trials, " trials", average_items_accumulated print "This assumes that you are moving items to new MUFG capsules when the capsule reaches 90 or so items and keeping your inventory from becoming overfull." <commit_msg>Correct off by one error in trial count<commit_after>#!/usr/bin/pyton from __future__ import division import random initial_items = int(raw_input("how many items do you have at the start?: ") or "50") iteration_days = int(raw_input("how many days do you have to multiple them?: ") or "100") trials = 1000 def iterate_n_days(n, initial_items): current_items = initial_items for x in range(1, n): new_items = 0; for y in range (1,current_items): if (random.random() < 0.01): new_items =new_items +1 current_items=current_items+new_items; print "day=",y," m=",current_items return current_items total_items_accumulated = 0 for y in range(trials): total_items_accumulated += iterate_n_days(iteration_days,initial_items) average_items_accumulated = total_items_accumulated / trials print "average items after ", iteration_days, " days over", trials, " trials", average_items_accumulated print "This assumes that you are moving items to new MUFG capsules when the capsule reaches 90 or so items and keeping your inventory from becoming overfull."
1999e66070b02a30460c76d90787c7c20905363a
kboard/board/tests/test_templatetags.py
kboard/board/tests/test_templatetags.py
from .base import BoardAppTest from board.templatetags.url_parameter import url_parameter class UrlParameterTest(BoardAppTest): def test_contains_correct_string(self): parameter = { 'a': 13, 'query': 'hello', 'b': 'This is a test' } url_string = url_parameter(**parameter) self.assertRegex(url_string, '^\?.*') self.assertIn('a=13', url_string) self.assertIn('query=hello', url_string) self.assertIn('b=This+is+a+test', url_string)
from .base import BoardAppTest from board.templatetags.url_parameter import url_parameter from board.templatetags.hide_ip import hide_ip class UrlParameterTest(BoardAppTest): def test_contains_correct_string(self): parameter = { 'a': 13, 'query': 'hello', 'b': 'This is a test' } url_string = url_parameter(**parameter) self.assertRegex(url_string, '^\?.*') self.assertIn('a=13', url_string) self.assertIn('query=hello', url_string) self.assertIn('b=This+is+a+test', url_string) class HideIPTest(BoardAppTest): def test_can_hide_ip(self): ip = '127.0.0.1' self.assertEqual(hide_ip(ip), '127.0.xxx.1') ip2 = '192.168.132.3' self.assertEqual(hide_ip(ip2), '192.168.xxx.3')
Add test of hide ip template tag
Add test of hide ip template tag
Python
mit
kboard/kboard,cjh5414/kboard,hyesun03/k-board,hyesun03/k-board,hyesun03/k-board,kboard/kboard,guswnsxodlf/k-board,kboard/kboard,guswnsxodlf/k-board,cjh5414/kboard,guswnsxodlf/k-board,cjh5414/kboard,darjeeling/k-board
from .base import BoardAppTest from board.templatetags.url_parameter import url_parameter class UrlParameterTest(BoardAppTest): def test_contains_correct_string(self): parameter = { 'a': 13, 'query': 'hello', 'b': 'This is a test' } url_string = url_parameter(**parameter) self.assertRegex(url_string, '^\?.*') self.assertIn('a=13', url_string) self.assertIn('query=hello', url_string) self.assertIn('b=This+is+a+test', url_string) Add test of hide ip template tag
from .base import BoardAppTest from board.templatetags.url_parameter import url_parameter from board.templatetags.hide_ip import hide_ip class UrlParameterTest(BoardAppTest): def test_contains_correct_string(self): parameter = { 'a': 13, 'query': 'hello', 'b': 'This is a test' } url_string = url_parameter(**parameter) self.assertRegex(url_string, '^\?.*') self.assertIn('a=13', url_string) self.assertIn('query=hello', url_string) self.assertIn('b=This+is+a+test', url_string) class HideIPTest(BoardAppTest): def test_can_hide_ip(self): ip = '127.0.0.1' self.assertEqual(hide_ip(ip), '127.0.xxx.1') ip2 = '192.168.132.3' self.assertEqual(hide_ip(ip2), '192.168.xxx.3')
<commit_before>from .base import BoardAppTest from board.templatetags.url_parameter import url_parameter class UrlParameterTest(BoardAppTest): def test_contains_correct_string(self): parameter = { 'a': 13, 'query': 'hello', 'b': 'This is a test' } url_string = url_parameter(**parameter) self.assertRegex(url_string, '^\?.*') self.assertIn('a=13', url_string) self.assertIn('query=hello', url_string) self.assertIn('b=This+is+a+test', url_string) <commit_msg>Add test of hide ip template tag<commit_after>
from .base import BoardAppTest from board.templatetags.url_parameter import url_parameter from board.templatetags.hide_ip import hide_ip class UrlParameterTest(BoardAppTest): def test_contains_correct_string(self): parameter = { 'a': 13, 'query': 'hello', 'b': 'This is a test' } url_string = url_parameter(**parameter) self.assertRegex(url_string, '^\?.*') self.assertIn('a=13', url_string) self.assertIn('query=hello', url_string) self.assertIn('b=This+is+a+test', url_string) class HideIPTest(BoardAppTest): def test_can_hide_ip(self): ip = '127.0.0.1' self.assertEqual(hide_ip(ip), '127.0.xxx.1') ip2 = '192.168.132.3' self.assertEqual(hide_ip(ip2), '192.168.xxx.3')
from .base import BoardAppTest from board.templatetags.url_parameter import url_parameter class UrlParameterTest(BoardAppTest): def test_contains_correct_string(self): parameter = { 'a': 13, 'query': 'hello', 'b': 'This is a test' } url_string = url_parameter(**parameter) self.assertRegex(url_string, '^\?.*') self.assertIn('a=13', url_string) self.assertIn('query=hello', url_string) self.assertIn('b=This+is+a+test', url_string) Add test of hide ip template tagfrom .base import BoardAppTest from board.templatetags.url_parameter import url_parameter from board.templatetags.hide_ip import hide_ip class UrlParameterTest(BoardAppTest): def test_contains_correct_string(self): parameter = { 'a': 13, 'query': 'hello', 'b': 'This is a test' } url_string = url_parameter(**parameter) self.assertRegex(url_string, '^\?.*') self.assertIn('a=13', url_string) self.assertIn('query=hello', url_string) self.assertIn('b=This+is+a+test', url_string) class HideIPTest(BoardAppTest): def test_can_hide_ip(self): ip = '127.0.0.1' self.assertEqual(hide_ip(ip), '127.0.xxx.1') ip2 = '192.168.132.3' self.assertEqual(hide_ip(ip2), '192.168.xxx.3')
<commit_before>from .base import BoardAppTest from board.templatetags.url_parameter import url_parameter class UrlParameterTest(BoardAppTest): def test_contains_correct_string(self): parameter = { 'a': 13, 'query': 'hello', 'b': 'This is a test' } url_string = url_parameter(**parameter) self.assertRegex(url_string, '^\?.*') self.assertIn('a=13', url_string) self.assertIn('query=hello', url_string) self.assertIn('b=This+is+a+test', url_string) <commit_msg>Add test of hide ip template tag<commit_after>from .base import BoardAppTest from board.templatetags.url_parameter import url_parameter from board.templatetags.hide_ip import hide_ip class UrlParameterTest(BoardAppTest): def test_contains_correct_string(self): parameter = { 'a': 13, 'query': 'hello', 'b': 'This is a test' } url_string = url_parameter(**parameter) self.assertRegex(url_string, '^\?.*') self.assertIn('a=13', url_string) self.assertIn('query=hello', url_string) self.assertIn('b=This+is+a+test', url_string) class HideIPTest(BoardAppTest): def test_can_hide_ip(self): ip = '127.0.0.1' self.assertEqual(hide_ip(ip), '127.0.xxx.1') ip2 = '192.168.132.3' self.assertEqual(hide_ip(ip2), '192.168.xxx.3')
32e066988a902f19d171225891f0a52a13945526
frappe/patches/v12_0/move_form_attachments_to_attachments_folder.py
frappe/patches/v12_0/move_form_attachments_to_attachments_folder.py
import frappe def execute(): frappe.db.sql(''' UPDATE tabFile SET folder = 'Home/Attachments' WHERE ifnull(attached_to_doctype, '') != '' ''')
import frappe def execute(): frappe.db.sql(''' UPDATE tabFile SET folder = 'Home/Attachments' WHERE ifnull(attached_to_doctype, '') != '' AND folder = 'Home' ''')
Move files only from Home folder
fix(patch): Move files only from Home folder
Python
mit
mhbu50/frappe,frappe/frappe,vjFaLk/frappe,adityahase/frappe,adityahase/frappe,mhbu50/frappe,mhbu50/frappe,vjFaLk/frappe,vjFaLk/frappe,StrellaGroup/frappe,yashodhank/frappe,yashodhank/frappe,frappe/frappe,almeidapaulopt/frappe,yashodhank/frappe,StrellaGroup/frappe,yashodhank/frappe,vjFaLk/frappe,saurabh6790/frappe,mhbu50/frappe,adityahase/frappe,saurabh6790/frappe,almeidapaulopt/frappe,adityahase/frappe,almeidapaulopt/frappe,almeidapaulopt/frappe,saurabh6790/frappe,frappe/frappe,StrellaGroup/frappe,saurabh6790/frappe
import frappe def execute(): frappe.db.sql(''' UPDATE tabFile SET folder = 'Home/Attachments' WHERE ifnull(attached_to_doctype, '') != '' ''') fix(patch): Move files only from Home folder
import frappe def execute(): frappe.db.sql(''' UPDATE tabFile SET folder = 'Home/Attachments' WHERE ifnull(attached_to_doctype, '') != '' AND folder = 'Home' ''')
<commit_before>import frappe def execute(): frappe.db.sql(''' UPDATE tabFile SET folder = 'Home/Attachments' WHERE ifnull(attached_to_doctype, '') != '' ''') <commit_msg>fix(patch): Move files only from Home folder<commit_after>
import frappe def execute(): frappe.db.sql(''' UPDATE tabFile SET folder = 'Home/Attachments' WHERE ifnull(attached_to_doctype, '') != '' AND folder = 'Home' ''')
import frappe def execute(): frappe.db.sql(''' UPDATE tabFile SET folder = 'Home/Attachments' WHERE ifnull(attached_to_doctype, '') != '' ''') fix(patch): Move files only from Home folderimport frappe def execute(): frappe.db.sql(''' UPDATE tabFile SET folder = 'Home/Attachments' WHERE ifnull(attached_to_doctype, '') != '' AND folder = 'Home' ''')
<commit_before>import frappe def execute(): frappe.db.sql(''' UPDATE tabFile SET folder = 'Home/Attachments' WHERE ifnull(attached_to_doctype, '') != '' ''') <commit_msg>fix(patch): Move files only from Home folder<commit_after>import frappe def execute(): frappe.db.sql(''' UPDATE tabFile SET folder = 'Home/Attachments' WHERE ifnull(attached_to_doctype, '') != '' AND folder = 'Home' ''')
fe3559103917f6e9b61d0f6515502e3e530896cf
inidiff/cli.py
inidiff/cli.py
from __future__ import print_function from . import diff import argparse RED = '\033[1;31m' GREEN = '\033[1;32m' END = '\033[0m' def format_option(opt): """Return a formatted option in the form name=value.""" return '{}={}\n'.format(opt.option, opt.value) def format_output(first, second, color=True): """Return a string showing the differences between two ini strings.""" diffs = diff(first, second) sections = set() out = '' for d in diffs: if d.first.section not in sections: out += '[{}]\n'.format(d.first.section) sections.add(d.first.section) if d.first.value is not None: if color: out += RED out += '-' + format_option(d.first) if color: out += END if d.second.value is not None: if color: out += GREEN out += '+' + format_option(d.second) if color: out += END return out def main(): """Run the main CLI.""" parser = argparse.ArgumentParser() parser.add_argument('first', type=argparse.FileType('r')) parser.add_argument('second', type=argparse.FileType('r')) args = parser.parse_args() first = args.first.read() second = args.second.read() print(format_output(first, second), end='')
from __future__ import print_function import argparse import sys from . import diff RED = '\033[1;31m' GREEN = '\033[1;32m' END = '\033[0m' def format_option(opt): """Return a formatted option in the form name=value.""" return '{}={}\n'.format(opt.option, opt.value) def format_output(first, second, color=True): """Return a string showing the differences between two ini strings.""" diffs = diff(first, second) sections = set() out = '' for d in diffs: if d.first.section not in sections: out += '[{}]\n'.format(d.first.section) sections.add(d.first.section) if d.first.value is not None: if color: out += RED out += '-' + format_option(d.first) if color: out += END if d.second.value is not None: if color: out += GREEN out += '+' + format_option(d.second) if color: out += END return out def main(): """Run the main CLI.""" parser = argparse.ArgumentParser() parser.add_argument('first', type=argparse.FileType('r')) parser.add_argument('second', type=argparse.FileType('r')) args = parser.parse_args() first = args.first.read() second = args.second.read() out = format_output(first, second) print(out, end='') if out: sys.exit(1)
Exit with 1 if there's a difference
Exit with 1 if there's a difference
Python
mit
kragniz/inidiff
from __future__ import print_function from . import diff import argparse RED = '\033[1;31m' GREEN = '\033[1;32m' END = '\033[0m' def format_option(opt): """Return a formatted option in the form name=value.""" return '{}={}\n'.format(opt.option, opt.value) def format_output(first, second, color=True): """Return a string showing the differences between two ini strings.""" diffs = diff(first, second) sections = set() out = '' for d in diffs: if d.first.section not in sections: out += '[{}]\n'.format(d.first.section) sections.add(d.first.section) if d.first.value is not None: if color: out += RED out += '-' + format_option(d.first) if color: out += END if d.second.value is not None: if color: out += GREEN out += '+' + format_option(d.second) if color: out += END return out def main(): """Run the main CLI.""" parser = argparse.ArgumentParser() parser.add_argument('first', type=argparse.FileType('r')) parser.add_argument('second', type=argparse.FileType('r')) args = parser.parse_args() first = args.first.read() second = args.second.read() print(format_output(first, second), end='') Exit with 1 if there's a difference
from __future__ import print_function import argparse import sys from . import diff RED = '\033[1;31m' GREEN = '\033[1;32m' END = '\033[0m' def format_option(opt): """Return a formatted option in the form name=value.""" return '{}={}\n'.format(opt.option, opt.value) def format_output(first, second, color=True): """Return a string showing the differences between two ini strings.""" diffs = diff(first, second) sections = set() out = '' for d in diffs: if d.first.section not in sections: out += '[{}]\n'.format(d.first.section) sections.add(d.first.section) if d.first.value is not None: if color: out += RED out += '-' + format_option(d.first) if color: out += END if d.second.value is not None: if color: out += GREEN out += '+' + format_option(d.second) if color: out += END return out def main(): """Run the main CLI.""" parser = argparse.ArgumentParser() parser.add_argument('first', type=argparse.FileType('r')) parser.add_argument('second', type=argparse.FileType('r')) args = parser.parse_args() first = args.first.read() second = args.second.read() out = format_output(first, second) print(out, end='') if out: sys.exit(1)
<commit_before>from __future__ import print_function from . import diff import argparse RED = '\033[1;31m' GREEN = '\033[1;32m' END = '\033[0m' def format_option(opt): """Return a formatted option in the form name=value.""" return '{}={}\n'.format(opt.option, opt.value) def format_output(first, second, color=True): """Return a string showing the differences between two ini strings.""" diffs = diff(first, second) sections = set() out = '' for d in diffs: if d.first.section not in sections: out += '[{}]\n'.format(d.first.section) sections.add(d.first.section) if d.first.value is not None: if color: out += RED out += '-' + format_option(d.first) if color: out += END if d.second.value is not None: if color: out += GREEN out += '+' + format_option(d.second) if color: out += END return out def main(): """Run the main CLI.""" parser = argparse.ArgumentParser() parser.add_argument('first', type=argparse.FileType('r')) parser.add_argument('second', type=argparse.FileType('r')) args = parser.parse_args() first = args.first.read() second = args.second.read() print(format_output(first, second), end='') <commit_msg>Exit with 1 if there's a difference<commit_after>
from __future__ import print_function import argparse import sys from . import diff RED = '\033[1;31m' GREEN = '\033[1;32m' END = '\033[0m' def format_option(opt): """Return a formatted option in the form name=value.""" return '{}={}\n'.format(opt.option, opt.value) def format_output(first, second, color=True): """Return a string showing the differences between two ini strings.""" diffs = diff(first, second) sections = set() out = '' for d in diffs: if d.first.section not in sections: out += '[{}]\n'.format(d.first.section) sections.add(d.first.section) if d.first.value is not None: if color: out += RED out += '-' + format_option(d.first) if color: out += END if d.second.value is not None: if color: out += GREEN out += '+' + format_option(d.second) if color: out += END return out def main(): """Run the main CLI.""" parser = argparse.ArgumentParser() parser.add_argument('first', type=argparse.FileType('r')) parser.add_argument('second', type=argparse.FileType('r')) args = parser.parse_args() first = args.first.read() second = args.second.read() out = format_output(first, second) print(out, end='') if out: sys.exit(1)
from __future__ import print_function from . import diff import argparse RED = '\033[1;31m' GREEN = '\033[1;32m' END = '\033[0m' def format_option(opt): """Return a formatted option in the form name=value.""" return '{}={}\n'.format(opt.option, opt.value) def format_output(first, second, color=True): """Return a string showing the differences between two ini strings.""" diffs = diff(first, second) sections = set() out = '' for d in diffs: if d.first.section not in sections: out += '[{}]\n'.format(d.first.section) sections.add(d.first.section) if d.first.value is not None: if color: out += RED out += '-' + format_option(d.first) if color: out += END if d.second.value is not None: if color: out += GREEN out += '+' + format_option(d.second) if color: out += END return out def main(): """Run the main CLI.""" parser = argparse.ArgumentParser() parser.add_argument('first', type=argparse.FileType('r')) parser.add_argument('second', type=argparse.FileType('r')) args = parser.parse_args() first = args.first.read() second = args.second.read() print(format_output(first, second), end='') Exit with 1 if there's a differencefrom __future__ import print_function import argparse import sys from . import diff RED = '\033[1;31m' GREEN = '\033[1;32m' END = '\033[0m' def format_option(opt): """Return a formatted option in the form name=value.""" return '{}={}\n'.format(opt.option, opt.value) def format_output(first, second, color=True): """Return a string showing the differences between two ini strings.""" diffs = diff(first, second) sections = set() out = '' for d in diffs: if d.first.section not in sections: out += '[{}]\n'.format(d.first.section) sections.add(d.first.section) if d.first.value is not None: if color: out += RED out += '-' + format_option(d.first) if color: out += END if d.second.value is not None: if color: out += GREEN out += '+' + format_option(d.second) if color: out += END return out def main(): """Run the main CLI.""" parser = argparse.ArgumentParser() parser.add_argument('first', type=argparse.FileType('r')) parser.add_argument('second', type=argparse.FileType('r')) args = parser.parse_args() first = args.first.read() second = args.second.read() out = format_output(first, second) print(out, end='') if out: sys.exit(1)
<commit_before>from __future__ import print_function from . import diff import argparse RED = '\033[1;31m' GREEN = '\033[1;32m' END = '\033[0m' def format_option(opt): """Return a formatted option in the form name=value.""" return '{}={}\n'.format(opt.option, opt.value) def format_output(first, second, color=True): """Return a string showing the differences between two ini strings.""" diffs = diff(first, second) sections = set() out = '' for d in diffs: if d.first.section not in sections: out += '[{}]\n'.format(d.first.section) sections.add(d.first.section) if d.first.value is not None: if color: out += RED out += '-' + format_option(d.first) if color: out += END if d.second.value is not None: if color: out += GREEN out += '+' + format_option(d.second) if color: out += END return out def main(): """Run the main CLI.""" parser = argparse.ArgumentParser() parser.add_argument('first', type=argparse.FileType('r')) parser.add_argument('second', type=argparse.FileType('r')) args = parser.parse_args() first = args.first.read() second = args.second.read() print(format_output(first, second), end='') <commit_msg>Exit with 1 if there's a difference<commit_after>from __future__ import print_function import argparse import sys from . import diff RED = '\033[1;31m' GREEN = '\033[1;32m' END = '\033[0m' def format_option(opt): """Return a formatted option in the form name=value.""" return '{}={}\n'.format(opt.option, opt.value) def format_output(first, second, color=True): """Return a string showing the differences between two ini strings.""" diffs = diff(first, second) sections = set() out = '' for d in diffs: if d.first.section not in sections: out += '[{}]\n'.format(d.first.section) sections.add(d.first.section) if d.first.value is not None: if color: out += RED out += '-' + format_option(d.first) if color: out += END if d.second.value is not None: if color: out += GREEN out += '+' + format_option(d.second) if color: out += END return out def main(): """Run the main CLI.""" parser = argparse.ArgumentParser() parser.add_argument('first', type=argparse.FileType('r')) parser.add_argument('second', type=argparse.FileType('r')) args = parser.parse_args() first = args.first.read() second = args.second.read() out = format_output(first, second) print(out, end='') if out: sys.exit(1)
5227ef25d9944c5e33b4a4f7e58259e3646ae52a
interactive.py
interactive.py
#Main program executor import pyRecipeBook import FoodGroups #Welcome screen welcomeMessage = "Welcome to pyRecipeBook!\n" welcomeMessage += "Enter a command below:\n" print(welcomeMessage) # pre = '# ' on = True #Keep asking for inpyt while(on): command = input(pre) #Run command #Exiting commands "Thank you for choosing to use pyRecipeBook"
#Main program executor import pyRecipeBook import FoodGroups #Welcome screen welcomeMessage = "Welcome to pyRecipeBook!\n" welcomeMessage += "Enter a command below:\n" print(welcomeMessage) #Method to run commands def runCommand(command): if command.strip() == 'exit': return False else: return True # pre = '# ' on = True #Keep asking for inpyt while(on): #Enter a command command = raw_input(pre) #Run command on = runCommand(command) #Exiting commands exitMessage = "\nThank you for choosing to use pyRecipeBook!\n" print(exitMessage)
Update interacitve.py - Add a method to run predefined commands.
Update interacitve.py - Add a method to run predefined commands.
Python
mit
VictorLoren/pyRecipeBook
#Main program executor import pyRecipeBook import FoodGroups #Welcome screen welcomeMessage = "Welcome to pyRecipeBook!\n" welcomeMessage += "Enter a command below:\n" print(welcomeMessage) # pre = '# ' on = True #Keep asking for inpyt while(on): command = input(pre) #Run command #Exiting commands "Thank you for choosing to use pyRecipeBook"Update interacitve.py - Add a method to run predefined commands.
#Main program executor import pyRecipeBook import FoodGroups #Welcome screen welcomeMessage = "Welcome to pyRecipeBook!\n" welcomeMessage += "Enter a command below:\n" print(welcomeMessage) #Method to run commands def runCommand(command): if command.strip() == 'exit': return False else: return True # pre = '# ' on = True #Keep asking for inpyt while(on): #Enter a command command = raw_input(pre) #Run command on = runCommand(command) #Exiting commands exitMessage = "\nThank you for choosing to use pyRecipeBook!\n" print(exitMessage)
<commit_before>#Main program executor import pyRecipeBook import FoodGroups #Welcome screen welcomeMessage = "Welcome to pyRecipeBook!\n" welcomeMessage += "Enter a command below:\n" print(welcomeMessage) # pre = '# ' on = True #Keep asking for inpyt while(on): command = input(pre) #Run command #Exiting commands "Thank you for choosing to use pyRecipeBook"<commit_msg>Update interacitve.py - Add a method to run predefined commands.<commit_after>
#Main program executor import pyRecipeBook import FoodGroups #Welcome screen welcomeMessage = "Welcome to pyRecipeBook!\n" welcomeMessage += "Enter a command below:\n" print(welcomeMessage) #Method to run commands def runCommand(command): if command.strip() == 'exit': return False else: return True # pre = '# ' on = True #Keep asking for inpyt while(on): #Enter a command command = raw_input(pre) #Run command on = runCommand(command) #Exiting commands exitMessage = "\nThank you for choosing to use pyRecipeBook!\n" print(exitMessage)
#Main program executor import pyRecipeBook import FoodGroups #Welcome screen welcomeMessage = "Welcome to pyRecipeBook!\n" welcomeMessage += "Enter a command below:\n" print(welcomeMessage) # pre = '# ' on = True #Keep asking for inpyt while(on): command = input(pre) #Run command #Exiting commands "Thank you for choosing to use pyRecipeBook"Update interacitve.py - Add a method to run predefined commands.#Main program executor import pyRecipeBook import FoodGroups #Welcome screen welcomeMessage = "Welcome to pyRecipeBook!\n" welcomeMessage += "Enter a command below:\n" print(welcomeMessage) #Method to run commands def runCommand(command): if command.strip() == 'exit': return False else: return True # pre = '# ' on = True #Keep asking for inpyt while(on): #Enter a command command = raw_input(pre) #Run command on = runCommand(command) #Exiting commands exitMessage = "\nThank you for choosing to use pyRecipeBook!\n" print(exitMessage)
<commit_before>#Main program executor import pyRecipeBook import FoodGroups #Welcome screen welcomeMessage = "Welcome to pyRecipeBook!\n" welcomeMessage += "Enter a command below:\n" print(welcomeMessage) # pre = '# ' on = True #Keep asking for inpyt while(on): command = input(pre) #Run command #Exiting commands "Thank you for choosing to use pyRecipeBook"<commit_msg>Update interacitve.py - Add a method to run predefined commands.<commit_after>#Main program executor import pyRecipeBook import FoodGroups #Welcome screen welcomeMessage = "Welcome to pyRecipeBook!\n" welcomeMessage += "Enter a command below:\n" print(welcomeMessage) #Method to run commands def runCommand(command): if command.strip() == 'exit': return False else: return True # pre = '# ' on = True #Keep asking for inpyt while(on): #Enter a command command = raw_input(pre) #Run command on = runCommand(command) #Exiting commands exitMessage = "\nThank you for choosing to use pyRecipeBook!\n" print(exitMessage)
aa65464c86c562a690ba42901fa9dc24f17ba714
xbrowse_server/base/management/commands/add_project.py
xbrowse_server/base/management/commands/add_project.py
from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project class Command(BaseCommand): def handle(self, *args, **options): project_id = args[0] if Project.objects.filter(project_id=project_id).exists(): raise Exception("Project exists :(") Project.objects.create(project_id=project_id)
from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project import sys class Command(BaseCommand): def handle(self, *args, **options): project_id = args[0] if "." in project_id: sys.exit("ERROR: A '.' in the project ID is not supported") if Project.objects.filter(project_id=project_id).exists(): raise Exception("Project exists :(") Project.objects.create(project_id=project_id)
Print error if dot in project ids
Print error if dot in project ids
Python
agpl-3.0
ssadedin/seqr,ssadedin/seqr,macarthur-lab/xbrowse,macarthur-lab/seqr,macarthur-lab/xbrowse,macarthur-lab/xbrowse,macarthur-lab/seqr,macarthur-lab/seqr,macarthur-lab/xbrowse,macarthur-lab/seqr,macarthur-lab/xbrowse,macarthur-lab/seqr,ssadedin/seqr,macarthur-lab/xbrowse,ssadedin/seqr,ssadedin/seqr
from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project class Command(BaseCommand): def handle(self, *args, **options): project_id = args[0] if Project.objects.filter(project_id=project_id).exists(): raise Exception("Project exists :(") Project.objects.create(project_id=project_id)Print error if dot in project ids
from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project import sys class Command(BaseCommand): def handle(self, *args, **options): project_id = args[0] if "." in project_id: sys.exit("ERROR: A '.' in the project ID is not supported") if Project.objects.filter(project_id=project_id).exists(): raise Exception("Project exists :(") Project.objects.create(project_id=project_id)
<commit_before>from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project class Command(BaseCommand): def handle(self, *args, **options): project_id = args[0] if Project.objects.filter(project_id=project_id).exists(): raise Exception("Project exists :(") Project.objects.create(project_id=project_id)<commit_msg>Print error if dot in project ids<commit_after>
from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project import sys class Command(BaseCommand): def handle(self, *args, **options): project_id = args[0] if "." in project_id: sys.exit("ERROR: A '.' in the project ID is not supported") if Project.objects.filter(project_id=project_id).exists(): raise Exception("Project exists :(") Project.objects.create(project_id=project_id)
from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project class Command(BaseCommand): def handle(self, *args, **options): project_id = args[0] if Project.objects.filter(project_id=project_id).exists(): raise Exception("Project exists :(") Project.objects.create(project_id=project_id)Print error if dot in project idsfrom django.core.management.base import BaseCommand from xbrowse_server.base.models import Project import sys class Command(BaseCommand): def handle(self, *args, **options): project_id = args[0] if "." in project_id: sys.exit("ERROR: A '.' in the project ID is not supported") if Project.objects.filter(project_id=project_id).exists(): raise Exception("Project exists :(") Project.objects.create(project_id=project_id)
<commit_before>from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project class Command(BaseCommand): def handle(self, *args, **options): project_id = args[0] if Project.objects.filter(project_id=project_id).exists(): raise Exception("Project exists :(") Project.objects.create(project_id=project_id)<commit_msg>Print error if dot in project ids<commit_after>from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project import sys class Command(BaseCommand): def handle(self, *args, **options): project_id = args[0] if "." in project_id: sys.exit("ERROR: A '.' in the project ID is not supported") if Project.objects.filter(project_id=project_id).exists(): raise Exception("Project exists :(") Project.objects.create(project_id=project_id)
1b7509d8bd624bbf33352f622d8c03be6f3e35f2
src/sentry/api/serializers/models/organization_member.py
src/sentry/api/serializers/models/organization_member.py
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import OrganizationMember @register(OrganizationMember) class OrganizationMemberSerializer(Serializer): def serialize(self, obj, attrs, user): d = { 'id': str(obj.id), 'email': obj.email or obj.user.email, 'access': obj.get_type_display(), 'pending': obj.is_pending, 'dateCreated': obj.date_added, } return d
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import OrganizationMember from sentry.utils.avatar import get_gravatar_url @register(OrganizationMember) class OrganizationMemberSerializer(Serializer): def serialize(self, obj, attrs, user): d = { 'id': str(obj.id), 'email': obj.email or obj.user.email, 'access': obj.get_type_display(), 'pending': obj.is_pending, 'dateCreated': obj.date_added, 'avatarUrl': get_gravatar_url(obj.email, size=32), } return d
Add avatarUrl to team member serializers
Add avatarUrl to team member serializers Conflicts: src/sentry/api/serializers/models/organization_member.py src/sentry/api/serializers/models/release.py cherry-pick 8ee1bee748ae7f51987ea8ec5ee10795b656cfd9
Python
bsd-3-clause
jean/sentry,gencer/sentry,looker/sentry,ngonzalvez/sentry,gg7/sentry,mvaled/sentry,nicholasserra/sentry,wong2/sentry,beeftornado/sentry,JamesMura/sentry,alexm92/sentry,JamesMura/sentry,korealerts1/sentry,wujuguang/sentry,BayanGroup/sentry,imankulov/sentry,fotinakis/sentry,JTCunning/sentry,kevinlondon/sentry,jean/sentry,gencer/sentry,hongliang5623/sentry,TedaLIEz/sentry,looker/sentry,pauloschilling/sentry,llonchj/sentry,llonchj/sentry,hongliang5623/sentry,Natim/sentry,wong2/sentry,BuildingLink/sentry,fuziontech/sentry,daevaorn/sentry,jokey2k/sentry,argonemyth/sentry,zenefits/sentry,nicholasserra/sentry,daevaorn/sentry,mvaled/sentry,nicholasserra/sentry,ifduyue/sentry,ngonzalvez/sentry,vperron/sentry,ifduyue/sentry,JTCunning/sentry,gencer/sentry,beeftornado/sentry,gg7/sentry,ewdurbin/sentry,mvaled/sentry,fotinakis/sentry,JTCunning/sentry,BayanGroup/sentry,vperron/sentry,drcapulet/sentry,felixbuenemann/sentry,zenefits/sentry,camilonova/sentry,korealerts1/sentry,JackDanger/sentry,kevinastone/sentry,fuziontech/sentry,kevinlondon/sentry,BuildingLink/sentry,alexm92/sentry,kevinlondon/sentry,korealerts1/sentry,drcapulet/sentry,wong2/sentry,pauloschilling/sentry,JamesMura/sentry,kevinastone/sentry,JackDanger/sentry,looker/sentry,daevaorn/sentry,Kryz/sentry,jean/sentry,felixbuenemann/sentry,looker/sentry,Natim/sentry,1tush/sentry,TedaLIEz/sentry,beeftornado/sentry,JamesMura/sentry,ifduyue/sentry,JamesMura/sentry,felixbuenemann/sentry,mvaled/sentry,boneyao/sentry,zenefits/sentry,looker/sentry,Kryz/sentry,zenefits/sentry,argonemyth/sentry,jokey2k/sentry,camilonova/sentry,Natim/sentry,daevaorn/sentry,jean/sentry,mvaled/sentry,wujuguang/sentry,BuildingLink/sentry,wujuguang/sentry,imankulov/sentry,ewdurbin/sentry,fotinakis/sentry,argonemyth/sentry,hongliang5623/sentry,ifduyue/sentry,llonchj/sentry,drcapulet/sentry,1tush/sentry,ewdurbin/sentry,songyi199111/sentry,gg7/sentry,fotinakis/sentry,songyi199111/sentry,Kryz/sentry,boneyao/sentry,jean/sentry,1tush/sentry,jokey2k/sentry,vperron/sentry,fuziontech/sentry,zenefits/sentry,TedaLIEz/sentry,gencer/sentry,kevinastone/sentry,songyi199111/sentry,boneyao/sentry,JackDanger/sentry,mitsuhiko/sentry,BuildingLink/sentry,alexm92/sentry,ngonzalvez/sentry,mvaled/sentry,pauloschilling/sentry,mitsuhiko/sentry,BayanGroup/sentry,imankulov/sentry,ifduyue/sentry,camilonova/sentry,BuildingLink/sentry,gencer/sentry
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import OrganizationMember @register(OrganizationMember) class OrganizationMemberSerializer(Serializer): def serialize(self, obj, attrs, user): d = { 'id': str(obj.id), 'email': obj.email or obj.user.email, 'access': obj.get_type_display(), 'pending': obj.is_pending, 'dateCreated': obj.date_added, } return d Add avatarUrl to team member serializers Conflicts: src/sentry/api/serializers/models/organization_member.py src/sentry/api/serializers/models/release.py cherry-pick 8ee1bee748ae7f51987ea8ec5ee10795b656cfd9
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import OrganizationMember from sentry.utils.avatar import get_gravatar_url @register(OrganizationMember) class OrganizationMemberSerializer(Serializer): def serialize(self, obj, attrs, user): d = { 'id': str(obj.id), 'email': obj.email or obj.user.email, 'access': obj.get_type_display(), 'pending': obj.is_pending, 'dateCreated': obj.date_added, 'avatarUrl': get_gravatar_url(obj.email, size=32), } return d
<commit_before>from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import OrganizationMember @register(OrganizationMember) class OrganizationMemberSerializer(Serializer): def serialize(self, obj, attrs, user): d = { 'id': str(obj.id), 'email': obj.email or obj.user.email, 'access': obj.get_type_display(), 'pending': obj.is_pending, 'dateCreated': obj.date_added, } return d <commit_msg>Add avatarUrl to team member serializers Conflicts: src/sentry/api/serializers/models/organization_member.py src/sentry/api/serializers/models/release.py cherry-pick 8ee1bee748ae7f51987ea8ec5ee10795b656cfd9<commit_after>
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import OrganizationMember from sentry.utils.avatar import get_gravatar_url @register(OrganizationMember) class OrganizationMemberSerializer(Serializer): def serialize(self, obj, attrs, user): d = { 'id': str(obj.id), 'email': obj.email or obj.user.email, 'access': obj.get_type_display(), 'pending': obj.is_pending, 'dateCreated': obj.date_added, 'avatarUrl': get_gravatar_url(obj.email, size=32), } return d
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import OrganizationMember @register(OrganizationMember) class OrganizationMemberSerializer(Serializer): def serialize(self, obj, attrs, user): d = { 'id': str(obj.id), 'email': obj.email or obj.user.email, 'access': obj.get_type_display(), 'pending': obj.is_pending, 'dateCreated': obj.date_added, } return d Add avatarUrl to team member serializers Conflicts: src/sentry/api/serializers/models/organization_member.py src/sentry/api/serializers/models/release.py cherry-pick 8ee1bee748ae7f51987ea8ec5ee10795b656cfd9from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import OrganizationMember from sentry.utils.avatar import get_gravatar_url @register(OrganizationMember) class OrganizationMemberSerializer(Serializer): def serialize(self, obj, attrs, user): d = { 'id': str(obj.id), 'email': obj.email or obj.user.email, 'access': obj.get_type_display(), 'pending': obj.is_pending, 'dateCreated': obj.date_added, 'avatarUrl': get_gravatar_url(obj.email, size=32), } return d
<commit_before>from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import OrganizationMember @register(OrganizationMember) class OrganizationMemberSerializer(Serializer): def serialize(self, obj, attrs, user): d = { 'id': str(obj.id), 'email': obj.email or obj.user.email, 'access': obj.get_type_display(), 'pending': obj.is_pending, 'dateCreated': obj.date_added, } return d <commit_msg>Add avatarUrl to team member serializers Conflicts: src/sentry/api/serializers/models/organization_member.py src/sentry/api/serializers/models/release.py cherry-pick 8ee1bee748ae7f51987ea8ec5ee10795b656cfd9<commit_after>from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import OrganizationMember from sentry.utils.avatar import get_gravatar_url @register(OrganizationMember) class OrganizationMemberSerializer(Serializer): def serialize(self, obj, attrs, user): d = { 'id': str(obj.id), 'email': obj.email or obj.user.email, 'access': obj.get_type_display(), 'pending': obj.is_pending, 'dateCreated': obj.date_added, 'avatarUrl': get_gravatar_url(obj.email, size=32), } return d
91ea026fa0c354c81cf0a1e52dbbe626b83a00f8
app.py
app.py
import feedparser from flask import Flask, render_template app = Flask(__name__) BBC_FEED = "http://feeds.bbci.co.uk/news/rss.xml" @app.route("/") def index(): feed = feedparser.parse(BBC_FEED) return render_template("index.html", feed=feed.get('entries')) if __name__ == "__main__": app.run()
import requests from flask import Flask, render_template app = Flask(__name__) BBC_FEED = "http://feeds.bbci.co.uk/news/rss.xml" API_KEY = "c4002216fa5446d582b5f31d73959d36" @app.route("/") def index(): r = requests.get( f"https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey={API_KEY}" ) return render_template("index.html", articles=r.json().get("articles")) if __name__ == "__main__": app.run()
Use requests instead of feedparser.
Use requests instead of feedparser.
Python
mit
alchermd/headlines,alchermd/headlines
import feedparser from flask import Flask, render_template app = Flask(__name__) BBC_FEED = "http://feeds.bbci.co.uk/news/rss.xml" @app.route("/") def index(): feed = feedparser.parse(BBC_FEED) return render_template("index.html", feed=feed.get('entries')) if __name__ == "__main__": app.run()Use requests instead of feedparser.
import requests from flask import Flask, render_template app = Flask(__name__) BBC_FEED = "http://feeds.bbci.co.uk/news/rss.xml" API_KEY = "c4002216fa5446d582b5f31d73959d36" @app.route("/") def index(): r = requests.get( f"https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey={API_KEY}" ) return render_template("index.html", articles=r.json().get("articles")) if __name__ == "__main__": app.run()
<commit_before>import feedparser from flask import Flask, render_template app = Flask(__name__) BBC_FEED = "http://feeds.bbci.co.uk/news/rss.xml" @app.route("/") def index(): feed = feedparser.parse(BBC_FEED) return render_template("index.html", feed=feed.get('entries')) if __name__ == "__main__": app.run()<commit_msg>Use requests instead of feedparser.<commit_after>
import requests from flask import Flask, render_template app = Flask(__name__) BBC_FEED = "http://feeds.bbci.co.uk/news/rss.xml" API_KEY = "c4002216fa5446d582b5f31d73959d36" @app.route("/") def index(): r = requests.get( f"https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey={API_KEY}" ) return render_template("index.html", articles=r.json().get("articles")) if __name__ == "__main__": app.run()
import feedparser from flask import Flask, render_template app = Flask(__name__) BBC_FEED = "http://feeds.bbci.co.uk/news/rss.xml" @app.route("/") def index(): feed = feedparser.parse(BBC_FEED) return render_template("index.html", feed=feed.get('entries')) if __name__ == "__main__": app.run()Use requests instead of feedparser.import requests from flask import Flask, render_template app = Flask(__name__) BBC_FEED = "http://feeds.bbci.co.uk/news/rss.xml" API_KEY = "c4002216fa5446d582b5f31d73959d36" @app.route("/") def index(): r = requests.get( f"https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey={API_KEY}" ) return render_template("index.html", articles=r.json().get("articles")) if __name__ == "__main__": app.run()
<commit_before>import feedparser from flask import Flask, render_template app = Flask(__name__) BBC_FEED = "http://feeds.bbci.co.uk/news/rss.xml" @app.route("/") def index(): feed = feedparser.parse(BBC_FEED) return render_template("index.html", feed=feed.get('entries')) if __name__ == "__main__": app.run()<commit_msg>Use requests instead of feedparser.<commit_after>import requests from flask import Flask, render_template app = Flask(__name__) BBC_FEED = "http://feeds.bbci.co.uk/news/rss.xml" API_KEY = "c4002216fa5446d582b5f31d73959d36" @app.route("/") def index(): r = requests.get( f"https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey={API_KEY}" ) return render_template("index.html", articles=r.json().get("articles")) if __name__ == "__main__": app.run()
79e23159c308a69896c464eda13c043dbbc8086e
thezombies/management/commands/validate_all_data_catalogs.py
thezombies/management/commands/validate_all_data_catalogs.py
from django.core.management.base import NoArgsCommand from thezombies.tasks.main import validate_data_catalogs class Command(NoArgsCommand): """Validate all of the agency data catalogs""" def handle_noargs(self): validator_group = validate_data_catalogs.delay() self.stdout.write(u"\nSpawned data catalog task group: {0}\n".format(validator_group.id))
from django.core.management.base import NoArgsCommand from thezombies.tasks.main import validate_data_catalogs class Command(NoArgsCommand): """Validate all of the agency data catalogs""" def handle_noargs(self, **options): validator_group = validate_data_catalogs.delay() self.stdout.write(u"\nSpawned data catalog task group: {0}\n".format(validator_group.id))
Fix options on NoArgsCommand. Huh.
Fix options on NoArgsCommand. Huh.
Python
bsd-3-clause
sunlightlabs/thezombies,sunlightlabs/thezombies,sunlightlabs/thezombies,sunlightlabs/thezombies
from django.core.management.base import NoArgsCommand from thezombies.tasks.main import validate_data_catalogs class Command(NoArgsCommand): """Validate all of the agency data catalogs""" def handle_noargs(self): validator_group = validate_data_catalogs.delay() self.stdout.write(u"\nSpawned data catalog task group: {0}\n".format(validator_group.id)) Fix options on NoArgsCommand. Huh.
from django.core.management.base import NoArgsCommand from thezombies.tasks.main import validate_data_catalogs class Command(NoArgsCommand): """Validate all of the agency data catalogs""" def handle_noargs(self, **options): validator_group = validate_data_catalogs.delay() self.stdout.write(u"\nSpawned data catalog task group: {0}\n".format(validator_group.id))
<commit_before>from django.core.management.base import NoArgsCommand from thezombies.tasks.main import validate_data_catalogs class Command(NoArgsCommand): """Validate all of the agency data catalogs""" def handle_noargs(self): validator_group = validate_data_catalogs.delay() self.stdout.write(u"\nSpawned data catalog task group: {0}\n".format(validator_group.id)) <commit_msg>Fix options on NoArgsCommand. Huh.<commit_after>
from django.core.management.base import NoArgsCommand from thezombies.tasks.main import validate_data_catalogs class Command(NoArgsCommand): """Validate all of the agency data catalogs""" def handle_noargs(self, **options): validator_group = validate_data_catalogs.delay() self.stdout.write(u"\nSpawned data catalog task group: {0}\n".format(validator_group.id))
from django.core.management.base import NoArgsCommand from thezombies.tasks.main import validate_data_catalogs class Command(NoArgsCommand): """Validate all of the agency data catalogs""" def handle_noargs(self): validator_group = validate_data_catalogs.delay() self.stdout.write(u"\nSpawned data catalog task group: {0}\n".format(validator_group.id)) Fix options on NoArgsCommand. Huh.from django.core.management.base import NoArgsCommand from thezombies.tasks.main import validate_data_catalogs class Command(NoArgsCommand): """Validate all of the agency data catalogs""" def handle_noargs(self, **options): validator_group = validate_data_catalogs.delay() self.stdout.write(u"\nSpawned data catalog task group: {0}\n".format(validator_group.id))
<commit_before>from django.core.management.base import NoArgsCommand from thezombies.tasks.main import validate_data_catalogs class Command(NoArgsCommand): """Validate all of the agency data catalogs""" def handle_noargs(self): validator_group = validate_data_catalogs.delay() self.stdout.write(u"\nSpawned data catalog task group: {0}\n".format(validator_group.id)) <commit_msg>Fix options on NoArgsCommand. Huh.<commit_after>from django.core.management.base import NoArgsCommand from thezombies.tasks.main import validate_data_catalogs class Command(NoArgsCommand): """Validate all of the agency data catalogs""" def handle_noargs(self, **options): validator_group = validate_data_catalogs.delay() self.stdout.write(u"\nSpawned data catalog task group: {0}\n".format(validator_group.id))
7ca17e79f8c3dba7bc04377e7746a383a281562d
serverless_helpers/__init__.py
serverless_helpers/__init__.py
# -*- coding: utf-8 -*- # MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com> import dotenv
# -*- coding: utf-8 -*- # MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com> from dotenv import load_dotenv, get_key, set_key, unset_key def load_envs(path): import os path, _ = os.path.split(path) if path == '/': # bail out when you reach top of the FS load_dotenv(os.path.join(path, '.env')) return # load higher envs first # closer-to-base environments need higher precedence. load_envs(path) load_dotenv(os.path.join(path, '.env'))
Add `load_envs` to take a base path and recurse up, looking for .envs
Add `load_envs` to take a base path and recurse up, looking for .envs
Python
mit
serverless/serverless-helpers-py
# -*- coding: utf-8 -*- # MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com> import dotenv Add `load_envs` to take a base path and recurse up, looking for .envs
# -*- coding: utf-8 -*- # MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com> from dotenv import load_dotenv, get_key, set_key, unset_key def load_envs(path): import os path, _ = os.path.split(path) if path == '/': # bail out when you reach top of the FS load_dotenv(os.path.join(path, '.env')) return # load higher envs first # closer-to-base environments need higher precedence. load_envs(path) load_dotenv(os.path.join(path, '.env'))
<commit_before># -*- coding: utf-8 -*- # MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com> import dotenv <commit_msg>Add `load_envs` to take a base path and recurse up, looking for .envs<commit_after>
# -*- coding: utf-8 -*- # MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com> from dotenv import load_dotenv, get_key, set_key, unset_key def load_envs(path): import os path, _ = os.path.split(path) if path == '/': # bail out when you reach top of the FS load_dotenv(os.path.join(path, '.env')) return # load higher envs first # closer-to-base environments need higher precedence. load_envs(path) load_dotenv(os.path.join(path, '.env'))
# -*- coding: utf-8 -*- # MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com> import dotenv Add `load_envs` to take a base path and recurse up, looking for .envs# -*- coding: utf-8 -*- # MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com> from dotenv import load_dotenv, get_key, set_key, unset_key def load_envs(path): import os path, _ = os.path.split(path) if path == '/': # bail out when you reach top of the FS load_dotenv(os.path.join(path, '.env')) return # load higher envs first # closer-to-base environments need higher precedence. load_envs(path) load_dotenv(os.path.join(path, '.env'))
<commit_before># -*- coding: utf-8 -*- # MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com> import dotenv <commit_msg>Add `load_envs` to take a base path and recurse up, looking for .envs<commit_after># -*- coding: utf-8 -*- # MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com> from dotenv import load_dotenv, get_key, set_key, unset_key def load_envs(path): import os path, _ = os.path.split(path) if path == '/': # bail out when you reach top of the FS load_dotenv(os.path.join(path, '.env')) return # load higher envs first # closer-to-base environments need higher precedence. load_envs(path) load_dotenv(os.path.join(path, '.env'))
4c019b149510f74f614240d031ef03f96fa017e4
lab_members/urls.py
lab_members/urls.py
from django.conf.urls import patterns, url from lab_members.views import ScientistListView, ScientistDetailView urlpatterns = patterns('', url(r'^$', ScientistListView.as_view(), name='scientist_list'), url(r'^(?P<slug>[^/]+)$', ScientistDetailView.as_view(), name='scientist_detail'), )
from django.conf.urls import patterns, url from lab_members.views import ScientistListView, ScientistDetailView urlpatterns = patterns('', url(r'^$', ScientistListView.as_view(), name='scientist_list'), url(r'^(?P<slug>[^/]+)/$', ScientistDetailView.as_view(), name='scientist_detail'), )
Add trailing '/' for scientist detail URL pattern
Add trailing '/' for scientist detail URL pattern
Python
bsd-3-clause
mfcovington/django-lab-members,mfcovington/django-lab-members,mfcovington/django-lab-members
from django.conf.urls import patterns, url from lab_members.views import ScientistListView, ScientistDetailView urlpatterns = patterns('', url(r'^$', ScientistListView.as_view(), name='scientist_list'), url(r'^(?P<slug>[^/]+)$', ScientistDetailView.as_view(), name='scientist_detail'), ) Add trailing '/' for scientist detail URL pattern
from django.conf.urls import patterns, url from lab_members.views import ScientistListView, ScientistDetailView urlpatterns = patterns('', url(r'^$', ScientistListView.as_view(), name='scientist_list'), url(r'^(?P<slug>[^/]+)/$', ScientistDetailView.as_view(), name='scientist_detail'), )
<commit_before>from django.conf.urls import patterns, url from lab_members.views import ScientistListView, ScientistDetailView urlpatterns = patterns('', url(r'^$', ScientistListView.as_view(), name='scientist_list'), url(r'^(?P<slug>[^/]+)$', ScientistDetailView.as_view(), name='scientist_detail'), ) <commit_msg>Add trailing '/' for scientist detail URL pattern<commit_after>
from django.conf.urls import patterns, url from lab_members.views import ScientistListView, ScientistDetailView urlpatterns = patterns('', url(r'^$', ScientistListView.as_view(), name='scientist_list'), url(r'^(?P<slug>[^/]+)/$', ScientistDetailView.as_view(), name='scientist_detail'), )
from django.conf.urls import patterns, url from lab_members.views import ScientistListView, ScientistDetailView urlpatterns = patterns('', url(r'^$', ScientistListView.as_view(), name='scientist_list'), url(r'^(?P<slug>[^/]+)$', ScientistDetailView.as_view(), name='scientist_detail'), ) Add trailing '/' for scientist detail URL patternfrom django.conf.urls import patterns, url from lab_members.views import ScientistListView, ScientistDetailView urlpatterns = patterns('', url(r'^$', ScientistListView.as_view(), name='scientist_list'), url(r'^(?P<slug>[^/]+)/$', ScientistDetailView.as_view(), name='scientist_detail'), )
<commit_before>from django.conf.urls import patterns, url from lab_members.views import ScientistListView, ScientistDetailView urlpatterns = patterns('', url(r'^$', ScientistListView.as_view(), name='scientist_list'), url(r'^(?P<slug>[^/]+)$', ScientistDetailView.as_view(), name='scientist_detail'), ) <commit_msg>Add trailing '/' for scientist detail URL pattern<commit_after>from django.conf.urls import patterns, url from lab_members.views import ScientistListView, ScientistDetailView urlpatterns = patterns('', url(r'^$', ScientistListView.as_view(), name='scientist_list'), url(r'^(?P<slug>[^/]+)/$', ScientistDetailView.as_view(), name='scientist_detail'), )
4d793c8790b714e7e923d276cc139d9ca70e5a7d
temba/msgs/migrations/0089_populate_broadcast_send_all.py
temba/msgs/migrations/0089_populate_broadcast_send_all.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-06 17:33 from __future__ import unicode_literals from django.db import migrations, models from temba.utils import chunk_list def do_populate_send_all(Broadcast): broadcast_ids = Broadcast.objects.all().values_list('id', flat=True) broadcast_count = len(broadcast_ids) if broadcast_count: print('Starting to update %d broadcasts send all field...' % broadcast_count) updated = 0 for chunk in chunk_list(broadcast_ids, 1000): Broadcast.objects.filter(pk__in=chunk).update(send_all=False) print("Updated %d of %d broadcasts" % (updated + len(chunk), broadcast_count)) def apply_as_migration(apps, schema_editor): Broadcast = apps.get_model('msgs', 'Broadcast') do_populate_send_all(Broadcast) def apply_manual(): from temba.msgs.models import Broadcast do_populate_send_all(Broadcast) class Migration(migrations.Migration): dependencies = [ ('msgs', '0088_broadcast_send_all'), ] operations = [ migrations.RunPython(apply_as_migration), migrations.AlterField( model_name='broadcast', name='send_all', field=models.NullBooleanField(default=False, help_text='Whether this broadcast should send to all URNs for each contact'), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-06 17:33 from __future__ import unicode_literals from django.db import migrations, models from temba.utils import chunk_list def do_populate_send_all(Broadcast): broadcast_ids = Broadcast.objects.all().values_list('id', flat=True) broadcast_count = len(broadcast_ids) if broadcast_count: print('Starting to update %d broadcasts send all field...' % broadcast_count) updated = 0 for chunk in chunk_list(broadcast_ids, 5000): Broadcast.objects.filter(pk__in=chunk).update(send_all=False) print("Updated %d of %d broadcasts" % (updated + len(chunk), broadcast_count)) def apply_as_migration(apps, schema_editor): Broadcast = apps.get_model('msgs', 'Broadcast') do_populate_send_all(Broadcast) def apply_manual(): from temba.msgs.models import Broadcast do_populate_send_all(Broadcast) class Migration(migrations.Migration): dependencies = [ ('msgs', '0088_broadcast_send_all'), ] operations = [ migrations.AlterField( model_name='broadcast', name='send_all', field=models.NullBooleanField(default=False, help_text='Whether this broadcast should send to all URNs for each contact'), ), migrations.RunPython(apply_as_migration), ]
Tweak order of operations in populate migration
Tweak order of operations in populate migration
Python
agpl-3.0
pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-06 17:33 from __future__ import unicode_literals from django.db import migrations, models from temba.utils import chunk_list def do_populate_send_all(Broadcast): broadcast_ids = Broadcast.objects.all().values_list('id', flat=True) broadcast_count = len(broadcast_ids) if broadcast_count: print('Starting to update %d broadcasts send all field...' % broadcast_count) updated = 0 for chunk in chunk_list(broadcast_ids, 1000): Broadcast.objects.filter(pk__in=chunk).update(send_all=False) print("Updated %d of %d broadcasts" % (updated + len(chunk), broadcast_count)) def apply_as_migration(apps, schema_editor): Broadcast = apps.get_model('msgs', 'Broadcast') do_populate_send_all(Broadcast) def apply_manual(): from temba.msgs.models import Broadcast do_populate_send_all(Broadcast) class Migration(migrations.Migration): dependencies = [ ('msgs', '0088_broadcast_send_all'), ] operations = [ migrations.RunPython(apply_as_migration), migrations.AlterField( model_name='broadcast', name='send_all', field=models.NullBooleanField(default=False, help_text='Whether this broadcast should send to all URNs for each contact'), ), ] Tweak order of operations in populate migration
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-06 17:33 from __future__ import unicode_literals from django.db import migrations, models from temba.utils import chunk_list def do_populate_send_all(Broadcast): broadcast_ids = Broadcast.objects.all().values_list('id', flat=True) broadcast_count = len(broadcast_ids) if broadcast_count: print('Starting to update %d broadcasts send all field...' % broadcast_count) updated = 0 for chunk in chunk_list(broadcast_ids, 5000): Broadcast.objects.filter(pk__in=chunk).update(send_all=False) print("Updated %d of %d broadcasts" % (updated + len(chunk), broadcast_count)) def apply_as_migration(apps, schema_editor): Broadcast = apps.get_model('msgs', 'Broadcast') do_populate_send_all(Broadcast) def apply_manual(): from temba.msgs.models import Broadcast do_populate_send_all(Broadcast) class Migration(migrations.Migration): dependencies = [ ('msgs', '0088_broadcast_send_all'), ] operations = [ migrations.AlterField( model_name='broadcast', name='send_all', field=models.NullBooleanField(default=False, help_text='Whether this broadcast should send to all URNs for each contact'), ), migrations.RunPython(apply_as_migration), ]
<commit_before># -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-06 17:33 from __future__ import unicode_literals from django.db import migrations, models from temba.utils import chunk_list def do_populate_send_all(Broadcast): broadcast_ids = Broadcast.objects.all().values_list('id', flat=True) broadcast_count = len(broadcast_ids) if broadcast_count: print('Starting to update %d broadcasts send all field...' % broadcast_count) updated = 0 for chunk in chunk_list(broadcast_ids, 1000): Broadcast.objects.filter(pk__in=chunk).update(send_all=False) print("Updated %d of %d broadcasts" % (updated + len(chunk), broadcast_count)) def apply_as_migration(apps, schema_editor): Broadcast = apps.get_model('msgs', 'Broadcast') do_populate_send_all(Broadcast) def apply_manual(): from temba.msgs.models import Broadcast do_populate_send_all(Broadcast) class Migration(migrations.Migration): dependencies = [ ('msgs', '0088_broadcast_send_all'), ] operations = [ migrations.RunPython(apply_as_migration), migrations.AlterField( model_name='broadcast', name='send_all', field=models.NullBooleanField(default=False, help_text='Whether this broadcast should send to all URNs for each contact'), ), ] <commit_msg>Tweak order of operations in populate migration<commit_after>
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-06 17:33 from __future__ import unicode_literals from django.db import migrations, models from temba.utils import chunk_list def do_populate_send_all(Broadcast): broadcast_ids = Broadcast.objects.all().values_list('id', flat=True) broadcast_count = len(broadcast_ids) if broadcast_count: print('Starting to update %d broadcasts send all field...' % broadcast_count) updated = 0 for chunk in chunk_list(broadcast_ids, 5000): Broadcast.objects.filter(pk__in=chunk).update(send_all=False) print("Updated %d of %d broadcasts" % (updated + len(chunk), broadcast_count)) def apply_as_migration(apps, schema_editor): Broadcast = apps.get_model('msgs', 'Broadcast') do_populate_send_all(Broadcast) def apply_manual(): from temba.msgs.models import Broadcast do_populate_send_all(Broadcast) class Migration(migrations.Migration): dependencies = [ ('msgs', '0088_broadcast_send_all'), ] operations = [ migrations.AlterField( model_name='broadcast', name='send_all', field=models.NullBooleanField(default=False, help_text='Whether this broadcast should send to all URNs for each contact'), ), migrations.RunPython(apply_as_migration), ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-06 17:33 from __future__ import unicode_literals from django.db import migrations, models from temba.utils import chunk_list def do_populate_send_all(Broadcast): broadcast_ids = Broadcast.objects.all().values_list('id', flat=True) broadcast_count = len(broadcast_ids) if broadcast_count: print('Starting to update %d broadcasts send all field...' % broadcast_count) updated = 0 for chunk in chunk_list(broadcast_ids, 1000): Broadcast.objects.filter(pk__in=chunk).update(send_all=False) print("Updated %d of %d broadcasts" % (updated + len(chunk), broadcast_count)) def apply_as_migration(apps, schema_editor): Broadcast = apps.get_model('msgs', 'Broadcast') do_populate_send_all(Broadcast) def apply_manual(): from temba.msgs.models import Broadcast do_populate_send_all(Broadcast) class Migration(migrations.Migration): dependencies = [ ('msgs', '0088_broadcast_send_all'), ] operations = [ migrations.RunPython(apply_as_migration), migrations.AlterField( model_name='broadcast', name='send_all', field=models.NullBooleanField(default=False, help_text='Whether this broadcast should send to all URNs for each contact'), ), ] Tweak order of operations in populate migration# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-06 17:33 from __future__ import unicode_literals from django.db import migrations, models from temba.utils import chunk_list def do_populate_send_all(Broadcast): broadcast_ids = Broadcast.objects.all().values_list('id', flat=True) broadcast_count = len(broadcast_ids) if broadcast_count: print('Starting to update %d broadcasts send all field...' % broadcast_count) updated = 0 for chunk in chunk_list(broadcast_ids, 5000): Broadcast.objects.filter(pk__in=chunk).update(send_all=False) print("Updated %d of %d broadcasts" % (updated + len(chunk), broadcast_count)) def apply_as_migration(apps, schema_editor): Broadcast = apps.get_model('msgs', 'Broadcast') do_populate_send_all(Broadcast) def apply_manual(): from temba.msgs.models import Broadcast do_populate_send_all(Broadcast) class Migration(migrations.Migration): dependencies = [ ('msgs', '0088_broadcast_send_all'), ] operations = [ migrations.AlterField( model_name='broadcast', name='send_all', field=models.NullBooleanField(default=False, help_text='Whether this broadcast should send to all URNs for each contact'), ), migrations.RunPython(apply_as_migration), ]
<commit_before># -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-06 17:33 from __future__ import unicode_literals from django.db import migrations, models from temba.utils import chunk_list def do_populate_send_all(Broadcast): broadcast_ids = Broadcast.objects.all().values_list('id', flat=True) broadcast_count = len(broadcast_ids) if broadcast_count: print('Starting to update %d broadcasts send all field...' % broadcast_count) updated = 0 for chunk in chunk_list(broadcast_ids, 1000): Broadcast.objects.filter(pk__in=chunk).update(send_all=False) print("Updated %d of %d broadcasts" % (updated + len(chunk), broadcast_count)) def apply_as_migration(apps, schema_editor): Broadcast = apps.get_model('msgs', 'Broadcast') do_populate_send_all(Broadcast) def apply_manual(): from temba.msgs.models import Broadcast do_populate_send_all(Broadcast) class Migration(migrations.Migration): dependencies = [ ('msgs', '0088_broadcast_send_all'), ] operations = [ migrations.RunPython(apply_as_migration), migrations.AlterField( model_name='broadcast', name='send_all', field=models.NullBooleanField(default=False, help_text='Whether this broadcast should send to all URNs for each contact'), ), ] <commit_msg>Tweak order of operations in populate migration<commit_after># -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-06 17:33 from __future__ import unicode_literals from django.db import migrations, models from temba.utils import chunk_list def do_populate_send_all(Broadcast): broadcast_ids = Broadcast.objects.all().values_list('id', flat=True) broadcast_count = len(broadcast_ids) if broadcast_count: print('Starting to update %d broadcasts send all field...' % broadcast_count) updated = 0 for chunk in chunk_list(broadcast_ids, 5000): Broadcast.objects.filter(pk__in=chunk).update(send_all=False) print("Updated %d of %d broadcasts" % (updated + len(chunk), broadcast_count)) def apply_as_migration(apps, schema_editor): Broadcast = apps.get_model('msgs', 'Broadcast') do_populate_send_all(Broadcast) def apply_manual(): from temba.msgs.models import Broadcast do_populate_send_all(Broadcast) class Migration(migrations.Migration): dependencies = [ ('msgs', '0088_broadcast_send_all'), ] operations = [ migrations.AlterField( model_name='broadcast', name='send_all', field=models.NullBooleanField(default=False, help_text='Whether this broadcast should send to all URNs for each contact'), ), migrations.RunPython(apply_as_migration), ]
cfbb2e479577cdc3bce8f5f61dcc5ff5042fab48
api_tests/institutions/views/test_institution_detail.py
api_tests/institutions/views/test_institution_detail.py
from nose.tools import * # flake8: noqa from tests.base import ApiTestCase from osf_tests.factories import InstitutionFactory from api.base.settings.defaults import API_BASE class TestInstitutionDetail(ApiTestCase): def setUp(self): super(TestInstitutionDetail, self).setUp() self.institution = InstitutionFactory() self.institution_url = '/' + API_BASE + 'institutions/{id}/' def test_return_wrong_id(self): res = self.app.get(self.institution_url.format(id='1PO'), expect_errors=True) assert_equal(res.status_code, 404) def test_return_with_id(self): res = self.app.get(self.institution_url.format(id=self.institution._id)) assert_equal(res.status_code, 200) assert_equal(res.json['data']['attributes']['name'], self.institution.name)
import pytest from api.base.settings.defaults import API_BASE from osf_tests.factories import InstitutionFactory @pytest.mark.django_db class TestInstitutionDetail: @pytest.fixture() def institution(self): return InstitutionFactory() @pytest.fixture() def url_institution(self): def url(id): return '/{}institutions/{}/'.format(API_BASE, id) return url def test_detail_response(self, app, institution, url_institution): #return_wrong_id res = app.get(url_institution(id='1PO'), expect_errors=True) assert res.status_code == 404 #test_return_with_id res = app.get(url_institution(id=institution._id)) assert res.status_code == 200 assert res.json['data']['attributes']['name'] == institution.name
Convert institutions detail to pytest
Convert institutions detail to pytest
Python
apache-2.0
HalcyonChimera/osf.io,cslzchen/osf.io,mfraezz/osf.io,leb2dg/osf.io,mattclark/osf.io,HalcyonChimera/osf.io,baylee-d/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,caneruguz/osf.io,sloria/osf.io,leb2dg/osf.io,cslzchen/osf.io,cslzchen/osf.io,adlius/osf.io,caneruguz/osf.io,CenterForOpenScience/osf.io,felliott/osf.io,pattisdr/osf.io,crcresearch/osf.io,chrisseto/osf.io,brianjgeiger/osf.io,laurenrevere/osf.io,chrisseto/osf.io,mfraezz/osf.io,mattclark/osf.io,Johnetordoff/osf.io,adlius/osf.io,adlius/osf.io,icereval/osf.io,aaxelb/osf.io,icereval/osf.io,sloria/osf.io,mattclark/osf.io,caseyrollins/osf.io,saradbowman/osf.io,pattisdr/osf.io,felliott/osf.io,Johnetordoff/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,chennan47/osf.io,aaxelb/osf.io,caneruguz/osf.io,laurenrevere/osf.io,adlius/osf.io,binoculars/osf.io,laurenrevere/osf.io,felliott/osf.io,chennan47/osf.io,CenterForOpenScience/osf.io,sloria/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,caneruguz/osf.io,crcresearch/osf.io,chrisseto/osf.io,baylee-d/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,binoculars/osf.io,chrisseto/osf.io,brianjgeiger/osf.io,TomBaxter/osf.io,baylee-d/osf.io,icereval/osf.io,chennan47/osf.io,TomBaxter/osf.io,CenterForOpenScience/osf.io,mfraezz/osf.io,leb2dg/osf.io,saradbowman/osf.io,binoculars/osf.io,erinspace/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,crcresearch/osf.io,TomBaxter/osf.io,mfraezz/osf.io,erinspace/osf.io,erinspace/osf.io,HalcyonChimera/osf.io,leb2dg/osf.io,HalcyonChimera/osf.io,cslzchen/osf.io,felliott/osf.io
from nose.tools import * # flake8: noqa from tests.base import ApiTestCase from osf_tests.factories import InstitutionFactory from api.base.settings.defaults import API_BASE class TestInstitutionDetail(ApiTestCase): def setUp(self): super(TestInstitutionDetail, self).setUp() self.institution = InstitutionFactory() self.institution_url = '/' + API_BASE + 'institutions/{id}/' def test_return_wrong_id(self): res = self.app.get(self.institution_url.format(id='1PO'), expect_errors=True) assert_equal(res.status_code, 404) def test_return_with_id(self): res = self.app.get(self.institution_url.format(id=self.institution._id)) assert_equal(res.status_code, 200) assert_equal(res.json['data']['attributes']['name'], self.institution.name) Convert institutions detail to pytest
import pytest from api.base.settings.defaults import API_BASE from osf_tests.factories import InstitutionFactory @pytest.mark.django_db class TestInstitutionDetail: @pytest.fixture() def institution(self): return InstitutionFactory() @pytest.fixture() def url_institution(self): def url(id): return '/{}institutions/{}/'.format(API_BASE, id) return url def test_detail_response(self, app, institution, url_institution): #return_wrong_id res = app.get(url_institution(id='1PO'), expect_errors=True) assert res.status_code == 404 #test_return_with_id res = app.get(url_institution(id=institution._id)) assert res.status_code == 200 assert res.json['data']['attributes']['name'] == institution.name
<commit_before>from nose.tools import * # flake8: noqa from tests.base import ApiTestCase from osf_tests.factories import InstitutionFactory from api.base.settings.defaults import API_BASE class TestInstitutionDetail(ApiTestCase): def setUp(self): super(TestInstitutionDetail, self).setUp() self.institution = InstitutionFactory() self.institution_url = '/' + API_BASE + 'institutions/{id}/' def test_return_wrong_id(self): res = self.app.get(self.institution_url.format(id='1PO'), expect_errors=True) assert_equal(res.status_code, 404) def test_return_with_id(self): res = self.app.get(self.institution_url.format(id=self.institution._id)) assert_equal(res.status_code, 200) assert_equal(res.json['data']['attributes']['name'], self.institution.name) <commit_msg>Convert institutions detail to pytest<commit_after>
import pytest from api.base.settings.defaults import API_BASE from osf_tests.factories import InstitutionFactory @pytest.mark.django_db class TestInstitutionDetail: @pytest.fixture() def institution(self): return InstitutionFactory() @pytest.fixture() def url_institution(self): def url(id): return '/{}institutions/{}/'.format(API_BASE, id) return url def test_detail_response(self, app, institution, url_institution): #return_wrong_id res = app.get(url_institution(id='1PO'), expect_errors=True) assert res.status_code == 404 #test_return_with_id res = app.get(url_institution(id=institution._id)) assert res.status_code == 200 assert res.json['data']['attributes']['name'] == institution.name
from nose.tools import * # flake8: noqa from tests.base import ApiTestCase from osf_tests.factories import InstitutionFactory from api.base.settings.defaults import API_BASE class TestInstitutionDetail(ApiTestCase): def setUp(self): super(TestInstitutionDetail, self).setUp() self.institution = InstitutionFactory() self.institution_url = '/' + API_BASE + 'institutions/{id}/' def test_return_wrong_id(self): res = self.app.get(self.institution_url.format(id='1PO'), expect_errors=True) assert_equal(res.status_code, 404) def test_return_with_id(self): res = self.app.get(self.institution_url.format(id=self.institution._id)) assert_equal(res.status_code, 200) assert_equal(res.json['data']['attributes']['name'], self.institution.name) Convert institutions detail to pytestimport pytest from api.base.settings.defaults import API_BASE from osf_tests.factories import InstitutionFactory @pytest.mark.django_db class TestInstitutionDetail: @pytest.fixture() def institution(self): return InstitutionFactory() @pytest.fixture() def url_institution(self): def url(id): return '/{}institutions/{}/'.format(API_BASE, id) return url def test_detail_response(self, app, institution, url_institution): #return_wrong_id res = app.get(url_institution(id='1PO'), expect_errors=True) assert res.status_code == 404 #test_return_with_id res = app.get(url_institution(id=institution._id)) assert res.status_code == 200 assert res.json['data']['attributes']['name'] == institution.name
<commit_before>from nose.tools import * # flake8: noqa from tests.base import ApiTestCase from osf_tests.factories import InstitutionFactory from api.base.settings.defaults import API_BASE class TestInstitutionDetail(ApiTestCase): def setUp(self): super(TestInstitutionDetail, self).setUp() self.institution = InstitutionFactory() self.institution_url = '/' + API_BASE + 'institutions/{id}/' def test_return_wrong_id(self): res = self.app.get(self.institution_url.format(id='1PO'), expect_errors=True) assert_equal(res.status_code, 404) def test_return_with_id(self): res = self.app.get(self.institution_url.format(id=self.institution._id)) assert_equal(res.status_code, 200) assert_equal(res.json['data']['attributes']['name'], self.institution.name) <commit_msg>Convert institutions detail to pytest<commit_after>import pytest from api.base.settings.defaults import API_BASE from osf_tests.factories import InstitutionFactory @pytest.mark.django_db class TestInstitutionDetail: @pytest.fixture() def institution(self): return InstitutionFactory() @pytest.fixture() def url_institution(self): def url(id): return '/{}institutions/{}/'.format(API_BASE, id) return url def test_detail_response(self, app, institution, url_institution): #return_wrong_id res = app.get(url_institution(id='1PO'), expect_errors=True) assert res.status_code == 404 #test_return_with_id res = app.get(url_institution(id=institution._id)) assert res.status_code == 200 assert res.json['data']['attributes']['name'] == institution.name
1082be09cee7d94a245d89469dea9ff347c2796e
app/routes/users/schemas.py
app/routes/users/schemas.py
from app.schema_validation.definitions import uuid, datetime post_create_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for creating user", "type": "object", "properties": { 'email': {"type": "string"}, 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, }, "required": ['email'] } post_update_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for updating user", "type": "object", "properties": { 'email': {"format": "email", "type": "string"}, 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, 'last_login': {"type": "date-time"}, 'session_id': {"type": "string"}, 'ip': {"type": "string"}, }, "required": ['email'] }
from app.schema_validation.definitions import uuid, datetime post_create_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for creating user", "type": "object", "properties": { 'email': {"type": "string"}, 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, }, "required": ['email'] } post_update_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for updating user", "type": "object", "properties": { 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, 'last_login': {"type": "date-time"}, 'session_id': {"type": "string"}, 'ip': {"type": "string"}, }, "required": [] }
Drop email as property from post_update_user_schema
Drop email as property from post_update_user_schema
Python
mit
NewAcropolis/api,NewAcropolis/api,NewAcropolis/api
from app.schema_validation.definitions import uuid, datetime post_create_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for creating user", "type": "object", "properties": { 'email': {"type": "string"}, 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, }, "required": ['email'] } post_update_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for updating user", "type": "object", "properties": { 'email': {"format": "email", "type": "string"}, 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, 'last_login': {"type": "date-time"}, 'session_id': {"type": "string"}, 'ip': {"type": "string"}, }, "required": ['email'] } Drop email as property from post_update_user_schema
from app.schema_validation.definitions import uuid, datetime post_create_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for creating user", "type": "object", "properties": { 'email': {"type": "string"}, 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, }, "required": ['email'] } post_update_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for updating user", "type": "object", "properties": { 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, 'last_login': {"type": "date-time"}, 'session_id': {"type": "string"}, 'ip': {"type": "string"}, }, "required": [] }
<commit_before>from app.schema_validation.definitions import uuid, datetime post_create_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for creating user", "type": "object", "properties": { 'email': {"type": "string"}, 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, }, "required": ['email'] } post_update_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for updating user", "type": "object", "properties": { 'email': {"format": "email", "type": "string"}, 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, 'last_login': {"type": "date-time"}, 'session_id': {"type": "string"}, 'ip': {"type": "string"}, }, "required": ['email'] } <commit_msg>Drop email as property from post_update_user_schema<commit_after>
from app.schema_validation.definitions import uuid, datetime post_create_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for creating user", "type": "object", "properties": { 'email': {"type": "string"}, 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, }, "required": ['email'] } post_update_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for updating user", "type": "object", "properties": { 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, 'last_login': {"type": "date-time"}, 'session_id': {"type": "string"}, 'ip': {"type": "string"}, }, "required": [] }
from app.schema_validation.definitions import uuid, datetime post_create_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for creating user", "type": "object", "properties": { 'email': {"type": "string"}, 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, }, "required": ['email'] } post_update_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for updating user", "type": "object", "properties": { 'email': {"format": "email", "type": "string"}, 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, 'last_login': {"type": "date-time"}, 'session_id': {"type": "string"}, 'ip': {"type": "string"}, }, "required": ['email'] } Drop email as property from post_update_user_schemafrom app.schema_validation.definitions import uuid, datetime post_create_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for creating user", "type": "object", "properties": { 'email': {"type": "string"}, 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, }, "required": ['email'] } post_update_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for updating user", "type": "object", "properties": { 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, 'last_login': {"type": "date-time"}, 'session_id': {"type": "string"}, 'ip': {"type": "string"}, }, "required": [] }
<commit_before>from app.schema_validation.definitions import uuid, datetime post_create_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for creating user", "type": "object", "properties": { 'email': {"type": "string"}, 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, }, "required": ['email'] } post_update_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for updating user", "type": "object", "properties": { 'email': {"format": "email", "type": "string"}, 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, 'last_login': {"type": "date-time"}, 'session_id': {"type": "string"}, 'ip': {"type": "string"}, }, "required": ['email'] } <commit_msg>Drop email as property from post_update_user_schema<commit_after>from app.schema_validation.definitions import uuid, datetime post_create_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for creating user", "type": "object", "properties": { 'email': {"type": "string"}, 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, }, "required": ['email'] } post_update_user_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for updating user", "type": "object", "properties": { 'name': {"type": "string"}, 'active': {"type": "boolean"}, 'access_area': {"type": "string"}, 'last_login': {"type": "date-time"}, 'session_id': {"type": "string"}, 'ip': {"type": "string"}, }, "required": [] }
a65d6ae9a6be0988bb74ecff7982c91be5273c58
meinberlin/apps/bplan/management/commands/bplan_auto_archive.py
meinberlin/apps/bplan/management/commands/bplan_auto_archive.py
from django.core.management.base import BaseCommand from meinberlin.apps.bplan import models as bplan_models class Command(BaseCommand): help = 'Archive finished bplan projects.' def handle(self, *args, **options): bplans = bplan_models.Bplan.objects.filter(is_draft=False) for bplan in bplans: if bplan.has_finished: bplan.is_archived = True bplan.save() self.stdout.write('Archived bplan {}.'.format(bplan.name))
from datetime import timedelta from django.core.management.base import BaseCommand from django.utils import timezone from meinberlin.apps.bplan import models as bplan_models class Command(BaseCommand): help = 'Archive finished bplan projects and delete old statements.' def handle(self, *args, **options): bplans = bplan_models.Bplan.objects.filter(is_draft=False) for bplan in bplans: if bplan.has_finished and not bplan.is_archived: bplan.is_archived = True bplan.save() self.stdout.write('Archived bplan {}.'.format(bplan.name)) # Delete statements of archived projects # To prevent deleting statements that have not been sent by mail yet # only statements older then 48h are deleted. num_deleted, _ = bplan_models.Statement.objects\ .filter(module__project__is_archived=True)\ .filter(created__lt=timezone.now() - timedelta(hours=48))\ .delete() if num_deleted: self.stdout.write('Deleted {} statements from archived bplans.' .format(num_deleted))
Delete statements from archived bplans
Delete statements from archived bplans After a bplan is archived it's related statements may be deleted. For simpler development/deployment the auto_archive script is extended to delete the statements, altough it may have been possible to add another command. To prevent from loosing statements that are created just before the participation ends, the deletion is delayed for 48 hours. (In rare cases a statement may not have been sent due to the async nature of our email interface, when the project is already archived)
Python
agpl-3.0
liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin
from django.core.management.base import BaseCommand from meinberlin.apps.bplan import models as bplan_models class Command(BaseCommand): help = 'Archive finished bplan projects.' def handle(self, *args, **options): bplans = bplan_models.Bplan.objects.filter(is_draft=False) for bplan in bplans: if bplan.has_finished: bplan.is_archived = True bplan.save() self.stdout.write('Archived bplan {}.'.format(bplan.name)) Delete statements from archived bplans After a bplan is archived it's related statements may be deleted. For simpler development/deployment the auto_archive script is extended to delete the statements, altough it may have been possible to add another command. To prevent from loosing statements that are created just before the participation ends, the deletion is delayed for 48 hours. (In rare cases a statement may not have been sent due to the async nature of our email interface, when the project is already archived)
from datetime import timedelta from django.core.management.base import BaseCommand from django.utils import timezone from meinberlin.apps.bplan import models as bplan_models class Command(BaseCommand): help = 'Archive finished bplan projects and delete old statements.' def handle(self, *args, **options): bplans = bplan_models.Bplan.objects.filter(is_draft=False) for bplan in bplans: if bplan.has_finished and not bplan.is_archived: bplan.is_archived = True bplan.save() self.stdout.write('Archived bplan {}.'.format(bplan.name)) # Delete statements of archived projects # To prevent deleting statements that have not been sent by mail yet # only statements older then 48h are deleted. num_deleted, _ = bplan_models.Statement.objects\ .filter(module__project__is_archived=True)\ .filter(created__lt=timezone.now() - timedelta(hours=48))\ .delete() if num_deleted: self.stdout.write('Deleted {} statements from archived bplans.' .format(num_deleted))
<commit_before>from django.core.management.base import BaseCommand from meinberlin.apps.bplan import models as bplan_models class Command(BaseCommand): help = 'Archive finished bplan projects.' def handle(self, *args, **options): bplans = bplan_models.Bplan.objects.filter(is_draft=False) for bplan in bplans: if bplan.has_finished: bplan.is_archived = True bplan.save() self.stdout.write('Archived bplan {}.'.format(bplan.name)) <commit_msg>Delete statements from archived bplans After a bplan is archived it's related statements may be deleted. For simpler development/deployment the auto_archive script is extended to delete the statements, altough it may have been possible to add another command. To prevent from loosing statements that are created just before the participation ends, the deletion is delayed for 48 hours. (In rare cases a statement may not have been sent due to the async nature of our email interface, when the project is already archived)<commit_after>
from datetime import timedelta from django.core.management.base import BaseCommand from django.utils import timezone from meinberlin.apps.bplan import models as bplan_models class Command(BaseCommand): help = 'Archive finished bplan projects and delete old statements.' def handle(self, *args, **options): bplans = bplan_models.Bplan.objects.filter(is_draft=False) for bplan in bplans: if bplan.has_finished and not bplan.is_archived: bplan.is_archived = True bplan.save() self.stdout.write('Archived bplan {}.'.format(bplan.name)) # Delete statements of archived projects # To prevent deleting statements that have not been sent by mail yet # only statements older then 48h are deleted. num_deleted, _ = bplan_models.Statement.objects\ .filter(module__project__is_archived=True)\ .filter(created__lt=timezone.now() - timedelta(hours=48))\ .delete() if num_deleted: self.stdout.write('Deleted {} statements from archived bplans.' .format(num_deleted))
from django.core.management.base import BaseCommand from meinberlin.apps.bplan import models as bplan_models class Command(BaseCommand): help = 'Archive finished bplan projects.' def handle(self, *args, **options): bplans = bplan_models.Bplan.objects.filter(is_draft=False) for bplan in bplans: if bplan.has_finished: bplan.is_archived = True bplan.save() self.stdout.write('Archived bplan {}.'.format(bplan.name)) Delete statements from archived bplans After a bplan is archived it's related statements may be deleted. For simpler development/deployment the auto_archive script is extended to delete the statements, altough it may have been possible to add another command. To prevent from loosing statements that are created just before the participation ends, the deletion is delayed for 48 hours. (In rare cases a statement may not have been sent due to the async nature of our email interface, when the project is already archived)from datetime import timedelta from django.core.management.base import BaseCommand from django.utils import timezone from meinberlin.apps.bplan import models as bplan_models class Command(BaseCommand): help = 'Archive finished bplan projects and delete old statements.' def handle(self, *args, **options): bplans = bplan_models.Bplan.objects.filter(is_draft=False) for bplan in bplans: if bplan.has_finished and not bplan.is_archived: bplan.is_archived = True bplan.save() self.stdout.write('Archived bplan {}.'.format(bplan.name)) # Delete statements of archived projects # To prevent deleting statements that have not been sent by mail yet # only statements older then 48h are deleted. num_deleted, _ = bplan_models.Statement.objects\ .filter(module__project__is_archived=True)\ .filter(created__lt=timezone.now() - timedelta(hours=48))\ .delete() if num_deleted: self.stdout.write('Deleted {} statements from archived bplans.' .format(num_deleted))
<commit_before>from django.core.management.base import BaseCommand from meinberlin.apps.bplan import models as bplan_models class Command(BaseCommand): help = 'Archive finished bplan projects.' def handle(self, *args, **options): bplans = bplan_models.Bplan.objects.filter(is_draft=False) for bplan in bplans: if bplan.has_finished: bplan.is_archived = True bplan.save() self.stdout.write('Archived bplan {}.'.format(bplan.name)) <commit_msg>Delete statements from archived bplans After a bplan is archived it's related statements may be deleted. For simpler development/deployment the auto_archive script is extended to delete the statements, altough it may have been possible to add another command. To prevent from loosing statements that are created just before the participation ends, the deletion is delayed for 48 hours. (In rare cases a statement may not have been sent due to the async nature of our email interface, when the project is already archived)<commit_after>from datetime import timedelta from django.core.management.base import BaseCommand from django.utils import timezone from meinberlin.apps.bplan import models as bplan_models class Command(BaseCommand): help = 'Archive finished bplan projects and delete old statements.' def handle(self, *args, **options): bplans = bplan_models.Bplan.objects.filter(is_draft=False) for bplan in bplans: if bplan.has_finished and not bplan.is_archived: bplan.is_archived = True bplan.save() self.stdout.write('Archived bplan {}.'.format(bplan.name)) # Delete statements of archived projects # To prevent deleting statements that have not been sent by mail yet # only statements older then 48h are deleted. num_deleted, _ = bplan_models.Statement.objects\ .filter(module__project__is_archived=True)\ .filter(created__lt=timezone.now() - timedelta(hours=48))\ .delete() if num_deleted: self.stdout.write('Deleted {} statements from archived bplans.' .format(num_deleted))
1f2d0b0978d55d471322ec3e8a93464f9da4c59b
xlsxcompose.py
xlsxcompose.py
import argparse __author__ = 'perks' if __name__ == '__main__': parser = argparse.ArgumentParser( description='Migrate columns from one spreadsheet to columns in a new spreadsheet.' ) parser.add_argument( '-i', '--input', help='Input .xlsx file', required=True ) parser.add_argument( '-o', '--output', help='Output .xlsx file name', default='xlsxcompose.xlsx' ) parser.add_argument( 'mapping', nargs='+', help='Comma separated column relations in the form of OriginalCol=TargetCol' ) args = parser.parse_args() print args
__author__ = 'perks' from xlutils.copy import copy from xlrd import open_workbook import xlsxwriter def compose(input, output, mappings): START_ROW = 501 END_ROW = 1000 rb = open_workbook(input) r_sheet = rb.sheet_by_name("CLEAN") workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet("Clients") dic = {} print "gothere" for col_index, mapping in enumerate(mappings): target_header = mapping[0] orig_header = mapping[1] for i in range(1, r_sheet.ncols): col_values = filter(None, r_sheet.col(i)) col_values = map(lambda x: str(int(x.value)) if x.ctype == 2 else x.value, col_values) col_head = col_values[0] if orig_header == col_head: migrate_col = [target_header] + col_values[START_ROW:END_ROW] dic.update({target_header: migrate_col}) break if dic.has_key(target_header): for row_index, cell in enumerate(dic[target_header]): cell_write(worksheet, row_index, col_index, cell) workbook.close() def cell_write(sheet,row_index, col_index, value): sheet.write(row_index, col_index, value) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser( description='Migrate columns from one spreadsheet to columns in a new spreadsheet.' ) parser.add_argument( '-i', '--input', help='Input .xlsx file', required=True ) parser.add_argument( '-o', '--output', help='Output .xlsx file name', default='xlsxcompose.xlsx' ) parser.add_argument( '-m', '--mappings', help='File with map configurations inform of TargetCol=OriginalCol', required=True ) args = parser.parse_args() try: lines = [line.strip() for line in open(args.mappings)] mappings = [tuple(mapping.split("=")) for mapping in lines if mapping.split("=")[1]] compose(args.input, args.output, mappings) except Exception,e: print "Error parsing your column mappings" print e print "Succesfull composition:\n\t {} => {}".format(args.input, args.output)
Load settings from file, fix logic
Load settings from file, fix logic
Python
mit
perks/xlsxcompose
import argparse __author__ = 'perks' if __name__ == '__main__': parser = argparse.ArgumentParser( description='Migrate columns from one spreadsheet to columns in a new spreadsheet.' ) parser.add_argument( '-i', '--input', help='Input .xlsx file', required=True ) parser.add_argument( '-o', '--output', help='Output .xlsx file name', default='xlsxcompose.xlsx' ) parser.add_argument( 'mapping', nargs='+', help='Comma separated column relations in the form of OriginalCol=TargetCol' ) args = parser.parse_args() print args Load settings from file, fix logic
__author__ = 'perks' from xlutils.copy import copy from xlrd import open_workbook import xlsxwriter def compose(input, output, mappings): START_ROW = 501 END_ROW = 1000 rb = open_workbook(input) r_sheet = rb.sheet_by_name("CLEAN") workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet("Clients") dic = {} print "gothere" for col_index, mapping in enumerate(mappings): target_header = mapping[0] orig_header = mapping[1] for i in range(1, r_sheet.ncols): col_values = filter(None, r_sheet.col(i)) col_values = map(lambda x: str(int(x.value)) if x.ctype == 2 else x.value, col_values) col_head = col_values[0] if orig_header == col_head: migrate_col = [target_header] + col_values[START_ROW:END_ROW] dic.update({target_header: migrate_col}) break if dic.has_key(target_header): for row_index, cell in enumerate(dic[target_header]): cell_write(worksheet, row_index, col_index, cell) workbook.close() def cell_write(sheet,row_index, col_index, value): sheet.write(row_index, col_index, value) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser( description='Migrate columns from one spreadsheet to columns in a new spreadsheet.' ) parser.add_argument( '-i', '--input', help='Input .xlsx file', required=True ) parser.add_argument( '-o', '--output', help='Output .xlsx file name', default='xlsxcompose.xlsx' ) parser.add_argument( '-m', '--mappings', help='File with map configurations inform of TargetCol=OriginalCol', required=True ) args = parser.parse_args() try: lines = [line.strip() for line in open(args.mappings)] mappings = [tuple(mapping.split("=")) for mapping in lines if mapping.split("=")[1]] compose(args.input, args.output, mappings) except Exception,e: print "Error parsing your column mappings" print e print "Succesfull composition:\n\t {} => {}".format(args.input, args.output)
<commit_before>import argparse __author__ = 'perks' if __name__ == '__main__': parser = argparse.ArgumentParser( description='Migrate columns from one spreadsheet to columns in a new spreadsheet.' ) parser.add_argument( '-i', '--input', help='Input .xlsx file', required=True ) parser.add_argument( '-o', '--output', help='Output .xlsx file name', default='xlsxcompose.xlsx' ) parser.add_argument( 'mapping', nargs='+', help='Comma separated column relations in the form of OriginalCol=TargetCol' ) args = parser.parse_args() print args <commit_msg>Load settings from file, fix logic<commit_after>
__author__ = 'perks' from xlutils.copy import copy from xlrd import open_workbook import xlsxwriter def compose(input, output, mappings): START_ROW = 501 END_ROW = 1000 rb = open_workbook(input) r_sheet = rb.sheet_by_name("CLEAN") workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet("Clients") dic = {} print "gothere" for col_index, mapping in enumerate(mappings): target_header = mapping[0] orig_header = mapping[1] for i in range(1, r_sheet.ncols): col_values = filter(None, r_sheet.col(i)) col_values = map(lambda x: str(int(x.value)) if x.ctype == 2 else x.value, col_values) col_head = col_values[0] if orig_header == col_head: migrate_col = [target_header] + col_values[START_ROW:END_ROW] dic.update({target_header: migrate_col}) break if dic.has_key(target_header): for row_index, cell in enumerate(dic[target_header]): cell_write(worksheet, row_index, col_index, cell) workbook.close() def cell_write(sheet,row_index, col_index, value): sheet.write(row_index, col_index, value) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser( description='Migrate columns from one spreadsheet to columns in a new spreadsheet.' ) parser.add_argument( '-i', '--input', help='Input .xlsx file', required=True ) parser.add_argument( '-o', '--output', help='Output .xlsx file name', default='xlsxcompose.xlsx' ) parser.add_argument( '-m', '--mappings', help='File with map configurations inform of TargetCol=OriginalCol', required=True ) args = parser.parse_args() try: lines = [line.strip() for line in open(args.mappings)] mappings = [tuple(mapping.split("=")) for mapping in lines if mapping.split("=")[1]] compose(args.input, args.output, mappings) except Exception,e: print "Error parsing your column mappings" print e print "Succesfull composition:\n\t {} => {}".format(args.input, args.output)
import argparse __author__ = 'perks' if __name__ == '__main__': parser = argparse.ArgumentParser( description='Migrate columns from one spreadsheet to columns in a new spreadsheet.' ) parser.add_argument( '-i', '--input', help='Input .xlsx file', required=True ) parser.add_argument( '-o', '--output', help='Output .xlsx file name', default='xlsxcompose.xlsx' ) parser.add_argument( 'mapping', nargs='+', help='Comma separated column relations in the form of OriginalCol=TargetCol' ) args = parser.parse_args() print args Load settings from file, fix logic__author__ = 'perks' from xlutils.copy import copy from xlrd import open_workbook import xlsxwriter def compose(input, output, mappings): START_ROW = 501 END_ROW = 1000 rb = open_workbook(input) r_sheet = rb.sheet_by_name("CLEAN") workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet("Clients") dic = {} print "gothere" for col_index, mapping in enumerate(mappings): target_header = mapping[0] orig_header = mapping[1] for i in range(1, r_sheet.ncols): col_values = filter(None, r_sheet.col(i)) col_values = map(lambda x: str(int(x.value)) if x.ctype == 2 else x.value, col_values) col_head = col_values[0] if orig_header == col_head: migrate_col = [target_header] + col_values[START_ROW:END_ROW] dic.update({target_header: migrate_col}) break if dic.has_key(target_header): for row_index, cell in enumerate(dic[target_header]): cell_write(worksheet, row_index, col_index, cell) workbook.close() def cell_write(sheet,row_index, col_index, value): sheet.write(row_index, col_index, value) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser( description='Migrate columns from one spreadsheet to columns in a new spreadsheet.' ) parser.add_argument( '-i', '--input', help='Input .xlsx file', required=True ) parser.add_argument( '-o', '--output', help='Output .xlsx file name', default='xlsxcompose.xlsx' ) parser.add_argument( '-m', '--mappings', help='File with map configurations inform of TargetCol=OriginalCol', required=True ) args = parser.parse_args() try: lines = [line.strip() for line in open(args.mappings)] mappings = [tuple(mapping.split("=")) for mapping in lines if mapping.split("=")[1]] compose(args.input, args.output, mappings) except Exception,e: print "Error parsing your column mappings" print e print "Succesfull composition:\n\t {} => {}".format(args.input, args.output)
<commit_before>import argparse __author__ = 'perks' if __name__ == '__main__': parser = argparse.ArgumentParser( description='Migrate columns from one spreadsheet to columns in a new spreadsheet.' ) parser.add_argument( '-i', '--input', help='Input .xlsx file', required=True ) parser.add_argument( '-o', '--output', help='Output .xlsx file name', default='xlsxcompose.xlsx' ) parser.add_argument( 'mapping', nargs='+', help='Comma separated column relations in the form of OriginalCol=TargetCol' ) args = parser.parse_args() print args <commit_msg>Load settings from file, fix logic<commit_after>__author__ = 'perks' from xlutils.copy import copy from xlrd import open_workbook import xlsxwriter def compose(input, output, mappings): START_ROW = 501 END_ROW = 1000 rb = open_workbook(input) r_sheet = rb.sheet_by_name("CLEAN") workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet("Clients") dic = {} print "gothere" for col_index, mapping in enumerate(mappings): target_header = mapping[0] orig_header = mapping[1] for i in range(1, r_sheet.ncols): col_values = filter(None, r_sheet.col(i)) col_values = map(lambda x: str(int(x.value)) if x.ctype == 2 else x.value, col_values) col_head = col_values[0] if orig_header == col_head: migrate_col = [target_header] + col_values[START_ROW:END_ROW] dic.update({target_header: migrate_col}) break if dic.has_key(target_header): for row_index, cell in enumerate(dic[target_header]): cell_write(worksheet, row_index, col_index, cell) workbook.close() def cell_write(sheet,row_index, col_index, value): sheet.write(row_index, col_index, value) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser( description='Migrate columns from one spreadsheet to columns in a new spreadsheet.' ) parser.add_argument( '-i', '--input', help='Input .xlsx file', required=True ) parser.add_argument( '-o', '--output', help='Output .xlsx file name', default='xlsxcompose.xlsx' ) parser.add_argument( '-m', '--mappings', help='File with map configurations inform of TargetCol=OriginalCol', required=True ) args = parser.parse_args() try: lines = [line.strip() for line in open(args.mappings)] mappings = [tuple(mapping.split("=")) for mapping in lines if mapping.split("=")[1]] compose(args.input, args.output, mappings) except Exception,e: print "Error parsing your column mappings" print e print "Succesfull composition:\n\t {} => {}".format(args.input, args.output)
d8f8d7d2e6b9c7537a4f5cdd2c3b7251017186a3
xutils/util.py
xutils/util.py
# -*- coding: utf-8 -*- from subprocess import check_output def which(command, which="/usr/bin/which"): """Find and return the first absolute path of command used by `which`. If not found, return "". """ try: return check_output([which, command]).split("\n")[0] except Exception: return ""
# -*- coding: utf-8 -*- from subprocess import check_output as _check_output from xutils import PY3, to_unicode if PY3: def check_output(cmd, timeout=None, encoding=None, **kwargs): return _check_output(cmd, timeout=timeout, encoding=encoding, **kwargs) else: def check_output(cmd, timeout=None, encoding=None, **kwargs): out = _check_output(cmd, **kwargs) return to_unicode(out, encoding) if encoding else out def which(command, which="/usr/bin/which"): """Find and return the first absolute path of command used by `which`. If not found, return "". """ try: return check_output([which, command]).split("\n")[0] except Exception: return ""
Add check_output to be compatible with Py2 and Py3
Add check_output to be compatible with Py2 and Py3
Python
mit
xgfone/xutils,xgfone/pycom
# -*- coding: utf-8 -*- from subprocess import check_output def which(command, which="/usr/bin/which"): """Find and return the first absolute path of command used by `which`. If not found, return "". """ try: return check_output([which, command]).split("\n")[0] except Exception: return "" Add check_output to be compatible with Py2 and Py3
# -*- coding: utf-8 -*- from subprocess import check_output as _check_output from xutils import PY3, to_unicode if PY3: def check_output(cmd, timeout=None, encoding=None, **kwargs): return _check_output(cmd, timeout=timeout, encoding=encoding, **kwargs) else: def check_output(cmd, timeout=None, encoding=None, **kwargs): out = _check_output(cmd, **kwargs) return to_unicode(out, encoding) if encoding else out def which(command, which="/usr/bin/which"): """Find and return the first absolute path of command used by `which`. If not found, return "". """ try: return check_output([which, command]).split("\n")[0] except Exception: return ""
<commit_before># -*- coding: utf-8 -*- from subprocess import check_output def which(command, which="/usr/bin/which"): """Find and return the first absolute path of command used by `which`. If not found, return "". """ try: return check_output([which, command]).split("\n")[0] except Exception: return "" <commit_msg>Add check_output to be compatible with Py2 and Py3<commit_after>
# -*- coding: utf-8 -*- from subprocess import check_output as _check_output from xutils import PY3, to_unicode if PY3: def check_output(cmd, timeout=None, encoding=None, **kwargs): return _check_output(cmd, timeout=timeout, encoding=encoding, **kwargs) else: def check_output(cmd, timeout=None, encoding=None, **kwargs): out = _check_output(cmd, **kwargs) return to_unicode(out, encoding) if encoding else out def which(command, which="/usr/bin/which"): """Find and return the first absolute path of command used by `which`. If not found, return "". """ try: return check_output([which, command]).split("\n")[0] except Exception: return ""
# -*- coding: utf-8 -*- from subprocess import check_output def which(command, which="/usr/bin/which"): """Find and return the first absolute path of command used by `which`. If not found, return "". """ try: return check_output([which, command]).split("\n")[0] except Exception: return "" Add check_output to be compatible with Py2 and Py3# -*- coding: utf-8 -*- from subprocess import check_output as _check_output from xutils import PY3, to_unicode if PY3: def check_output(cmd, timeout=None, encoding=None, **kwargs): return _check_output(cmd, timeout=timeout, encoding=encoding, **kwargs) else: def check_output(cmd, timeout=None, encoding=None, **kwargs): out = _check_output(cmd, **kwargs) return to_unicode(out, encoding) if encoding else out def which(command, which="/usr/bin/which"): """Find and return the first absolute path of command used by `which`. If not found, return "". """ try: return check_output([which, command]).split("\n")[0] except Exception: return ""
<commit_before># -*- coding: utf-8 -*- from subprocess import check_output def which(command, which="/usr/bin/which"): """Find and return the first absolute path of command used by `which`. If not found, return "". """ try: return check_output([which, command]).split("\n")[0] except Exception: return "" <commit_msg>Add check_output to be compatible with Py2 and Py3<commit_after># -*- coding: utf-8 -*- from subprocess import check_output as _check_output from xutils import PY3, to_unicode if PY3: def check_output(cmd, timeout=None, encoding=None, **kwargs): return _check_output(cmd, timeout=timeout, encoding=encoding, **kwargs) else: def check_output(cmd, timeout=None, encoding=None, **kwargs): out = _check_output(cmd, **kwargs) return to_unicode(out, encoding) if encoding else out def which(command, which="/usr/bin/which"): """Find and return the first absolute path of command used by `which`. If not found, return "". """ try: return check_output([which, command]).split("\n")[0] except Exception: return ""
b06f7fb883e3e5dd03aa86e2ad8646f1ed907ce1
awx/fact/__init__.py
awx/fact/__init__.py
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. import logging logger = logging.getLogger('awx.fact')
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved.
Remove logging from fact init
Remove logging from fact init
Python
apache-2.0
wwitzel3/awx,wwitzel3/awx,snahelou/awx,snahelou/awx,wwitzel3/awx,snahelou/awx,snahelou/awx,wwitzel3/awx
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. import logging logger = logging.getLogger('awx.fact') Remove logging from fact init
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved.
<commit_before># Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. import logging logger = logging.getLogger('awx.fact') <commit_msg>Remove logging from fact init<commit_after>
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved.
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. import logging logger = logging.getLogger('awx.fact') Remove logging from fact init# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved.
<commit_before># Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. import logging logger = logging.getLogger('awx.fact') <commit_msg>Remove logging from fact init<commit_after># Copyright (c) 2015 Ansible, Inc. # All Rights Reserved.
28dd3f171fe422ba6e15530e7dc4f6d7d831ba09
xbrowse_server/base/management/commands/reload_family.py
xbrowse_server/base/management/commands/reload_family.py
from django.core.management.base import BaseCommand from xbrowse_server import xbrowse_controls from xbrowse_server.base.models import Project from xbrowse_server.mall import get_datastore class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('-p', "--project-id") def handle(self, *args, **options): project_id = options["project_id"] family_ids = args project = Project.objects.get(project_id=project_id) for vcf_file, families in project.families_by_vcf().items(): families_to_load = [] for family in families: family_id = family.family_id print("Checking id: " + family_id) if not family_ids or family.family_id not in family_ids: continue # delete this family get_datastore(project_id).delete_family(project_id, family_id) families_to_load.append(family) # reload family print("Loading %(project_id)s %(families_to_load)s" % locals()) xbrowse_controls.load_variants_for_family_list(project, families_to_load, vcf_file)
from django.core.management.base import BaseCommand from xbrowse_server import xbrowse_controls from xbrowse_server.base.models import Project from xbrowse_server.mall import get_datastore class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('-p', "--project-id") def handle(self, *args, **options): project_id = options["project_id"] family_ids = args project = Project.objects.get(project_id=project_id) already_deleted_once = set() # set of family ids for which get_datastore(project_id).delete_family has already been called once for vcf_file, families in project.families_by_vcf().items(): families_to_load = [] for family in families: family_id = family.family_id print("Checking id: " + family_id) if not family_ids or family.family_id not in family_ids: continue # delete this family if family_id not in already_deleted_once: get_datastore(project_id).delete_family(project_id, family_id) already_deleted_once.add(family_id) families_to_load.append(family) # reload family print("Loading %(project_id)s %(families_to_load)s" % locals()) xbrowse_controls.load_variants_for_family_list(project, families_to_load, vcf_file)
Fix reload command for projects where each chrom is in a different vcf
Fix reload command for projects where each chrom is in a different vcf
Python
agpl-3.0
ssadedin/seqr,macarthur-lab/xbrowse,macarthur-lab/seqr,ssadedin/seqr,macarthur-lab/seqr,ssadedin/seqr,macarthur-lab/xbrowse,macarthur-lab/xbrowse,ssadedin/seqr,macarthur-lab/xbrowse,ssadedin/seqr,macarthur-lab/xbrowse,macarthur-lab/seqr,macarthur-lab/seqr,macarthur-lab/seqr,macarthur-lab/xbrowse
from django.core.management.base import BaseCommand from xbrowse_server import xbrowse_controls from xbrowse_server.base.models import Project from xbrowse_server.mall import get_datastore class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('-p', "--project-id") def handle(self, *args, **options): project_id = options["project_id"] family_ids = args project = Project.objects.get(project_id=project_id) for vcf_file, families in project.families_by_vcf().items(): families_to_load = [] for family in families: family_id = family.family_id print("Checking id: " + family_id) if not family_ids or family.family_id not in family_ids: continue # delete this family get_datastore(project_id).delete_family(project_id, family_id) families_to_load.append(family) # reload family print("Loading %(project_id)s %(families_to_load)s" % locals()) xbrowse_controls.load_variants_for_family_list(project, families_to_load, vcf_file) Fix reload command for projects where each chrom is in a different vcf
from django.core.management.base import BaseCommand from xbrowse_server import xbrowse_controls from xbrowse_server.base.models import Project from xbrowse_server.mall import get_datastore class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('-p', "--project-id") def handle(self, *args, **options): project_id = options["project_id"] family_ids = args project = Project.objects.get(project_id=project_id) already_deleted_once = set() # set of family ids for which get_datastore(project_id).delete_family has already been called once for vcf_file, families in project.families_by_vcf().items(): families_to_load = [] for family in families: family_id = family.family_id print("Checking id: " + family_id) if not family_ids or family.family_id not in family_ids: continue # delete this family if family_id not in already_deleted_once: get_datastore(project_id).delete_family(project_id, family_id) already_deleted_once.add(family_id) families_to_load.append(family) # reload family print("Loading %(project_id)s %(families_to_load)s" % locals()) xbrowse_controls.load_variants_for_family_list(project, families_to_load, vcf_file)
<commit_before>from django.core.management.base import BaseCommand from xbrowse_server import xbrowse_controls from xbrowse_server.base.models import Project from xbrowse_server.mall import get_datastore class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('-p', "--project-id") def handle(self, *args, **options): project_id = options["project_id"] family_ids = args project = Project.objects.get(project_id=project_id) for vcf_file, families in project.families_by_vcf().items(): families_to_load = [] for family in families: family_id = family.family_id print("Checking id: " + family_id) if not family_ids or family.family_id not in family_ids: continue # delete this family get_datastore(project_id).delete_family(project_id, family_id) families_to_load.append(family) # reload family print("Loading %(project_id)s %(families_to_load)s" % locals()) xbrowse_controls.load_variants_for_family_list(project, families_to_load, vcf_file) <commit_msg>Fix reload command for projects where each chrom is in a different vcf<commit_after>
from django.core.management.base import BaseCommand from xbrowse_server import xbrowse_controls from xbrowse_server.base.models import Project from xbrowse_server.mall import get_datastore class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('-p', "--project-id") def handle(self, *args, **options): project_id = options["project_id"] family_ids = args project = Project.objects.get(project_id=project_id) already_deleted_once = set() # set of family ids for which get_datastore(project_id).delete_family has already been called once for vcf_file, families in project.families_by_vcf().items(): families_to_load = [] for family in families: family_id = family.family_id print("Checking id: " + family_id) if not family_ids or family.family_id not in family_ids: continue # delete this family if family_id not in already_deleted_once: get_datastore(project_id).delete_family(project_id, family_id) already_deleted_once.add(family_id) families_to_load.append(family) # reload family print("Loading %(project_id)s %(families_to_load)s" % locals()) xbrowse_controls.load_variants_for_family_list(project, families_to_load, vcf_file)
from django.core.management.base import BaseCommand from xbrowse_server import xbrowse_controls from xbrowse_server.base.models import Project from xbrowse_server.mall import get_datastore class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('-p', "--project-id") def handle(self, *args, **options): project_id = options["project_id"] family_ids = args project = Project.objects.get(project_id=project_id) for vcf_file, families in project.families_by_vcf().items(): families_to_load = [] for family in families: family_id = family.family_id print("Checking id: " + family_id) if not family_ids or family.family_id not in family_ids: continue # delete this family get_datastore(project_id).delete_family(project_id, family_id) families_to_load.append(family) # reload family print("Loading %(project_id)s %(families_to_load)s" % locals()) xbrowse_controls.load_variants_for_family_list(project, families_to_load, vcf_file) Fix reload command for projects where each chrom is in a different vcffrom django.core.management.base import BaseCommand from xbrowse_server import xbrowse_controls from xbrowse_server.base.models import Project from xbrowse_server.mall import get_datastore class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('-p', "--project-id") def handle(self, *args, **options): project_id = options["project_id"] family_ids = args project = Project.objects.get(project_id=project_id) already_deleted_once = set() # set of family ids for which get_datastore(project_id).delete_family has already been called once for vcf_file, families in project.families_by_vcf().items(): families_to_load = [] for family in families: family_id = family.family_id print("Checking id: " + family_id) if not family_ids or family.family_id not in family_ids: continue # delete this family if family_id not in already_deleted_once: get_datastore(project_id).delete_family(project_id, family_id) already_deleted_once.add(family_id) families_to_load.append(family) # reload family print("Loading %(project_id)s %(families_to_load)s" % locals()) xbrowse_controls.load_variants_for_family_list(project, families_to_load, vcf_file)
<commit_before>from django.core.management.base import BaseCommand from xbrowse_server import xbrowse_controls from xbrowse_server.base.models import Project from xbrowse_server.mall import get_datastore class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('-p', "--project-id") def handle(self, *args, **options): project_id = options["project_id"] family_ids = args project = Project.objects.get(project_id=project_id) for vcf_file, families in project.families_by_vcf().items(): families_to_load = [] for family in families: family_id = family.family_id print("Checking id: " + family_id) if not family_ids or family.family_id not in family_ids: continue # delete this family get_datastore(project_id).delete_family(project_id, family_id) families_to_load.append(family) # reload family print("Loading %(project_id)s %(families_to_load)s" % locals()) xbrowse_controls.load_variants_for_family_list(project, families_to_load, vcf_file) <commit_msg>Fix reload command for projects where each chrom is in a different vcf<commit_after>from django.core.management.base import BaseCommand from xbrowse_server import xbrowse_controls from xbrowse_server.base.models import Project from xbrowse_server.mall import get_datastore class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('-p', "--project-id") def handle(self, *args, **options): project_id = options["project_id"] family_ids = args project = Project.objects.get(project_id=project_id) already_deleted_once = set() # set of family ids for which get_datastore(project_id).delete_family has already been called once for vcf_file, families in project.families_by_vcf().items(): families_to_load = [] for family in families: family_id = family.family_id print("Checking id: " + family_id) if not family_ids or family.family_id not in family_ids: continue # delete this family if family_id not in already_deleted_once: get_datastore(project_id).delete_family(project_id, family_id) already_deleted_once.add(family_id) families_to_load.append(family) # reload family print("Loading %(project_id)s %(families_to_load)s" % locals()) xbrowse_controls.load_variants_for_family_list(project, families_to_load, vcf_file)
f535f44e625663d21f26d8879f293206ec60cf39
lms/envs/dev_int.py
lms/envs/dev_int.py
""" This enables use of course listings by subdomain. To see it in action, point the following domains to 127.0.0.1 in your /etc/hosts file: berkeley.dev harvard.dev mit.dev Note that OS X has a bug where using *.local domains is excruciatingly slow, so use *.dev domains instead for local testing. """ from .dev import * MITX_FEATURES['SUBDOMAIN_COURSE_LISTINGS'] = True COURSE_LISTINGS = { 'default' : ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall', 'HarvardX/CS50x/2012', 'HarvardX/PH207x/2012_Fall' 'MITx/3.091x/2012_Fall', 'MITx/6.002x/2012_Fall', 'MITx/6.00x/2012_Fall'], 'berkeley': ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall'], 'harvard' : ['HarvardX/CS50x/2012'], 'mit' : ['MITx/3.091x/2012_Fall', 'MITx/6.00x/2012_Fall'] }
""" This enables use of course listings by subdomain. To see it in action, point the following domains to 127.0.0.1 in your /etc/hosts file: berkeley.dev harvard.dev mit.dev Note that OS X has a bug where using *.local domains is excruciatingly slow, so use *.dev domains instead for local testing. """ from .dev import * MITX_FEATURES['SUBDOMAIN_COURSE_LISTINGS'] = True COURSE_LISTINGS = { 'default' : ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall', 'HarvardX/CS50x/2012', 'HarvardX/PH207x/2012_Fall', 'MITx/3.091x/2012_Fall', 'MITx/6.002x/2012_Fall', 'MITx/6.00x/2012_Fall'], 'berkeley': ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall'], 'harvard' : ['HarvardX/CS50x/2012'], 'mit' : ['MITx/3.091x/2012_Fall', 'MITx/6.00x/2012_Fall'] }
Fix typo that caused two classes to not get loaded
Fix typo that caused two classes to not get loaded
Python
agpl-3.0
J861449197/edx-platform,nanolearningllc/edx-platform-cypress-2,Semi-global/edx-platform,dcosentino/edx-platform,beni55/edx-platform,xuxiao19910803/edx-platform,pelikanchik/edx-platform,dkarakats/edx-platform,adoosii/edx-platform,shashank971/edx-platform,shabab12/edx-platform,nttks/jenkins-test,knehez/edx-platform,auferack08/edx-platform,hkawasaki/kawasaki-aio8-0,openfun/edx-platform,antonve/s4-project-mooc,Softmotions/edx-platform,IndonesiaX/edx-platform,Semi-global/edx-platform,chrisndodge/edx-platform,edry/edx-platform,Edraak/edraak-platform,dsajkl/123,ZLLab-Mooc/edx-platform,edx/edx-platform,eemirtekin/edx-platform,cselis86/edx-platform,sudheerchintala/LearnEraPlatForm,mjirayu/sit_academy,IITBinterns13/edx-platform-dev,morpheby/levelup-by,appliedx/edx-platform,ferabra/edx-platform,Endika/edx-platform,pomegranited/edx-platform,nanolearningllc/edx-platform-cypress-2,chrisndodge/edx-platform,unicri/edx-platform,shubhdev/edx-platform,abdoosh00/edx-rtl-final,eemirtekin/edx-platform,martynovp/edx-platform,cecep-edu/edx-platform,motion2015/edx-platform,ZLLab-Mooc/edx-platform,hkawasaki/kawasaki-aio8-2,rismalrv/edx-platform,nikolas/edx-platform,OmarIthawi/edx-platform,Softmotions/edx-platform,knehez/edx-platform,marcore/edx-platform,kamalx/edx-platform,gymnasium/edx-platform,shubhdev/openedx,yokose-ks/edx-platform,edry/edx-platform,jamiefolsom/edx-platform,jbzdak/edx-platform,zubair-arbi/edx-platform,raccoongang/edx-platform,shabab12/edx-platform,devs1991/test_edx_docmode,SivilTaram/edx-platform,IndonesiaX/edx-platform,wwj718/ANALYSE,bdero/edx-platform,praveen-pal/edx-platform,4eek/edx-platform,andyzsf/edx,tiagochiavericosta/edx-platform,IndonesiaX/edx-platform,mahendra-r/edx-platform,xuxiao19910803/edx,doganov/edx-platform,raccoongang/edx-platform,dsajkl/reqiop,J861449197/edx-platform,Ayub-Khan/edx-platform,etzhou/edx-platform,arbrandes/edx-platform,cpennington/edx-platform,knehez/edx-platform,pomegranited/edx-platform,hkawasaki/kawasaki-aio8-1,vikas1885/test1,vismartltd/edx-platform,jonathan-beard/edx-platform,cecep-edu/edx-platform,dcosentino/edx-platform,vismartltd/edx-platform,bitifirefly/edx-platform,playm2mboy/edx-platform,nttks/edx-platform,ahmadiga/min_edx,jamesblunt/edx-platform,Kalyzee/edx-platform,dsajkl/reqiop,EduPepperPD/pepper2013,jjmiranda/edx-platform,lduarte1991/edx-platform,kmoocdev2/edx-platform,xingyepei/edx-platform,apigee/edx-platform,lduarte1991/edx-platform,DNFcode/edx-platform,xuxiao19910803/edx,iivic/BoiseStateX,y12uc231/edx-platform,polimediaupv/edx-platform,zadgroup/edx-platform,waheedahmed/edx-platform,beacloudgenius/edx-platform,defance/edx-platform,naresh21/synergetics-edx-platform,Endika/edx-platform,Unow/edx-platform,y12uc231/edx-platform,valtech-mooc/edx-platform,atsolakid/edx-platform,SravanthiSinha/edx-platform,ferabra/edx-platform,RPI-OPENEDX/edx-platform,IONISx/edx-platform,jonathan-beard/edx-platform,ESOedX/edx-platform,longmen21/edx-platform,jazkarta/edx-platform-for-isc,dkarakats/edx-platform,eemirtekin/edx-platform,eduNEXT/edx-platform,hamzehd/edx-platform,kursitet/edx-platform,ahmedaljazzar/edx-platform,ak2703/edx-platform,Edraak/edx-platform,xuxiao19910803/edx-platform,shabab12/edx-platform,mjg2203/edx-platform-seas,jazkarta/edx-platform-for-isc,Unow/edx-platform,motion2015/a3,nanolearningllc/edx-platform-cypress-2,EduPepperPD/pepper2013,msegado/edx-platform,rue89-tech/edx-platform,proversity-org/edx-platform,martynovp/edx-platform,Ayub-Khan/edx-platform,LearnEra/LearnEraPlaftform,vikas1885/test1,rationalAgent/edx-platform-custom,bigdatauniversity/edx-platform,Softmotions/edx-platform,beacloudgenius/edx-platform,dkarakats/edx-platform,rhndg/openedx,xingyepei/edx-platform,nanolearningllc/edx-platform-cypress,abdoosh00/edraak,Softmotions/edx-platform,ak2703/edx-platform,gsehub/edx-platform,jazkarta/edx-platform,romain-li/edx-platform,RPI-OPENEDX/edx-platform,kmoocdev/edx-platform,sudheerchintala/LearnEraPlatForm,etzhou/edx-platform,jbassen/edx-platform,chudaol/edx-platform,kmoocdev/edx-platform,WatanabeYasumasa/edx-platform,IONISx/edx-platform,leansoft/edx-platform,nikolas/edx-platform,caesar2164/edx-platform,zhenzhai/edx-platform,nagyistoce/edx-platform,jelugbo/tundex,pdehaye/theming-edx-platform,olexiim/edx-platform,JCBarahona/edX,morenopc/edx-platform,TsinghuaX/edx-platform,defance/edx-platform,jzoldak/edx-platform,arbrandes/edx-platform,louyihua/edx-platform,peterm-itr/edx-platform,shashank971/edx-platform,ferabra/edx-platform,sameetb-cuelogic/edx-platform-test,pelikanchik/edx-platform,RPI-OPENEDX/edx-platform,cognitiveclass/edx-platform,jamiefolsom/edx-platform,hkawasaki/kawasaki-aio8-0,ESOedX/edx-platform,TsinghuaX/edx-platform,pabloborrego93/edx-platform,jjmiranda/edx-platform,abdoosh00/edraak,JioEducation/edx-platform,ZLLab-Mooc/edx-platform,EduPepperPDTesting/pepper2013-testing,morenopc/edx-platform,halvertoluke/edx-platform,hmcmooc/muddx-platform,vikas1885/test1,wwj718/ANALYSE,stvstnfrd/edx-platform,rue89-tech/edx-platform,torchingloom/edx-platform,CredoReference/edx-platform,nikolas/edx-platform,torchingloom/edx-platform,auferack08/edx-platform,morpheby/levelup-by,don-github/edx-platform,philanthropy-u/edx-platform,zerobatu/edx-platform,OmarIthawi/edx-platform,playm2mboy/edx-platform,Kalyzee/edx-platform,franosincic/edx-platform,LICEF/edx-platform,chauhanhardik/populo,chauhanhardik/populo_2,romain-li/edx-platform,eestay/edx-platform,analyseuc3m/ANALYSE-v1,stvstnfrd/edx-platform,peterm-itr/edx-platform,hkawasaki/kawasaki-aio8-2,olexiim/edx-platform,etzhou/edx-platform,mushtaqak/edx-platform,motion2015/a3,halvertoluke/edx-platform,IONISx/edx-platform,alexthered/kienhoc-platform,jjmiranda/edx-platform,nikolas/edx-platform,kmoocdev/edx-platform,iivic/BoiseStateX,itsjeyd/edx-platform,DefyVentures/edx-platform,hamzehd/edx-platform,jazkarta/edx-platform-for-isc,ak2703/edx-platform,DNFcode/edx-platform,fintech-circle/edx-platform,y12uc231/edx-platform,AkA84/edx-platform,UXE/local-edx,SravanthiSinha/edx-platform,B-MOOC/edx-platform,martynovp/edx-platform,EduPepperPDTesting/pepper2013-testing,SivilTaram/edx-platform,analyseuc3m/ANALYSE-v1,Shrhawk/edx-platform,kursitet/edx-platform,pepeportela/edx-platform,eduNEXT/edunext-platform,motion2015/a3,ampax/edx-platform-backup,ahmadiga/min_edx,JCBarahona/edX,vismartltd/edx-platform,benpatterson/edx-platform,AkA84/edx-platform,mtlchun/edx,morenopc/edx-platform,kalebhartje/schoolboost,pku9104038/edx-platform,LICEF/edx-platform,rhndg/openedx,pku9104038/edx-platform,IndonesiaX/edx-platform,antoviaque/edx-platform,apigee/edx-platform,xuxiao19910803/edx-platform,philanthropy-u/edx-platform,carsongee/edx-platform,olexiim/edx-platform,doganov/edx-platform,shabab12/edx-platform,shubhdev/edx-platform,cselis86/edx-platform,caesar2164/edx-platform,openfun/edx-platform,iivic/BoiseStateX,TeachAtTUM/edx-platform,shubhdev/edx-platform,iivic/BoiseStateX,hastexo/edx-platform,polimediaupv/edx-platform,wwj718/ANALYSE,nanolearningllc/edx-platform-cypress,jruiperezv/ANALYSE,zerobatu/edx-platform,bigdatauniversity/edx-platform,dsajkl/123,eemirtekin/edx-platform,cpennington/edx-platform,MSOpenTech/edx-platform,mcgachey/edx-platform,pabloborrego93/edx-platform,MakeHer/edx-platform,CourseTalk/edx-platform,hamzehd/edx-platform,benpatterson/edx-platform,Stanford-Online/edx-platform,UOMx/edx-platform,PepperPD/edx-pepper-platform,EDUlib/edx-platform,xinjiguaike/edx-platform,vasyarv/edx-platform,motion2015/edx-platform,Edraak/circleci-edx-platform,doganov/edx-platform,angelapper/edx-platform,mahendra-r/edx-platform,analyseuc3m/ANALYSE-v1,BehavioralInsightsTeam/edx-platform,ovnicraft/edx-platform,defance/edx-platform,ahmedaljazzar/edx-platform,sameetb-cuelogic/edx-platform-test,zerobatu/edx-platform,nttks/edx-platform,sameetb-cuelogic/edx-platform-test,utecuy/edx-platform,mushtaqak/edx-platform,edx-solutions/edx-platform,gsehub/edx-platform,CredoReference/edx-platform,MSOpenTech/edx-platform,MSOpenTech/edx-platform,louyihua/edx-platform,jonathan-beard/edx-platform,JCBarahona/edX,procangroup/edx-platform,simbs/edx-platform,shubhdev/edxOnBaadal,nanolearningllc/edx-platform-cypress,mahendra-r/edx-platform,eestay/edx-platform,leansoft/edx-platform,inares/edx-platform,nttks/edx-platform,eduNEXT/edunext-platform,ahmedaljazzar/edx-platform,LearnEra/LearnEraPlaftform,raccoongang/edx-platform,ESOedX/edx-platform,miptliot/edx-platform,inares/edx-platform,jazztpt/edx-platform,raccoongang/edx-platform,fly19890211/edx-platform,MakeHer/edx-platform,xinjiguaike/edx-platform,franosincic/edx-platform,gymnasium/edx-platform,benpatterson/edx-platform,cognitiveclass/edx-platform,jbassen/edx-platform,alexthered/kienhoc-platform,torchingloom/edx-platform,J861449197/edx-platform,Edraak/edx-platform,kursitet/edx-platform,appliedx/edx-platform,don-github/edx-platform,andyzsf/edx,devs1991/test_edx_docmode,ak2703/edx-platform,BehavioralInsightsTeam/edx-platform,doismellburning/edx-platform,rhndg/openedx,yokose-ks/edx-platform,msegado/edx-platform,lduarte1991/edx-platform,simbs/edx-platform,mtlchun/edx,edx/edx-platform,xuxiao19910803/edx-platform,hastexo/edx-platform,rue89-tech/edx-platform,TsinghuaX/edx-platform,hkawasaki/kawasaki-aio8-2,cselis86/edx-platform,morenopc/edx-platform,teltek/edx-platform,zadgroup/edx-platform,wwj718/edx-platform,morpheby/levelup-by,arifsetiawan/edx-platform,doganov/edx-platform,eduNEXT/edunext-platform,Shrhawk/edx-platform,nagyistoce/edx-platform,prarthitm/edxplatform,Lektorium-LLC/edx-platform,mjirayu/sit_academy,chand3040/cloud_that,jelugbo/tundex,amir-qayyum-khan/edx-platform,hkawasaki/kawasaki-aio8-1,zubair-arbi/edx-platform,jazztpt/edx-platform,edry/edx-platform,amir-qayyum-khan/edx-platform,Edraak/edraak-platform,gsehub/edx-platform,kxliugang/edx-platform,a-parhom/edx-platform,zadgroup/edx-platform,waheedahmed/edx-platform,valtech-mooc/edx-platform,angelapper/edx-platform,chand3040/cloud_that,ampax/edx-platform-backup,syjeon/new_edx,eestay/edx-platform,kmoocdev2/edx-platform,jjmiranda/edx-platform,edx-solutions/edx-platform,ampax/edx-platform-backup,pepeportela/edx-platform,fly19890211/edx-platform,ferabra/edx-platform,alu042/edx-platform,Edraak/edx-platform,jruiperezv/ANALYSE,ESOedX/edx-platform,vikas1885/test1,prarthitm/edxplatform,rhndg/openedx,kursitet/edx-platform,EduPepperPDTesting/pepper2013-testing,motion2015/edx-platform,appliedx/edx-platform,jswope00/GAI,mahendra-r/edx-platform,valtech-mooc/edx-platform,kalebhartje/schoolboost,Softmotions/edx-platform,bigdatauniversity/edx-platform,solashirai/edx-platform,etzhou/edx-platform,inares/edx-platform,Semi-global/edx-platform,zhenzhai/edx-platform,vasyarv/edx-platform,MakeHer/edx-platform,Semi-global/edx-platform,Stanford-Online/edx-platform,antonve/s4-project-mooc,gymnasium/edx-platform,PepperPD/edx-pepper-platform,jazkarta/edx-platform,playm2mboy/edx-platform,openfun/edx-platform,abdoosh00/edraak,Livit/Livit.Learn.EdX,AkA84/edx-platform,devs1991/test_edx_docmode,10clouds/edx-platform,jswope00/griffinx,hmcmooc/muddx-platform,jelugbo/tundex,shurihell/testasia,nttks/edx-platform,devs1991/test_edx_docmode,PepperPD/edx-pepper-platform,mtlchun/edx,DefyVentures/edx-platform,marcore/edx-platform,shubhdev/openedx,gymnasium/edx-platform,kamalx/edx-platform,UXE/local-edx,PepperPD/edx-pepper-platform,cecep-edu/edx-platform,mushtaqak/edx-platform,hamzehd/edx-platform,teltek/edx-platform,mbareta/edx-platform-ft,ahmadiga/min_edx,fly19890211/edx-platform,defance/edx-platform,sameetb-cuelogic/edx-platform-test,jswope00/griffinx,SivilTaram/edx-platform,ovnicraft/edx-platform,unicri/edx-platform,ahmadio/edx-platform,AkA84/edx-platform,CourseTalk/edx-platform,DNFcode/edx-platform,nagyistoce/edx-platform,atsolakid/edx-platform,bigdatauniversity/edx-platform,LearnEra/LearnEraPlaftform,vasyarv/edx-platform,shurihell/testasia,motion2015/edx-platform,openfun/edx-platform,beni55/edx-platform,xuxiao19910803/edx,beacloudgenius/edx-platform,jzoldak/edx-platform,stvstnfrd/edx-platform,teltek/edx-platform,EduPepperPD/pepper2013,Ayub-Khan/edx-platform,zubair-arbi/edx-platform,4eek/edx-platform,doismellburning/edx-platform,andyzsf/edx,Stanford-Online/edx-platform,WatanabeYasumasa/edx-platform,jruiperezv/ANALYSE,atsolakid/edx-platform,cyanna/edx-platform,alu042/edx-platform,vismartltd/edx-platform,mcgachey/edx-platform,chauhanhardik/populo,hkawasaki/kawasaki-aio8-2,olexiim/edx-platform,Endika/edx-platform,jelugbo/tundex,antonve/s4-project-mooc,UXE/local-edx,edx/edx-platform,chand3040/cloud_that,shubhdev/edxOnBaadal,longmen21/edx-platform,eemirtekin/edx-platform,jbassen/edx-platform,synergeticsedx/deployment-wipro,nttks/edx-platform,Edraak/edraak-platform,rismalrv/edx-platform,beni55/edx-platform,pelikanchik/edx-platform,jbzdak/edx-platform,UOMx/edx-platform,edx-solutions/edx-platform,B-MOOC/edx-platform,TeachAtTUM/edx-platform,fintech-circle/edx-platform,DNFcode/edx-platform,leansoft/edx-platform,adoosii/edx-platform,antoviaque/edx-platform,mbareta/edx-platform-ft,polimediaupv/edx-platform,SravanthiSinha/edx-platform,arifsetiawan/edx-platform,alexthered/kienhoc-platform,kalebhartje/schoolboost,IONISx/edx-platform,gsehub/edx-platform,shashank971/edx-platform,wwj718/edx-platform,jazztpt/edx-platform,shubhdev/edxOnBaadal,jolyonb/edx-platform,jelugbo/tundex,edry/edx-platform,dsajkl/123,bigdatauniversity/edx-platform,chauhanhardik/populo_2,simbs/edx-platform,waheedahmed/edx-platform,ubc/edx-platform,deepsrijit1105/edx-platform,longmen21/edx-platform,romain-li/edx-platform,nanolearning/edx-platform,ak2703/edx-platform,chudaol/edx-platform,nikolas/edx-platform,syjeon/new_edx,jruiperezv/ANALYSE,DefyVentures/edx-platform,synergeticsedx/deployment-wipro,cognitiveclass/edx-platform,mitocw/edx-platform,ampax/edx-platform,OmarIthawi/edx-platform,pdehaye/theming-edx-platform,devs1991/test_edx_docmode,nanolearningllc/edx-platform-cypress,zhenzhai/edx-platform,ubc/edx-platform,inares/edx-platform,xinjiguaike/edx-platform,ampax/edx-platform,Semi-global/edx-platform,jzoldak/edx-platform,andyzsf/edx,adoosii/edx-platform,franosincic/edx-platform,mjirayu/sit_academy,chand3040/cloud_that,jruiperezv/ANALYSE,a-parhom/edx-platform,alexthered/kienhoc-platform,teltek/edx-platform,hamzehd/edx-platform,cecep-edu/edx-platform,hkawasaki/kawasaki-aio8-0,bitifirefly/edx-platform,auferack08/edx-platform,torchingloom/edx-platform,chauhanhardik/populo_2,ovnicraft/edx-platform,nanolearning/edx-platform,nttks/jenkins-test,shubhdev/openedx,shubhdev/edxOnBaadal,dsajkl/123,mjg2203/edx-platform-seas,jonathan-beard/edx-platform,tanmaykm/edx-platform,eduNEXT/edx-platform,Shrhawk/edx-platform,adoosii/edx-platform,zofuthan/edx-platform,mjirayu/sit_academy,vasyarv/edx-platform,mushtaqak/edx-platform,BehavioralInsightsTeam/edx-platform,arifsetiawan/edx-platform,chrisndodge/edx-platform,Edraak/circleci-edx-platform,4eek/edx-platform,caesar2164/edx-platform,arifsetiawan/edx-platform,jonathan-beard/edx-platform,hkawasaki/kawasaki-aio8-1,shashank971/edx-platform,shubhdev/edx-platform,UOMx/edx-platform,MakeHer/edx-platform,LICEF/edx-platform,halvertoluke/edx-platform,a-parhom/edx-platform,Unow/edx-platform,louyihua/edx-platform,WatanabeYasumasa/edx-platform,wwj718/edx-platform,utecuy/edx-platform,rismalrv/edx-platform,zubair-arbi/edx-platform,itsjeyd/edx-platform,JioEducation/edx-platform,chauhanhardik/populo,RPI-OPENEDX/edx-platform,ubc/edx-platform,bdero/edx-platform,philanthropy-u/edx-platform,inares/edx-platform,pku9104038/edx-platform,B-MOOC/edx-platform,JioEducation/edx-platform,arbrandes/edx-platform,apigee/edx-platform,deepsrijit1105/edx-platform,analyseuc3m/ANALYSE-v1,ahmadio/edx-platform,bdero/edx-platform,itsjeyd/edx-platform,don-github/edx-platform,CourseTalk/edx-platform,EDUlib/edx-platform,mitocw/edx-platform,mbareta/edx-platform-ft,Shrhawk/edx-platform,miptliot/edx-platform,simbs/edx-platform,jzoldak/edx-platform,Ayub-Khan/edx-platform,rationalAgent/edx-platform-custom,Shrhawk/edx-platform,devs1991/test_edx_docmode,MSOpenTech/edx-platform,pdehaye/theming-edx-platform,dkarakats/edx-platform,tanmaykm/edx-platform,abdoosh00/edx-rtl-final,xinjiguaike/edx-platform,nagyistoce/edx-platform,marcore/edx-platform,pabloborrego93/edx-platform,kxliugang/edx-platform,CredoReference/edx-platform,chudaol/edx-platform,proversity-org/edx-platform,wwj718/edx-platform,openfun/edx-platform,Stanford-Online/edx-platform,appsembler/edx-platform,shurihell/testasia,leansoft/edx-platform,4eek/edx-platform,solashirai/edx-platform,TeachAtTUM/edx-platform,alu042/edx-platform,rismalrv/edx-platform,yokose-ks/edx-platform,hmcmooc/muddx-platform,jazztpt/edx-platform,pomegranited/edx-platform,doismellburning/edx-platform,fly19890211/edx-platform,yokose-ks/edx-platform,antonve/s4-project-mooc,y12uc231/edx-platform,J861449197/edx-platform,Endika/edx-platform,Edraak/edraak-platform,chrisndodge/edx-platform,vismartltd/edx-platform,Edraak/circleci-edx-platform,solashirai/edx-platform,proversity-org/edx-platform,LearnEra/LearnEraPlaftform,amir-qayyum-khan/edx-platform,cyanna/edx-platform,kamalx/edx-platform,UOMx/edx-platform,halvertoluke/edx-platform,morenopc/edx-platform,procangroup/edx-platform,B-MOOC/edx-platform,dsajkl/reqiop,EDUlib/edx-platform,auferack08/edx-platform,romain-li/edx-platform,playm2mboy/edx-platform,rationalAgent/edx-platform-custom,kamalx/edx-platform,tiagochiavericosta/edx-platform,jazkarta/edx-platform,polimediaupv/edx-platform,eduNEXT/edx-platform,jbassen/edx-platform,eduNEXT/edx-platform,edry/edx-platform,shashank971/edx-platform,mushtaqak/edx-platform,eestay/edx-platform,kxliugang/edx-platform,vikas1885/test1,dsajkl/123,utecuy/edx-platform,eduNEXT/edunext-platform,chand3040/cloud_that,jswope00/GAI,abdoosh00/edraak,mitocw/edx-platform,msegado/edx-platform,sudheerchintala/LearnEraPlatForm,cyanna/edx-platform,atsolakid/edx-platform,ampax/edx-platform,zhenzhai/edx-platform,chauhanhardik/populo_2,zerobatu/edx-platform,rue89-tech/edx-platform,jazkarta/edx-platform-for-isc,mtlchun/edx,apigee/edx-platform,pdehaye/theming-edx-platform,procangroup/edx-platform,beacloudgenius/edx-platform,hkawasaki/kawasaki-aio8-1,kmoocdev2/edx-platform,cselis86/edx-platform,ubc/edx-platform,polimediaupv/edx-platform,leansoft/edx-platform,devs1991/test_edx_docmode,jazztpt/edx-platform,bitifirefly/edx-platform,franosincic/edx-platform,waheedahmed/edx-platform,alu042/edx-platform,ampax/edx-platform-backup,zerobatu/edx-platform,peterm-itr/edx-platform,solashirai/edx-platform,EDUlib/edx-platform,zofuthan/edx-platform,caesar2164/edx-platform,peterm-itr/edx-platform,TsinghuaX/edx-platform,y12uc231/edx-platform,jswope00/griffinx,Ayub-Khan/edx-platform,LICEF/edx-platform,tiagochiavericosta/edx-platform,marcore/edx-platform,praveen-pal/edx-platform,utecuy/edx-platform,unicri/edx-platform,antoviaque/edx-platform,jazkarta/edx-platform,hastexo/edx-platform,DefyVentures/edx-platform,EduPepperPDTesting/pepper2013-testing,franosincic/edx-platform,jbzdak/edx-platform,carsongee/edx-platform,valtech-mooc/edx-platform,tanmaykm/edx-platform,rismalrv/edx-platform,Edraak/edx-platform,appliedx/edx-platform,Unow/edx-platform,JioEducation/edx-platform,pepeportela/edx-platform,rationalAgent/edx-platform-custom,jswope00/griffinx,nagyistoce/edx-platform,ahmadio/edx-platform,jolyonb/edx-platform,bdero/edx-platform,rationalAgent/edx-platform-custom,jolyonb/edx-platform,jazkarta/edx-platform,proversity-org/edx-platform,chauhanhardik/populo,LICEF/edx-platform,Lektorium-LLC/edx-platform,carsongee/edx-platform,kursitet/edx-platform,JCBarahona/edX,dcosentino/edx-platform,benpatterson/edx-platform,MSOpenTech/edx-platform,zofuthan/edx-platform,abdoosh00/edx-rtl-final,benpatterson/edx-platform,jamiefolsom/edx-platform,xuxiao19910803/edx,beacloudgenius/edx-platform,EduPepperPDTesting/pepper2013-testing,UXE/local-edx,kalebhartje/schoolboost,DNFcode/edx-platform,shubhdev/edx-platform,itsjeyd/edx-platform,beni55/edx-platform,Edraak/edx-platform,zubair-arbi/edx-platform,cpennington/edx-platform,jswope00/griffinx,jamesblunt/edx-platform,fintech-circle/edx-platform,ZLLab-Mooc/edx-platform,vasyarv/edx-platform,ZLLab-Mooc/edx-platform,knehez/edx-platform,waheedahmed/edx-platform,arifsetiawan/edx-platform,10clouds/edx-platform,pku9104038/edx-platform,pelikanchik/edx-platform,SravanthiSinha/edx-platform,nttks/jenkins-test,ferabra/edx-platform,chudaol/edx-platform,xinjiguaike/edx-platform,arbrandes/edx-platform,zofuthan/edx-platform,xuxiao19910803/edx-platform,10clouds/edx-platform,naresh21/synergetics-edx-platform,dkarakats/edx-platform,Kalyzee/edx-platform,angelapper/edx-platform,cyanna/edx-platform,halvertoluke/edx-platform,cpennington/edx-platform,jswope00/GAI,playm2mboy/edx-platform,etzhou/edx-platform,hastexo/edx-platform,SravanthiSinha/edx-platform,a-parhom/edx-platform,ovnicraft/edx-platform,AkA84/edx-platform,kalebhartje/schoolboost,IITBinterns13/edx-platform-dev,knehez/edx-platform,hmcmooc/muddx-platform,chauhanhardik/populo,don-github/edx-platform,utecuy/edx-platform,ahmedaljazzar/edx-platform,JCBarahona/edX,B-MOOC/edx-platform,lduarte1991/edx-platform,tiagochiavericosta/edx-platform,beni55/edx-platform,angelapper/edx-platform,cognitiveclass/edx-platform,mitocw/edx-platform,10clouds/edx-platform,pomegranited/edx-platform,romain-li/edx-platform,martynovp/edx-platform,Livit/Livit.Learn.EdX,doismellburning/edx-platform,zadgroup/edx-platform,kmoocdev/edx-platform,eestay/edx-platform,fintech-circle/edx-platform,cselis86/edx-platform,chauhanhardik/populo_2,motion2015/edx-platform,Livit/Livit.Learn.EdX,doismellburning/edx-platform,bitifirefly/edx-platform,kmoocdev2/edx-platform,cyanna/edx-platform,Kalyzee/edx-platform,don-github/edx-platform,ahmadio/edx-platform,xuxiao19910803/edx,antonve/s4-project-mooc,SivilTaram/edx-platform,longmen21/edx-platform,nanolearning/edx-platform,jolyonb/edx-platform,torchingloom/edx-platform,IndonesiaX/edx-platform,jamiefolsom/edx-platform,motion2015/a3,ahmadiga/min_edx,mbareta/edx-platform-ft,mcgachey/edx-platform,prarthitm/edxplatform,mjg2203/edx-platform-seas,louyihua/edx-platform,jbzdak/edx-platform,kxliugang/edx-platform,CredoReference/edx-platform,IITBinterns13/edx-platform-dev,deepsrijit1105/edx-platform,DefyVentures/edx-platform,IONISx/edx-platform,SivilTaram/edx-platform,ampax/edx-platform,carsongee/edx-platform,nanolearning/edx-platform,mjirayu/sit_academy,shurihell/testasia,shubhdev/edxOnBaadal,unicri/edx-platform,jamesblunt/edx-platform,rue89-tech/edx-platform,tiagochiavericosta/edx-platform,procangroup/edx-platform,kmoocdev2/edx-platform,Lektorium-LLC/edx-platform,sameetb-cuelogic/edx-platform-test,dcosentino/edx-platform,xingyepei/edx-platform,praveen-pal/edx-platform,Edraak/circleci-edx-platform,synergeticsedx/deployment-wipro,ahmadio/edx-platform,IITBinterns13/edx-platform-dev,zofuthan/edx-platform,4eek/edx-platform,iivic/BoiseStateX,olexiim/edx-platform,nttks/jenkins-test,kxliugang/edx-platform,martynovp/edx-platform,kamalx/edx-platform,praveen-pal/edx-platform,mahendra-r/edx-platform,Lektorium-LLC/edx-platform,wwj718/edx-platform,naresh21/synergetics-edx-platform,adoosii/edx-platform,jamesblunt/edx-platform,wwj718/ANALYSE,TeachAtTUM/edx-platform,appliedx/edx-platform,zhenzhai/edx-platform,EduPepperPD/pepper2013,jamiefolsom/edx-platform,hkawasaki/kawasaki-aio8-0,ubc/edx-platform,valtech-mooc/edx-platform,solashirai/edx-platform,Livit/Livit.Learn.EdX,pabloborrego93/edx-platform,RPI-OPENEDX/edx-platform,cognitiveclass/edx-platform,bitifirefly/edx-platform,dsajkl/reqiop,EduPepperPD/pepper2013,syjeon/new_edx,longmen21/edx-platform,cecep-edu/edx-platform,tanmaykm/edx-platform,CourseTalk/edx-platform,EduPepperPDTesting/pepper2013-testing,morpheby/levelup-by,OmarIthawi/edx-platform,mtlchun/edx,Kalyzee/edx-platform,alexthered/kienhoc-platform,philanthropy-u/edx-platform,PepperPD/edx-pepper-platform,MakeHer/edx-platform,antoviaque/edx-platform,fly19890211/edx-platform,xingyepei/edx-platform,jazkarta/edx-platform-for-isc,jbzdak/edx-platform,chudaol/edx-platform,doganov/edx-platform,mcgachey/edx-platform,WatanabeYasumasa/edx-platform,atsolakid/edx-platform,abdoosh00/edx-rtl-final,synergeticsedx/deployment-wipro,ampax/edx-platform-backup,pepeportela/edx-platform,ahmadiga/min_edx,unicri/edx-platform,msegado/edx-platform,devs1991/test_edx_docmode,yokose-ks/edx-platform,prarthitm/edxplatform,syjeon/new_edx,J861449197/edx-platform,jswope00/GAI,stvstnfrd/edx-platform,xingyepei/edx-platform,edx-solutions/edx-platform,nanolearningllc/edx-platform-cypress-2,dcosentino/edx-platform,rhndg/openedx,nanolearningllc/edx-platform-cypress,nanolearning/edx-platform,simbs/edx-platform,edx/edx-platform,shurihell/testasia,miptliot/edx-platform,jbassen/edx-platform,deepsrijit1105/edx-platform,miptliot/edx-platform,amir-qayyum-khan/edx-platform,motion2015/a3,ovnicraft/edx-platform,mjg2203/edx-platform-seas,sudheerchintala/LearnEraPlatForm,shubhdev/openedx,naresh21/synergetics-edx-platform,appsembler/edx-platform,nanolearningllc/edx-platform-cypress-2,shubhdev/openedx,pomegranited/edx-platform,appsembler/edx-platform,mcgachey/edx-platform,appsembler/edx-platform,BehavioralInsightsTeam/edx-platform,wwj718/ANALYSE,nttks/jenkins-test,jamesblunt/edx-platform,Edraak/circleci-edx-platform,zadgroup/edx-platform,msegado/edx-platform,kmoocdev/edx-platform
""" This enables use of course listings by subdomain. To see it in action, point the following domains to 127.0.0.1 in your /etc/hosts file: berkeley.dev harvard.dev mit.dev Note that OS X has a bug where using *.local domains is excruciatingly slow, so use *.dev domains instead for local testing. """ from .dev import * MITX_FEATURES['SUBDOMAIN_COURSE_LISTINGS'] = True COURSE_LISTINGS = { 'default' : ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall', 'HarvardX/CS50x/2012', 'HarvardX/PH207x/2012_Fall' 'MITx/3.091x/2012_Fall', 'MITx/6.002x/2012_Fall', 'MITx/6.00x/2012_Fall'], 'berkeley': ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall'], 'harvard' : ['HarvardX/CS50x/2012'], 'mit' : ['MITx/3.091x/2012_Fall', 'MITx/6.00x/2012_Fall'] } Fix typo that caused two classes to not get loaded
""" This enables use of course listings by subdomain. To see it in action, point the following domains to 127.0.0.1 in your /etc/hosts file: berkeley.dev harvard.dev mit.dev Note that OS X has a bug where using *.local domains is excruciatingly slow, so use *.dev domains instead for local testing. """ from .dev import * MITX_FEATURES['SUBDOMAIN_COURSE_LISTINGS'] = True COURSE_LISTINGS = { 'default' : ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall', 'HarvardX/CS50x/2012', 'HarvardX/PH207x/2012_Fall', 'MITx/3.091x/2012_Fall', 'MITx/6.002x/2012_Fall', 'MITx/6.00x/2012_Fall'], 'berkeley': ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall'], 'harvard' : ['HarvardX/CS50x/2012'], 'mit' : ['MITx/3.091x/2012_Fall', 'MITx/6.00x/2012_Fall'] }
<commit_before>""" This enables use of course listings by subdomain. To see it in action, point the following domains to 127.0.0.1 in your /etc/hosts file: berkeley.dev harvard.dev mit.dev Note that OS X has a bug where using *.local domains is excruciatingly slow, so use *.dev domains instead for local testing. """ from .dev import * MITX_FEATURES['SUBDOMAIN_COURSE_LISTINGS'] = True COURSE_LISTINGS = { 'default' : ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall', 'HarvardX/CS50x/2012', 'HarvardX/PH207x/2012_Fall' 'MITx/3.091x/2012_Fall', 'MITx/6.002x/2012_Fall', 'MITx/6.00x/2012_Fall'], 'berkeley': ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall'], 'harvard' : ['HarvardX/CS50x/2012'], 'mit' : ['MITx/3.091x/2012_Fall', 'MITx/6.00x/2012_Fall'] } <commit_msg>Fix typo that caused two classes to not get loaded<commit_after>
""" This enables use of course listings by subdomain. To see it in action, point the following domains to 127.0.0.1 in your /etc/hosts file: berkeley.dev harvard.dev mit.dev Note that OS X has a bug where using *.local domains is excruciatingly slow, so use *.dev domains instead for local testing. """ from .dev import * MITX_FEATURES['SUBDOMAIN_COURSE_LISTINGS'] = True COURSE_LISTINGS = { 'default' : ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall', 'HarvardX/CS50x/2012', 'HarvardX/PH207x/2012_Fall', 'MITx/3.091x/2012_Fall', 'MITx/6.002x/2012_Fall', 'MITx/6.00x/2012_Fall'], 'berkeley': ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall'], 'harvard' : ['HarvardX/CS50x/2012'], 'mit' : ['MITx/3.091x/2012_Fall', 'MITx/6.00x/2012_Fall'] }
""" This enables use of course listings by subdomain. To see it in action, point the following domains to 127.0.0.1 in your /etc/hosts file: berkeley.dev harvard.dev mit.dev Note that OS X has a bug where using *.local domains is excruciatingly slow, so use *.dev domains instead for local testing. """ from .dev import * MITX_FEATURES['SUBDOMAIN_COURSE_LISTINGS'] = True COURSE_LISTINGS = { 'default' : ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall', 'HarvardX/CS50x/2012', 'HarvardX/PH207x/2012_Fall' 'MITx/3.091x/2012_Fall', 'MITx/6.002x/2012_Fall', 'MITx/6.00x/2012_Fall'], 'berkeley': ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall'], 'harvard' : ['HarvardX/CS50x/2012'], 'mit' : ['MITx/3.091x/2012_Fall', 'MITx/6.00x/2012_Fall'] } Fix typo that caused two classes to not get loaded""" This enables use of course listings by subdomain. To see it in action, point the following domains to 127.0.0.1 in your /etc/hosts file: berkeley.dev harvard.dev mit.dev Note that OS X has a bug where using *.local domains is excruciatingly slow, so use *.dev domains instead for local testing. """ from .dev import * MITX_FEATURES['SUBDOMAIN_COURSE_LISTINGS'] = True COURSE_LISTINGS = { 'default' : ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall', 'HarvardX/CS50x/2012', 'HarvardX/PH207x/2012_Fall', 'MITx/3.091x/2012_Fall', 'MITx/6.002x/2012_Fall', 'MITx/6.00x/2012_Fall'], 'berkeley': ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall'], 'harvard' : ['HarvardX/CS50x/2012'], 'mit' : ['MITx/3.091x/2012_Fall', 'MITx/6.00x/2012_Fall'] }
<commit_before>""" This enables use of course listings by subdomain. To see it in action, point the following domains to 127.0.0.1 in your /etc/hosts file: berkeley.dev harvard.dev mit.dev Note that OS X has a bug where using *.local domains is excruciatingly slow, so use *.dev domains instead for local testing. """ from .dev import * MITX_FEATURES['SUBDOMAIN_COURSE_LISTINGS'] = True COURSE_LISTINGS = { 'default' : ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall', 'HarvardX/CS50x/2012', 'HarvardX/PH207x/2012_Fall' 'MITx/3.091x/2012_Fall', 'MITx/6.002x/2012_Fall', 'MITx/6.00x/2012_Fall'], 'berkeley': ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall'], 'harvard' : ['HarvardX/CS50x/2012'], 'mit' : ['MITx/3.091x/2012_Fall', 'MITx/6.00x/2012_Fall'] } <commit_msg>Fix typo that caused two classes to not get loaded<commit_after>""" This enables use of course listings by subdomain. To see it in action, point the following domains to 127.0.0.1 in your /etc/hosts file: berkeley.dev harvard.dev mit.dev Note that OS X has a bug where using *.local domains is excruciatingly slow, so use *.dev domains instead for local testing. """ from .dev import * MITX_FEATURES['SUBDOMAIN_COURSE_LISTINGS'] = True COURSE_LISTINGS = { 'default' : ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall', 'HarvardX/CS50x/2012', 'HarvardX/PH207x/2012_Fall', 'MITx/3.091x/2012_Fall', 'MITx/6.002x/2012_Fall', 'MITx/6.00x/2012_Fall'], 'berkeley': ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall'], 'harvard' : ['HarvardX/CS50x/2012'], 'mit' : ['MITx/3.091x/2012_Fall', 'MITx/6.00x/2012_Fall'] }
1acd2471f667abf78155ee71fe9c6d8487a284ee
sklearn/linear_model/tests/test_isotonic_regression.py
sklearn/linear_model/tests/test_isotonic_regression.py
import numpy as np from numpy.testing import assert_array_equal from sklearn.linear_model.isotonic_regression_ import isotonic_regression from sklearn.linear_model import IsotonicRegression from nose.tools import assert_raises def test_isotonic_regression(): y = np.array([3, 7, 5, 9, 8, 7, 10]) y_ = np.array([3, 6, 6, 8, 8, 8, 10]) assert_array_equal(y_, isotonic_regression(y)) x = np.arange(len(y)) ir = IsotonicRegression(x_min=0., x_max=1.) ir.fit(x, y) assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) assert_array_equal(ir.transform(x), ir.predict(x)) def test_assert_raises_exceptions(): ir = IsotonicRegression() assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6]) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7]) assert_raises(ValueError, ir.fit, np.random.randn(3, 10), [0, 1, 2]) assert_raises(ValueError, ir.transform, np.random.randn(3, 10))
import numpy as np from numpy.testing import assert_array_equal from sklearn.linear_model.isotonic_regression_ import isotonic_regression from sklearn.linear_model import IsotonicRegression from nose.tools import assert_raises def test_isotonic_regression(): y = np.array([3, 7, 5, 9, 8, 7, 10]) y_ = np.array([3, 6, 6, 8, 8, 8, 10]) assert_array_equal(y_, isotonic_regression(y)) x = np.arange(len(y)) ir = IsotonicRegression(x_min=0., x_max=1.) ir.fit(x, y) assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) assert_array_equal(ir.transform(x), ir.predict(x)) def test_assert_raises_exceptions(): ir = IsotonicRegression() rng = np.random.RandomState(42) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6]) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7]) assert_raises(ValueError, ir.fit, rng.randn(3, 10), [0, 1, 2]) assert_raises(ValueError, ir.transform, rng.randn(3, 10))
FIX : fix LLE test (don't ask me why...)
FIX : fix LLE test (don't ask me why...)
Python
bsd-3-clause
untom/scikit-learn,trungnt13/scikit-learn,nrhine1/scikit-learn,hrjn/scikit-learn,arjoly/scikit-learn,rohanp/scikit-learn,khkaminska/scikit-learn,ky822/scikit-learn,JosmanPS/scikit-learn,madjelan/scikit-learn,PatrickOReilly/scikit-learn,arjoly/scikit-learn,fabioticconi/scikit-learn,olologin/scikit-learn,saiwing-yeung/scikit-learn,nhejazi/scikit-learn,abhishekgahlot/scikit-learn,rahul-c1/scikit-learn,zhenv5/scikit-learn,MechCoder/scikit-learn,lenovor/scikit-learn,elkingtonmcb/scikit-learn,abhishekkrthakur/scikit-learn,LiaoPan/scikit-learn,ClimbsRocks/scikit-learn,rvraghav93/scikit-learn,pypot/scikit-learn,jereze/scikit-learn,yonglehou/scikit-learn,Obus/scikit-learn,larsmans/scikit-learn,shangwuhencc/scikit-learn,JPFrancoia/scikit-learn,f3r/scikit-learn,jm-begon/scikit-learn,pianomania/scikit-learn,treycausey/scikit-learn,sanketloke/scikit-learn,jayflo/scikit-learn,aabadie/scikit-learn,wzbozon/scikit-learn,mwv/scikit-learn,NunoEdgarGub1/scikit-learn,Myasuka/scikit-learn,mrshu/scikit-learn,Srisai85/scikit-learn,procoder317/scikit-learn,CVML/scikit-learn,petosegan/scikit-learn,hainm/scikit-learn,xiaoxiamii/scikit-learn,aabadie/scikit-learn,kagayakidan/scikit-learn,ashhher3/scikit-learn,bigdataelephants/scikit-learn,ashhher3/scikit-learn,CforED/Machine-Learning,MartinDelzant/scikit-learn,wlamond/scikit-learn,anurag313/scikit-learn,moutai/scikit-learn,Barmaley-exe/scikit-learn,waterponey/scikit-learn,qifeigit/scikit-learn,espg/scikit-learn,iismd17/scikit-learn,xubenben/scikit-learn,Achuth17/scikit-learn,treycausey/scikit-learn,maheshakya/scikit-learn,Garrett-R/scikit-learn,depet/scikit-learn,anirudhjayaraman/scikit-learn,andaag/scikit-learn,ahoyosid/scikit-learn,lesteve/scikit-learn,DonBeo/scikit-learn,kagayakidan/scikit-learn,lazywei/scikit-learn,saiwing-yeung/scikit-learn,Vimos/scikit-learn,nvoron23/scikit-learn,vybstat/scikit-learn,spallavolu/scikit-learn,AlexandreAbraham/scikit-learn,ishanic/scikit-learn,sonnyhu/scikit-learn,ZenDevelopmentSystems/scikit-learn,mattilyra/scikit-learn,ilyes14/scikit-learn,hsuantien/scikit-learn,aabadie/scikit-learn,robbymeals/scikit-learn,vibhorag/scikit-learn,mattilyra/scikit-learn,glemaitre/scikit-learn,ltiao/scikit-learn,jakobworldpeace/scikit-learn,jkarnows/scikit-learn,deepesch/scikit-learn,cainiaocome/scikit-learn,r-mart/scikit-learn,jjx02230808/project0223,AlexanderFabisch/scikit-learn,carrillo/scikit-learn,imaculate/scikit-learn,carrillo/scikit-learn,chrsrds/scikit-learn,shenzebang/scikit-learn,trankmichael/scikit-learn,btabibian/scikit-learn,nomadcube/scikit-learn,mikebenfield/scikit-learn,Lawrence-Liu/scikit-learn,wlamond/scikit-learn,henrykironde/scikit-learn,huobaowangxi/scikit-learn,nikitasingh981/scikit-learn,fabianp/scikit-learn,lucidfrontier45/scikit-learn,waterponey/scikit-learn,joernhees/scikit-learn,xyguo/scikit-learn,Obus/scikit-learn,fredhusser/scikit-learn,bhargav/scikit-learn,harshaneelhg/scikit-learn,florian-f/sklearn,adamgreenhall/scikit-learn,eickenberg/scikit-learn,UNR-AERIAL/scikit-learn,mayblue9/scikit-learn,murali-munna/scikit-learn,3manuek/scikit-learn,aflaxman/scikit-learn,saiwing-yeung/scikit-learn,potash/scikit-learn,mikebenfield/scikit-learn,ivannz/scikit-learn,jayflo/scikit-learn,massmutual/scikit-learn,zaxtax/scikit-learn,r-mart/scikit-learn,dhruv13J/scikit-learn,0x0all/scikit-learn,theoryno3/scikit-learn,pianomania/scikit-learn,olologin/scikit-learn,kjung/scikit-learn,zuku1985/scikit-learn,AIML/scikit-learn,abhishekgahlot/scikit-learn,ivannz/scikit-learn,ChanderG/scikit-learn,Obus/scikit-learn,shangwuhencc/scikit-learn,bikong2/scikit-learn,xiaoxiamii/scikit-learn,Lawrence-Liu/scikit-learn,altairpearl/scikit-learn,kevin-intel/scikit-learn,tmhm/scikit-learn,aewhatley/scikit-learn,russel1237/scikit-learn,belltailjp/scikit-learn,yanlend/scikit-learn,wzbozon/scikit-learn,hrjn/scikit-learn,smartscheduling/scikit-learn-categorical-tree,shyamalschandra/scikit-learn,chrsrds/scikit-learn,xwolf12/scikit-learn,DSLituiev/scikit-learn,zorojean/scikit-learn,zuku1985/scikit-learn,fbagirov/scikit-learn,jblackburne/scikit-learn,beepee14/scikit-learn,Fireblend/scikit-learn,saiwing-yeung/scikit-learn,huzq/scikit-learn,espg/scikit-learn,fabioticconi/scikit-learn,giorgiop/scikit-learn,ilo10/scikit-learn,rexshihaoren/scikit-learn,Srisai85/scikit-learn,ZenDevelopmentSystems/scikit-learn,liangz0707/scikit-learn,NunoEdgarGub1/scikit-learn,Akshay0724/scikit-learn,q1ang/scikit-learn,poryfly/scikit-learn,arabenjamin/scikit-learn,UNR-AERIAL/scikit-learn,CforED/Machine-Learning,marcocaccin/scikit-learn,Jimmy-Morzaria/scikit-learn,alvarofierroclavero/scikit-learn,madjelan/scikit-learn,wzbozon/scikit-learn,hsuantien/scikit-learn,MatthieuBizien/scikit-learn,cybernet14/scikit-learn,fyffyt/scikit-learn,PrashntS/scikit-learn,IshankGulati/scikit-learn,kashif/scikit-learn,ClimbsRocks/scikit-learn,HolgerPeters/scikit-learn,shyamalschandra/scikit-learn,sergeyf/scikit-learn,joernhees/scikit-learn,mrshu/scikit-learn,billy-inn/scikit-learn,zaxtax/scikit-learn,xyguo/scikit-learn,TomDLT/scikit-learn,fabianp/scikit-learn,0asa/scikit-learn,bnaul/scikit-learn,pnedunuri/scikit-learn,cybernet14/scikit-learn,procoder317/scikit-learn,jakirkham/scikit-learn,amueller/scikit-learn,imaculate/scikit-learn,elkingtonmcb/scikit-learn,frank-tancf/scikit-learn,pratapvardhan/scikit-learn,devanshdalal/scikit-learn,fbagirov/scikit-learn,AlexandreAbraham/scikit-learn,B3AU/waveTree,gclenaghan/scikit-learn,q1ang/scikit-learn,walterreade/scikit-learn,hainm/scikit-learn,billy-inn/scikit-learn,samzhang111/scikit-learn,DSLituiev/scikit-learn,tdhopper/scikit-learn,xyguo/scikit-learn,sonnyhu/scikit-learn,harshaneelhg/scikit-learn,Jimmy-Morzaria/scikit-learn,BiaDarkia/scikit-learn,davidgbe/scikit-learn,murali-munna/scikit-learn,shikhardb/scikit-learn,nvoron23/scikit-learn,mhdella/scikit-learn,evgchz/scikit-learn,schets/scikit-learn,smartscheduling/scikit-learn-categorical-tree,nelson-liu/scikit-learn,aminert/scikit-learn,ephes/scikit-learn,kashif/scikit-learn,procoder317/scikit-learn,PatrickChrist/scikit-learn,PrashntS/scikit-learn,bigdataelephants/scikit-learn,ngoix/OCRF,f3r/scikit-learn,phdowling/scikit-learn,vibhorag/scikit-learn,jm-begon/scikit-learn,xiaoxiamii/scikit-learn,Titan-C/scikit-learn,giorgiop/scikit-learn,manashmndl/scikit-learn,yonglehou/scikit-learn,henridwyer/scikit-learn,mhue/scikit-learn,terkkila/scikit-learn,ycaihua/scikit-learn,kjung/scikit-learn,ashhher3/scikit-learn,herilalaina/scikit-learn,moutai/scikit-learn,mjudsp/Tsallis,alexsavio/scikit-learn,glouppe/scikit-learn,pythonvietnam/scikit-learn,ldirer/scikit-learn,arahuja/scikit-learn,YinongLong/scikit-learn,ky822/scikit-learn,theoryno3/scikit-learn,cl4rke/scikit-learn,devanshdalal/scikit-learn,aminert/scikit-learn,amueller/scikit-learn,potash/scikit-learn,MartinDelzant/scikit-learn,bhargav/scikit-learn,CforED/Machine-Learning,ogrisel/scikit-learn,tosolveit/scikit-learn,rahuldhote/scikit-learn,marcocaccin/scikit-learn,thilbern/scikit-learn,hitszxp/scikit-learn,JPFrancoia/scikit-learn,ogrisel/scikit-learn,etkirsch/scikit-learn,xwolf12/scikit-learn,tmhm/scikit-learn,simon-pepin/scikit-learn,fengzhyuan/scikit-learn,Fireblend/scikit-learn,wazeerzulfikar/scikit-learn,sarahgrogan/scikit-learn,equialgo/scikit-learn,PatrickOReilly/scikit-learn,mugizico/scikit-learn,rrohan/scikit-learn,jm-begon/scikit-learn,bigdataelephants/scikit-learn,RayMick/scikit-learn,treycausey/scikit-learn,bhargav/scikit-learn,vinayak-mehta/scikit-learn,cainiaocome/scikit-learn,plissonf/scikit-learn,murali-munna/scikit-learn,Vimos/scikit-learn,abimannans/scikit-learn,cwu2011/scikit-learn,mayblue9/scikit-learn,shangwuhencc/scikit-learn,ngoix/OCRF,yanlend/scikit-learn,jlegendary/scikit-learn,yask123/scikit-learn,stylianos-kampakis/scikit-learn,bigdataelephants/scikit-learn,liyu1990/sklearn,ClimbsRocks/scikit-learn,themrmax/scikit-learn,Windy-Ground/scikit-learn,zihua/scikit-learn,vshtanko/scikit-learn,PatrickChrist/scikit-learn,CVML/scikit-learn,mugizico/scikit-learn,russel1237/scikit-learn,cauchycui/scikit-learn,costypetrisor/scikit-learn,B3AU/waveTree,jjx02230808/project0223,beepee14/scikit-learn,yunfeilu/scikit-learn,kylerbrown/scikit-learn,jakirkham/scikit-learn,kmike/scikit-learn,Aasmi/scikit-learn,NelisVerhoef/scikit-learn,xavierwu/scikit-learn,lesteve/scikit-learn,ltiao/scikit-learn,joernhees/scikit-learn,ephes/scikit-learn,abimannans/scikit-learn,tomlof/scikit-learn,samzhang111/scikit-learn,hlin117/scikit-learn,ankurankan/scikit-learn,kmike/scikit-learn,thientu/scikit-learn,maheshakya/scikit-learn,anntzer/scikit-learn,davidgbe/scikit-learn,luo66/scikit-learn,gotomypc/scikit-learn,ZENGXH/scikit-learn,sanketloke/scikit-learn,djgagne/scikit-learn,yonglehou/scikit-learn,MartinSavc/scikit-learn,clemkoa/scikit-learn,MohammedWasim/scikit-learn,aewhatley/scikit-learn,jorik041/scikit-learn,xavierwu/scikit-learn,adamgreenhall/scikit-learn,rahuldhote/scikit-learn,manhhomienbienthuy/scikit-learn,evgchz/scikit-learn,maheshakya/scikit-learn,shangwuhencc/scikit-learn,madjelan/scikit-learn,lazywei/scikit-learn,kevin-intel/scikit-learn,Achuth17/scikit-learn,hdmetor/scikit-learn,yanlend/scikit-learn,ldirer/scikit-learn,alexsavio/scikit-learn,AlexanderFabisch/scikit-learn,Nyker510/scikit-learn,jmetzen/scikit-learn,RPGOne/scikit-learn,466152112/scikit-learn,xuewei4d/scikit-learn,0asa/scikit-learn,alexsavio/scikit-learn,murali-munna/scikit-learn,ilo10/scikit-learn,h2educ/scikit-learn,h2educ/scikit-learn,manashmndl/scikit-learn,0asa/scikit-learn,Srisai85/scikit-learn,zorojean/scikit-learn,manhhomienbienthuy/scikit-learn,rvraghav93/scikit-learn,kylerbrown/scikit-learn,fabianp/scikit-learn,moutai/scikit-learn,lesteve/scikit-learn,sinhrks/scikit-learn,ningchi/scikit-learn,aflaxman/scikit-learn,etkirsch/scikit-learn,jorge2703/scikit-learn,fzalkow/scikit-learn,mxjl620/scikit-learn,jereze/scikit-learn,nvoron23/scikit-learn,massmutual/scikit-learn,Myasuka/scikit-learn,samuel1208/scikit-learn,vinayak-mehta/scikit-learn,r-mart/scikit-learn,krez13/scikit-learn,Windy-Ground/scikit-learn,kaichogami/scikit-learn,xuewei4d/scikit-learn,appapantula/scikit-learn,joshloyal/scikit-learn,justincassidy/scikit-learn,jaidevd/scikit-learn,LohithBlaze/scikit-learn,fengzhyuan/scikit-learn,AnasGhrab/scikit-learn,0x0all/scikit-learn,mrshu/scikit-learn,IndraVikas/scikit-learn,alexeyum/scikit-learn,anntzer/scikit-learn,Myasuka/scikit-learn,NunoEdgarGub1/scikit-learn,mjudsp/Tsallis,henridwyer/scikit-learn,vivekmishra1991/scikit-learn,yyjiang/scikit-learn,UNR-AERIAL/scikit-learn,Djabbz/scikit-learn,Garrett-R/scikit-learn,nhejazi/scikit-learn,henridwyer/scikit-learn,sergeyf/scikit-learn,zihua/scikit-learn,Aasmi/scikit-learn,kylerbrown/scikit-learn,glennq/scikit-learn,jmschrei/scikit-learn,voxlol/scikit-learn,f3r/scikit-learn,JosmanPS/scikit-learn,dsquareindia/scikit-learn,icdishb/scikit-learn,loli/semisupervisedforests,466152112/scikit-learn,pompiduskus/scikit-learn,roxyboy/scikit-learn,anntzer/scikit-learn,xzh86/scikit-learn,ogrisel/scikit-learn,akionakamura/scikit-learn,Garrett-R/scikit-learn,mlyundin/scikit-learn,RayMick/scikit-learn,nesterione/scikit-learn,abimannans/scikit-learn,AlexandreAbraham/scikit-learn,evgchz/scikit-learn,arjoly/scikit-learn,betatim/scikit-learn,kevin-intel/scikit-learn,pypot/scikit-learn,lazywei/scikit-learn,jjx02230808/project0223,potash/scikit-learn,jakobworldpeace/scikit-learn,dingocuster/scikit-learn,dingocuster/scikit-learn,sumspr/scikit-learn,bnaul/scikit-learn,Adai0808/scikit-learn,pompiduskus/scikit-learn,trankmichael/scikit-learn,elkingtonmcb/scikit-learn,vibhorag/scikit-learn,petosegan/scikit-learn,dsullivan7/scikit-learn,eickenberg/scikit-learn,equialgo/scikit-learn,petosegan/scikit-learn,ishanic/scikit-learn,lin-credible/scikit-learn,shahankhatch/scikit-learn,shusenl/scikit-learn,equialgo/scikit-learn,glennq/scikit-learn,xavierwu/scikit-learn,mxjl620/scikit-learn,anirudhjayaraman/scikit-learn,justincassidy/scikit-learn,nesterione/scikit-learn,schets/scikit-learn,tmhm/scikit-learn,siutanwong/scikit-learn,bthirion/scikit-learn,Myasuka/scikit-learn,IssamLaradji/scikit-learn,jzt5132/scikit-learn,abimannans/scikit-learn,ycaihua/scikit-learn,cauchycui/scikit-learn,BiaDarkia/scikit-learn,kylerbrown/scikit-learn,altairpearl/scikit-learn,tawsifkhan/scikit-learn,huobaowangxi/scikit-learn,florian-f/sklearn,ZENGXH/scikit-learn,nmayorov/scikit-learn,ogrisel/scikit-learn,jkarnows/scikit-learn,yask123/scikit-learn,huobaowangxi/scikit-learn,YinongLong/scikit-learn,jaidevd/scikit-learn,anntzer/scikit-learn,terkkila/scikit-learn,dsullivan7/scikit-learn,xzh86/scikit-learn,amueller/scikit-learn,fyffyt/scikit-learn,fbagirov/scikit-learn,jayflo/scikit-learn,rishikksh20/scikit-learn,marcocaccin/scikit-learn,vybstat/scikit-learn,walterreade/scikit-learn,vshtanko/scikit-learn,raghavrv/scikit-learn,DSLituiev/scikit-learn,loli/sklearn-ensembletrees,abhishekkrthakur/scikit-learn,q1ang/scikit-learn,dsquareindia/scikit-learn,luo66/scikit-learn,sonnyhu/scikit-learn,roxyboy/scikit-learn,alvarofierroclavero/scikit-learn,hugobowne/scikit-learn,betatim/scikit-learn,abhishekkrthakur/scikit-learn,yunfeilu/scikit-learn,vermouthmjl/scikit-learn,kjung/scikit-learn,mattgiguere/scikit-learn,h2educ/scikit-learn,icdishb/scikit-learn,djgagne/scikit-learn,Clyde-fare/scikit-learn,pianomania/scikit-learn,rohanp/scikit-learn,lbishal/scikit-learn,waterponey/scikit-learn,michigraber/scikit-learn,jakobworldpeace/scikit-learn,mikebenfield/scikit-learn,mattilyra/scikit-learn,mfjb/scikit-learn,Adai0808/scikit-learn,ngoix/OCRF,mfjb/scikit-learn,nelson-liu/scikit-learn,r-mart/scikit-learn,IshankGulati/scikit-learn,fzalkow/scikit-learn,MartinDelzant/scikit-learn,imaculate/scikit-learn,mhdella/scikit-learn,yyjiang/scikit-learn,rsivapr/scikit-learn,AlexRobson/scikit-learn,cwu2011/scikit-learn,wanggang3333/scikit-learn,ankurankan/scikit-learn,dingocuster/scikit-learn,ephes/scikit-learn,hitszxp/scikit-learn,BiaDarkia/scikit-learn,nikitasingh981/scikit-learn,mugizico/scikit-learn,mojoboss/scikit-learn,sinhrks/scikit-learn,Akshay0724/scikit-learn,ivannz/scikit-learn,ashhher3/scikit-learn,JeanKossaifi/scikit-learn,zaxtax/scikit-learn,btabibian/scikit-learn,mjgrav2001/scikit-learn,akionakamura/scikit-learn,mxjl620/scikit-learn,Adai0808/scikit-learn,HolgerPeters/scikit-learn,zihua/scikit-learn,gotomypc/scikit-learn,hrjn/scikit-learn,zuku1985/scikit-learn,zihua/scikit-learn,fyffyt/scikit-learn,ZENGXH/scikit-learn,akionakamura/scikit-learn,bthirion/scikit-learn,voxlol/scikit-learn,lazywei/scikit-learn,IndraVikas/scikit-learn,joshloyal/scikit-learn,rrohan/scikit-learn,jblackburne/scikit-learn,lbishal/scikit-learn,ChanChiChoi/scikit-learn,Vimos/scikit-learn,zhenv5/scikit-learn,cwu2011/scikit-learn,dsquareindia/scikit-learn,rajat1994/scikit-learn,Nyker510/scikit-learn,ndingwall/scikit-learn,michigraber/scikit-learn,rajat1994/scikit-learn,ElDeveloper/scikit-learn,joshloyal/scikit-learn,pythonvietnam/scikit-learn,spallavolu/scikit-learn,pompiduskus/scikit-learn,ilo10/scikit-learn,IndraVikas/scikit-learn,xubenben/scikit-learn,giorgiop/scikit-learn,dsquareindia/scikit-learn,hsiaoyi0504/scikit-learn,arahuja/scikit-learn,ltiao/scikit-learn,hsuantien/scikit-learn,MartinDelzant/scikit-learn,heli522/scikit-learn,tomlof/scikit-learn,schets/scikit-learn,MartinSavc/scikit-learn,yonglehou/scikit-learn,hugobowne/scikit-learn,joernhees/scikit-learn,betatim/scikit-learn,MatthieuBizien/scikit-learn,nomadcube/scikit-learn,carrillo/scikit-learn,loli/semisupervisedforests,hdmetor/scikit-learn,Clyde-fare/scikit-learn,anurag313/scikit-learn,kagayakidan/scikit-learn,liberatorqjw/scikit-learn,fredhusser/scikit-learn,hsiaoyi0504/scikit-learn,qifeigit/scikit-learn,thilbern/scikit-learn,billy-inn/scikit-learn,djgagne/scikit-learn,liangz0707/scikit-learn,ankurankan/scikit-learn,betatim/scikit-learn,xubenben/scikit-learn,samuel1208/scikit-learn,0asa/scikit-learn,pkruskal/scikit-learn,spallavolu/scikit-learn,shenzebang/scikit-learn,mjgrav2001/scikit-learn,yanlend/scikit-learn,krez13/scikit-learn,mblondel/scikit-learn,PatrickOReilly/scikit-learn,Djabbz/scikit-learn,evgchz/scikit-learn,untom/scikit-learn,deepesch/scikit-learn,MechCoder/scikit-learn,ssaeger/scikit-learn,xyguo/scikit-learn,robbymeals/scikit-learn,fbagirov/scikit-learn,RayMick/scikit-learn,jereze/scikit-learn,nelson-liu/scikit-learn,hsiaoyi0504/scikit-learn,abhishekgahlot/scikit-learn,Sentient07/scikit-learn,nikitasingh981/scikit-learn,pypot/scikit-learn,AnasGhrab/scikit-learn,Barmaley-exe/scikit-learn,tosolveit/scikit-learn,wazeerzulfikar/scikit-learn,phdowling/scikit-learn,kaichogami/scikit-learn,mxjl620/scikit-learn,ningchi/scikit-learn,vigilv/scikit-learn,hitszxp/scikit-learn,466152112/scikit-learn,yask123/scikit-learn,ankurankan/scikit-learn,scikit-learn/scikit-learn,meduz/scikit-learn,cybernet14/scikit-learn,liberatorqjw/scikit-learn,walterreade/scikit-learn,fzalkow/scikit-learn,OshynSong/scikit-learn,kmike/scikit-learn,aetilley/scikit-learn,chrisburr/scikit-learn,mwv/scikit-learn,sarahgrogan/scikit-learn,ssaeger/scikit-learn,Clyde-fare/scikit-learn,ndingwall/scikit-learn,ycaihua/scikit-learn,aflaxman/scikit-learn,chrsrds/scikit-learn,vinayak-mehta/scikit-learn,kaichogami/scikit-learn,frank-tancf/scikit-learn,dhruv13J/scikit-learn,Djabbz/scikit-learn,scikit-learn/scikit-learn,ilyes14/scikit-learn,mattgiguere/scikit-learn,pv/scikit-learn,yask123/scikit-learn,aminert/scikit-learn,khkaminska/scikit-learn,fredhusser/scikit-learn,PatrickChrist/scikit-learn,altairpearl/scikit-learn,Windy-Ground/scikit-learn,rohanp/scikit-learn,mlyundin/scikit-learn,lenovor/scikit-learn,rvraghav93/scikit-learn,samzhang111/scikit-learn,costypetrisor/scikit-learn,mikebenfield/scikit-learn,jjx02230808/project0223,jblackburne/scikit-learn,huzq/scikit-learn,alexeyum/scikit-learn,ssaeger/scikit-learn,wzbozon/scikit-learn,mhue/scikit-learn,pv/scikit-learn,aewhatley/scikit-learn,stylianos-kampakis/scikit-learn,ChanderG/scikit-learn,AIML/scikit-learn,tomlof/scikit-learn,krez13/scikit-learn,shikhardb/scikit-learn,MechCoder/scikit-learn,mojoboss/scikit-learn,justincassidy/scikit-learn,NelisVerhoef/scikit-learn,tomlof/scikit-learn,raghavrv/scikit-learn,meduz/scikit-learn,xuewei4d/scikit-learn,rahul-c1/scikit-learn,0x0all/scikit-learn,rrohan/scikit-learn,xavierwu/scikit-learn,billy-inn/scikit-learn,rsivapr/scikit-learn,jzt5132/scikit-learn,arabenjamin/scikit-learn,icdishb/scikit-learn,466152112/scikit-learn,JsNoNo/scikit-learn,joshloyal/scikit-learn,siutanwong/scikit-learn,shahankhatch/scikit-learn,meduz/scikit-learn,gotomypc/scikit-learn,bikong2/scikit-learn,terkkila/scikit-learn,vybstat/scikit-learn,thientu/scikit-learn,manhhomienbienthuy/scikit-learn,0x0all/scikit-learn,evgchz/scikit-learn,raghavrv/scikit-learn,rajat1994/scikit-learn,tosolveit/scikit-learn,Lawrence-Liu/scikit-learn,qifeigit/scikit-learn,q1ang/scikit-learn,fyffyt/scikit-learn,ilyes14/scikit-learn,shusenl/scikit-learn,ChanderG/scikit-learn,mrshu/scikit-learn,pypot/scikit-learn,xwolf12/scikit-learn,rrohan/scikit-learn,idlead/scikit-learn,Fireblend/scikit-learn,f3r/scikit-learn,hlin117/scikit-learn,jseabold/scikit-learn,Fireblend/scikit-learn,anirudhjayaraman/scikit-learn,gclenaghan/scikit-learn,Garrett-R/scikit-learn,mehdidc/scikit-learn,zorroblue/scikit-learn,nelson-liu/scikit-learn,btabibian/scikit-learn,clemkoa/scikit-learn,AIML/scikit-learn,RomainBrault/scikit-learn,JosmanPS/scikit-learn,IshankGulati/scikit-learn,bhargav/scikit-learn,larsmans/scikit-learn,aetilley/scikit-learn,kmike/scikit-learn,nvoron23/scikit-learn,ahoyosid/scikit-learn,eickenberg/scikit-learn,huzq/scikit-learn,jkarnows/scikit-learn,zorojean/scikit-learn,wanggang3333/scikit-learn,yyjiang/scikit-learn,pompiduskus/scikit-learn,altairpearl/scikit-learn,rajat1994/scikit-learn,loli/semisupervisedforests,glouppe/scikit-learn,michigraber/scikit-learn,luo66/scikit-learn,jseabold/scikit-learn,mugizico/scikit-learn,RomainBrault/scikit-learn,jorge2703/scikit-learn,loli/sklearn-ensembletrees,hdmetor/scikit-learn,abhishekgahlot/scikit-learn,jmetzen/scikit-learn,pratapvardhan/scikit-learn,vortex-ape/scikit-learn,ElDeveloper/scikit-learn,etkirsch/scikit-learn,untom/scikit-learn,poryfly/scikit-learn,dsullivan7/scikit-learn,procoder317/scikit-learn,alvarofierroclavero/scikit-learn,vibhorag/scikit-learn,ningchi/scikit-learn,lin-credible/scikit-learn,AIML/scikit-learn,vermouthmjl/scikit-learn,alexeyum/scikit-learn,mjudsp/Tsallis,vigilv/scikit-learn,3manuek/scikit-learn,LohithBlaze/scikit-learn,jakirkham/scikit-learn,vivekmishra1991/scikit-learn,herilalaina/scikit-learn,rishikksh20/scikit-learn,aewhatley/scikit-learn,vivekmishra1991/scikit-learn,CforED/Machine-Learning,ky822/scikit-learn,zorroblue/scikit-learn,alexsavio/scikit-learn,elkingtonmcb/scikit-learn,themrmax/scikit-learn,themrmax/scikit-learn,massmutual/scikit-learn,hsiaoyi0504/scikit-learn,iismd17/scikit-learn,robin-lai/scikit-learn,lucidfrontier45/scikit-learn,samzhang111/scikit-learn,arjoly/scikit-learn,jakirkham/scikit-learn,maheshakya/scikit-learn,aflaxman/scikit-learn,bnaul/scikit-learn,iismd17/scikit-learn,eickenberg/scikit-learn,JsNoNo/scikit-learn,bthirion/scikit-learn,devanshdalal/scikit-learn,LiaoPan/scikit-learn,chrisburr/scikit-learn,belltailjp/scikit-learn,michigraber/scikit-learn,depet/scikit-learn,stylianos-kampakis/scikit-learn,rishikksh20/scikit-learn,sergeyf/scikit-learn,zhenv5/scikit-learn,terkkila/scikit-learn,glemaitre/scikit-learn,frank-tancf/scikit-learn,robin-lai/scikit-learn,spallavolu/scikit-learn,wlamond/scikit-learn,Barmaley-exe/scikit-learn,thientu/scikit-learn,bthirion/scikit-learn,zaxtax/scikit-learn,theoryno3/scikit-learn,espg/scikit-learn,mblondel/scikit-learn,Titan-C/scikit-learn,icdishb/scikit-learn,liberatorqjw/scikit-learn,smartscheduling/scikit-learn-categorical-tree,RayMick/scikit-learn,florian-f/sklearn,marcocaccin/scikit-learn,rahul-c1/scikit-learn,arahuja/scikit-learn,thilbern/scikit-learn,glemaitre/scikit-learn,abhishekkrthakur/scikit-learn,belltailjp/scikit-learn,CVML/scikit-learn,cainiaocome/scikit-learn,amueller/scikit-learn,herilalaina/scikit-learn,lucidfrontier45/scikit-learn,jlegendary/scikit-learn,Nyker510/scikit-learn,idlead/scikit-learn,cybernet14/scikit-learn,jlegendary/scikit-learn,larsmans/scikit-learn,appapantula/scikit-learn,Vimos/scikit-learn,giorgiop/scikit-learn,sinhrks/scikit-learn,ephes/scikit-learn,rexshihaoren/scikit-learn,liangz0707/scikit-learn,rexshihaoren/scikit-learn,aabadie/scikit-learn,shahankhatch/scikit-learn,JosmanPS/scikit-learn,trungnt13/scikit-learn,tawsifkhan/scikit-learn,LiaoPan/scikit-learn,massmutual/scikit-learn,jaidevd/scikit-learn,pythonvietnam/scikit-learn,CVML/scikit-learn,glennq/scikit-learn,BiaDarkia/scikit-learn,RPGOne/scikit-learn,MohammedWasim/scikit-learn,TomDLT/scikit-learn,macks22/scikit-learn,AlexRobson/scikit-learn,andrewnc/scikit-learn,vigilv/scikit-learn,jlegendary/scikit-learn,chrisburr/scikit-learn,andrewnc/scikit-learn,RachitKansal/scikit-learn,jorik041/scikit-learn,jereze/scikit-learn,DonBeo/scikit-learn,etkirsch/scikit-learn,yunfeilu/scikit-learn,RachitKansal/scikit-learn,jorik041/scikit-learn,plissonf/scikit-learn,chrsrds/scikit-learn,belltailjp/scikit-learn,AlexRobson/scikit-learn,ilo10/scikit-learn,vinayak-mehta/scikit-learn,vermouthmjl/scikit-learn,themrmax/scikit-learn,victorbergelin/scikit-learn,ky822/scikit-learn,simon-pepin/scikit-learn,russel1237/scikit-learn,DonBeo/scikit-learn,0asa/scikit-learn,fabioticconi/scikit-learn,deepesch/scikit-learn,shenzebang/scikit-learn,JPFrancoia/scikit-learn,pv/scikit-learn,HolgerPeters/scikit-learn,imaculate/scikit-learn,rahuldhote/scikit-learn,jayflo/scikit-learn,lbishal/scikit-learn,ssaeger/scikit-learn,mayblue9/scikit-learn,AlexanderFabisch/scikit-learn,alvarofierroclavero/scikit-learn,clemkoa/scikit-learn,walterreade/scikit-learn,roxyboy/scikit-learn,3manuek/scikit-learn,gclenaghan/scikit-learn,kjung/scikit-learn,aetilley/scikit-learn,xubenben/scikit-learn,RPGOne/scikit-learn,mjudsp/Tsallis,ngoix/OCRF,vortex-ape/scikit-learn,nikitasingh981/scikit-learn,khkaminska/scikit-learn,vivekmishra1991/scikit-learn,costypetrisor/scikit-learn,wazeerzulfikar/scikit-learn,zorroblue/scikit-learn,hrjn/scikit-learn,hugobowne/scikit-learn,mrshu/scikit-learn,smartscheduling/scikit-learn-categorical-tree,hlin117/scikit-learn,poryfly/scikit-learn,ishanic/scikit-learn,liberatorqjw/scikit-learn,lin-credible/scikit-learn,AnasGhrab/scikit-learn,bikong2/scikit-learn,trungnt13/scikit-learn,robin-lai/scikit-learn,ilyes14/scikit-learn,andrewnc/scikit-learn,NelisVerhoef/scikit-learn,rsivapr/scikit-learn,zorojean/scikit-learn,wanggang3333/scikit-learn,russel1237/scikit-learn,RomainBrault/scikit-learn,IssamLaradji/scikit-learn,voxlol/scikit-learn,Adai0808/scikit-learn,shikhardb/scikit-learn,appapantula/scikit-learn,eg-zhang/scikit-learn,thilbern/scikit-learn,B3AU/waveTree,IshankGulati/scikit-learn,tdhopper/scikit-learn,nrhine1/scikit-learn,eg-zhang/scikit-learn,untom/scikit-learn,manashmndl/scikit-learn,dhruv13J/scikit-learn,depet/scikit-learn,ElDeveloper/scikit-learn,roxyboy/scikit-learn,anirudhjayaraman/scikit-learn,equialgo/scikit-learn,davidgbe/scikit-learn,mhue/scikit-learn,kashif/scikit-learn,mblondel/scikit-learn,jzt5132/scikit-learn,plissonf/scikit-learn,hainm/scikit-learn,tdhopper/scikit-learn,cwu2011/scikit-learn,MohammedWasim/scikit-learn,lesteve/scikit-learn,jseabold/scikit-learn,B3AU/waveTree,sarahgrogan/scikit-learn,raghavrv/scikit-learn,florian-f/sklearn,MechCoder/scikit-learn,liyu1990/sklearn,MatthieuBizien/scikit-learn,Titan-C/scikit-learn,iismd17/scikit-learn,olologin/scikit-learn,loli/semisupervisedforests,dingocuster/scikit-learn,heli522/scikit-learn,simon-pepin/scikit-learn,jmetzen/scikit-learn,mfjb/scikit-learn,appapantula/scikit-learn,luo66/scikit-learn,PatrickChrist/scikit-learn,zorroblue/scikit-learn,mjgrav2001/scikit-learn,sanketloke/scikit-learn,macks22/scikit-learn,mlyundin/scikit-learn,Barmaley-exe/scikit-learn,henrykironde/scikit-learn,xwolf12/scikit-learn,loli/sklearn-ensembletrees,nomadcube/scikit-learn,beepee14/scikit-learn,rsivapr/scikit-learn,hitszxp/scikit-learn,TomDLT/scikit-learn,loli/sklearn-ensembletrees,nhejazi/scikit-learn,mwv/scikit-learn,bnaul/scikit-learn,ElDeveloper/scikit-learn,rahuldhote/scikit-learn,mjudsp/Tsallis,ahoyosid/scikit-learn,jpautom/scikit-learn,PrashntS/scikit-learn,0x0all/scikit-learn,nhejazi/scikit-learn,zuku1985/scikit-learn,schets/scikit-learn,toastedcornflakes/scikit-learn,mehdidc/scikit-learn,shyamalschandra/scikit-learn,fengzhyuan/scikit-learn,potash/scikit-learn,jkarnows/scikit-learn,LohithBlaze/scikit-learn,robbymeals/scikit-learn,heli522/scikit-learn,wazeerzulfikar/scikit-learn,deepesch/scikit-learn,idlead/scikit-learn,HolgerPeters/scikit-learn,ankurankan/scikit-learn,Achuth17/scikit-learn,Akshay0724/scikit-learn,heli522/scikit-learn,poryfly/scikit-learn,nmayorov/scikit-learn,sonnyhu/scikit-learn,ndingwall/scikit-learn,vermouthmjl/scikit-learn,phdowling/scikit-learn,ChanChiChoi/scikit-learn,xzh86/scikit-learn,Achuth17/scikit-learn,glennq/scikit-learn,DSLituiev/scikit-learn,stylianos-kampakis/scikit-learn,liangz0707/scikit-learn,JeanKossaifi/scikit-learn,krez13/scikit-learn,qifeigit/scikit-learn,siutanwong/scikit-learn,alexeyum/scikit-learn,depet/scikit-learn,trungnt13/scikit-learn,abhishekgahlot/scikit-learn,YinongLong/scikit-learn,macks22/scikit-learn,h2educ/scikit-learn,jmetzen/scikit-learn,jpautom/scikit-learn,hlin117/scikit-learn,adamgreenhall/scikit-learn,DonBeo/scikit-learn,nomadcube/scikit-learn,djgagne/scikit-learn,jakobworldpeace/scikit-learn,harshaneelhg/scikit-learn,beepee14/scikit-learn,henrykironde/scikit-learn,vshtanko/scikit-learn,idlead/scikit-learn,ldirer/scikit-learn,vybstat/scikit-learn,jpautom/scikit-learn,anurag313/scikit-learn,scikit-learn/scikit-learn,arabenjamin/scikit-learn,moutai/scikit-learn,dhruv13J/scikit-learn,trankmichael/scikit-learn,nmayorov/scikit-learn,jseabold/scikit-learn,aminert/scikit-learn,MatthieuBizien/scikit-learn,theoryno3/scikit-learn,anurag313/scikit-learn,fabianp/scikit-learn,pnedunuri/scikit-learn,huzq/scikit-learn,glouppe/scikit-learn,victorbergelin/scikit-learn,trankmichael/scikit-learn,xzh86/scikit-learn,Akshay0724/scikit-learn,hainm/scikit-learn,Sentient07/scikit-learn,frank-tancf/scikit-learn,jm-begon/scikit-learn,mehdidc/scikit-learn,simon-pepin/scikit-learn,jorge2703/scikit-learn,wanggang3333/scikit-learn,lenovor/scikit-learn,Garrett-R/scikit-learn,andaag/scikit-learn,jblackburne/scikit-learn,ningchi/scikit-learn,IssamLaradji/scikit-learn,vigilv/scikit-learn,tosolveit/scikit-learn,RPGOne/scikit-learn,OshynSong/scikit-learn,lbishal/scikit-learn,sinhrks/scikit-learn,nesterione/scikit-learn,ZenDevelopmentSystems/scikit-learn,samuel1208/scikit-learn,MartinSavc/scikit-learn,eg-zhang/scikit-learn,arabenjamin/scikit-learn,pkruskal/scikit-learn,rexshihaoren/scikit-learn,meduz/scikit-learn,phdowling/scikit-learn,Jimmy-Morzaria/scikit-learn,robin-lai/scikit-learn,Clyde-fare/scikit-learn,eg-zhang/scikit-learn,arahuja/scikit-learn,mhdella/scikit-learn,shahankhatch/scikit-learn,rsivapr/scikit-learn,espg/scikit-learn,ClimbsRocks/scikit-learn,ishanic/scikit-learn,lucidfrontier45/scikit-learn,MartinSavc/scikit-learn,manashmndl/scikit-learn,Nyker510/scikit-learn,pkruskal/scikit-learn,vortex-ape/scikit-learn,mojoboss/scikit-learn,ndingwall/scikit-learn,andaag/scikit-learn,LohithBlaze/scikit-learn,mehdidc/scikit-learn,xiaoxiamii/scikit-learn,glouppe/scikit-learn,thientu/scikit-learn,mblondel/scikit-learn,AnasGhrab/scikit-learn,Sentient07/scikit-learn,ChanderG/scikit-learn,quheng/scikit-learn,jzt5132/scikit-learn,jaidevd/scikit-learn,liyu1990/sklearn,pnedunuri/scikit-learn,ahoyosid/scikit-learn,waterponey/scikit-learn,akionakamura/scikit-learn,eickenberg/scikit-learn,justincassidy/scikit-learn,siutanwong/scikit-learn,jmschrei/scikit-learn,JsNoNo/scikit-learn,sumspr/scikit-learn,chrisburr/scikit-learn,larsmans/scikit-learn,hitszxp/scikit-learn,mlyundin/scikit-learn,mwv/scikit-learn,pv/scikit-learn,jpautom/scikit-learn,Aasmi/scikit-learn,B3AU/waveTree,andrewnc/scikit-learn,ChanChiChoi/scikit-learn,lenovor/scikit-learn,treycausey/scikit-learn,kmike/scikit-learn,3manuek/scikit-learn,YinongLong/scikit-learn,dsullivan7/scikit-learn,ivannz/scikit-learn,pratapvardhan/scikit-learn,aetilley/scikit-learn,herilalaina/scikit-learn,shyamalschandra/scikit-learn,jorge2703/scikit-learn,loli/sklearn-ensembletrees,victorbergelin/scikit-learn,kashif/scikit-learn,toastedcornflakes/scikit-learn,pianomania/scikit-learn,quheng/scikit-learn,Sentient07/scikit-learn,NelisVerhoef/scikit-learn,hdmetor/scikit-learn,shikhardb/scikit-learn,henridwyer/scikit-learn,kaichogami/scikit-learn,cauchycui/scikit-learn,btabibian/scikit-learn,Lawrence-Liu/scikit-learn,voxlol/scikit-learn,adamgreenhall/scikit-learn,RomainBrault/scikit-learn,JeanKossaifi/scikit-learn,scikit-learn/scikit-learn,gotomypc/scikit-learn,harshaneelhg/scikit-learn,carrillo/scikit-learn,liyu1990/sklearn,toastedcornflakes/scikit-learn,fzalkow/scikit-learn,quheng/scikit-learn,Windy-Ground/scikit-learn,andaag/scikit-learn,huobaowangxi/scikit-learn,cauchycui/scikit-learn,costypetrisor/scikit-learn,devanshdalal/scikit-learn,pnedunuri/scikit-learn,Srisai85/scikit-learn,nmayorov/scikit-learn,ldirer/scikit-learn,ChanChiChoi/scikit-learn,victorbergelin/scikit-learn,mattilyra/scikit-learn,JsNoNo/scikit-learn,toastedcornflakes/scikit-learn,cl4rke/scikit-learn,sanketloke/scikit-learn,mayblue9/scikit-learn,macks22/scikit-learn,RachitKansal/scikit-learn,ZENGXH/scikit-learn,rishikksh20/scikit-learn,quheng/scikit-learn,ycaihua/scikit-learn,ngoix/OCRF,jmschrei/scikit-learn,ycaihua/scikit-learn,Obus/scikit-learn,sarahgrogan/scikit-learn,lucidfrontier45/scikit-learn,pythonvietnam/scikit-learn,bikong2/scikit-learn,zhenv5/scikit-learn,petosegan/scikit-learn,mojoboss/scikit-learn,nrhine1/scikit-learn,nesterione/scikit-learn,jmschrei/scikit-learn,larsmans/scikit-learn,fabioticconi/scikit-learn,shusenl/scikit-learn,davidgbe/scikit-learn,rahul-c1/scikit-learn,plissonf/scikit-learn,mattilyra/scikit-learn,henrykironde/scikit-learn,khkaminska/scikit-learn,gclenaghan/scikit-learn,vortex-ape/scikit-learn,kagayakidan/scikit-learn,tmhm/scikit-learn,glemaitre/scikit-learn,PrashntS/scikit-learn,madjelan/scikit-learn,Aasmi/scikit-learn,JPFrancoia/scikit-learn,cl4rke/scikit-learn,cainiaocome/scikit-learn,fengzhyuan/scikit-learn,samuel1208/scikit-learn,kevin-intel/scikit-learn,OshynSong/scikit-learn,mfjb/scikit-learn,IssamLaradji/scikit-learn,pkruskal/scikit-learn,sumspr/scikit-learn,yunfeilu/scikit-learn,UNR-AERIAL/scikit-learn,florian-f/sklearn,ngoix/OCRF,nrhine1/scikit-learn,tawsifkhan/scikit-learn,jorik041/scikit-learn,RachitKansal/scikit-learn,AlexandreAbraham/scikit-learn,mjgrav2001/scikit-learn,Djabbz/scikit-learn,pratapvardhan/scikit-learn,fredhusser/scikit-learn,AlexanderFabisch/scikit-learn,PatrickOReilly/scikit-learn,mhue/scikit-learn,rohanp/scikit-learn,IndraVikas/scikit-learn,Titan-C/scikit-learn,mattgiguere/scikit-learn,clemkoa/scikit-learn,maheshakya/scikit-learn,depet/scikit-learn,sergeyf/scikit-learn,rvraghav93/scikit-learn,mattgiguere/scikit-learn,wlamond/scikit-learn,hsuantien/scikit-learn,NunoEdgarGub1/scikit-learn,robbymeals/scikit-learn,ZenDevelopmentSystems/scikit-learn,ltiao/scikit-learn,JeanKossaifi/scikit-learn,sumspr/scikit-learn,tdhopper/scikit-learn,OshynSong/scikit-learn,cl4rke/scikit-learn,manhhomienbienthuy/scikit-learn,tawsifkhan/scikit-learn,mhdella/scikit-learn,xuewei4d/scikit-learn,treycausey/scikit-learn,MohammedWasim/scikit-learn,olologin/scikit-learn,shusenl/scikit-learn,hugobowne/scikit-learn,shenzebang/scikit-learn,TomDLT/scikit-learn,vshtanko/scikit-learn,LiaoPan/scikit-learn,Jimmy-Morzaria/scikit-learn,AlexRobson/scikit-learn,yyjiang/scikit-learn,lin-credible/scikit-learn
import numpy as np from numpy.testing import assert_array_equal from sklearn.linear_model.isotonic_regression_ import isotonic_regression from sklearn.linear_model import IsotonicRegression from nose.tools import assert_raises def test_isotonic_regression(): y = np.array([3, 7, 5, 9, 8, 7, 10]) y_ = np.array([3, 6, 6, 8, 8, 8, 10]) assert_array_equal(y_, isotonic_regression(y)) x = np.arange(len(y)) ir = IsotonicRegression(x_min=0., x_max=1.) ir.fit(x, y) assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) assert_array_equal(ir.transform(x), ir.predict(x)) def test_assert_raises_exceptions(): ir = IsotonicRegression() assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6]) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7]) assert_raises(ValueError, ir.fit, np.random.randn(3, 10), [0, 1, 2]) assert_raises(ValueError, ir.transform, np.random.randn(3, 10)) FIX : fix LLE test (don't ask me why...)
import numpy as np from numpy.testing import assert_array_equal from sklearn.linear_model.isotonic_regression_ import isotonic_regression from sklearn.linear_model import IsotonicRegression from nose.tools import assert_raises def test_isotonic_regression(): y = np.array([3, 7, 5, 9, 8, 7, 10]) y_ = np.array([3, 6, 6, 8, 8, 8, 10]) assert_array_equal(y_, isotonic_regression(y)) x = np.arange(len(y)) ir = IsotonicRegression(x_min=0., x_max=1.) ir.fit(x, y) assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) assert_array_equal(ir.transform(x), ir.predict(x)) def test_assert_raises_exceptions(): ir = IsotonicRegression() rng = np.random.RandomState(42) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6]) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7]) assert_raises(ValueError, ir.fit, rng.randn(3, 10), [0, 1, 2]) assert_raises(ValueError, ir.transform, rng.randn(3, 10))
<commit_before>import numpy as np from numpy.testing import assert_array_equal from sklearn.linear_model.isotonic_regression_ import isotonic_regression from sklearn.linear_model import IsotonicRegression from nose.tools import assert_raises def test_isotonic_regression(): y = np.array([3, 7, 5, 9, 8, 7, 10]) y_ = np.array([3, 6, 6, 8, 8, 8, 10]) assert_array_equal(y_, isotonic_regression(y)) x = np.arange(len(y)) ir = IsotonicRegression(x_min=0., x_max=1.) ir.fit(x, y) assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) assert_array_equal(ir.transform(x), ir.predict(x)) def test_assert_raises_exceptions(): ir = IsotonicRegression() assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6]) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7]) assert_raises(ValueError, ir.fit, np.random.randn(3, 10), [0, 1, 2]) assert_raises(ValueError, ir.transform, np.random.randn(3, 10)) <commit_msg>FIX : fix LLE test (don't ask me why...)<commit_after>
import numpy as np from numpy.testing import assert_array_equal from sklearn.linear_model.isotonic_regression_ import isotonic_regression from sklearn.linear_model import IsotonicRegression from nose.tools import assert_raises def test_isotonic_regression(): y = np.array([3, 7, 5, 9, 8, 7, 10]) y_ = np.array([3, 6, 6, 8, 8, 8, 10]) assert_array_equal(y_, isotonic_regression(y)) x = np.arange(len(y)) ir = IsotonicRegression(x_min=0., x_max=1.) ir.fit(x, y) assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) assert_array_equal(ir.transform(x), ir.predict(x)) def test_assert_raises_exceptions(): ir = IsotonicRegression() rng = np.random.RandomState(42) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6]) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7]) assert_raises(ValueError, ir.fit, rng.randn(3, 10), [0, 1, 2]) assert_raises(ValueError, ir.transform, rng.randn(3, 10))
import numpy as np from numpy.testing import assert_array_equal from sklearn.linear_model.isotonic_regression_ import isotonic_regression from sklearn.linear_model import IsotonicRegression from nose.tools import assert_raises def test_isotonic_regression(): y = np.array([3, 7, 5, 9, 8, 7, 10]) y_ = np.array([3, 6, 6, 8, 8, 8, 10]) assert_array_equal(y_, isotonic_regression(y)) x = np.arange(len(y)) ir = IsotonicRegression(x_min=0., x_max=1.) ir.fit(x, y) assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) assert_array_equal(ir.transform(x), ir.predict(x)) def test_assert_raises_exceptions(): ir = IsotonicRegression() assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6]) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7]) assert_raises(ValueError, ir.fit, np.random.randn(3, 10), [0, 1, 2]) assert_raises(ValueError, ir.transform, np.random.randn(3, 10)) FIX : fix LLE test (don't ask me why...)import numpy as np from numpy.testing import assert_array_equal from sklearn.linear_model.isotonic_regression_ import isotonic_regression from sklearn.linear_model import IsotonicRegression from nose.tools import assert_raises def test_isotonic_regression(): y = np.array([3, 7, 5, 9, 8, 7, 10]) y_ = np.array([3, 6, 6, 8, 8, 8, 10]) assert_array_equal(y_, isotonic_regression(y)) x = np.arange(len(y)) ir = IsotonicRegression(x_min=0., x_max=1.) ir.fit(x, y) assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) assert_array_equal(ir.transform(x), ir.predict(x)) def test_assert_raises_exceptions(): ir = IsotonicRegression() rng = np.random.RandomState(42) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6]) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7]) assert_raises(ValueError, ir.fit, rng.randn(3, 10), [0, 1, 2]) assert_raises(ValueError, ir.transform, rng.randn(3, 10))
<commit_before>import numpy as np from numpy.testing import assert_array_equal from sklearn.linear_model.isotonic_regression_ import isotonic_regression from sklearn.linear_model import IsotonicRegression from nose.tools import assert_raises def test_isotonic_regression(): y = np.array([3, 7, 5, 9, 8, 7, 10]) y_ = np.array([3, 6, 6, 8, 8, 8, 10]) assert_array_equal(y_, isotonic_regression(y)) x = np.arange(len(y)) ir = IsotonicRegression(x_min=0., x_max=1.) ir.fit(x, y) assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) assert_array_equal(ir.transform(x), ir.predict(x)) def test_assert_raises_exceptions(): ir = IsotonicRegression() assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6]) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7]) assert_raises(ValueError, ir.fit, np.random.randn(3, 10), [0, 1, 2]) assert_raises(ValueError, ir.transform, np.random.randn(3, 10)) <commit_msg>FIX : fix LLE test (don't ask me why...)<commit_after>import numpy as np from numpy.testing import assert_array_equal from sklearn.linear_model.isotonic_regression_ import isotonic_regression from sklearn.linear_model import IsotonicRegression from nose.tools import assert_raises def test_isotonic_regression(): y = np.array([3, 7, 5, 9, 8, 7, 10]) y_ = np.array([3, 6, 6, 8, 8, 8, 10]) assert_array_equal(y_, isotonic_regression(y)) x = np.arange(len(y)) ir = IsotonicRegression(x_min=0., x_max=1.) ir.fit(x, y) assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) assert_array_equal(ir.transform(x), ir.predict(x)) def test_assert_raises_exceptions(): ir = IsotonicRegression() rng = np.random.RandomState(42) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6]) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7]) assert_raises(ValueError, ir.fit, rng.randn(3, 10), [0, 1, 2]) assert_raises(ValueError, ir.transform, rng.randn(3, 10))
7cdc7d1157f7bd37277115d378d76a1daf717b47
source/run.py
source/run.py
# -*- coding: utf-8 -*- from autoreiv import AutoReiv bot = AutoReiv() bot.load() try: bot.run(bot.config.get('login'), bot.config.get('password')) except KeyboardInterrupt: bot.close() finally: print('* Bye!')
# -*- coding: utf-8 -*- import asyncio import time from autoreiv import AutoReiv def main(): while True: bot = AutoReiv() bot.load() try: bot.run(bot.config.get('login'), bot.config.get('password')) except Exception as e: print('* Crashed with error: {}'.format(e)) finally: print('* Disconnected.') asyncio.set_event_loop(asyncio.new_event_loop()) print('* Waiting 10 seconds before reconnecting (press ^C to stop)...') try: time.sleep(10) except KeyboardInterrupt: break if __name__ == '__main__': main()
Fix the main loop & reconnecting
Fix the main loop & reconnecting
Python
mit
diath/AutoReiv
# -*- coding: utf-8 -*- from autoreiv import AutoReiv bot = AutoReiv() bot.load() try: bot.run(bot.config.get('login'), bot.config.get('password')) except KeyboardInterrupt: bot.close() finally: print('* Bye!') Fix the main loop & reconnecting
# -*- coding: utf-8 -*- import asyncio import time from autoreiv import AutoReiv def main(): while True: bot = AutoReiv() bot.load() try: bot.run(bot.config.get('login'), bot.config.get('password')) except Exception as e: print('* Crashed with error: {}'.format(e)) finally: print('* Disconnected.') asyncio.set_event_loop(asyncio.new_event_loop()) print('* Waiting 10 seconds before reconnecting (press ^C to stop)...') try: time.sleep(10) except KeyboardInterrupt: break if __name__ == '__main__': main()
<commit_before># -*- coding: utf-8 -*- from autoreiv import AutoReiv bot = AutoReiv() bot.load() try: bot.run(bot.config.get('login'), bot.config.get('password')) except KeyboardInterrupt: bot.close() finally: print('* Bye!') <commit_msg>Fix the main loop & reconnecting<commit_after>
# -*- coding: utf-8 -*- import asyncio import time from autoreiv import AutoReiv def main(): while True: bot = AutoReiv() bot.load() try: bot.run(bot.config.get('login'), bot.config.get('password')) except Exception as e: print('* Crashed with error: {}'.format(e)) finally: print('* Disconnected.') asyncio.set_event_loop(asyncio.new_event_loop()) print('* Waiting 10 seconds before reconnecting (press ^C to stop)...') try: time.sleep(10) except KeyboardInterrupt: break if __name__ == '__main__': main()
# -*- coding: utf-8 -*- from autoreiv import AutoReiv bot = AutoReiv() bot.load() try: bot.run(bot.config.get('login'), bot.config.get('password')) except KeyboardInterrupt: bot.close() finally: print('* Bye!') Fix the main loop & reconnecting# -*- coding: utf-8 -*- import asyncio import time from autoreiv import AutoReiv def main(): while True: bot = AutoReiv() bot.load() try: bot.run(bot.config.get('login'), bot.config.get('password')) except Exception as e: print('* Crashed with error: {}'.format(e)) finally: print('* Disconnected.') asyncio.set_event_loop(asyncio.new_event_loop()) print('* Waiting 10 seconds before reconnecting (press ^C to stop)...') try: time.sleep(10) except KeyboardInterrupt: break if __name__ == '__main__': main()
<commit_before># -*- coding: utf-8 -*- from autoreiv import AutoReiv bot = AutoReiv() bot.load() try: bot.run(bot.config.get('login'), bot.config.get('password')) except KeyboardInterrupt: bot.close() finally: print('* Bye!') <commit_msg>Fix the main loop & reconnecting<commit_after># -*- coding: utf-8 -*- import asyncio import time from autoreiv import AutoReiv def main(): while True: bot = AutoReiv() bot.load() try: bot.run(bot.config.get('login'), bot.config.get('password')) except Exception as e: print('* Crashed with error: {}'.format(e)) finally: print('* Disconnected.') asyncio.set_event_loop(asyncio.new_event_loop()) print('* Waiting 10 seconds before reconnecting (press ^C to stop)...') try: time.sleep(10) except KeyboardInterrupt: break if __name__ == '__main__': main()
656e6bfb18212990fc33a0e5b4d394c807c8d3ab
photutils/utils/tests/test_colormaps.py
photutils/utils/tests/test_colormaps.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from astropy.tests.helper import pytest from ..colormaps import random_cmap def test_colormap(): cmap = random_cmap(100, random_state=12345) assert cmap(0) == (0., 0., 0., 1.0) def test_colormap_background(): cmap = random_cmap(100, background_color='white', random_state=12345) assert cmap(0) == (1., 1., 1., 1.0) def test_invalid_background(): with pytest.raises(ValueError): random_cmap(100, background_color='invalid', random_state=12345)
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from astropy.tests.helper import pytest from ..colormaps import random_cmap try: import matplotlib HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False @pytest.mark.skipif('not HAS_MATPLOTLIB') def test_colormap(): cmap = random_cmap(100, random_state=12345) assert cmap(0) == (0., 0., 0., 1.0) @pytest.mark.skipif('not HAS_MATPLOTLIB') def test_colormap_background(): cmap = random_cmap(100, background_color='white', random_state=12345) assert cmap(0) == (1., 1., 1., 1.0) @pytest.mark.skipif('not HAS_MATPLOTLIB') def test_invalid_background(): with pytest.raises(ValueError): random_cmap(100, background_color='invalid', random_state=12345)
Check for matplotlib in tests
Check for matplotlib in tests
Python
bsd-3-clause
astropy/photutils,larrybradley/photutils
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from astropy.tests.helper import pytest from ..colormaps import random_cmap def test_colormap(): cmap = random_cmap(100, random_state=12345) assert cmap(0) == (0., 0., 0., 1.0) def test_colormap_background(): cmap = random_cmap(100, background_color='white', random_state=12345) assert cmap(0) == (1., 1., 1., 1.0) def test_invalid_background(): with pytest.raises(ValueError): random_cmap(100, background_color='invalid', random_state=12345) Check for matplotlib in tests
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from astropy.tests.helper import pytest from ..colormaps import random_cmap try: import matplotlib HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False @pytest.mark.skipif('not HAS_MATPLOTLIB') def test_colormap(): cmap = random_cmap(100, random_state=12345) assert cmap(0) == (0., 0., 0., 1.0) @pytest.mark.skipif('not HAS_MATPLOTLIB') def test_colormap_background(): cmap = random_cmap(100, background_color='white', random_state=12345) assert cmap(0) == (1., 1., 1., 1.0) @pytest.mark.skipif('not HAS_MATPLOTLIB') def test_invalid_background(): with pytest.raises(ValueError): random_cmap(100, background_color='invalid', random_state=12345)
<commit_before># Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from astropy.tests.helper import pytest from ..colormaps import random_cmap def test_colormap(): cmap = random_cmap(100, random_state=12345) assert cmap(0) == (0., 0., 0., 1.0) def test_colormap_background(): cmap = random_cmap(100, background_color='white', random_state=12345) assert cmap(0) == (1., 1., 1., 1.0) def test_invalid_background(): with pytest.raises(ValueError): random_cmap(100, background_color='invalid', random_state=12345) <commit_msg>Check for matplotlib in tests<commit_after>
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from astropy.tests.helper import pytest from ..colormaps import random_cmap try: import matplotlib HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False @pytest.mark.skipif('not HAS_MATPLOTLIB') def test_colormap(): cmap = random_cmap(100, random_state=12345) assert cmap(0) == (0., 0., 0., 1.0) @pytest.mark.skipif('not HAS_MATPLOTLIB') def test_colormap_background(): cmap = random_cmap(100, background_color='white', random_state=12345) assert cmap(0) == (1., 1., 1., 1.0) @pytest.mark.skipif('not HAS_MATPLOTLIB') def test_invalid_background(): with pytest.raises(ValueError): random_cmap(100, background_color='invalid', random_state=12345)
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from astropy.tests.helper import pytest from ..colormaps import random_cmap def test_colormap(): cmap = random_cmap(100, random_state=12345) assert cmap(0) == (0., 0., 0., 1.0) def test_colormap_background(): cmap = random_cmap(100, background_color='white', random_state=12345) assert cmap(0) == (1., 1., 1., 1.0) def test_invalid_background(): with pytest.raises(ValueError): random_cmap(100, background_color='invalid', random_state=12345) Check for matplotlib in tests# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from astropy.tests.helper import pytest from ..colormaps import random_cmap try: import matplotlib HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False @pytest.mark.skipif('not HAS_MATPLOTLIB') def test_colormap(): cmap = random_cmap(100, random_state=12345) assert cmap(0) == (0., 0., 0., 1.0) @pytest.mark.skipif('not HAS_MATPLOTLIB') def test_colormap_background(): cmap = random_cmap(100, background_color='white', random_state=12345) assert cmap(0) == (1., 1., 1., 1.0) @pytest.mark.skipif('not HAS_MATPLOTLIB') def test_invalid_background(): with pytest.raises(ValueError): random_cmap(100, background_color='invalid', random_state=12345)
<commit_before># Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from astropy.tests.helper import pytest from ..colormaps import random_cmap def test_colormap(): cmap = random_cmap(100, random_state=12345) assert cmap(0) == (0., 0., 0., 1.0) def test_colormap_background(): cmap = random_cmap(100, background_color='white', random_state=12345) assert cmap(0) == (1., 1., 1., 1.0) def test_invalid_background(): with pytest.raises(ValueError): random_cmap(100, background_color='invalid', random_state=12345) <commit_msg>Check for matplotlib in tests<commit_after># Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from astropy.tests.helper import pytest from ..colormaps import random_cmap try: import matplotlib HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False @pytest.mark.skipif('not HAS_MATPLOTLIB') def test_colormap(): cmap = random_cmap(100, random_state=12345) assert cmap(0) == (0., 0., 0., 1.0) @pytest.mark.skipif('not HAS_MATPLOTLIB') def test_colormap_background(): cmap = random_cmap(100, background_color='white', random_state=12345) assert cmap(0) == (1., 1., 1., 1.0) @pytest.mark.skipif('not HAS_MATPLOTLIB') def test_invalid_background(): with pytest.raises(ValueError): random_cmap(100, background_color='invalid', random_state=12345)
f112e7754e4f4368f0a82c3aae3a58f5300176f0
spacy/language_data/tag_map.py
spacy/language_data/tag_map.py
# encoding: utf8 from __future__ import unicode_literals from ..symbols import * TAG_MAP = { "ADV": {POS: ADV}, "NOUN": {POS: NOUN}, "ADP": {POS: ADP}, "PRON": {POS: PRON}, "SCONJ": {POS: SCONJ}, "PROPN": {POS: PROPN}, "DET": {POS: DET}, "SYM": {POS: SYM}, "INTJ": {POS: INTJ}, "PUNCT": {POS: PUNCT}, "NUM": {POS: NUM}, "AUX": {POS: AUX}, "X": {POS: X}, "CONJ": {POS: CONJ}, "ADJ": {POS: ADJ}, "VERB": {POS: VERB} }
# encoding: utf8 from __future__ import unicode_literals from ..symbols import * TAG_MAP = { "ADV": {POS: ADV}, "NOUN": {POS: NOUN}, "ADP": {POS: ADP}, "PRON": {POS: PRON}, "SCONJ": {POS: SCONJ}, "PROPN": {POS: PROPN}, "DET": {POS: DET}, "SYM": {POS: SYM}, "INTJ": {POS: INTJ}, "PUNCT": {POS: PUNCT}, "NUM": {POS: NUM}, "AUX": {POS: AUX}, "X": {POS: X}, "CONJ": {POS: CONJ}, "ADJ": {POS: ADJ}, "VERB": {POS: VERB}, "PART": {POS: PART} }
Add PART to tag map
Add PART to tag map 16 of the 17 PoS tags in the UD tag set is added; PART is missing.
Python
mit
banglakit/spaCy,raphael0202/spaCy,recognai/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,recognai/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,raphael0202/spaCy,recognai/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,Gregory-Howard/spaCy,banglakit/spaCy,banglakit/spaCy,Gregory-Howard/spaCy,banglakit/spaCy,spacy-io/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,aikramer2/spaCy,honnibal/spaCy,banglakit/spaCy,recognai/spaCy,explosion/spaCy,aikramer2/spaCy,recognai/spaCy,raphael0202/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,oroszgy/spaCy.hu,explosion/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,honnibal/spaCy,banglakit/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy,explosion/spaCy
# encoding: utf8 from __future__ import unicode_literals from ..symbols import * TAG_MAP = { "ADV": {POS: ADV}, "NOUN": {POS: NOUN}, "ADP": {POS: ADP}, "PRON": {POS: PRON}, "SCONJ": {POS: SCONJ}, "PROPN": {POS: PROPN}, "DET": {POS: DET}, "SYM": {POS: SYM}, "INTJ": {POS: INTJ}, "PUNCT": {POS: PUNCT}, "NUM": {POS: NUM}, "AUX": {POS: AUX}, "X": {POS: X}, "CONJ": {POS: CONJ}, "ADJ": {POS: ADJ}, "VERB": {POS: VERB} } Add PART to tag map 16 of the 17 PoS tags in the UD tag set is added; PART is missing.
# encoding: utf8 from __future__ import unicode_literals from ..symbols import * TAG_MAP = { "ADV": {POS: ADV}, "NOUN": {POS: NOUN}, "ADP": {POS: ADP}, "PRON": {POS: PRON}, "SCONJ": {POS: SCONJ}, "PROPN": {POS: PROPN}, "DET": {POS: DET}, "SYM": {POS: SYM}, "INTJ": {POS: INTJ}, "PUNCT": {POS: PUNCT}, "NUM": {POS: NUM}, "AUX": {POS: AUX}, "X": {POS: X}, "CONJ": {POS: CONJ}, "ADJ": {POS: ADJ}, "VERB": {POS: VERB}, "PART": {POS: PART} }
<commit_before># encoding: utf8 from __future__ import unicode_literals from ..symbols import * TAG_MAP = { "ADV": {POS: ADV}, "NOUN": {POS: NOUN}, "ADP": {POS: ADP}, "PRON": {POS: PRON}, "SCONJ": {POS: SCONJ}, "PROPN": {POS: PROPN}, "DET": {POS: DET}, "SYM": {POS: SYM}, "INTJ": {POS: INTJ}, "PUNCT": {POS: PUNCT}, "NUM": {POS: NUM}, "AUX": {POS: AUX}, "X": {POS: X}, "CONJ": {POS: CONJ}, "ADJ": {POS: ADJ}, "VERB": {POS: VERB} } <commit_msg>Add PART to tag map 16 of the 17 PoS tags in the UD tag set is added; PART is missing.<commit_after>
# encoding: utf8 from __future__ import unicode_literals from ..symbols import * TAG_MAP = { "ADV": {POS: ADV}, "NOUN": {POS: NOUN}, "ADP": {POS: ADP}, "PRON": {POS: PRON}, "SCONJ": {POS: SCONJ}, "PROPN": {POS: PROPN}, "DET": {POS: DET}, "SYM": {POS: SYM}, "INTJ": {POS: INTJ}, "PUNCT": {POS: PUNCT}, "NUM": {POS: NUM}, "AUX": {POS: AUX}, "X": {POS: X}, "CONJ": {POS: CONJ}, "ADJ": {POS: ADJ}, "VERB": {POS: VERB}, "PART": {POS: PART} }
# encoding: utf8 from __future__ import unicode_literals from ..symbols import * TAG_MAP = { "ADV": {POS: ADV}, "NOUN": {POS: NOUN}, "ADP": {POS: ADP}, "PRON": {POS: PRON}, "SCONJ": {POS: SCONJ}, "PROPN": {POS: PROPN}, "DET": {POS: DET}, "SYM": {POS: SYM}, "INTJ": {POS: INTJ}, "PUNCT": {POS: PUNCT}, "NUM": {POS: NUM}, "AUX": {POS: AUX}, "X": {POS: X}, "CONJ": {POS: CONJ}, "ADJ": {POS: ADJ}, "VERB": {POS: VERB} } Add PART to tag map 16 of the 17 PoS tags in the UD tag set is added; PART is missing.# encoding: utf8 from __future__ import unicode_literals from ..symbols import * TAG_MAP = { "ADV": {POS: ADV}, "NOUN": {POS: NOUN}, "ADP": {POS: ADP}, "PRON": {POS: PRON}, "SCONJ": {POS: SCONJ}, "PROPN": {POS: PROPN}, "DET": {POS: DET}, "SYM": {POS: SYM}, "INTJ": {POS: INTJ}, "PUNCT": {POS: PUNCT}, "NUM": {POS: NUM}, "AUX": {POS: AUX}, "X": {POS: X}, "CONJ": {POS: CONJ}, "ADJ": {POS: ADJ}, "VERB": {POS: VERB}, "PART": {POS: PART} }
<commit_before># encoding: utf8 from __future__ import unicode_literals from ..symbols import * TAG_MAP = { "ADV": {POS: ADV}, "NOUN": {POS: NOUN}, "ADP": {POS: ADP}, "PRON": {POS: PRON}, "SCONJ": {POS: SCONJ}, "PROPN": {POS: PROPN}, "DET": {POS: DET}, "SYM": {POS: SYM}, "INTJ": {POS: INTJ}, "PUNCT": {POS: PUNCT}, "NUM": {POS: NUM}, "AUX": {POS: AUX}, "X": {POS: X}, "CONJ": {POS: CONJ}, "ADJ": {POS: ADJ}, "VERB": {POS: VERB} } <commit_msg>Add PART to tag map 16 of the 17 PoS tags in the UD tag set is added; PART is missing.<commit_after># encoding: utf8 from __future__ import unicode_literals from ..symbols import * TAG_MAP = { "ADV": {POS: ADV}, "NOUN": {POS: NOUN}, "ADP": {POS: ADP}, "PRON": {POS: PRON}, "SCONJ": {POS: SCONJ}, "PROPN": {POS: PROPN}, "DET": {POS: DET}, "SYM": {POS: SYM}, "INTJ": {POS: INTJ}, "PUNCT": {POS: PUNCT}, "NUM": {POS: NUM}, "AUX": {POS: AUX}, "X": {POS: X}, "CONJ": {POS: CONJ}, "ADJ": {POS: ADJ}, "VERB": {POS: VERB}, "PART": {POS: PART} }
32f30d869dd79f57bc5a00afc1f3ef55a1818ba8
phileo/models.py
phileo/models.py
from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic # Compatibility with custom user models, while keeping backwards-compatibility with <1.5 AUTH_USER_MODEL = getattr(settings, "AUTH_USER_MODEL", "auth.User") class Like(models.Model): sender = models.ForeignKey(AUTH_USER_MODEL, related_name="liking") receiver_content_type = models.ForeignKey(ContentType) receiver_object_id = models.PositiveIntegerField() receiver = generic.GenericForeignKey( ct_field="receiver_content_type", fk_field="receiver_object_id" ) timestamp = models.DateTimeField(default=timezone.now) class Meta: unique_together = ( ("sender", "receiver_content_type", "receiver_object_id"), ) def __unicode__(self): return "%s likes %s" % (self.sender, self.receiver)
from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic # Compatibility with custom user models, while keeping backwards-compatibility with <1.5 AUTH_USER_MODEL = getattr(settings, "AUTH_USER_MODEL", "auth.User") class Like(models.Model): sender = models.ForeignKey(AUTH_USER_MODEL, related_name="liking") receiver_content_type = models.ForeignKey(ContentType) receiver_object_id = models.PositiveIntegerField() receiver = generic.GenericForeignKey( ct_field="receiver_content_type", fk_field="receiver_object_id" ) timestamp = models.DateTimeField(default=timezone.now) class Meta: unique_together = ( ("sender", "receiver_content_type", "receiver_object_id"), ) def __unicode__(self): return u"%s likes %s" % (self.sender, self.receiver)
Fix potential unicode issues with Like.__unicode__()
Fix potential unicode issues with Like.__unicode__()
Python
mit
rizumu/pinax-likes,jacobwegner/phileo,jacobwegner/phileo,pinax/pinax-likes,pinax/phileo,rizumu/pinax-likes,pinax/phileo
from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic # Compatibility with custom user models, while keeping backwards-compatibility with <1.5 AUTH_USER_MODEL = getattr(settings, "AUTH_USER_MODEL", "auth.User") class Like(models.Model): sender = models.ForeignKey(AUTH_USER_MODEL, related_name="liking") receiver_content_type = models.ForeignKey(ContentType) receiver_object_id = models.PositiveIntegerField() receiver = generic.GenericForeignKey( ct_field="receiver_content_type", fk_field="receiver_object_id" ) timestamp = models.DateTimeField(default=timezone.now) class Meta: unique_together = ( ("sender", "receiver_content_type", "receiver_object_id"), ) def __unicode__(self): return "%s likes %s" % (self.sender, self.receiver) Fix potential unicode issues with Like.__unicode__()
from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic # Compatibility with custom user models, while keeping backwards-compatibility with <1.5 AUTH_USER_MODEL = getattr(settings, "AUTH_USER_MODEL", "auth.User") class Like(models.Model): sender = models.ForeignKey(AUTH_USER_MODEL, related_name="liking") receiver_content_type = models.ForeignKey(ContentType) receiver_object_id = models.PositiveIntegerField() receiver = generic.GenericForeignKey( ct_field="receiver_content_type", fk_field="receiver_object_id" ) timestamp = models.DateTimeField(default=timezone.now) class Meta: unique_together = ( ("sender", "receiver_content_type", "receiver_object_id"), ) def __unicode__(self): return u"%s likes %s" % (self.sender, self.receiver)
<commit_before>from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic # Compatibility with custom user models, while keeping backwards-compatibility with <1.5 AUTH_USER_MODEL = getattr(settings, "AUTH_USER_MODEL", "auth.User") class Like(models.Model): sender = models.ForeignKey(AUTH_USER_MODEL, related_name="liking") receiver_content_type = models.ForeignKey(ContentType) receiver_object_id = models.PositiveIntegerField() receiver = generic.GenericForeignKey( ct_field="receiver_content_type", fk_field="receiver_object_id" ) timestamp = models.DateTimeField(default=timezone.now) class Meta: unique_together = ( ("sender", "receiver_content_type", "receiver_object_id"), ) def __unicode__(self): return "%s likes %s" % (self.sender, self.receiver) <commit_msg>Fix potential unicode issues with Like.__unicode__()<commit_after>
from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic # Compatibility with custom user models, while keeping backwards-compatibility with <1.5 AUTH_USER_MODEL = getattr(settings, "AUTH_USER_MODEL", "auth.User") class Like(models.Model): sender = models.ForeignKey(AUTH_USER_MODEL, related_name="liking") receiver_content_type = models.ForeignKey(ContentType) receiver_object_id = models.PositiveIntegerField() receiver = generic.GenericForeignKey( ct_field="receiver_content_type", fk_field="receiver_object_id" ) timestamp = models.DateTimeField(default=timezone.now) class Meta: unique_together = ( ("sender", "receiver_content_type", "receiver_object_id"), ) def __unicode__(self): return u"%s likes %s" % (self.sender, self.receiver)
from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic # Compatibility with custom user models, while keeping backwards-compatibility with <1.5 AUTH_USER_MODEL = getattr(settings, "AUTH_USER_MODEL", "auth.User") class Like(models.Model): sender = models.ForeignKey(AUTH_USER_MODEL, related_name="liking") receiver_content_type = models.ForeignKey(ContentType) receiver_object_id = models.PositiveIntegerField() receiver = generic.GenericForeignKey( ct_field="receiver_content_type", fk_field="receiver_object_id" ) timestamp = models.DateTimeField(default=timezone.now) class Meta: unique_together = ( ("sender", "receiver_content_type", "receiver_object_id"), ) def __unicode__(self): return "%s likes %s" % (self.sender, self.receiver) Fix potential unicode issues with Like.__unicode__()from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic # Compatibility with custom user models, while keeping backwards-compatibility with <1.5 AUTH_USER_MODEL = getattr(settings, "AUTH_USER_MODEL", "auth.User") class Like(models.Model): sender = models.ForeignKey(AUTH_USER_MODEL, related_name="liking") receiver_content_type = models.ForeignKey(ContentType) receiver_object_id = models.PositiveIntegerField() receiver = generic.GenericForeignKey( ct_field="receiver_content_type", fk_field="receiver_object_id" ) timestamp = models.DateTimeField(default=timezone.now) class Meta: unique_together = ( ("sender", "receiver_content_type", "receiver_object_id"), ) def __unicode__(self): return u"%s likes %s" % (self.sender, self.receiver)
<commit_before>from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic # Compatibility with custom user models, while keeping backwards-compatibility with <1.5 AUTH_USER_MODEL = getattr(settings, "AUTH_USER_MODEL", "auth.User") class Like(models.Model): sender = models.ForeignKey(AUTH_USER_MODEL, related_name="liking") receiver_content_type = models.ForeignKey(ContentType) receiver_object_id = models.PositiveIntegerField() receiver = generic.GenericForeignKey( ct_field="receiver_content_type", fk_field="receiver_object_id" ) timestamp = models.DateTimeField(default=timezone.now) class Meta: unique_together = ( ("sender", "receiver_content_type", "receiver_object_id"), ) def __unicode__(self): return "%s likes %s" % (self.sender, self.receiver) <commit_msg>Fix potential unicode issues with Like.__unicode__()<commit_after>from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic # Compatibility with custom user models, while keeping backwards-compatibility with <1.5 AUTH_USER_MODEL = getattr(settings, "AUTH_USER_MODEL", "auth.User") class Like(models.Model): sender = models.ForeignKey(AUTH_USER_MODEL, related_name="liking") receiver_content_type = models.ForeignKey(ContentType) receiver_object_id = models.PositiveIntegerField() receiver = generic.GenericForeignKey( ct_field="receiver_content_type", fk_field="receiver_object_id" ) timestamp = models.DateTimeField(default=timezone.now) class Meta: unique_together = ( ("sender", "receiver_content_type", "receiver_object_id"), ) def __unicode__(self): return u"%s likes %s" % (self.sender, self.receiver)
c38e6b497457886cf829111b89d3f102765f0eb3
takeyourmeds/reminders/tasks.py
takeyourmeds/reminders/tasks.py
from __future__ import absolute_import import traceback from celery import shared_task from celery.utils.log import get_task_logger from django.contrib.staticfiles.storage import staticfiles_storage from takeyourmeds.utils.dt import local_time from takeyourmeds.telephony.utils import send_sms, make_call from .models import Reminder, Time from .reminders_logging.enums import StateEnum logger = get_task_logger(__name__) @shared_task() def schedule_reminders(): for x in Time.objects.filter(time='%02d:00' % local_time().hour): trigger_reminder.delay(x.reminder_id) @shared_task() def trigger_reminder(reminder_id): reminder = Reminder.objects.get(pk=reminder_id) entry = reminder.log_entries.create( state=StateEnum.in_progress, ) try: if reminder.message: sid = send_sms(reminder.phone_number, reminder.message) elif reminder.audio_url: sid = make_call( reminder.phone_number, staticfiles_storage.url(reminder.audio_url), ) else: raise NotImplementedError("Unhandled reminder action") entry.state = StateEnum.success entry.twilio_sid = sid except Exception, exc: entry.state = StateEnum.error entry.traceback = traceback.format_exc() raise finally: entry.save()
from __future__ import absolute_import import traceback from celery import shared_task from celery.utils.log import get_task_logger from django.contrib.staticfiles.storage import staticfiles_storage from takeyourmeds.utils.dt import local_time from takeyourmeds.telephony.utils import send_sms, make_call from .models import Reminder, Time from .reminders_logging.enums import StateEnum logger = get_task_logger(__name__) @shared_task() def schedule_reminders(): for x in Time.objects.filter(time='%02d:00' % local_time().hour): trigger_reminder.delay(x.reminder_id) @shared_task() def trigger_reminder(reminder_id): reminder = Reminder.objects.get(pk=reminder_id) entry = reminder.log_entries.create( state=StateEnum.in_progress, ) try: entry.state = StateEnum.success entry.twilio_sid = _trigger_reminder(reminder) except Exception, exc: entry.state = StateEnum.error entry.traceback = traceback.format_exc() raise finally: entry.save() def _trigger_reminder(reminder): if reminder.message: return send_sms(reminder.phone_number, reminder.message) if reminder.audio_url: return make_call( reminder.phone_number, staticfiles_storage.url(reminder.audio_url), ) raise NotImplementedError("Unhandled reminder action")
Split into own method for clariy and "return" support
Split into own method for clariy and "return" support
Python
mit
takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web
from __future__ import absolute_import import traceback from celery import shared_task from celery.utils.log import get_task_logger from django.contrib.staticfiles.storage import staticfiles_storage from takeyourmeds.utils.dt import local_time from takeyourmeds.telephony.utils import send_sms, make_call from .models import Reminder, Time from .reminders_logging.enums import StateEnum logger = get_task_logger(__name__) @shared_task() def schedule_reminders(): for x in Time.objects.filter(time='%02d:00' % local_time().hour): trigger_reminder.delay(x.reminder_id) @shared_task() def trigger_reminder(reminder_id): reminder = Reminder.objects.get(pk=reminder_id) entry = reminder.log_entries.create( state=StateEnum.in_progress, ) try: if reminder.message: sid = send_sms(reminder.phone_number, reminder.message) elif reminder.audio_url: sid = make_call( reminder.phone_number, staticfiles_storage.url(reminder.audio_url), ) else: raise NotImplementedError("Unhandled reminder action") entry.state = StateEnum.success entry.twilio_sid = sid except Exception, exc: entry.state = StateEnum.error entry.traceback = traceback.format_exc() raise finally: entry.save() Split into own method for clariy and "return" support
from __future__ import absolute_import import traceback from celery import shared_task from celery.utils.log import get_task_logger from django.contrib.staticfiles.storage import staticfiles_storage from takeyourmeds.utils.dt import local_time from takeyourmeds.telephony.utils import send_sms, make_call from .models import Reminder, Time from .reminders_logging.enums import StateEnum logger = get_task_logger(__name__) @shared_task() def schedule_reminders(): for x in Time.objects.filter(time='%02d:00' % local_time().hour): trigger_reminder.delay(x.reminder_id) @shared_task() def trigger_reminder(reminder_id): reminder = Reminder.objects.get(pk=reminder_id) entry = reminder.log_entries.create( state=StateEnum.in_progress, ) try: entry.state = StateEnum.success entry.twilio_sid = _trigger_reminder(reminder) except Exception, exc: entry.state = StateEnum.error entry.traceback = traceback.format_exc() raise finally: entry.save() def _trigger_reminder(reminder): if reminder.message: return send_sms(reminder.phone_number, reminder.message) if reminder.audio_url: return make_call( reminder.phone_number, staticfiles_storage.url(reminder.audio_url), ) raise NotImplementedError("Unhandled reminder action")
<commit_before>from __future__ import absolute_import import traceback from celery import shared_task from celery.utils.log import get_task_logger from django.contrib.staticfiles.storage import staticfiles_storage from takeyourmeds.utils.dt import local_time from takeyourmeds.telephony.utils import send_sms, make_call from .models import Reminder, Time from .reminders_logging.enums import StateEnum logger = get_task_logger(__name__) @shared_task() def schedule_reminders(): for x in Time.objects.filter(time='%02d:00' % local_time().hour): trigger_reminder.delay(x.reminder_id) @shared_task() def trigger_reminder(reminder_id): reminder = Reminder.objects.get(pk=reminder_id) entry = reminder.log_entries.create( state=StateEnum.in_progress, ) try: if reminder.message: sid = send_sms(reminder.phone_number, reminder.message) elif reminder.audio_url: sid = make_call( reminder.phone_number, staticfiles_storage.url(reminder.audio_url), ) else: raise NotImplementedError("Unhandled reminder action") entry.state = StateEnum.success entry.twilio_sid = sid except Exception, exc: entry.state = StateEnum.error entry.traceback = traceback.format_exc() raise finally: entry.save() <commit_msg>Split into own method for clariy and "return" support<commit_after>
from __future__ import absolute_import import traceback from celery import shared_task from celery.utils.log import get_task_logger from django.contrib.staticfiles.storage import staticfiles_storage from takeyourmeds.utils.dt import local_time from takeyourmeds.telephony.utils import send_sms, make_call from .models import Reminder, Time from .reminders_logging.enums import StateEnum logger = get_task_logger(__name__) @shared_task() def schedule_reminders(): for x in Time.objects.filter(time='%02d:00' % local_time().hour): trigger_reminder.delay(x.reminder_id) @shared_task() def trigger_reminder(reminder_id): reminder = Reminder.objects.get(pk=reminder_id) entry = reminder.log_entries.create( state=StateEnum.in_progress, ) try: entry.state = StateEnum.success entry.twilio_sid = _trigger_reminder(reminder) except Exception, exc: entry.state = StateEnum.error entry.traceback = traceback.format_exc() raise finally: entry.save() def _trigger_reminder(reminder): if reminder.message: return send_sms(reminder.phone_number, reminder.message) if reminder.audio_url: return make_call( reminder.phone_number, staticfiles_storage.url(reminder.audio_url), ) raise NotImplementedError("Unhandled reminder action")
from __future__ import absolute_import import traceback from celery import shared_task from celery.utils.log import get_task_logger from django.contrib.staticfiles.storage import staticfiles_storage from takeyourmeds.utils.dt import local_time from takeyourmeds.telephony.utils import send_sms, make_call from .models import Reminder, Time from .reminders_logging.enums import StateEnum logger = get_task_logger(__name__) @shared_task() def schedule_reminders(): for x in Time.objects.filter(time='%02d:00' % local_time().hour): trigger_reminder.delay(x.reminder_id) @shared_task() def trigger_reminder(reminder_id): reminder = Reminder.objects.get(pk=reminder_id) entry = reminder.log_entries.create( state=StateEnum.in_progress, ) try: if reminder.message: sid = send_sms(reminder.phone_number, reminder.message) elif reminder.audio_url: sid = make_call( reminder.phone_number, staticfiles_storage.url(reminder.audio_url), ) else: raise NotImplementedError("Unhandled reminder action") entry.state = StateEnum.success entry.twilio_sid = sid except Exception, exc: entry.state = StateEnum.error entry.traceback = traceback.format_exc() raise finally: entry.save() Split into own method for clariy and "return" supportfrom __future__ import absolute_import import traceback from celery import shared_task from celery.utils.log import get_task_logger from django.contrib.staticfiles.storage import staticfiles_storage from takeyourmeds.utils.dt import local_time from takeyourmeds.telephony.utils import send_sms, make_call from .models import Reminder, Time from .reminders_logging.enums import StateEnum logger = get_task_logger(__name__) @shared_task() def schedule_reminders(): for x in Time.objects.filter(time='%02d:00' % local_time().hour): trigger_reminder.delay(x.reminder_id) @shared_task() def trigger_reminder(reminder_id): reminder = Reminder.objects.get(pk=reminder_id) entry = reminder.log_entries.create( state=StateEnum.in_progress, ) try: entry.state = StateEnum.success entry.twilio_sid = _trigger_reminder(reminder) except Exception, exc: entry.state = StateEnum.error entry.traceback = traceback.format_exc() raise finally: entry.save() def _trigger_reminder(reminder): if reminder.message: return send_sms(reminder.phone_number, reminder.message) if reminder.audio_url: return make_call( reminder.phone_number, staticfiles_storage.url(reminder.audio_url), ) raise NotImplementedError("Unhandled reminder action")
<commit_before>from __future__ import absolute_import import traceback from celery import shared_task from celery.utils.log import get_task_logger from django.contrib.staticfiles.storage import staticfiles_storage from takeyourmeds.utils.dt import local_time from takeyourmeds.telephony.utils import send_sms, make_call from .models import Reminder, Time from .reminders_logging.enums import StateEnum logger = get_task_logger(__name__) @shared_task() def schedule_reminders(): for x in Time.objects.filter(time='%02d:00' % local_time().hour): trigger_reminder.delay(x.reminder_id) @shared_task() def trigger_reminder(reminder_id): reminder = Reminder.objects.get(pk=reminder_id) entry = reminder.log_entries.create( state=StateEnum.in_progress, ) try: if reminder.message: sid = send_sms(reminder.phone_number, reminder.message) elif reminder.audio_url: sid = make_call( reminder.phone_number, staticfiles_storage.url(reminder.audio_url), ) else: raise NotImplementedError("Unhandled reminder action") entry.state = StateEnum.success entry.twilio_sid = sid except Exception, exc: entry.state = StateEnum.error entry.traceback = traceback.format_exc() raise finally: entry.save() <commit_msg>Split into own method for clariy and "return" support<commit_after>from __future__ import absolute_import import traceback from celery import shared_task from celery.utils.log import get_task_logger from django.contrib.staticfiles.storage import staticfiles_storage from takeyourmeds.utils.dt import local_time from takeyourmeds.telephony.utils import send_sms, make_call from .models import Reminder, Time from .reminders_logging.enums import StateEnum logger = get_task_logger(__name__) @shared_task() def schedule_reminders(): for x in Time.objects.filter(time='%02d:00' % local_time().hour): trigger_reminder.delay(x.reminder_id) @shared_task() def trigger_reminder(reminder_id): reminder = Reminder.objects.get(pk=reminder_id) entry = reminder.log_entries.create( state=StateEnum.in_progress, ) try: entry.state = StateEnum.success entry.twilio_sid = _trigger_reminder(reminder) except Exception, exc: entry.state = StateEnum.error entry.traceback = traceback.format_exc() raise finally: entry.save() def _trigger_reminder(reminder): if reminder.message: return send_sms(reminder.phone_number, reminder.message) if reminder.audio_url: return make_call( reminder.phone_number, staticfiles_storage.url(reminder.audio_url), ) raise NotImplementedError("Unhandled reminder action")
c34c6e2ac2f4574a3ef770a8a3687c17a130a783
parsescrapegenerate/__init__.py
parsescrapegenerate/__init__.py
# -*- coding: utf-8 -*- """ parsescrapegenerate --------------- Main package for ParseScapeFeed """ __title__ = 'ParseScrapeGenerate' __version__ = '0.1.0'
# -*- coding: utf-8 -*- """ parsescrapegenerate --------------- Main package for ParseScrapeGenerate """ __title__ = 'ParseScrapeGenerate' __version__ = '0.1.0'
Make sure correct project name is used throughout
Make sure correct project name is used throughout
Python
bsd-3-clause
jonyamo/parsescrapegenerate,jonyamo/parsescrapegenerate
# -*- coding: utf-8 -*- """ parsescrapegenerate --------------- Main package for ParseScapeFeed """ __title__ = 'ParseScrapeGenerate' __version__ = '0.1.0' Make sure correct project name is used throughout
# -*- coding: utf-8 -*- """ parsescrapegenerate --------------- Main package for ParseScrapeGenerate """ __title__ = 'ParseScrapeGenerate' __version__ = '0.1.0'
<commit_before># -*- coding: utf-8 -*- """ parsescrapegenerate --------------- Main package for ParseScapeFeed """ __title__ = 'ParseScrapeGenerate' __version__ = '0.1.0' <commit_msg>Make sure correct project name is used throughout<commit_after>
# -*- coding: utf-8 -*- """ parsescrapegenerate --------------- Main package for ParseScrapeGenerate """ __title__ = 'ParseScrapeGenerate' __version__ = '0.1.0'
# -*- coding: utf-8 -*- """ parsescrapegenerate --------------- Main package for ParseScapeFeed """ __title__ = 'ParseScrapeGenerate' __version__ = '0.1.0' Make sure correct project name is used throughout# -*- coding: utf-8 -*- """ parsescrapegenerate --------------- Main package for ParseScrapeGenerate """ __title__ = 'ParseScrapeGenerate' __version__ = '0.1.0'
<commit_before># -*- coding: utf-8 -*- """ parsescrapegenerate --------------- Main package for ParseScapeFeed """ __title__ = 'ParseScrapeGenerate' __version__ = '0.1.0' <commit_msg>Make sure correct project name is used throughout<commit_after># -*- coding: utf-8 -*- """ parsescrapegenerate --------------- Main package for ParseScrapeGenerate """ __title__ = 'ParseScrapeGenerate' __version__ = '0.1.0'
ee0922cecbce8617afe36e9555078d5a3ba21878
src/django_future/management/commands/runscheduledjobs.py
src/django_future/management/commands/runscheduledjobs.py
"""Run scheduled jobs.""" import datetime from optparse import make_option from django.core.management.base import NoArgsCommand from django_future import run_jobs class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--delete-completed', '-d', action='store_true', dest='delete_completed', help='Do not keep entries for completed jobs in the database.'), make_option('--ignore-errors', '-i', action='store_true', dest='ignore_errors', help='Do not abort if a job handler raises an error.'), ) help = "Executes any outstanding scheduled jobs." def handle(self, **options): delete_completed = bool(options.get('delete_completed', False)) ignore_errors = bool(options.get('ignore_errors', False)) run_jobs(delete_completed=delete_completed, ignore_errors=ignore_errors)
"""Run scheduled jobs.""" import datetime from optparse import make_option from django.core.management.base import NoArgsCommand, CommandError from django_future import run_jobs class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--delete-completed', '-d', action='store_true', dest='delete_completed', help='Do not keep entries for completed jobs in the database.'), make_option('--ignore-errors', '-i', action='store_true', dest='ignore_errors', help='Do not abort if a job handler raises an error.'), ) help = "Executes any outstanding scheduled jobs." def handle(self, **options): delete_completed = bool(options.get('delete_completed', False)) ignore_errors = bool(options.get('ignore_errors', False)) try: run_jobs(delete_completed=delete_completed, ignore_errors=ignore_errors) except ValueError, e: raise CommandError(e)
Raise a nicer CommandError instead of showing the ValueError on the command line.
Raise a nicer CommandError instead of showing the ValueError on the command line.
Python
mit
shrubberysoft/django-future
"""Run scheduled jobs.""" import datetime from optparse import make_option from django.core.management.base import NoArgsCommand from django_future import run_jobs class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--delete-completed', '-d', action='store_true', dest='delete_completed', help='Do not keep entries for completed jobs in the database.'), make_option('--ignore-errors', '-i', action='store_true', dest='ignore_errors', help='Do not abort if a job handler raises an error.'), ) help = "Executes any outstanding scheduled jobs." def handle(self, **options): delete_completed = bool(options.get('delete_completed', False)) ignore_errors = bool(options.get('ignore_errors', False)) run_jobs(delete_completed=delete_completed, ignore_errors=ignore_errors) Raise a nicer CommandError instead of showing the ValueError on the command line.
"""Run scheduled jobs.""" import datetime from optparse import make_option from django.core.management.base import NoArgsCommand, CommandError from django_future import run_jobs class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--delete-completed', '-d', action='store_true', dest='delete_completed', help='Do not keep entries for completed jobs in the database.'), make_option('--ignore-errors', '-i', action='store_true', dest='ignore_errors', help='Do not abort if a job handler raises an error.'), ) help = "Executes any outstanding scheduled jobs." def handle(self, **options): delete_completed = bool(options.get('delete_completed', False)) ignore_errors = bool(options.get('ignore_errors', False)) try: run_jobs(delete_completed=delete_completed, ignore_errors=ignore_errors) except ValueError, e: raise CommandError(e)
<commit_before>"""Run scheduled jobs.""" import datetime from optparse import make_option from django.core.management.base import NoArgsCommand from django_future import run_jobs class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--delete-completed', '-d', action='store_true', dest='delete_completed', help='Do not keep entries for completed jobs in the database.'), make_option('--ignore-errors', '-i', action='store_true', dest='ignore_errors', help='Do not abort if a job handler raises an error.'), ) help = "Executes any outstanding scheduled jobs." def handle(self, **options): delete_completed = bool(options.get('delete_completed', False)) ignore_errors = bool(options.get('ignore_errors', False)) run_jobs(delete_completed=delete_completed, ignore_errors=ignore_errors) <commit_msg>Raise a nicer CommandError instead of showing the ValueError on the command line.<commit_after>
"""Run scheduled jobs.""" import datetime from optparse import make_option from django.core.management.base import NoArgsCommand, CommandError from django_future import run_jobs class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--delete-completed', '-d', action='store_true', dest='delete_completed', help='Do not keep entries for completed jobs in the database.'), make_option('--ignore-errors', '-i', action='store_true', dest='ignore_errors', help='Do not abort if a job handler raises an error.'), ) help = "Executes any outstanding scheduled jobs." def handle(self, **options): delete_completed = bool(options.get('delete_completed', False)) ignore_errors = bool(options.get('ignore_errors', False)) try: run_jobs(delete_completed=delete_completed, ignore_errors=ignore_errors) except ValueError, e: raise CommandError(e)
"""Run scheduled jobs.""" import datetime from optparse import make_option from django.core.management.base import NoArgsCommand from django_future import run_jobs class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--delete-completed', '-d', action='store_true', dest='delete_completed', help='Do not keep entries for completed jobs in the database.'), make_option('--ignore-errors', '-i', action='store_true', dest='ignore_errors', help='Do not abort if a job handler raises an error.'), ) help = "Executes any outstanding scheduled jobs." def handle(self, **options): delete_completed = bool(options.get('delete_completed', False)) ignore_errors = bool(options.get('ignore_errors', False)) run_jobs(delete_completed=delete_completed, ignore_errors=ignore_errors) Raise a nicer CommandError instead of showing the ValueError on the command line."""Run scheduled jobs.""" import datetime from optparse import make_option from django.core.management.base import NoArgsCommand, CommandError from django_future import run_jobs class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--delete-completed', '-d', action='store_true', dest='delete_completed', help='Do not keep entries for completed jobs in the database.'), make_option('--ignore-errors', '-i', action='store_true', dest='ignore_errors', help='Do not abort if a job handler raises an error.'), ) help = "Executes any outstanding scheduled jobs." def handle(self, **options): delete_completed = bool(options.get('delete_completed', False)) ignore_errors = bool(options.get('ignore_errors', False)) try: run_jobs(delete_completed=delete_completed, ignore_errors=ignore_errors) except ValueError, e: raise CommandError(e)
<commit_before>"""Run scheduled jobs.""" import datetime from optparse import make_option from django.core.management.base import NoArgsCommand from django_future import run_jobs class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--delete-completed', '-d', action='store_true', dest='delete_completed', help='Do not keep entries for completed jobs in the database.'), make_option('--ignore-errors', '-i', action='store_true', dest='ignore_errors', help='Do not abort if a job handler raises an error.'), ) help = "Executes any outstanding scheduled jobs." def handle(self, **options): delete_completed = bool(options.get('delete_completed', False)) ignore_errors = bool(options.get('ignore_errors', False)) run_jobs(delete_completed=delete_completed, ignore_errors=ignore_errors) <commit_msg>Raise a nicer CommandError instead of showing the ValueError on the command line.<commit_after>"""Run scheduled jobs.""" import datetime from optparse import make_option from django.core.management.base import NoArgsCommand, CommandError from django_future import run_jobs class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--delete-completed', '-d', action='store_true', dest='delete_completed', help='Do not keep entries for completed jobs in the database.'), make_option('--ignore-errors', '-i', action='store_true', dest='ignore_errors', help='Do not abort if a job handler raises an error.'), ) help = "Executes any outstanding scheduled jobs." def handle(self, **options): delete_completed = bool(options.get('delete_completed', False)) ignore_errors = bool(options.get('ignore_errors', False)) try: run_jobs(delete_completed=delete_completed, ignore_errors=ignore_errors) except ValueError, e: raise CommandError(e)
79e4839c06d8a3ae8de0c9a7c0cf7b536016dde3
pyglab/pyglab.py
pyglab/pyglab.py
_defaults = { 'api_url': 'api/v3', } from .apirequest import ApiRequest, RequestType from .users import Users class Pyglab(object): def __init__(self, url, token, api_url=_defaults['api_url']): self._base_url = url.rstrip('/') + '/' + api_url.strip() self._token = token self._user = None self._per_page = None def sudo(self, user): """Permanently set a different username. Returns the old username.""" previous_user = self._user self._user = user return previous_user def request(self, request_type, url, params={}, sudo=None, page=None, per_page=None): if sudo is None and self._user is not None: sudo = _self.user if per_page is None and self._per_page is None: per_page = self._per_page r = ApiRequest(request_type, self._base_url + '/' + url.lstrip('/'), self._token, params, sudo, page, per_page) return r.content @property def users(self): u = self.request(RequestType.GET, '/users') return Users(u) def users_by_name(self, name): params = {'search': name} u = self.request(RequestType.GET, '/users', params=params) return Users(u)
_defaults = { 'api_url': 'api/v3', } from .apirequest import ApiRequest, RequestType from .users import Users class Pyglab(object): def __init__(self, url, token, api_url=_defaults['api_url']): self._base_url = url.rstrip('/') + '/' + api_url.strip() self._token = token self._user = None self._per_page = None def sudo(self, user): """Permanently set a different username. Returns the old username.""" previous_user = self._user self._user = user return previous_user def request(self, request_type, url, params={}, sudo=None, page=None, per_page=None): if sudo is None and self._user is not None: sudo = _self.user if per_page is None and self._per_page is None: per_page = self._per_page r = ApiRequest(request_type, self._base_url + '/' + url.lstrip('/'), self._token, params, sudo, page, per_page) return r.content @property def users(self): return Users(self)
Create exactly one users function.
Create exactly one users function.
Python
mit
sloede/pyglab,sloede/pyglab
_defaults = { 'api_url': 'api/v3', } from .apirequest import ApiRequest, RequestType from .users import Users class Pyglab(object): def __init__(self, url, token, api_url=_defaults['api_url']): self._base_url = url.rstrip('/') + '/' + api_url.strip() self._token = token self._user = None self._per_page = None def sudo(self, user): """Permanently set a different username. Returns the old username.""" previous_user = self._user self._user = user return previous_user def request(self, request_type, url, params={}, sudo=None, page=None, per_page=None): if sudo is None and self._user is not None: sudo = _self.user if per_page is None and self._per_page is None: per_page = self._per_page r = ApiRequest(request_type, self._base_url + '/' + url.lstrip('/'), self._token, params, sudo, page, per_page) return r.content @property def users(self): u = self.request(RequestType.GET, '/users') return Users(u) def users_by_name(self, name): params = {'search': name} u = self.request(RequestType.GET, '/users', params=params) return Users(u) Create exactly one users function.
_defaults = { 'api_url': 'api/v3', } from .apirequest import ApiRequest, RequestType from .users import Users class Pyglab(object): def __init__(self, url, token, api_url=_defaults['api_url']): self._base_url = url.rstrip('/') + '/' + api_url.strip() self._token = token self._user = None self._per_page = None def sudo(self, user): """Permanently set a different username. Returns the old username.""" previous_user = self._user self._user = user return previous_user def request(self, request_type, url, params={}, sudo=None, page=None, per_page=None): if sudo is None and self._user is not None: sudo = _self.user if per_page is None and self._per_page is None: per_page = self._per_page r = ApiRequest(request_type, self._base_url + '/' + url.lstrip('/'), self._token, params, sudo, page, per_page) return r.content @property def users(self): return Users(self)
<commit_before>_defaults = { 'api_url': 'api/v3', } from .apirequest import ApiRequest, RequestType from .users import Users class Pyglab(object): def __init__(self, url, token, api_url=_defaults['api_url']): self._base_url = url.rstrip('/') + '/' + api_url.strip() self._token = token self._user = None self._per_page = None def sudo(self, user): """Permanently set a different username. Returns the old username.""" previous_user = self._user self._user = user return previous_user def request(self, request_type, url, params={}, sudo=None, page=None, per_page=None): if sudo is None and self._user is not None: sudo = _self.user if per_page is None and self._per_page is None: per_page = self._per_page r = ApiRequest(request_type, self._base_url + '/' + url.lstrip('/'), self._token, params, sudo, page, per_page) return r.content @property def users(self): u = self.request(RequestType.GET, '/users') return Users(u) def users_by_name(self, name): params = {'search': name} u = self.request(RequestType.GET, '/users', params=params) return Users(u) <commit_msg>Create exactly one users function.<commit_after>
_defaults = { 'api_url': 'api/v3', } from .apirequest import ApiRequest, RequestType from .users import Users class Pyglab(object): def __init__(self, url, token, api_url=_defaults['api_url']): self._base_url = url.rstrip('/') + '/' + api_url.strip() self._token = token self._user = None self._per_page = None def sudo(self, user): """Permanently set a different username. Returns the old username.""" previous_user = self._user self._user = user return previous_user def request(self, request_type, url, params={}, sudo=None, page=None, per_page=None): if sudo is None and self._user is not None: sudo = _self.user if per_page is None and self._per_page is None: per_page = self._per_page r = ApiRequest(request_type, self._base_url + '/' + url.lstrip('/'), self._token, params, sudo, page, per_page) return r.content @property def users(self): return Users(self)
_defaults = { 'api_url': 'api/v3', } from .apirequest import ApiRequest, RequestType from .users import Users class Pyglab(object): def __init__(self, url, token, api_url=_defaults['api_url']): self._base_url = url.rstrip('/') + '/' + api_url.strip() self._token = token self._user = None self._per_page = None def sudo(self, user): """Permanently set a different username. Returns the old username.""" previous_user = self._user self._user = user return previous_user def request(self, request_type, url, params={}, sudo=None, page=None, per_page=None): if sudo is None and self._user is not None: sudo = _self.user if per_page is None and self._per_page is None: per_page = self._per_page r = ApiRequest(request_type, self._base_url + '/' + url.lstrip('/'), self._token, params, sudo, page, per_page) return r.content @property def users(self): u = self.request(RequestType.GET, '/users') return Users(u) def users_by_name(self, name): params = {'search': name} u = self.request(RequestType.GET, '/users', params=params) return Users(u) Create exactly one users function._defaults = { 'api_url': 'api/v3', } from .apirequest import ApiRequest, RequestType from .users import Users class Pyglab(object): def __init__(self, url, token, api_url=_defaults['api_url']): self._base_url = url.rstrip('/') + '/' + api_url.strip() self._token = token self._user = None self._per_page = None def sudo(self, user): """Permanently set a different username. Returns the old username.""" previous_user = self._user self._user = user return previous_user def request(self, request_type, url, params={}, sudo=None, page=None, per_page=None): if sudo is None and self._user is not None: sudo = _self.user if per_page is None and self._per_page is None: per_page = self._per_page r = ApiRequest(request_type, self._base_url + '/' + url.lstrip('/'), self._token, params, sudo, page, per_page) return r.content @property def users(self): return Users(self)
<commit_before>_defaults = { 'api_url': 'api/v3', } from .apirequest import ApiRequest, RequestType from .users import Users class Pyglab(object): def __init__(self, url, token, api_url=_defaults['api_url']): self._base_url = url.rstrip('/') + '/' + api_url.strip() self._token = token self._user = None self._per_page = None def sudo(self, user): """Permanently set a different username. Returns the old username.""" previous_user = self._user self._user = user return previous_user def request(self, request_type, url, params={}, sudo=None, page=None, per_page=None): if sudo is None and self._user is not None: sudo = _self.user if per_page is None and self._per_page is None: per_page = self._per_page r = ApiRequest(request_type, self._base_url + '/' + url.lstrip('/'), self._token, params, sudo, page, per_page) return r.content @property def users(self): u = self.request(RequestType.GET, '/users') return Users(u) def users_by_name(self, name): params = {'search': name} u = self.request(RequestType.GET, '/users', params=params) return Users(u) <commit_msg>Create exactly one users function.<commit_after>_defaults = { 'api_url': 'api/v3', } from .apirequest import ApiRequest, RequestType from .users import Users class Pyglab(object): def __init__(self, url, token, api_url=_defaults['api_url']): self._base_url = url.rstrip('/') + '/' + api_url.strip() self._token = token self._user = None self._per_page = None def sudo(self, user): """Permanently set a different username. Returns the old username.""" previous_user = self._user self._user = user return previous_user def request(self, request_type, url, params={}, sudo=None, page=None, per_page=None): if sudo is None and self._user is not None: sudo = _self.user if per_page is None and self._per_page is None: per_page = self._per_page r = ApiRequest(request_type, self._base_url + '/' + url.lstrip('/'), self._token, params, sudo, page, per_page) return r.content @property def users(self): return Users(self)
01ade9ff21440aa0aedd7e32f2338003a256e912
readux/books/tests/__init__.py
readux/books/tests/__init__.py
# import tests so django will discover and run them from readux.books.tests.models import * from readux.books.tests.views import * from readux.books.tests.tei import * from readux.books.tests.annotate import * from readux.books.tests.markdown_tei import *
# import tests so django will discover and run them from readux.books.tests.models import * from readux.books.tests.views import * from readux.books.tests.tei import * from readux.books.tests.annotate import * from readux.books.tests.markdown_tei import * from readux.books.tests.export import * from readux.books.tests.consumers import *
Include consumer and export tests when running testsuite
Include consumer and export tests when running testsuite
Python
apache-2.0
emory-libraries/readux,emory-libraries/readux,emory-libraries/readux
# import tests so django will discover and run them from readux.books.tests.models import * from readux.books.tests.views import * from readux.books.tests.tei import * from readux.books.tests.annotate import * from readux.books.tests.markdown_tei import * Include consumer and export tests when running testsuite
# import tests so django will discover and run them from readux.books.tests.models import * from readux.books.tests.views import * from readux.books.tests.tei import * from readux.books.tests.annotate import * from readux.books.tests.markdown_tei import * from readux.books.tests.export import * from readux.books.tests.consumers import *
<commit_before># import tests so django will discover and run them from readux.books.tests.models import * from readux.books.tests.views import * from readux.books.tests.tei import * from readux.books.tests.annotate import * from readux.books.tests.markdown_tei import * <commit_msg>Include consumer and export tests when running testsuite<commit_after>
# import tests so django will discover and run them from readux.books.tests.models import * from readux.books.tests.views import * from readux.books.tests.tei import * from readux.books.tests.annotate import * from readux.books.tests.markdown_tei import * from readux.books.tests.export import * from readux.books.tests.consumers import *
# import tests so django will discover and run them from readux.books.tests.models import * from readux.books.tests.views import * from readux.books.tests.tei import * from readux.books.tests.annotate import * from readux.books.tests.markdown_tei import * Include consumer and export tests when running testsuite# import tests so django will discover and run them from readux.books.tests.models import * from readux.books.tests.views import * from readux.books.tests.tei import * from readux.books.tests.annotate import * from readux.books.tests.markdown_tei import * from readux.books.tests.export import * from readux.books.tests.consumers import *
<commit_before># import tests so django will discover and run them from readux.books.tests.models import * from readux.books.tests.views import * from readux.books.tests.tei import * from readux.books.tests.annotate import * from readux.books.tests.markdown_tei import * <commit_msg>Include consumer and export tests when running testsuite<commit_after># import tests so django will discover and run them from readux.books.tests.models import * from readux.books.tests.views import * from readux.books.tests.tei import * from readux.books.tests.annotate import * from readux.books.tests.markdown_tei import * from readux.books.tests.export import * from readux.books.tests.consumers import *
8d24a632dde955a9e4e093fe8764bc598cf65f4c
dynamic_subdomains/defaults.py
dynamic_subdomains/defaults.py
from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import SortedDict def patterns(*args): subdomains = SortedDict() for x in args: name = x['name'] if name in subdomains: raise ImproperlyConfigured("Duplicate subdomain name: %s" % name) if name == 'default': raise ImproperlyConfigured("Reserved subdomain name: %s" % name) subdomains[name] = x return subdomains class subdomain(dict): def __init__(self, regex, urlconf, name, callback=None): self.update({ 'regex': regex, 'urlconf': urlconf, 'name': name, }) if callback: self['callback'] = callback
from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import SortedDict def patterns(*args): subdomains = SortedDict() for x in args: name = x['name'] if name in subdomains: raise ImproperlyConfigured("Duplicate subdomain name: %s" % name) subdomains[name] = x return subdomains class subdomain(dict): def __init__(self, regex, urlconf, name, callback=None): self.update({ 'regex': regex, 'urlconf': urlconf, 'name': name, }) if callback: self['callback'] = callback
Remove unnecessary protection against using "default" as a subdomainconf
Remove unnecessary protection against using "default" as a subdomainconf Thanks to Jannis Leidel <jezdez@enn.io> for the pointer. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com>
Python
bsd-3-clause
playfire/django-dynamic-subdomains
from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import SortedDict def patterns(*args): subdomains = SortedDict() for x in args: name = x['name'] if name in subdomains: raise ImproperlyConfigured("Duplicate subdomain name: %s" % name) if name == 'default': raise ImproperlyConfigured("Reserved subdomain name: %s" % name) subdomains[name] = x return subdomains class subdomain(dict): def __init__(self, regex, urlconf, name, callback=None): self.update({ 'regex': regex, 'urlconf': urlconf, 'name': name, }) if callback: self['callback'] = callback Remove unnecessary protection against using "default" as a subdomainconf Thanks to Jannis Leidel <jezdez@enn.io> for the pointer. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com>
from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import SortedDict def patterns(*args): subdomains = SortedDict() for x in args: name = x['name'] if name in subdomains: raise ImproperlyConfigured("Duplicate subdomain name: %s" % name) subdomains[name] = x return subdomains class subdomain(dict): def __init__(self, regex, urlconf, name, callback=None): self.update({ 'regex': regex, 'urlconf': urlconf, 'name': name, }) if callback: self['callback'] = callback
<commit_before>from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import SortedDict def patterns(*args): subdomains = SortedDict() for x in args: name = x['name'] if name in subdomains: raise ImproperlyConfigured("Duplicate subdomain name: %s" % name) if name == 'default': raise ImproperlyConfigured("Reserved subdomain name: %s" % name) subdomains[name] = x return subdomains class subdomain(dict): def __init__(self, regex, urlconf, name, callback=None): self.update({ 'regex': regex, 'urlconf': urlconf, 'name': name, }) if callback: self['callback'] = callback <commit_msg>Remove unnecessary protection against using "default" as a subdomainconf Thanks to Jannis Leidel <jezdez@enn.io> for the pointer. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com><commit_after>
from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import SortedDict def patterns(*args): subdomains = SortedDict() for x in args: name = x['name'] if name in subdomains: raise ImproperlyConfigured("Duplicate subdomain name: %s" % name) subdomains[name] = x return subdomains class subdomain(dict): def __init__(self, regex, urlconf, name, callback=None): self.update({ 'regex': regex, 'urlconf': urlconf, 'name': name, }) if callback: self['callback'] = callback
from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import SortedDict def patterns(*args): subdomains = SortedDict() for x in args: name = x['name'] if name in subdomains: raise ImproperlyConfigured("Duplicate subdomain name: %s" % name) if name == 'default': raise ImproperlyConfigured("Reserved subdomain name: %s" % name) subdomains[name] = x return subdomains class subdomain(dict): def __init__(self, regex, urlconf, name, callback=None): self.update({ 'regex': regex, 'urlconf': urlconf, 'name': name, }) if callback: self['callback'] = callback Remove unnecessary protection against using "default" as a subdomainconf Thanks to Jannis Leidel <jezdez@enn.io> for the pointer. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com>from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import SortedDict def patterns(*args): subdomains = SortedDict() for x in args: name = x['name'] if name in subdomains: raise ImproperlyConfigured("Duplicate subdomain name: %s" % name) subdomains[name] = x return subdomains class subdomain(dict): def __init__(self, regex, urlconf, name, callback=None): self.update({ 'regex': regex, 'urlconf': urlconf, 'name': name, }) if callback: self['callback'] = callback
<commit_before>from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import SortedDict def patterns(*args): subdomains = SortedDict() for x in args: name = x['name'] if name in subdomains: raise ImproperlyConfigured("Duplicate subdomain name: %s" % name) if name == 'default': raise ImproperlyConfigured("Reserved subdomain name: %s" % name) subdomains[name] = x return subdomains class subdomain(dict): def __init__(self, regex, urlconf, name, callback=None): self.update({ 'regex': regex, 'urlconf': urlconf, 'name': name, }) if callback: self['callback'] = callback <commit_msg>Remove unnecessary protection against using "default" as a subdomainconf Thanks to Jannis Leidel <jezdez@enn.io> for the pointer. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com><commit_after>from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import SortedDict def patterns(*args): subdomains = SortedDict() for x in args: name = x['name'] if name in subdomains: raise ImproperlyConfigured("Duplicate subdomain name: %s" % name) subdomains[name] = x return subdomains class subdomain(dict): def __init__(self, regex, urlconf, name, callback=None): self.update({ 'regex': regex, 'urlconf': urlconf, 'name': name, }) if callback: self['callback'] = callback
9672bd20203bc4235910080cca6d79c3b8e126b1
nupic/research/frameworks/dendrites/modules/__init__.py
nupic/research/frameworks/dendrites/modules/__init__.py
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2021, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- from .apply_dendrites import * from .boosted_dendrites import * from .dendrite_segments import DendriteSegments from .dendritic_layers import ( AbsoluteMaxGatingDendriticLayer, AbsoluteMaxGatingDendriticLayer2d, BiasingDendriticLayer, GatingDendriticLayer, GatingDendriticLayer2d, )
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2021, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- from .apply_dendrites import * from .boosted_dendrites import * from .dendrite_segments import DendriteSegments from .dendritic_layers import ( AbsoluteMaxGatingDendriticLayer, AbsoluteMaxGatingDendriticLayer2d, BiasingDendriticLayer, GatingDendriticLayer, GatingDendriticLayer2d, DendriticLayerBase, )
Add DendriticLayerBase to init to ease experimentation
Add DendriticLayerBase to init to ease experimentation
Python
agpl-3.0
mrcslws/nupic.research,subutai/nupic.research,numenta/nupic.research,subutai/nupic.research,numenta/nupic.research,mrcslws/nupic.research
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2021, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- from .apply_dendrites import * from .boosted_dendrites import * from .dendrite_segments import DendriteSegments from .dendritic_layers import ( AbsoluteMaxGatingDendriticLayer, AbsoluteMaxGatingDendriticLayer2d, BiasingDendriticLayer, GatingDendriticLayer, GatingDendriticLayer2d, )Add DendriticLayerBase to init to ease experimentation
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2021, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- from .apply_dendrites import * from .boosted_dendrites import * from .dendrite_segments import DendriteSegments from .dendritic_layers import ( AbsoluteMaxGatingDendriticLayer, AbsoluteMaxGatingDendriticLayer2d, BiasingDendriticLayer, GatingDendriticLayer, GatingDendriticLayer2d, DendriticLayerBase, )
<commit_before># ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2021, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- from .apply_dendrites import * from .boosted_dendrites import * from .dendrite_segments import DendriteSegments from .dendritic_layers import ( AbsoluteMaxGatingDendriticLayer, AbsoluteMaxGatingDendriticLayer2d, BiasingDendriticLayer, GatingDendriticLayer, GatingDendriticLayer2d, )<commit_msg>Add DendriticLayerBase to init to ease experimentation<commit_after>
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2021, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- from .apply_dendrites import * from .boosted_dendrites import * from .dendrite_segments import DendriteSegments from .dendritic_layers import ( AbsoluteMaxGatingDendriticLayer, AbsoluteMaxGatingDendriticLayer2d, BiasingDendriticLayer, GatingDendriticLayer, GatingDendriticLayer2d, DendriticLayerBase, )
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2021, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- from .apply_dendrites import * from .boosted_dendrites import * from .dendrite_segments import DendriteSegments from .dendritic_layers import ( AbsoluteMaxGatingDendriticLayer, AbsoluteMaxGatingDendriticLayer2d, BiasingDendriticLayer, GatingDendriticLayer, GatingDendriticLayer2d, )Add DendriticLayerBase to init to ease experimentation# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2021, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- from .apply_dendrites import * from .boosted_dendrites import * from .dendrite_segments import DendriteSegments from .dendritic_layers import ( AbsoluteMaxGatingDendriticLayer, AbsoluteMaxGatingDendriticLayer2d, BiasingDendriticLayer, GatingDendriticLayer, GatingDendriticLayer2d, DendriticLayerBase, )
<commit_before># ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2021, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- from .apply_dendrites import * from .boosted_dendrites import * from .dendrite_segments import DendriteSegments from .dendritic_layers import ( AbsoluteMaxGatingDendriticLayer, AbsoluteMaxGatingDendriticLayer2d, BiasingDendriticLayer, GatingDendriticLayer, GatingDendriticLayer2d, )<commit_msg>Add DendriticLayerBase to init to ease experimentation<commit_after># ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2021, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- from .apply_dendrites import * from .boosted_dendrites import * from .dendrite_segments import DendriteSegments from .dendritic_layers import ( AbsoluteMaxGatingDendriticLayer, AbsoluteMaxGatingDendriticLayer2d, BiasingDendriticLayer, GatingDendriticLayer, GatingDendriticLayer2d, DendriticLayerBase, )
b49ecba8c0a8ca05351b3eff6c1c244064bb5081
tests/test_vector2_equality.py
tests/test_vector2_equality.py
import ppb_vector def test_equal(): test_vector_1 = ppb_vector.Vector2(50, 800) test_vector_2 = ppb_vector.Vector2(50, 800) assert test_vector_1 == test_vector_2 def test_not_equal(): test_vector_1 = ppb_vector.Vector2(800, 800) test_vector_2 = ppb_vector.Vector2(50, 800) assert test_vector_1 != test_vector_2
from hypothesis import given from ppb_vector import Vector2 from utils import vectors def test_equal(): test_vector_1 = Vector2(50, 800) test_vector_2 = Vector2(50, 800) assert test_vector_1 == test_vector_2 @given(x=vectors(), y=vectors()) def test_not_equal_equivalent(x: Vector2, y: Vector2): assert (x != y) == (not x == y)
Replace test for != with an Hypothesis test
tests/equality: Replace test for != with an Hypothesis test
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
import ppb_vector def test_equal(): test_vector_1 = ppb_vector.Vector2(50, 800) test_vector_2 = ppb_vector.Vector2(50, 800) assert test_vector_1 == test_vector_2 def test_not_equal(): test_vector_1 = ppb_vector.Vector2(800, 800) test_vector_2 = ppb_vector.Vector2(50, 800) assert test_vector_1 != test_vector_2 tests/equality: Replace test for != with an Hypothesis test
from hypothesis import given from ppb_vector import Vector2 from utils import vectors def test_equal(): test_vector_1 = Vector2(50, 800) test_vector_2 = Vector2(50, 800) assert test_vector_1 == test_vector_2 @given(x=vectors(), y=vectors()) def test_not_equal_equivalent(x: Vector2, y: Vector2): assert (x != y) == (not x == y)
<commit_before>import ppb_vector def test_equal(): test_vector_1 = ppb_vector.Vector2(50, 800) test_vector_2 = ppb_vector.Vector2(50, 800) assert test_vector_1 == test_vector_2 def test_not_equal(): test_vector_1 = ppb_vector.Vector2(800, 800) test_vector_2 = ppb_vector.Vector2(50, 800) assert test_vector_1 != test_vector_2 <commit_msg>tests/equality: Replace test for != with an Hypothesis test<commit_after>
from hypothesis import given from ppb_vector import Vector2 from utils import vectors def test_equal(): test_vector_1 = Vector2(50, 800) test_vector_2 = Vector2(50, 800) assert test_vector_1 == test_vector_2 @given(x=vectors(), y=vectors()) def test_not_equal_equivalent(x: Vector2, y: Vector2): assert (x != y) == (not x == y)
import ppb_vector def test_equal(): test_vector_1 = ppb_vector.Vector2(50, 800) test_vector_2 = ppb_vector.Vector2(50, 800) assert test_vector_1 == test_vector_2 def test_not_equal(): test_vector_1 = ppb_vector.Vector2(800, 800) test_vector_2 = ppb_vector.Vector2(50, 800) assert test_vector_1 != test_vector_2 tests/equality: Replace test for != with an Hypothesis testfrom hypothesis import given from ppb_vector import Vector2 from utils import vectors def test_equal(): test_vector_1 = Vector2(50, 800) test_vector_2 = Vector2(50, 800) assert test_vector_1 == test_vector_2 @given(x=vectors(), y=vectors()) def test_not_equal_equivalent(x: Vector2, y: Vector2): assert (x != y) == (not x == y)
<commit_before>import ppb_vector def test_equal(): test_vector_1 = ppb_vector.Vector2(50, 800) test_vector_2 = ppb_vector.Vector2(50, 800) assert test_vector_1 == test_vector_2 def test_not_equal(): test_vector_1 = ppb_vector.Vector2(800, 800) test_vector_2 = ppb_vector.Vector2(50, 800) assert test_vector_1 != test_vector_2 <commit_msg>tests/equality: Replace test for != with an Hypothesis test<commit_after>from hypothesis import given from ppb_vector import Vector2 from utils import vectors def test_equal(): test_vector_1 = Vector2(50, 800) test_vector_2 = Vector2(50, 800) assert test_vector_1 == test_vector_2 @given(x=vectors(), y=vectors()) def test_not_equal_equivalent(x: Vector2, y: Vector2): assert (x != y) == (not x == y)
8f4a8c2d463f3ed1592fcd1655de6435b4f2a047
dataproperty/type/_typecode.py
dataproperty/type/_typecode.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class Typecode(object): NONE = 0 INT = 1 << 0 FLOAT = 1 << 1 STRING = 1 << 2 DATETIME = 1 << 3 INFINITY = 1 << 4 NAN = 1 << 5 BOOL = 1 << 6 DEFAULT_TYPENAME_TABLE = { NONE: "NONE", INT: "INTEGER", FLOAT: "FLOAT", STRING: "STRING", DATETIME: "DATETIME", INFINITY: "INFINITY", NAN: "NAN", BOOL: "BOOL", } TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE @classmethod def get_typename(cls, typecode): type_name = cls.TYPENAME_TABLE.get(typecode) if type_name is None: raise ValueError("unknown typecode: {}".format(typecode)) return type_name
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class Typecode(object): NONE = 0 INT = 1 << 0 # delete in the future INTEGER = 1 << 0 FLOAT = 1 << 1 STRING = 1 << 2 DATETIME = 1 << 3 INFINITY = 1 << 4 NAN = 1 << 5 BOOL = 1 << 6 DEFAULT_TYPENAME_TABLE = { NONE: "NONE", INT: "INTEGER", FLOAT: "FLOAT", INTEGER: "INTEGER", STRING: "STRING", DATETIME: "DATETIME", INFINITY: "INFINITY", NAN: "NAN", BOOL: "BOOL", } TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE @classmethod def get_typename(cls, typecode): type_name = cls.TYPENAME_TABLE.get(typecode) if type_name is None: raise ValueError("unknown typecode: {}".format(typecode)) return type_name
Add INTEGER type as alias of INT type
Add INTEGER type as alias of INT type
Python
mit
thombashi/DataProperty
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class Typecode(object): NONE = 0 INT = 1 << 0 FLOAT = 1 << 1 STRING = 1 << 2 DATETIME = 1 << 3 INFINITY = 1 << 4 NAN = 1 << 5 BOOL = 1 << 6 DEFAULT_TYPENAME_TABLE = { NONE: "NONE", INT: "INTEGER", FLOAT: "FLOAT", STRING: "STRING", DATETIME: "DATETIME", INFINITY: "INFINITY", NAN: "NAN", BOOL: "BOOL", } TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE @classmethod def get_typename(cls, typecode): type_name = cls.TYPENAME_TABLE.get(typecode) if type_name is None: raise ValueError("unknown typecode: {}".format(typecode)) return type_name Add INTEGER type as alias of INT type
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class Typecode(object): NONE = 0 INT = 1 << 0 # delete in the future INTEGER = 1 << 0 FLOAT = 1 << 1 STRING = 1 << 2 DATETIME = 1 << 3 INFINITY = 1 << 4 NAN = 1 << 5 BOOL = 1 << 6 DEFAULT_TYPENAME_TABLE = { NONE: "NONE", INT: "INTEGER", FLOAT: "FLOAT", INTEGER: "INTEGER", STRING: "STRING", DATETIME: "DATETIME", INFINITY: "INFINITY", NAN: "NAN", BOOL: "BOOL", } TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE @classmethod def get_typename(cls, typecode): type_name = cls.TYPENAME_TABLE.get(typecode) if type_name is None: raise ValueError("unknown typecode: {}".format(typecode)) return type_name
<commit_before># encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class Typecode(object): NONE = 0 INT = 1 << 0 FLOAT = 1 << 1 STRING = 1 << 2 DATETIME = 1 << 3 INFINITY = 1 << 4 NAN = 1 << 5 BOOL = 1 << 6 DEFAULT_TYPENAME_TABLE = { NONE: "NONE", INT: "INTEGER", FLOAT: "FLOAT", STRING: "STRING", DATETIME: "DATETIME", INFINITY: "INFINITY", NAN: "NAN", BOOL: "BOOL", } TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE @classmethod def get_typename(cls, typecode): type_name = cls.TYPENAME_TABLE.get(typecode) if type_name is None: raise ValueError("unknown typecode: {}".format(typecode)) return type_name <commit_msg>Add INTEGER type as alias of INT type<commit_after>
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class Typecode(object): NONE = 0 INT = 1 << 0 # delete in the future INTEGER = 1 << 0 FLOAT = 1 << 1 STRING = 1 << 2 DATETIME = 1 << 3 INFINITY = 1 << 4 NAN = 1 << 5 BOOL = 1 << 6 DEFAULT_TYPENAME_TABLE = { NONE: "NONE", INT: "INTEGER", FLOAT: "FLOAT", INTEGER: "INTEGER", STRING: "STRING", DATETIME: "DATETIME", INFINITY: "INFINITY", NAN: "NAN", BOOL: "BOOL", } TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE @classmethod def get_typename(cls, typecode): type_name = cls.TYPENAME_TABLE.get(typecode) if type_name is None: raise ValueError("unknown typecode: {}".format(typecode)) return type_name
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class Typecode(object): NONE = 0 INT = 1 << 0 FLOAT = 1 << 1 STRING = 1 << 2 DATETIME = 1 << 3 INFINITY = 1 << 4 NAN = 1 << 5 BOOL = 1 << 6 DEFAULT_TYPENAME_TABLE = { NONE: "NONE", INT: "INTEGER", FLOAT: "FLOAT", STRING: "STRING", DATETIME: "DATETIME", INFINITY: "INFINITY", NAN: "NAN", BOOL: "BOOL", } TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE @classmethod def get_typename(cls, typecode): type_name = cls.TYPENAME_TABLE.get(typecode) if type_name is None: raise ValueError("unknown typecode: {}".format(typecode)) return type_name Add INTEGER type as alias of INT type# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class Typecode(object): NONE = 0 INT = 1 << 0 # delete in the future INTEGER = 1 << 0 FLOAT = 1 << 1 STRING = 1 << 2 DATETIME = 1 << 3 INFINITY = 1 << 4 NAN = 1 << 5 BOOL = 1 << 6 DEFAULT_TYPENAME_TABLE = { NONE: "NONE", INT: "INTEGER", FLOAT: "FLOAT", INTEGER: "INTEGER", STRING: "STRING", DATETIME: "DATETIME", INFINITY: "INFINITY", NAN: "NAN", BOOL: "BOOL", } TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE @classmethod def get_typename(cls, typecode): type_name = cls.TYPENAME_TABLE.get(typecode) if type_name is None: raise ValueError("unknown typecode: {}".format(typecode)) return type_name
<commit_before># encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class Typecode(object): NONE = 0 INT = 1 << 0 FLOAT = 1 << 1 STRING = 1 << 2 DATETIME = 1 << 3 INFINITY = 1 << 4 NAN = 1 << 5 BOOL = 1 << 6 DEFAULT_TYPENAME_TABLE = { NONE: "NONE", INT: "INTEGER", FLOAT: "FLOAT", STRING: "STRING", DATETIME: "DATETIME", INFINITY: "INFINITY", NAN: "NAN", BOOL: "BOOL", } TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE @classmethod def get_typename(cls, typecode): type_name = cls.TYPENAME_TABLE.get(typecode) if type_name is None: raise ValueError("unknown typecode: {}".format(typecode)) return type_name <commit_msg>Add INTEGER type as alias of INT type<commit_after># encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class Typecode(object): NONE = 0 INT = 1 << 0 # delete in the future INTEGER = 1 << 0 FLOAT = 1 << 1 STRING = 1 << 2 DATETIME = 1 << 3 INFINITY = 1 << 4 NAN = 1 << 5 BOOL = 1 << 6 DEFAULT_TYPENAME_TABLE = { NONE: "NONE", INT: "INTEGER", FLOAT: "FLOAT", INTEGER: "INTEGER", STRING: "STRING", DATETIME: "DATETIME", INFINITY: "INFINITY", NAN: "NAN", BOOL: "BOOL", } TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE @classmethod def get_typename(cls, typecode): type_name = cls.TYPENAME_TABLE.get(typecode) if type_name is None: raise ValueError("unknown typecode: {}".format(typecode)) return type_name
0a19e2a0dd7bed604e5ddd402d2d9f47b2760d77
bagpipe/bgp/engine/flowspec.py
bagpipe/bgp/engine/flowspec.py
from exabgp.bgp.message.update.nlri.flow import Flow as ExaBGPFlow from exabgp.bgp.message.update.nlri.nlri import NLRI from exabgp.reactor.protocol import AFI from exabgp.reactor.protocol import SAFI import logging log = logging.getLogger(__name__) @NLRI.register(AFI.ipv4, SAFI.flow_vpn, force=True) @NLRI.register(AFI.ipv6, SAFI.flow_vpn, force=True) class Flow(ExaBGPFlow): '''This wraps an ExaBGP Flow so that __eq__ and __hash__ meet the criteria for RouteTableManager (in particular, not look at actions and nexthop) ''' def __eq__(self, other): return self.rd == other.rd and self.rules == other.rules def __hash__(self): #FIXME: are dicts hashable ? log.debug("flow rules: %s", repr(self.rules)) return hash((self.rd, repr(self.rules))) def FlowRouteFactory(afi, rd): flowRoute = Flow(afi, safi=SAFI.flow_vpn) flowRoute.rd = rd return flowRoute
from exabgp.bgp.message.update.nlri.flow import Flow as ExaBGPFlow from exabgp.bgp.message.update.nlri.nlri import NLRI from exabgp.reactor.protocol import AFI from exabgp.reactor.protocol import SAFI import logging log = logging.getLogger(__name__) @NLRI.register(AFI.ipv4, SAFI.flow_vpn, force=True) @NLRI.register(AFI.ipv6, SAFI.flow_vpn, force=True) class Flow(ExaBGPFlow): '''This wraps an ExaBGP Flow so that __eq__ and __hash__ meet the criteria for RouteTableManager (in particular, not look at actions and nexthop) ''' def __eq__(self, other): return self.pack() == other.pack() def __hash__(self): return hash(self.pack()) def __repr__(self): return str(self) def FlowRouteFactory(afi, rd): flowRoute = Flow(afi, safi=SAFI.flow_vpn) flowRoute.rd = rd return flowRoute
Fix eq/hash for FlowSpec NLRI
Fix eq/hash for FlowSpec NLRI Bogus eq/hash was preventing withdraws from behaving properly.
Python
apache-2.0
openstack/networking-bagpipe,openstack/networking-bagpipe-l2,openstack/networking-bagpipe,stackforge/networking-bagpipe-l2,openstack/networking-bagpipe-l2,stackforge/networking-bagpipe-l2
from exabgp.bgp.message.update.nlri.flow import Flow as ExaBGPFlow from exabgp.bgp.message.update.nlri.nlri import NLRI from exabgp.reactor.protocol import AFI from exabgp.reactor.protocol import SAFI import logging log = logging.getLogger(__name__) @NLRI.register(AFI.ipv4, SAFI.flow_vpn, force=True) @NLRI.register(AFI.ipv6, SAFI.flow_vpn, force=True) class Flow(ExaBGPFlow): '''This wraps an ExaBGP Flow so that __eq__ and __hash__ meet the criteria for RouteTableManager (in particular, not look at actions and nexthop) ''' def __eq__(self, other): return self.rd == other.rd and self.rules == other.rules def __hash__(self): #FIXME: are dicts hashable ? log.debug("flow rules: %s", repr(self.rules)) return hash((self.rd, repr(self.rules))) def FlowRouteFactory(afi, rd): flowRoute = Flow(afi, safi=SAFI.flow_vpn) flowRoute.rd = rd return flowRoute Fix eq/hash for FlowSpec NLRI Bogus eq/hash was preventing withdraws from behaving properly.
from exabgp.bgp.message.update.nlri.flow import Flow as ExaBGPFlow from exabgp.bgp.message.update.nlri.nlri import NLRI from exabgp.reactor.protocol import AFI from exabgp.reactor.protocol import SAFI import logging log = logging.getLogger(__name__) @NLRI.register(AFI.ipv4, SAFI.flow_vpn, force=True) @NLRI.register(AFI.ipv6, SAFI.flow_vpn, force=True) class Flow(ExaBGPFlow): '''This wraps an ExaBGP Flow so that __eq__ and __hash__ meet the criteria for RouteTableManager (in particular, not look at actions and nexthop) ''' def __eq__(self, other): return self.pack() == other.pack() def __hash__(self): return hash(self.pack()) def __repr__(self): return str(self) def FlowRouteFactory(afi, rd): flowRoute = Flow(afi, safi=SAFI.flow_vpn) flowRoute.rd = rd return flowRoute
<commit_before>from exabgp.bgp.message.update.nlri.flow import Flow as ExaBGPFlow from exabgp.bgp.message.update.nlri.nlri import NLRI from exabgp.reactor.protocol import AFI from exabgp.reactor.protocol import SAFI import logging log = logging.getLogger(__name__) @NLRI.register(AFI.ipv4, SAFI.flow_vpn, force=True) @NLRI.register(AFI.ipv6, SAFI.flow_vpn, force=True) class Flow(ExaBGPFlow): '''This wraps an ExaBGP Flow so that __eq__ and __hash__ meet the criteria for RouteTableManager (in particular, not look at actions and nexthop) ''' def __eq__(self, other): return self.rd == other.rd and self.rules == other.rules def __hash__(self): #FIXME: are dicts hashable ? log.debug("flow rules: %s", repr(self.rules)) return hash((self.rd, repr(self.rules))) def FlowRouteFactory(afi, rd): flowRoute = Flow(afi, safi=SAFI.flow_vpn) flowRoute.rd = rd return flowRoute <commit_msg>Fix eq/hash for FlowSpec NLRI Bogus eq/hash was preventing withdraws from behaving properly.<commit_after>
from exabgp.bgp.message.update.nlri.flow import Flow as ExaBGPFlow from exabgp.bgp.message.update.nlri.nlri import NLRI from exabgp.reactor.protocol import AFI from exabgp.reactor.protocol import SAFI import logging log = logging.getLogger(__name__) @NLRI.register(AFI.ipv4, SAFI.flow_vpn, force=True) @NLRI.register(AFI.ipv6, SAFI.flow_vpn, force=True) class Flow(ExaBGPFlow): '''This wraps an ExaBGP Flow so that __eq__ and __hash__ meet the criteria for RouteTableManager (in particular, not look at actions and nexthop) ''' def __eq__(self, other): return self.pack() == other.pack() def __hash__(self): return hash(self.pack()) def __repr__(self): return str(self) def FlowRouteFactory(afi, rd): flowRoute = Flow(afi, safi=SAFI.flow_vpn) flowRoute.rd = rd return flowRoute
from exabgp.bgp.message.update.nlri.flow import Flow as ExaBGPFlow from exabgp.bgp.message.update.nlri.nlri import NLRI from exabgp.reactor.protocol import AFI from exabgp.reactor.protocol import SAFI import logging log = logging.getLogger(__name__) @NLRI.register(AFI.ipv4, SAFI.flow_vpn, force=True) @NLRI.register(AFI.ipv6, SAFI.flow_vpn, force=True) class Flow(ExaBGPFlow): '''This wraps an ExaBGP Flow so that __eq__ and __hash__ meet the criteria for RouteTableManager (in particular, not look at actions and nexthop) ''' def __eq__(self, other): return self.rd == other.rd and self.rules == other.rules def __hash__(self): #FIXME: are dicts hashable ? log.debug("flow rules: %s", repr(self.rules)) return hash((self.rd, repr(self.rules))) def FlowRouteFactory(afi, rd): flowRoute = Flow(afi, safi=SAFI.flow_vpn) flowRoute.rd = rd return flowRoute Fix eq/hash for FlowSpec NLRI Bogus eq/hash was preventing withdraws from behaving properly.from exabgp.bgp.message.update.nlri.flow import Flow as ExaBGPFlow from exabgp.bgp.message.update.nlri.nlri import NLRI from exabgp.reactor.protocol import AFI from exabgp.reactor.protocol import SAFI import logging log = logging.getLogger(__name__) @NLRI.register(AFI.ipv4, SAFI.flow_vpn, force=True) @NLRI.register(AFI.ipv6, SAFI.flow_vpn, force=True) class Flow(ExaBGPFlow): '''This wraps an ExaBGP Flow so that __eq__ and __hash__ meet the criteria for RouteTableManager (in particular, not look at actions and nexthop) ''' def __eq__(self, other): return self.pack() == other.pack() def __hash__(self): return hash(self.pack()) def __repr__(self): return str(self) def FlowRouteFactory(afi, rd): flowRoute = Flow(afi, safi=SAFI.flow_vpn) flowRoute.rd = rd return flowRoute
<commit_before>from exabgp.bgp.message.update.nlri.flow import Flow as ExaBGPFlow from exabgp.bgp.message.update.nlri.nlri import NLRI from exabgp.reactor.protocol import AFI from exabgp.reactor.protocol import SAFI import logging log = logging.getLogger(__name__) @NLRI.register(AFI.ipv4, SAFI.flow_vpn, force=True) @NLRI.register(AFI.ipv6, SAFI.flow_vpn, force=True) class Flow(ExaBGPFlow): '''This wraps an ExaBGP Flow so that __eq__ and __hash__ meet the criteria for RouteTableManager (in particular, not look at actions and nexthop) ''' def __eq__(self, other): return self.rd == other.rd and self.rules == other.rules def __hash__(self): #FIXME: are dicts hashable ? log.debug("flow rules: %s", repr(self.rules)) return hash((self.rd, repr(self.rules))) def FlowRouteFactory(afi, rd): flowRoute = Flow(afi, safi=SAFI.flow_vpn) flowRoute.rd = rd return flowRoute <commit_msg>Fix eq/hash for FlowSpec NLRI Bogus eq/hash was preventing withdraws from behaving properly.<commit_after>from exabgp.bgp.message.update.nlri.flow import Flow as ExaBGPFlow from exabgp.bgp.message.update.nlri.nlri import NLRI from exabgp.reactor.protocol import AFI from exabgp.reactor.protocol import SAFI import logging log = logging.getLogger(__name__) @NLRI.register(AFI.ipv4, SAFI.flow_vpn, force=True) @NLRI.register(AFI.ipv6, SAFI.flow_vpn, force=True) class Flow(ExaBGPFlow): '''This wraps an ExaBGP Flow so that __eq__ and __hash__ meet the criteria for RouteTableManager (in particular, not look at actions and nexthop) ''' def __eq__(self, other): return self.pack() == other.pack() def __hash__(self): return hash(self.pack()) def __repr__(self): return str(self) def FlowRouteFactory(afi, rd): flowRoute = Flow(afi, safi=SAFI.flow_vpn) flowRoute.rd = rd return flowRoute
20fa7e30e4658984a4057f5c99ef293216f57815
base_phone/controllers/main.py
base_phone/controllers/main.py
# -*- coding: utf-8 -*- ############################################################################## # # Base Phone module for Odoo # Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import http class BasePhoneController(http.Controller): @http.route('/base_phone/click2dial', type='json', auth='none') def click2dial(self, phone_number, click2dial_model, click2dial_id): res = http.request.env['phone.common'].click2dial( phone_number, { 'click2dial_model': click2dial_model, 'click2dial_id': click2dial_id, }) return res
# -*- coding: utf-8 -*- ############################################################################## # # Base Phone module for Odoo # Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import http class BasePhoneController(http.Controller): @http.route('/base_phone/click2dial', type='json', auth='user') def click2dial(self, phone_number, click2dial_model, click2dial_id): res = http.request.env['phone.common'].with_context( click2dial_model=click2dial_model, click2dial_id=click2dial_id).click2dial(phone_number) return res
Make click2dial work in real life
Make click2dial work in real life
Python
agpl-3.0
OCA/connector-telephony,OCA/connector-telephony,OCA/connector-telephony,OCA/connector-telephony
# -*- coding: utf-8 -*- ############################################################################## # # Base Phone module for Odoo # Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import http class BasePhoneController(http.Controller): @http.route('/base_phone/click2dial', type='json', auth='none') def click2dial(self, phone_number, click2dial_model, click2dial_id): res = http.request.env['phone.common'].click2dial( phone_number, { 'click2dial_model': click2dial_model, 'click2dial_id': click2dial_id, }) return res Make click2dial work in real life
# -*- coding: utf-8 -*- ############################################################################## # # Base Phone module for Odoo # Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import http class BasePhoneController(http.Controller): @http.route('/base_phone/click2dial', type='json', auth='user') def click2dial(self, phone_number, click2dial_model, click2dial_id): res = http.request.env['phone.common'].with_context( click2dial_model=click2dial_model, click2dial_id=click2dial_id).click2dial(phone_number) return res
<commit_before># -*- coding: utf-8 -*- ############################################################################## # # Base Phone module for Odoo # Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import http class BasePhoneController(http.Controller): @http.route('/base_phone/click2dial', type='json', auth='none') def click2dial(self, phone_number, click2dial_model, click2dial_id): res = http.request.env['phone.common'].click2dial( phone_number, { 'click2dial_model': click2dial_model, 'click2dial_id': click2dial_id, }) return res <commit_msg>Make click2dial work in real life<commit_after>
# -*- coding: utf-8 -*- ############################################################################## # # Base Phone module for Odoo # Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import http class BasePhoneController(http.Controller): @http.route('/base_phone/click2dial', type='json', auth='user') def click2dial(self, phone_number, click2dial_model, click2dial_id): res = http.request.env['phone.common'].with_context( click2dial_model=click2dial_model, click2dial_id=click2dial_id).click2dial(phone_number) return res
# -*- coding: utf-8 -*- ############################################################################## # # Base Phone module for Odoo # Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import http class BasePhoneController(http.Controller): @http.route('/base_phone/click2dial', type='json', auth='none') def click2dial(self, phone_number, click2dial_model, click2dial_id): res = http.request.env['phone.common'].click2dial( phone_number, { 'click2dial_model': click2dial_model, 'click2dial_id': click2dial_id, }) return res Make click2dial work in real life# -*- coding: utf-8 -*- ############################################################################## # # Base Phone module for Odoo # Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import http class BasePhoneController(http.Controller): @http.route('/base_phone/click2dial', type='json', auth='user') def click2dial(self, phone_number, click2dial_model, click2dial_id): res = http.request.env['phone.common'].with_context( click2dial_model=click2dial_model, click2dial_id=click2dial_id).click2dial(phone_number) return res
<commit_before># -*- coding: utf-8 -*- ############################################################################## # # Base Phone module for Odoo # Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import http class BasePhoneController(http.Controller): @http.route('/base_phone/click2dial', type='json', auth='none') def click2dial(self, phone_number, click2dial_model, click2dial_id): res = http.request.env['phone.common'].click2dial( phone_number, { 'click2dial_model': click2dial_model, 'click2dial_id': click2dial_id, }) return res <commit_msg>Make click2dial work in real life<commit_after># -*- coding: utf-8 -*- ############################################################################## # # Base Phone module for Odoo # Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import http class BasePhoneController(http.Controller): @http.route('/base_phone/click2dial', type='json', auth='user') def click2dial(self, phone_number, click2dial_model, click2dial_id): res = http.request.env['phone.common'].with_context( click2dial_model=click2dial_model, click2dial_id=click2dial_id).click2dial(phone_number) return res
78c96e56b46f800c972bcdb5c5aa525d73d84a80
src/setuptools_scm/__main__.py
src/setuptools_scm/__main__.py
import sys from setuptools_scm import _get_version from setuptools_scm import get_version from setuptools_scm.config import Configuration from setuptools_scm.integration import find_files def main() -> None: files = list(sorted(find_files("."), key=len)) try: pyproject = next(fname for fname in files if fname.endswith("pyproject.toml")) print(_get_version(Configuration.from_file(pyproject))) except (LookupError, StopIteration): print("Guessed Version", get_version()) if "ls" in sys.argv: for fname in files: print(fname) if __name__ == "__main__": main()
import argparse import os import warnings from setuptools_scm import _get_version from setuptools_scm.config import Configuration from setuptools_scm.discover import walk_potential_roots from setuptools_scm.integration import find_files def main() -> None: opts = _get_cli_opts() root = opts.root or "." try: pyproject = opts.config or _find_pyproject(root) root = opts.root or os.path.relpath(os.path.dirname(pyproject)) config = Configuration.from_file(pyproject) config.root = root except (LookupError, FileNotFoundError) as ex: # no pyproject.toml OR no [tool.setuptools_scm] warnings.warn(f"{ex}. Using default configuration.") config = Configuration(root) print(_get_version(config)) if opts.command == "ls": for fname in find_files(config.root): print(fname) def _get_cli_opts(): prog = "python -m setuptools_scm" desc = "Print project version according to SCM metadata" parser = argparse.ArgumentParser(prog, description=desc) # By default, help for `--help` starts with lower case, so we keep the pattern: parser.add_argument( "-r", "--root", default=None, help='directory managed by the SCM, default: inferred from config file, or "."', ) parser.add_argument( "-c", "--config", default=None, metavar="PATH", help="path to 'pyproject.toml' with setuptools_scm config, " "default: looked up in the current or parent directories", ) sub = parser.add_subparsers(title="extra commands", dest="command", metavar="") # We avoid `metavar` to prevent printing repetitive information desc = "List files managed by the SCM" sub.add_parser("ls", help=desc[0].lower() + desc[1:], description=desc) return parser.parse_args() def _find_pyproject(parent): for directory in walk_potential_roots(os.path.abspath(parent)): pyproject = os.path.join(directory, "pyproject.toml") if os.path.exists(pyproject): return pyproject raise FileNotFoundError("'pyproject.toml' was not found") if __name__ == "__main__": main()
Add options to better control CLI command
Add options to better control CLI command Instead of trying to guess the `pyprojec.toml` file by looking at the files controlled by the SCM, use explicit options to control it.
Python
mit
pypa/setuptools_scm,pypa/setuptools_scm,RonnyPfannschmidt/setuptools_scm,RonnyPfannschmidt/setuptools_scm
import sys from setuptools_scm import _get_version from setuptools_scm import get_version from setuptools_scm.config import Configuration from setuptools_scm.integration import find_files def main() -> None: files = list(sorted(find_files("."), key=len)) try: pyproject = next(fname for fname in files if fname.endswith("pyproject.toml")) print(_get_version(Configuration.from_file(pyproject))) except (LookupError, StopIteration): print("Guessed Version", get_version()) if "ls" in sys.argv: for fname in files: print(fname) if __name__ == "__main__": main() Add options to better control CLI command Instead of trying to guess the `pyprojec.toml` file by looking at the files controlled by the SCM, use explicit options to control it.
import argparse import os import warnings from setuptools_scm import _get_version from setuptools_scm.config import Configuration from setuptools_scm.discover import walk_potential_roots from setuptools_scm.integration import find_files def main() -> None: opts = _get_cli_opts() root = opts.root or "." try: pyproject = opts.config or _find_pyproject(root) root = opts.root or os.path.relpath(os.path.dirname(pyproject)) config = Configuration.from_file(pyproject) config.root = root except (LookupError, FileNotFoundError) as ex: # no pyproject.toml OR no [tool.setuptools_scm] warnings.warn(f"{ex}. Using default configuration.") config = Configuration(root) print(_get_version(config)) if opts.command == "ls": for fname in find_files(config.root): print(fname) def _get_cli_opts(): prog = "python -m setuptools_scm" desc = "Print project version according to SCM metadata" parser = argparse.ArgumentParser(prog, description=desc) # By default, help for `--help` starts with lower case, so we keep the pattern: parser.add_argument( "-r", "--root", default=None, help='directory managed by the SCM, default: inferred from config file, or "."', ) parser.add_argument( "-c", "--config", default=None, metavar="PATH", help="path to 'pyproject.toml' with setuptools_scm config, " "default: looked up in the current or parent directories", ) sub = parser.add_subparsers(title="extra commands", dest="command", metavar="") # We avoid `metavar` to prevent printing repetitive information desc = "List files managed by the SCM" sub.add_parser("ls", help=desc[0].lower() + desc[1:], description=desc) return parser.parse_args() def _find_pyproject(parent): for directory in walk_potential_roots(os.path.abspath(parent)): pyproject = os.path.join(directory, "pyproject.toml") if os.path.exists(pyproject): return pyproject raise FileNotFoundError("'pyproject.toml' was not found") if __name__ == "__main__": main()
<commit_before>import sys from setuptools_scm import _get_version from setuptools_scm import get_version from setuptools_scm.config import Configuration from setuptools_scm.integration import find_files def main() -> None: files = list(sorted(find_files("."), key=len)) try: pyproject = next(fname for fname in files if fname.endswith("pyproject.toml")) print(_get_version(Configuration.from_file(pyproject))) except (LookupError, StopIteration): print("Guessed Version", get_version()) if "ls" in sys.argv: for fname in files: print(fname) if __name__ == "__main__": main() <commit_msg>Add options to better control CLI command Instead of trying to guess the `pyprojec.toml` file by looking at the files controlled by the SCM, use explicit options to control it.<commit_after>
import argparse import os import warnings from setuptools_scm import _get_version from setuptools_scm.config import Configuration from setuptools_scm.discover import walk_potential_roots from setuptools_scm.integration import find_files def main() -> None: opts = _get_cli_opts() root = opts.root or "." try: pyproject = opts.config or _find_pyproject(root) root = opts.root or os.path.relpath(os.path.dirname(pyproject)) config = Configuration.from_file(pyproject) config.root = root except (LookupError, FileNotFoundError) as ex: # no pyproject.toml OR no [tool.setuptools_scm] warnings.warn(f"{ex}. Using default configuration.") config = Configuration(root) print(_get_version(config)) if opts.command == "ls": for fname in find_files(config.root): print(fname) def _get_cli_opts(): prog = "python -m setuptools_scm" desc = "Print project version according to SCM metadata" parser = argparse.ArgumentParser(prog, description=desc) # By default, help for `--help` starts with lower case, so we keep the pattern: parser.add_argument( "-r", "--root", default=None, help='directory managed by the SCM, default: inferred from config file, or "."', ) parser.add_argument( "-c", "--config", default=None, metavar="PATH", help="path to 'pyproject.toml' with setuptools_scm config, " "default: looked up in the current or parent directories", ) sub = parser.add_subparsers(title="extra commands", dest="command", metavar="") # We avoid `metavar` to prevent printing repetitive information desc = "List files managed by the SCM" sub.add_parser("ls", help=desc[0].lower() + desc[1:], description=desc) return parser.parse_args() def _find_pyproject(parent): for directory in walk_potential_roots(os.path.abspath(parent)): pyproject = os.path.join(directory, "pyproject.toml") if os.path.exists(pyproject): return pyproject raise FileNotFoundError("'pyproject.toml' was not found") if __name__ == "__main__": main()
import sys from setuptools_scm import _get_version from setuptools_scm import get_version from setuptools_scm.config import Configuration from setuptools_scm.integration import find_files def main() -> None: files = list(sorted(find_files("."), key=len)) try: pyproject = next(fname for fname in files if fname.endswith("pyproject.toml")) print(_get_version(Configuration.from_file(pyproject))) except (LookupError, StopIteration): print("Guessed Version", get_version()) if "ls" in sys.argv: for fname in files: print(fname) if __name__ == "__main__": main() Add options to better control CLI command Instead of trying to guess the `pyprojec.toml` file by looking at the files controlled by the SCM, use explicit options to control it.import argparse import os import warnings from setuptools_scm import _get_version from setuptools_scm.config import Configuration from setuptools_scm.discover import walk_potential_roots from setuptools_scm.integration import find_files def main() -> None: opts = _get_cli_opts() root = opts.root or "." try: pyproject = opts.config or _find_pyproject(root) root = opts.root or os.path.relpath(os.path.dirname(pyproject)) config = Configuration.from_file(pyproject) config.root = root except (LookupError, FileNotFoundError) as ex: # no pyproject.toml OR no [tool.setuptools_scm] warnings.warn(f"{ex}. Using default configuration.") config = Configuration(root) print(_get_version(config)) if opts.command == "ls": for fname in find_files(config.root): print(fname) def _get_cli_opts(): prog = "python -m setuptools_scm" desc = "Print project version according to SCM metadata" parser = argparse.ArgumentParser(prog, description=desc) # By default, help for `--help` starts with lower case, so we keep the pattern: parser.add_argument( "-r", "--root", default=None, help='directory managed by the SCM, default: inferred from config file, or "."', ) parser.add_argument( "-c", "--config", default=None, metavar="PATH", help="path to 'pyproject.toml' with setuptools_scm config, " "default: looked up in the current or parent directories", ) sub = parser.add_subparsers(title="extra commands", dest="command", metavar="") # We avoid `metavar` to prevent printing repetitive information desc = "List files managed by the SCM" sub.add_parser("ls", help=desc[0].lower() + desc[1:], description=desc) return parser.parse_args() def _find_pyproject(parent): for directory in walk_potential_roots(os.path.abspath(parent)): pyproject = os.path.join(directory, "pyproject.toml") if os.path.exists(pyproject): return pyproject raise FileNotFoundError("'pyproject.toml' was not found") if __name__ == "__main__": main()
<commit_before>import sys from setuptools_scm import _get_version from setuptools_scm import get_version from setuptools_scm.config import Configuration from setuptools_scm.integration import find_files def main() -> None: files = list(sorted(find_files("."), key=len)) try: pyproject = next(fname for fname in files if fname.endswith("pyproject.toml")) print(_get_version(Configuration.from_file(pyproject))) except (LookupError, StopIteration): print("Guessed Version", get_version()) if "ls" in sys.argv: for fname in files: print(fname) if __name__ == "__main__": main() <commit_msg>Add options to better control CLI command Instead of trying to guess the `pyprojec.toml` file by looking at the files controlled by the SCM, use explicit options to control it.<commit_after>import argparse import os import warnings from setuptools_scm import _get_version from setuptools_scm.config import Configuration from setuptools_scm.discover import walk_potential_roots from setuptools_scm.integration import find_files def main() -> None: opts = _get_cli_opts() root = opts.root or "." try: pyproject = opts.config or _find_pyproject(root) root = opts.root or os.path.relpath(os.path.dirname(pyproject)) config = Configuration.from_file(pyproject) config.root = root except (LookupError, FileNotFoundError) as ex: # no pyproject.toml OR no [tool.setuptools_scm] warnings.warn(f"{ex}. Using default configuration.") config = Configuration(root) print(_get_version(config)) if opts.command == "ls": for fname in find_files(config.root): print(fname) def _get_cli_opts(): prog = "python -m setuptools_scm" desc = "Print project version according to SCM metadata" parser = argparse.ArgumentParser(prog, description=desc) # By default, help for `--help` starts with lower case, so we keep the pattern: parser.add_argument( "-r", "--root", default=None, help='directory managed by the SCM, default: inferred from config file, or "."', ) parser.add_argument( "-c", "--config", default=None, metavar="PATH", help="path to 'pyproject.toml' with setuptools_scm config, " "default: looked up in the current or parent directories", ) sub = parser.add_subparsers(title="extra commands", dest="command", metavar="") # We avoid `metavar` to prevent printing repetitive information desc = "List files managed by the SCM" sub.add_parser("ls", help=desc[0].lower() + desc[1:], description=desc) return parser.parse_args() def _find_pyproject(parent): for directory in walk_potential_roots(os.path.abspath(parent)): pyproject = os.path.join(directory, "pyproject.toml") if os.path.exists(pyproject): return pyproject raise FileNotFoundError("'pyproject.toml' was not found") if __name__ == "__main__": main()
261f48b4b8c61baea26389017994678aa6cc9c73
scanblog/scanning/management/commands/fixuploadperms.py
scanblog/scanning/management/commands/fixuploadperms.py
import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO), os.path.join(settings.MEDIA_ROOT, "letters"), os.path.join(settings.MEDIA_ROOT, "mailings"), os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname # files: -rw-rw-r-- os.system('sudo chmod -R u=rwX,g=rwX,o=rX "%s"' % dirname) os.system('sudo chown -R www-data.btb "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod g+s {} +' % dirname)
import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO), os.path.join(settings.MEDIA_ROOT, "letters"), os.path.join(settings.MEDIA_ROOT, "mailings"), os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname # files: -rw-rw-r-- os.system('sudo chmod -R u=rwX,g=rwX,o=rX "%s"' % dirname) os.system('sudo chown -R www-data.btb "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod g+s {} ;' % dirname)
Revert to non-parallel chmod (argument list too long)
Revert to non-parallel chmod (argument list too long)
Python
agpl-3.0
yourcelf/btb,yourcelf/btb,yourcelf/btb,yourcelf/btb,yourcelf/btb
import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO), os.path.join(settings.MEDIA_ROOT, "letters"), os.path.join(settings.MEDIA_ROOT, "mailings"), os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname # files: -rw-rw-r-- os.system('sudo chmod -R u=rwX,g=rwX,o=rX "%s"' % dirname) os.system('sudo chown -R www-data.btb "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod g+s {} +' % dirname) Revert to non-parallel chmod (argument list too long)
import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO), os.path.join(settings.MEDIA_ROOT, "letters"), os.path.join(settings.MEDIA_ROOT, "mailings"), os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname # files: -rw-rw-r-- os.system('sudo chmod -R u=rwX,g=rwX,o=rX "%s"' % dirname) os.system('sudo chown -R www-data.btb "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod g+s {} ;' % dirname)
<commit_before>import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO), os.path.join(settings.MEDIA_ROOT, "letters"), os.path.join(settings.MEDIA_ROOT, "mailings"), os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname # files: -rw-rw-r-- os.system('sudo chmod -R u=rwX,g=rwX,o=rX "%s"' % dirname) os.system('sudo chown -R www-data.btb "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod g+s {} +' % dirname) <commit_msg>Revert to non-parallel chmod (argument list too long)<commit_after>
import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO), os.path.join(settings.MEDIA_ROOT, "letters"), os.path.join(settings.MEDIA_ROOT, "mailings"), os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname # files: -rw-rw-r-- os.system('sudo chmod -R u=rwX,g=rwX,o=rX "%s"' % dirname) os.system('sudo chown -R www-data.btb "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod g+s {} ;' % dirname)
import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO), os.path.join(settings.MEDIA_ROOT, "letters"), os.path.join(settings.MEDIA_ROOT, "mailings"), os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname # files: -rw-rw-r-- os.system('sudo chmod -R u=rwX,g=rwX,o=rX "%s"' % dirname) os.system('sudo chown -R www-data.btb "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod g+s {} +' % dirname) Revert to non-parallel chmod (argument list too long)import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO), os.path.join(settings.MEDIA_ROOT, "letters"), os.path.join(settings.MEDIA_ROOT, "mailings"), os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname # files: -rw-rw-r-- os.system('sudo chmod -R u=rwX,g=rwX,o=rX "%s"' % dirname) os.system('sudo chown -R www-data.btb "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod g+s {} ;' % dirname)
<commit_before>import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO), os.path.join(settings.MEDIA_ROOT, "letters"), os.path.join(settings.MEDIA_ROOT, "mailings"), os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname # files: -rw-rw-r-- os.system('sudo chmod -R u=rwX,g=rwX,o=rX "%s"' % dirname) os.system('sudo chown -R www-data.btb "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod g+s {} +' % dirname) <commit_msg>Revert to non-parallel chmod (argument list too long)<commit_after>import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO), os.path.join(settings.MEDIA_ROOT, "letters"), os.path.join(settings.MEDIA_ROOT, "mailings"), os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname # files: -rw-rw-r-- os.system('sudo chmod -R u=rwX,g=rwX,o=rX "%s"' % dirname) os.system('sudo chown -R www-data.btb "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod g+s {} ;' % dirname)
0b19a32d8d0d2f10e53ecaf545c7be15d29f8e82
posts/feeds.py
posts/feeds.py
from django.contrib.syndication.views import Feed from posts.models import Post from helpers import get_post_url, post_as_components from settings import BLOG_FULL_TITLE, BLOG_DESCRIPTION import markdown class LatestEntries(Feed): title = BLOG_FULL_TITLE link = '/' description = BLOG_DESCRIPTION def items(self): return Post.objects.order_by("-publication_date")[:10] def item_title(self, item): return post_as_components(item.body)[0] def item_description(self, item): first_para = post_as_components(item.body)[1] return markdown.markdown(first_para) def item_link(self, item): return get_post_url(item)
from django.contrib.syndication.views import Feed from posts.models import Post from helpers import get_post_url, post_as_components from blog.settings import BLOG_FULL_TITLE, BLOG_DESCRIPTION import markdown class LatestEntries(Feed): title = BLOG_FULL_TITLE link = '/' description = BLOG_DESCRIPTION def items(self): return Post.objects.order_by("-publication_date")[:10] def item_title(self, item): return post_as_components(item.body)[0] def item_description(self, item): first_para = post_as_components(item.body)[1] return markdown.markdown(first_para) def item_link(self, item): return get_post_url(item)
Fix a bug introduced by the last commit.
Fix a bug introduced by the last commit.
Python
mit
Lukasa/minimalog
from django.contrib.syndication.views import Feed from posts.models import Post from helpers import get_post_url, post_as_components from settings import BLOG_FULL_TITLE, BLOG_DESCRIPTION import markdown class LatestEntries(Feed): title = BLOG_FULL_TITLE link = '/' description = BLOG_DESCRIPTION def items(self): return Post.objects.order_by("-publication_date")[:10] def item_title(self, item): return post_as_components(item.body)[0] def item_description(self, item): first_para = post_as_components(item.body)[1] return markdown.markdown(first_para) def item_link(self, item): return get_post_url(item) Fix a bug introduced by the last commit.
from django.contrib.syndication.views import Feed from posts.models import Post from helpers import get_post_url, post_as_components from blog.settings import BLOG_FULL_TITLE, BLOG_DESCRIPTION import markdown class LatestEntries(Feed): title = BLOG_FULL_TITLE link = '/' description = BLOG_DESCRIPTION def items(self): return Post.objects.order_by("-publication_date")[:10] def item_title(self, item): return post_as_components(item.body)[0] def item_description(self, item): first_para = post_as_components(item.body)[1] return markdown.markdown(first_para) def item_link(self, item): return get_post_url(item)
<commit_before>from django.contrib.syndication.views import Feed from posts.models import Post from helpers import get_post_url, post_as_components from settings import BLOG_FULL_TITLE, BLOG_DESCRIPTION import markdown class LatestEntries(Feed): title = BLOG_FULL_TITLE link = '/' description = BLOG_DESCRIPTION def items(self): return Post.objects.order_by("-publication_date")[:10] def item_title(self, item): return post_as_components(item.body)[0] def item_description(self, item): first_para = post_as_components(item.body)[1] return markdown.markdown(first_para) def item_link(self, item): return get_post_url(item) <commit_msg>Fix a bug introduced by the last commit.<commit_after>
from django.contrib.syndication.views import Feed from posts.models import Post from helpers import get_post_url, post_as_components from blog.settings import BLOG_FULL_TITLE, BLOG_DESCRIPTION import markdown class LatestEntries(Feed): title = BLOG_FULL_TITLE link = '/' description = BLOG_DESCRIPTION def items(self): return Post.objects.order_by("-publication_date")[:10] def item_title(self, item): return post_as_components(item.body)[0] def item_description(self, item): first_para = post_as_components(item.body)[1] return markdown.markdown(first_para) def item_link(self, item): return get_post_url(item)
from django.contrib.syndication.views import Feed from posts.models import Post from helpers import get_post_url, post_as_components from settings import BLOG_FULL_TITLE, BLOG_DESCRIPTION import markdown class LatestEntries(Feed): title = BLOG_FULL_TITLE link = '/' description = BLOG_DESCRIPTION def items(self): return Post.objects.order_by("-publication_date")[:10] def item_title(self, item): return post_as_components(item.body)[0] def item_description(self, item): first_para = post_as_components(item.body)[1] return markdown.markdown(first_para) def item_link(self, item): return get_post_url(item) Fix a bug introduced by the last commit.from django.contrib.syndication.views import Feed from posts.models import Post from helpers import get_post_url, post_as_components from blog.settings import BLOG_FULL_TITLE, BLOG_DESCRIPTION import markdown class LatestEntries(Feed): title = BLOG_FULL_TITLE link = '/' description = BLOG_DESCRIPTION def items(self): return Post.objects.order_by("-publication_date")[:10] def item_title(self, item): return post_as_components(item.body)[0] def item_description(self, item): first_para = post_as_components(item.body)[1] return markdown.markdown(first_para) def item_link(self, item): return get_post_url(item)
<commit_before>from django.contrib.syndication.views import Feed from posts.models import Post from helpers import get_post_url, post_as_components from settings import BLOG_FULL_TITLE, BLOG_DESCRIPTION import markdown class LatestEntries(Feed): title = BLOG_FULL_TITLE link = '/' description = BLOG_DESCRIPTION def items(self): return Post.objects.order_by("-publication_date")[:10] def item_title(self, item): return post_as_components(item.body)[0] def item_description(self, item): first_para = post_as_components(item.body)[1] return markdown.markdown(first_para) def item_link(self, item): return get_post_url(item) <commit_msg>Fix a bug introduced by the last commit.<commit_after>from django.contrib.syndication.views import Feed from posts.models import Post from helpers import get_post_url, post_as_components from blog.settings import BLOG_FULL_TITLE, BLOG_DESCRIPTION import markdown class LatestEntries(Feed): title = BLOG_FULL_TITLE link = '/' description = BLOG_DESCRIPTION def items(self): return Post.objects.order_by("-publication_date")[:10] def item_title(self, item): return post_as_components(item.body)[0] def item_description(self, item): first_para = post_as_components(item.body)[1] return markdown.markdown(first_para) def item_link(self, item): return get_post_url(item)
35b076258427e5641ba25b67d804b009a05d49c5
tests/helpers.py
tests/helpers.py
import re from contextlib import contextmanager from datetime import timedelta from django.utils import timezone from freezegun import freeze_time @contextmanager def active_phase(module, phase_type): now = timezone.now() phase = module.phase_set.create( start_date=now, end_date=now + timedelta(days=1), name='TEST PHASE', description='TEST DESCRIPTION', type=phase_type().identifier, weight=0, ) with freeze_time(phase.start_date): yield phase.delete() class pytest_regex: """Assert that a given string meets some expectations.""" def __init__(self, pattern, flags=0): self._regex = re.compile(pattern, flags) def __eq__(self, actual): return bool(self._regex.match(actual)) def __repr__(self): return self._regex.pattern
import re from contextlib import contextmanager from datetime import timedelta from django.utils import timezone from freezegun import freeze_time @contextmanager def active_phase(module, phase_type): now = timezone.now() phase = module.phase_set.create( start_date=now, end_date=now + timedelta(days=1), name='TEST PHASE', description='TEST DESCRIPTION', type=phase_type().identifier, weight=0, ) with freeze_time(phase.start_date): yield phase.delete() class pytest_regex: """Assert that a given string meets some expectations.""" def __init__(self, pattern, flags=0): self._regex = re.compile(pattern, flags) def __eq__(self, actual): return bool(self._regex.match(str(actual))) def __repr__(self): return self._regex.pattern
Make regex helper accept more types
tests/helper: Make regex helper accept more types
Python
agpl-3.0
liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4
import re from contextlib import contextmanager from datetime import timedelta from django.utils import timezone from freezegun import freeze_time @contextmanager def active_phase(module, phase_type): now = timezone.now() phase = module.phase_set.create( start_date=now, end_date=now + timedelta(days=1), name='TEST PHASE', description='TEST DESCRIPTION', type=phase_type().identifier, weight=0, ) with freeze_time(phase.start_date): yield phase.delete() class pytest_regex: """Assert that a given string meets some expectations.""" def __init__(self, pattern, flags=0): self._regex = re.compile(pattern, flags) def __eq__(self, actual): return bool(self._regex.match(actual)) def __repr__(self): return self._regex.pattern tests/helper: Make regex helper accept more types
import re from contextlib import contextmanager from datetime import timedelta from django.utils import timezone from freezegun import freeze_time @contextmanager def active_phase(module, phase_type): now = timezone.now() phase = module.phase_set.create( start_date=now, end_date=now + timedelta(days=1), name='TEST PHASE', description='TEST DESCRIPTION', type=phase_type().identifier, weight=0, ) with freeze_time(phase.start_date): yield phase.delete() class pytest_regex: """Assert that a given string meets some expectations.""" def __init__(self, pattern, flags=0): self._regex = re.compile(pattern, flags) def __eq__(self, actual): return bool(self._regex.match(str(actual))) def __repr__(self): return self._regex.pattern
<commit_before>import re from contextlib import contextmanager from datetime import timedelta from django.utils import timezone from freezegun import freeze_time @contextmanager def active_phase(module, phase_type): now = timezone.now() phase = module.phase_set.create( start_date=now, end_date=now + timedelta(days=1), name='TEST PHASE', description='TEST DESCRIPTION', type=phase_type().identifier, weight=0, ) with freeze_time(phase.start_date): yield phase.delete() class pytest_regex: """Assert that a given string meets some expectations.""" def __init__(self, pattern, flags=0): self._regex = re.compile(pattern, flags) def __eq__(self, actual): return bool(self._regex.match(actual)) def __repr__(self): return self._regex.pattern <commit_msg>tests/helper: Make regex helper accept more types<commit_after>
import re from contextlib import contextmanager from datetime import timedelta from django.utils import timezone from freezegun import freeze_time @contextmanager def active_phase(module, phase_type): now = timezone.now() phase = module.phase_set.create( start_date=now, end_date=now + timedelta(days=1), name='TEST PHASE', description='TEST DESCRIPTION', type=phase_type().identifier, weight=0, ) with freeze_time(phase.start_date): yield phase.delete() class pytest_regex: """Assert that a given string meets some expectations.""" def __init__(self, pattern, flags=0): self._regex = re.compile(pattern, flags) def __eq__(self, actual): return bool(self._regex.match(str(actual))) def __repr__(self): return self._regex.pattern
import re from contextlib import contextmanager from datetime import timedelta from django.utils import timezone from freezegun import freeze_time @contextmanager def active_phase(module, phase_type): now = timezone.now() phase = module.phase_set.create( start_date=now, end_date=now + timedelta(days=1), name='TEST PHASE', description='TEST DESCRIPTION', type=phase_type().identifier, weight=0, ) with freeze_time(phase.start_date): yield phase.delete() class pytest_regex: """Assert that a given string meets some expectations.""" def __init__(self, pattern, flags=0): self._regex = re.compile(pattern, flags) def __eq__(self, actual): return bool(self._regex.match(actual)) def __repr__(self): return self._regex.pattern tests/helper: Make regex helper accept more typesimport re from contextlib import contextmanager from datetime import timedelta from django.utils import timezone from freezegun import freeze_time @contextmanager def active_phase(module, phase_type): now = timezone.now() phase = module.phase_set.create( start_date=now, end_date=now + timedelta(days=1), name='TEST PHASE', description='TEST DESCRIPTION', type=phase_type().identifier, weight=0, ) with freeze_time(phase.start_date): yield phase.delete() class pytest_regex: """Assert that a given string meets some expectations.""" def __init__(self, pattern, flags=0): self._regex = re.compile(pattern, flags) def __eq__(self, actual): return bool(self._regex.match(str(actual))) def __repr__(self): return self._regex.pattern
<commit_before>import re from contextlib import contextmanager from datetime import timedelta from django.utils import timezone from freezegun import freeze_time @contextmanager def active_phase(module, phase_type): now = timezone.now() phase = module.phase_set.create( start_date=now, end_date=now + timedelta(days=1), name='TEST PHASE', description='TEST DESCRIPTION', type=phase_type().identifier, weight=0, ) with freeze_time(phase.start_date): yield phase.delete() class pytest_regex: """Assert that a given string meets some expectations.""" def __init__(self, pattern, flags=0): self._regex = re.compile(pattern, flags) def __eq__(self, actual): return bool(self._regex.match(actual)) def __repr__(self): return self._regex.pattern <commit_msg>tests/helper: Make regex helper accept more types<commit_after>import re from contextlib import contextmanager from datetime import timedelta from django.utils import timezone from freezegun import freeze_time @contextmanager def active_phase(module, phase_type): now = timezone.now() phase = module.phase_set.create( start_date=now, end_date=now + timedelta(days=1), name='TEST PHASE', description='TEST DESCRIPTION', type=phase_type().identifier, weight=0, ) with freeze_time(phase.start_date): yield phase.delete() class pytest_regex: """Assert that a given string meets some expectations.""" def __init__(self, pattern, flags=0): self._regex = re.compile(pattern, flags) def __eq__(self, actual): return bool(self._regex.match(str(actual))) def __repr__(self): return self._regex.pattern
7806937a4a3b9853becdf963dbcbfe79a256097d
rapidsms/router/celery/tasks.py
rapidsms/router/celery/tasks.py
import celery from celery.utils.log import get_task_logger from rapidsms.errors import MessageSendingError logger = get_task_logger(__name__) @celery.task def receive_async(text, connection_id, message_id, fields): """Task used to send inbound message through router phases.""" from rapidsms.models import Connection from rapidsms.router import get_router logger.debug('receive_async: %s' % text) router = get_router() # reconstruct incoming message connection = Connection.objects.select_related().get(pk=connection_id) message = router.new_incoming_message(text=text, connections=[connection], id_=message_id, fields=fields) try: # call process_incoming directly to skip receive_incoming router.process_incoming(message) except Exception: logger.exception("Exception processing incoming message") @celery.task def send_async(backend_name, id_, text, identities, context): """Task used to send outgoing messages to backends.""" logger.debug('send_async: %s' % text) from rapidsms.router import get_router router = get_router() try: router.send_to_backend(backend_name=backend_name, id_=id_, text=text, identities=identities, context=context) except MessageSendingError: # This exception has already been logged in send_to_backend. # We'll simply pass here and not re-raise or log the exception again. pass
import celery import logging from rapidsms.errors import MessageSendingError logger = logging.getLogger(__name__) @celery.task def receive_async(text, connection_id, message_id, fields): """Task used to send inbound message through router phases.""" from rapidsms.models import Connection from rapidsms.router import get_router logger.debug('receive_async: %s' % text) router = get_router() # reconstruct incoming message connection = Connection.objects.select_related().get(pk=connection_id) message = router.new_incoming_message(text=text, connections=[connection], id_=message_id, fields=fields) try: # call process_incoming directly to skip receive_incoming router.process_incoming(message) except Exception: logger.exception("Exception processing incoming message") raise @celery.task def send_async(backend_name, id_, text, identities, context): """Task used to send outgoing messages to backends.""" logger.debug('send_async: %s' % text) from rapidsms.router import get_router router = get_router() try: router.send_to_backend(backend_name=backend_name, id_=id_, text=text, identities=identities, context=context) except MessageSendingError: # This exception has already been logged in send_to_backend. # We'll simply pass here and not re-raise or log the exception again. pass
Refactor logging in celery router
Refactor logging in celery router Send logging for celery router tasks to the 'rapidsms' logger rather than the 'celery' logger, and make sure celery knows the task failed by re-raising the exception.
Python
bsd-3-clause
eHealthAfrica/rapidsms,eHealthAfrica/rapidsms,lsgunth/rapidsms,peterayeni/rapidsms,peterayeni/rapidsms,caktus/rapidsms,peterayeni/rapidsms,ehealthafrica-ci/rapidsms,caktus/rapidsms,catalpainternational/rapidsms,lsgunth/rapidsms,lsgunth/rapidsms,peterayeni/rapidsms,ehealthafrica-ci/rapidsms,catalpainternational/rapidsms,ehealthafrica-ci/rapidsms,eHealthAfrica/rapidsms,caktus/rapidsms,catalpainternational/rapidsms,catalpainternational/rapidsms,lsgunth/rapidsms
import celery from celery.utils.log import get_task_logger from rapidsms.errors import MessageSendingError logger = get_task_logger(__name__) @celery.task def receive_async(text, connection_id, message_id, fields): """Task used to send inbound message through router phases.""" from rapidsms.models import Connection from rapidsms.router import get_router logger.debug('receive_async: %s' % text) router = get_router() # reconstruct incoming message connection = Connection.objects.select_related().get(pk=connection_id) message = router.new_incoming_message(text=text, connections=[connection], id_=message_id, fields=fields) try: # call process_incoming directly to skip receive_incoming router.process_incoming(message) except Exception: logger.exception("Exception processing incoming message") @celery.task def send_async(backend_name, id_, text, identities, context): """Task used to send outgoing messages to backends.""" logger.debug('send_async: %s' % text) from rapidsms.router import get_router router = get_router() try: router.send_to_backend(backend_name=backend_name, id_=id_, text=text, identities=identities, context=context) except MessageSendingError: # This exception has already been logged in send_to_backend. # We'll simply pass here and not re-raise or log the exception again. pass Refactor logging in celery router Send logging for celery router tasks to the 'rapidsms' logger rather than the 'celery' logger, and make sure celery knows the task failed by re-raising the exception.
import celery import logging from rapidsms.errors import MessageSendingError logger = logging.getLogger(__name__) @celery.task def receive_async(text, connection_id, message_id, fields): """Task used to send inbound message through router phases.""" from rapidsms.models import Connection from rapidsms.router import get_router logger.debug('receive_async: %s' % text) router = get_router() # reconstruct incoming message connection = Connection.objects.select_related().get(pk=connection_id) message = router.new_incoming_message(text=text, connections=[connection], id_=message_id, fields=fields) try: # call process_incoming directly to skip receive_incoming router.process_incoming(message) except Exception: logger.exception("Exception processing incoming message") raise @celery.task def send_async(backend_name, id_, text, identities, context): """Task used to send outgoing messages to backends.""" logger.debug('send_async: %s' % text) from rapidsms.router import get_router router = get_router() try: router.send_to_backend(backend_name=backend_name, id_=id_, text=text, identities=identities, context=context) except MessageSendingError: # This exception has already been logged in send_to_backend. # We'll simply pass here and not re-raise or log the exception again. pass
<commit_before>import celery from celery.utils.log import get_task_logger from rapidsms.errors import MessageSendingError logger = get_task_logger(__name__) @celery.task def receive_async(text, connection_id, message_id, fields): """Task used to send inbound message through router phases.""" from rapidsms.models import Connection from rapidsms.router import get_router logger.debug('receive_async: %s' % text) router = get_router() # reconstruct incoming message connection = Connection.objects.select_related().get(pk=connection_id) message = router.new_incoming_message(text=text, connections=[connection], id_=message_id, fields=fields) try: # call process_incoming directly to skip receive_incoming router.process_incoming(message) except Exception: logger.exception("Exception processing incoming message") @celery.task def send_async(backend_name, id_, text, identities, context): """Task used to send outgoing messages to backends.""" logger.debug('send_async: %s' % text) from rapidsms.router import get_router router = get_router() try: router.send_to_backend(backend_name=backend_name, id_=id_, text=text, identities=identities, context=context) except MessageSendingError: # This exception has already been logged in send_to_backend. # We'll simply pass here and not re-raise or log the exception again. pass <commit_msg>Refactor logging in celery router Send logging for celery router tasks to the 'rapidsms' logger rather than the 'celery' logger, and make sure celery knows the task failed by re-raising the exception.<commit_after>
import celery import logging from rapidsms.errors import MessageSendingError logger = logging.getLogger(__name__) @celery.task def receive_async(text, connection_id, message_id, fields): """Task used to send inbound message through router phases.""" from rapidsms.models import Connection from rapidsms.router import get_router logger.debug('receive_async: %s' % text) router = get_router() # reconstruct incoming message connection = Connection.objects.select_related().get(pk=connection_id) message = router.new_incoming_message(text=text, connections=[connection], id_=message_id, fields=fields) try: # call process_incoming directly to skip receive_incoming router.process_incoming(message) except Exception: logger.exception("Exception processing incoming message") raise @celery.task def send_async(backend_name, id_, text, identities, context): """Task used to send outgoing messages to backends.""" logger.debug('send_async: %s' % text) from rapidsms.router import get_router router = get_router() try: router.send_to_backend(backend_name=backend_name, id_=id_, text=text, identities=identities, context=context) except MessageSendingError: # This exception has already been logged in send_to_backend. # We'll simply pass here and not re-raise or log the exception again. pass
import celery from celery.utils.log import get_task_logger from rapidsms.errors import MessageSendingError logger = get_task_logger(__name__) @celery.task def receive_async(text, connection_id, message_id, fields): """Task used to send inbound message through router phases.""" from rapidsms.models import Connection from rapidsms.router import get_router logger.debug('receive_async: %s' % text) router = get_router() # reconstruct incoming message connection = Connection.objects.select_related().get(pk=connection_id) message = router.new_incoming_message(text=text, connections=[connection], id_=message_id, fields=fields) try: # call process_incoming directly to skip receive_incoming router.process_incoming(message) except Exception: logger.exception("Exception processing incoming message") @celery.task def send_async(backend_name, id_, text, identities, context): """Task used to send outgoing messages to backends.""" logger.debug('send_async: %s' % text) from rapidsms.router import get_router router = get_router() try: router.send_to_backend(backend_name=backend_name, id_=id_, text=text, identities=identities, context=context) except MessageSendingError: # This exception has already been logged in send_to_backend. # We'll simply pass here and not re-raise or log the exception again. pass Refactor logging in celery router Send logging for celery router tasks to the 'rapidsms' logger rather than the 'celery' logger, and make sure celery knows the task failed by re-raising the exception.import celery import logging from rapidsms.errors import MessageSendingError logger = logging.getLogger(__name__) @celery.task def receive_async(text, connection_id, message_id, fields): """Task used to send inbound message through router phases.""" from rapidsms.models import Connection from rapidsms.router import get_router logger.debug('receive_async: %s' % text) router = get_router() # reconstruct incoming message connection = Connection.objects.select_related().get(pk=connection_id) message = router.new_incoming_message(text=text, connections=[connection], id_=message_id, fields=fields) try: # call process_incoming directly to skip receive_incoming router.process_incoming(message) except Exception: logger.exception("Exception processing incoming message") raise @celery.task def send_async(backend_name, id_, text, identities, context): """Task used to send outgoing messages to backends.""" logger.debug('send_async: %s' % text) from rapidsms.router import get_router router = get_router() try: router.send_to_backend(backend_name=backend_name, id_=id_, text=text, identities=identities, context=context) except MessageSendingError: # This exception has already been logged in send_to_backend. # We'll simply pass here and not re-raise or log the exception again. pass
<commit_before>import celery from celery.utils.log import get_task_logger from rapidsms.errors import MessageSendingError logger = get_task_logger(__name__) @celery.task def receive_async(text, connection_id, message_id, fields): """Task used to send inbound message through router phases.""" from rapidsms.models import Connection from rapidsms.router import get_router logger.debug('receive_async: %s' % text) router = get_router() # reconstruct incoming message connection = Connection.objects.select_related().get(pk=connection_id) message = router.new_incoming_message(text=text, connections=[connection], id_=message_id, fields=fields) try: # call process_incoming directly to skip receive_incoming router.process_incoming(message) except Exception: logger.exception("Exception processing incoming message") @celery.task def send_async(backend_name, id_, text, identities, context): """Task used to send outgoing messages to backends.""" logger.debug('send_async: %s' % text) from rapidsms.router import get_router router = get_router() try: router.send_to_backend(backend_name=backend_name, id_=id_, text=text, identities=identities, context=context) except MessageSendingError: # This exception has already been logged in send_to_backend. # We'll simply pass here and not re-raise or log the exception again. pass <commit_msg>Refactor logging in celery router Send logging for celery router tasks to the 'rapidsms' logger rather than the 'celery' logger, and make sure celery knows the task failed by re-raising the exception.<commit_after>import celery import logging from rapidsms.errors import MessageSendingError logger = logging.getLogger(__name__) @celery.task def receive_async(text, connection_id, message_id, fields): """Task used to send inbound message through router phases.""" from rapidsms.models import Connection from rapidsms.router import get_router logger.debug('receive_async: %s' % text) router = get_router() # reconstruct incoming message connection = Connection.objects.select_related().get(pk=connection_id) message = router.new_incoming_message(text=text, connections=[connection], id_=message_id, fields=fields) try: # call process_incoming directly to skip receive_incoming router.process_incoming(message) except Exception: logger.exception("Exception processing incoming message") raise @celery.task def send_async(backend_name, id_, text, identities, context): """Task used to send outgoing messages to backends.""" logger.debug('send_async: %s' % text) from rapidsms.router import get_router router = get_router() try: router.send_to_backend(backend_name=backend_name, id_=id_, text=text, identities=identities, context=context) except MessageSendingError: # This exception has already been logged in send_to_backend. # We'll simply pass here and not re-raise or log the exception again. pass
f304e2437870e553056fef1808b1218886143a27
ResourcePool.py
ResourcePool.py
#Copyright (C) 2011,2012 Colin Rice #This software is licensed under an included MIT license. #See the file entitled LICENSE #If you were not provided with a copy of the license please contact: # Colin Rice colin@daedrum.net import threading class ResourceGenerator: def __init__(self, generate = lambda:None, pool = None, timeout = None): #Pool is a list of items #Generate creates a new item self.generate = generate self.pool = pool self.timeout = timeout def __enter__(self): #Check if an item is available while len(self.pool) > 5: for lock, item in self.pool: if lock.acquire(False): self.lock = lock return item if len(self.pool) > 5: gevent.sleep(0) #Otherwise make a new item (lock, item) = (threading.Lock(), self.generate(self.timeout)) lock.acquire() self.lock = lock self.pool.add((lock,item)) return item def __exit__(self, type, value, traceback): self.lock.release() class Pool: def __init__(self, generate): self.pools = {} self.generate = generate def __call__(self, url, timeout=None): key = url+str(timeout) if url not in self.pools: self.pools[key] = set() return ResourceGenerator(self.generate, pool = self.pools[key], timeout=timeout)
#Copyright (C) 2011,2012 Colin Rice #This software is licensed under an included MIT license. #See the file entitled LICENSE #If you were not provided with a copy of the license please contact: # Colin Rice colin@daedrum.net import threading class ResourceGenerator: def __init__(self, generate = lambda:None, pool = None, timeout = None): #Pool is a list of items #Generate creates a new item self.generate = generate self.pool = pool self.timeout = timeout def __enter__(self): #Check if an item is available while len(self.pool) > 10: for lock, item in self.pool: if lock.acquire(False): self.lock = lock return item if len(self.pool) > 10: gevent.sleep(0) #Otherwise make a new item (lock, item) = (threading.Lock(), self.generate(self.timeout)) lock.acquire() self.lock = lock self.pool.add((lock,item)) return item def __exit__(self, type, value, traceback): self.lock.release() class Pool: def __init__(self, generate): self.pools = {} self.generate = generate def __call__(self, url, timeout=None): key = url+str(timeout) if url not in self.pools: self.pools[key] = set() return ResourceGenerator(self.generate, pool = self.pools[key], timeout=timeout)
Make use allow more connections per pool. Now capped at 10.
Make use allow more connections per pool. Now capped at 10.
Python
mit
c00w/bitHopper,c00w/bitHopper
#Copyright (C) 2011,2012 Colin Rice #This software is licensed under an included MIT license. #See the file entitled LICENSE #If you were not provided with a copy of the license please contact: # Colin Rice colin@daedrum.net import threading class ResourceGenerator: def __init__(self, generate = lambda:None, pool = None, timeout = None): #Pool is a list of items #Generate creates a new item self.generate = generate self.pool = pool self.timeout = timeout def __enter__(self): #Check if an item is available while len(self.pool) > 5: for lock, item in self.pool: if lock.acquire(False): self.lock = lock return item if len(self.pool) > 5: gevent.sleep(0) #Otherwise make a new item (lock, item) = (threading.Lock(), self.generate(self.timeout)) lock.acquire() self.lock = lock self.pool.add((lock,item)) return item def __exit__(self, type, value, traceback): self.lock.release() class Pool: def __init__(self, generate): self.pools = {} self.generate = generate def __call__(self, url, timeout=None): key = url+str(timeout) if url not in self.pools: self.pools[key] = set() return ResourceGenerator(self.generate, pool = self.pools[key], timeout=timeout) Make use allow more connections per pool. Now capped at 10.
#Copyright (C) 2011,2012 Colin Rice #This software is licensed under an included MIT license. #See the file entitled LICENSE #If you were not provided with a copy of the license please contact: # Colin Rice colin@daedrum.net import threading class ResourceGenerator: def __init__(self, generate = lambda:None, pool = None, timeout = None): #Pool is a list of items #Generate creates a new item self.generate = generate self.pool = pool self.timeout = timeout def __enter__(self): #Check if an item is available while len(self.pool) > 10: for lock, item in self.pool: if lock.acquire(False): self.lock = lock return item if len(self.pool) > 10: gevent.sleep(0) #Otherwise make a new item (lock, item) = (threading.Lock(), self.generate(self.timeout)) lock.acquire() self.lock = lock self.pool.add((lock,item)) return item def __exit__(self, type, value, traceback): self.lock.release() class Pool: def __init__(self, generate): self.pools = {} self.generate = generate def __call__(self, url, timeout=None): key = url+str(timeout) if url not in self.pools: self.pools[key] = set() return ResourceGenerator(self.generate, pool = self.pools[key], timeout=timeout)
<commit_before>#Copyright (C) 2011,2012 Colin Rice #This software is licensed under an included MIT license. #See the file entitled LICENSE #If you were not provided with a copy of the license please contact: # Colin Rice colin@daedrum.net import threading class ResourceGenerator: def __init__(self, generate = lambda:None, pool = None, timeout = None): #Pool is a list of items #Generate creates a new item self.generate = generate self.pool = pool self.timeout = timeout def __enter__(self): #Check if an item is available while len(self.pool) > 5: for lock, item in self.pool: if lock.acquire(False): self.lock = lock return item if len(self.pool) > 5: gevent.sleep(0) #Otherwise make a new item (lock, item) = (threading.Lock(), self.generate(self.timeout)) lock.acquire() self.lock = lock self.pool.add((lock,item)) return item def __exit__(self, type, value, traceback): self.lock.release() class Pool: def __init__(self, generate): self.pools = {} self.generate = generate def __call__(self, url, timeout=None): key = url+str(timeout) if url not in self.pools: self.pools[key] = set() return ResourceGenerator(self.generate, pool = self.pools[key], timeout=timeout) <commit_msg>Make use allow more connections per pool. Now capped at 10.<commit_after>
#Copyright (C) 2011,2012 Colin Rice #This software is licensed under an included MIT license. #See the file entitled LICENSE #If you were not provided with a copy of the license please contact: # Colin Rice colin@daedrum.net import threading class ResourceGenerator: def __init__(self, generate = lambda:None, pool = None, timeout = None): #Pool is a list of items #Generate creates a new item self.generate = generate self.pool = pool self.timeout = timeout def __enter__(self): #Check if an item is available while len(self.pool) > 10: for lock, item in self.pool: if lock.acquire(False): self.lock = lock return item if len(self.pool) > 10: gevent.sleep(0) #Otherwise make a new item (lock, item) = (threading.Lock(), self.generate(self.timeout)) lock.acquire() self.lock = lock self.pool.add((lock,item)) return item def __exit__(self, type, value, traceback): self.lock.release() class Pool: def __init__(self, generate): self.pools = {} self.generate = generate def __call__(self, url, timeout=None): key = url+str(timeout) if url not in self.pools: self.pools[key] = set() return ResourceGenerator(self.generate, pool = self.pools[key], timeout=timeout)
#Copyright (C) 2011,2012 Colin Rice #This software is licensed under an included MIT license. #See the file entitled LICENSE #If you were not provided with a copy of the license please contact: # Colin Rice colin@daedrum.net import threading class ResourceGenerator: def __init__(self, generate = lambda:None, pool = None, timeout = None): #Pool is a list of items #Generate creates a new item self.generate = generate self.pool = pool self.timeout = timeout def __enter__(self): #Check if an item is available while len(self.pool) > 5: for lock, item in self.pool: if lock.acquire(False): self.lock = lock return item if len(self.pool) > 5: gevent.sleep(0) #Otherwise make a new item (lock, item) = (threading.Lock(), self.generate(self.timeout)) lock.acquire() self.lock = lock self.pool.add((lock,item)) return item def __exit__(self, type, value, traceback): self.lock.release() class Pool: def __init__(self, generate): self.pools = {} self.generate = generate def __call__(self, url, timeout=None): key = url+str(timeout) if url not in self.pools: self.pools[key] = set() return ResourceGenerator(self.generate, pool = self.pools[key], timeout=timeout) Make use allow more connections per pool. Now capped at 10.#Copyright (C) 2011,2012 Colin Rice #This software is licensed under an included MIT license. #See the file entitled LICENSE #If you were not provided with a copy of the license please contact: # Colin Rice colin@daedrum.net import threading class ResourceGenerator: def __init__(self, generate = lambda:None, pool = None, timeout = None): #Pool is a list of items #Generate creates a new item self.generate = generate self.pool = pool self.timeout = timeout def __enter__(self): #Check if an item is available while len(self.pool) > 10: for lock, item in self.pool: if lock.acquire(False): self.lock = lock return item if len(self.pool) > 10: gevent.sleep(0) #Otherwise make a new item (lock, item) = (threading.Lock(), self.generate(self.timeout)) lock.acquire() self.lock = lock self.pool.add((lock,item)) return item def __exit__(self, type, value, traceback): self.lock.release() class Pool: def __init__(self, generate): self.pools = {} self.generate = generate def __call__(self, url, timeout=None): key = url+str(timeout) if url not in self.pools: self.pools[key] = set() return ResourceGenerator(self.generate, pool = self.pools[key], timeout=timeout)
<commit_before>#Copyright (C) 2011,2012 Colin Rice #This software is licensed under an included MIT license. #See the file entitled LICENSE #If you were not provided with a copy of the license please contact: # Colin Rice colin@daedrum.net import threading class ResourceGenerator: def __init__(self, generate = lambda:None, pool = None, timeout = None): #Pool is a list of items #Generate creates a new item self.generate = generate self.pool = pool self.timeout = timeout def __enter__(self): #Check if an item is available while len(self.pool) > 5: for lock, item in self.pool: if lock.acquire(False): self.lock = lock return item if len(self.pool) > 5: gevent.sleep(0) #Otherwise make a new item (lock, item) = (threading.Lock(), self.generate(self.timeout)) lock.acquire() self.lock = lock self.pool.add((lock,item)) return item def __exit__(self, type, value, traceback): self.lock.release() class Pool: def __init__(self, generate): self.pools = {} self.generate = generate def __call__(self, url, timeout=None): key = url+str(timeout) if url not in self.pools: self.pools[key] = set() return ResourceGenerator(self.generate, pool = self.pools[key], timeout=timeout) <commit_msg>Make use allow more connections per pool. Now capped at 10.<commit_after>#Copyright (C) 2011,2012 Colin Rice #This software is licensed under an included MIT license. #See the file entitled LICENSE #If you were not provided with a copy of the license please contact: # Colin Rice colin@daedrum.net import threading class ResourceGenerator: def __init__(self, generate = lambda:None, pool = None, timeout = None): #Pool is a list of items #Generate creates a new item self.generate = generate self.pool = pool self.timeout = timeout def __enter__(self): #Check if an item is available while len(self.pool) > 10: for lock, item in self.pool: if lock.acquire(False): self.lock = lock return item if len(self.pool) > 10: gevent.sleep(0) #Otherwise make a new item (lock, item) = (threading.Lock(), self.generate(self.timeout)) lock.acquire() self.lock = lock self.pool.add((lock,item)) return item def __exit__(self, type, value, traceback): self.lock.release() class Pool: def __init__(self, generate): self.pools = {} self.generate = generate def __call__(self, url, timeout=None): key = url+str(timeout) if url not in self.pools: self.pools[key] = set() return ResourceGenerator(self.generate, pool = self.pools[key], timeout=timeout)
24bac74c13a8bc1a54a2629ed757ab5ce36f133c
fedimg/messenger.py
fedimg/messenger.py
#!/bin/env python # -*- coding: utf8 -*- import fedmsg def message(image_name, dest, status): """ Takes an upload destination (ex. "EC2-east") and a status (ex. "failed"). Emits a fedmsg appropriate for each image upload task. """ fedmsg.publish(topic='image.upload', modname='fedimg', msg={ 'image': image_name, 'destination': dest, 'status': status, })
#!/bin/env python # -*- coding: utf8 -*- import fedmsg def message(image_name, dest, status): """ Takes an upload destination (ex. "EC2-east") and a status (ex. "failed"). Emits a fedmsg appropriate for each image upload task. """ fedmsg.publish(topic='image.upload', modname='fedimg', msg={ 'image_name': image_name, 'destination': dest, 'status': status, })
Make fedmsg message attribute 'image_name', not just 'image'
Make fedmsg message attribute 'image_name', not just 'image'
Python
agpl-3.0
fedora-infra/fedimg,fedora-infra/fedimg
#!/bin/env python # -*- coding: utf8 -*- import fedmsg def message(image_name, dest, status): """ Takes an upload destination (ex. "EC2-east") and a status (ex. "failed"). Emits a fedmsg appropriate for each image upload task. """ fedmsg.publish(topic='image.upload', modname='fedimg', msg={ 'image': image_name, 'destination': dest, 'status': status, }) Make fedmsg message attribute 'image_name', not just 'image'
#!/bin/env python # -*- coding: utf8 -*- import fedmsg def message(image_name, dest, status): """ Takes an upload destination (ex. "EC2-east") and a status (ex. "failed"). Emits a fedmsg appropriate for each image upload task. """ fedmsg.publish(topic='image.upload', modname='fedimg', msg={ 'image_name': image_name, 'destination': dest, 'status': status, })
<commit_before>#!/bin/env python # -*- coding: utf8 -*- import fedmsg def message(image_name, dest, status): """ Takes an upload destination (ex. "EC2-east") and a status (ex. "failed"). Emits a fedmsg appropriate for each image upload task. """ fedmsg.publish(topic='image.upload', modname='fedimg', msg={ 'image': image_name, 'destination': dest, 'status': status, }) <commit_msg>Make fedmsg message attribute 'image_name', not just 'image'<commit_after>
#!/bin/env python # -*- coding: utf8 -*- import fedmsg def message(image_name, dest, status): """ Takes an upload destination (ex. "EC2-east") and a status (ex. "failed"). Emits a fedmsg appropriate for each image upload task. """ fedmsg.publish(topic='image.upload', modname='fedimg', msg={ 'image_name': image_name, 'destination': dest, 'status': status, })
#!/bin/env python # -*- coding: utf8 -*- import fedmsg def message(image_name, dest, status): """ Takes an upload destination (ex. "EC2-east") and a status (ex. "failed"). Emits a fedmsg appropriate for each image upload task. """ fedmsg.publish(topic='image.upload', modname='fedimg', msg={ 'image': image_name, 'destination': dest, 'status': status, }) Make fedmsg message attribute 'image_name', not just 'image'#!/bin/env python # -*- coding: utf8 -*- import fedmsg def message(image_name, dest, status): """ Takes an upload destination (ex. "EC2-east") and a status (ex. "failed"). Emits a fedmsg appropriate for each image upload task. """ fedmsg.publish(topic='image.upload', modname='fedimg', msg={ 'image_name': image_name, 'destination': dest, 'status': status, })
<commit_before>#!/bin/env python # -*- coding: utf8 -*- import fedmsg def message(image_name, dest, status): """ Takes an upload destination (ex. "EC2-east") and a status (ex. "failed"). Emits a fedmsg appropriate for each image upload task. """ fedmsg.publish(topic='image.upload', modname='fedimg', msg={ 'image': image_name, 'destination': dest, 'status': status, }) <commit_msg>Make fedmsg message attribute 'image_name', not just 'image'<commit_after>#!/bin/env python # -*- coding: utf8 -*- import fedmsg def message(image_name, dest, status): """ Takes an upload destination (ex. "EC2-east") and a status (ex. "failed"). Emits a fedmsg appropriate for each image upload task. """ fedmsg.publish(topic='image.upload', modname='fedimg', msg={ 'image_name': image_name, 'destination': dest, 'status': status, })
ce2855d82331fc7bb1ffdb07761d6ad235a1c6c9
transport/tests/test_models.py
transport/tests/test_models.py
from django.test import TestCase from org.models import Organization from ..models import Bus class BusModelTest(TestCase): def setUp(self): self.org = Organization.objects.create( name='Some Org', logo='/media/logos/some-org-logo.jpg', description='We are a familiar condominium', rules='Please check our conduct code page at https://some-url.foo' ) self.bus = Bus.objects.create( name='Bus 1', organization=self.org ) def test_str(self): self.assertEqual('Bus 1', str(self.bus)) def test_can_create(self): self.assertTrue(Bus.objects.exists())
from django.test import TestCase from org.models import Organization from ..models import Bus, Route class BusModelTest(TestCase): def setUp(self): self.org = Organization.objects.create( name='Some Org', logo='/media/logos/some-org-logo.jpg', description='We are a familiar condominium', rules='Please check our conduct code page at https://some-url.foo' ) self.bus = Bus.objects.create( name='Bus 1', organization=self.org ) def test_str(self): self.assertEqual('Bus 1', str(self.bus)) def test_can_create(self): self.assertTrue(Bus.objects.exists()) class RouteModelTest(TestCase): def setUp(self): self.org = Organization.objects.create( name='Some Org', logo='/media/logos/some-org-logo.jpg', description='We are a familiar condominium', rules='Please check our conduct code page at https://some-url.foo' ) self.route = Route.objects.create( name='Route 1', organization=self.org ) def test_str(self): self.assertEqual('Route 1', str(self.route)) def test_can_create(self): self.assertTrue(Route.objects.exists())
Add some Route model tests
Add some Route model tests
Python
mit
arturfelipe/condobus,arturfelipe/condobus,arturfelipe/condobus,arturfelipe/condobus
from django.test import TestCase from org.models import Organization from ..models import Bus class BusModelTest(TestCase): def setUp(self): self.org = Organization.objects.create( name='Some Org', logo='/media/logos/some-org-logo.jpg', description='We are a familiar condominium', rules='Please check our conduct code page at https://some-url.foo' ) self.bus = Bus.objects.create( name='Bus 1', organization=self.org ) def test_str(self): self.assertEqual('Bus 1', str(self.bus)) def test_can_create(self): self.assertTrue(Bus.objects.exists()) Add some Route model tests
from django.test import TestCase from org.models import Organization from ..models import Bus, Route class BusModelTest(TestCase): def setUp(self): self.org = Organization.objects.create( name='Some Org', logo='/media/logos/some-org-logo.jpg', description='We are a familiar condominium', rules='Please check our conduct code page at https://some-url.foo' ) self.bus = Bus.objects.create( name='Bus 1', organization=self.org ) def test_str(self): self.assertEqual('Bus 1', str(self.bus)) def test_can_create(self): self.assertTrue(Bus.objects.exists()) class RouteModelTest(TestCase): def setUp(self): self.org = Organization.objects.create( name='Some Org', logo='/media/logos/some-org-logo.jpg', description='We are a familiar condominium', rules='Please check our conduct code page at https://some-url.foo' ) self.route = Route.objects.create( name='Route 1', organization=self.org ) def test_str(self): self.assertEqual('Route 1', str(self.route)) def test_can_create(self): self.assertTrue(Route.objects.exists())
<commit_before>from django.test import TestCase from org.models import Organization from ..models import Bus class BusModelTest(TestCase): def setUp(self): self.org = Organization.objects.create( name='Some Org', logo='/media/logos/some-org-logo.jpg', description='We are a familiar condominium', rules='Please check our conduct code page at https://some-url.foo' ) self.bus = Bus.objects.create( name='Bus 1', organization=self.org ) def test_str(self): self.assertEqual('Bus 1', str(self.bus)) def test_can_create(self): self.assertTrue(Bus.objects.exists()) <commit_msg>Add some Route model tests<commit_after>
from django.test import TestCase from org.models import Organization from ..models import Bus, Route class BusModelTest(TestCase): def setUp(self): self.org = Organization.objects.create( name='Some Org', logo='/media/logos/some-org-logo.jpg', description='We are a familiar condominium', rules='Please check our conduct code page at https://some-url.foo' ) self.bus = Bus.objects.create( name='Bus 1', organization=self.org ) def test_str(self): self.assertEqual('Bus 1', str(self.bus)) def test_can_create(self): self.assertTrue(Bus.objects.exists()) class RouteModelTest(TestCase): def setUp(self): self.org = Organization.objects.create( name='Some Org', logo='/media/logos/some-org-logo.jpg', description='We are a familiar condominium', rules='Please check our conduct code page at https://some-url.foo' ) self.route = Route.objects.create( name='Route 1', organization=self.org ) def test_str(self): self.assertEqual('Route 1', str(self.route)) def test_can_create(self): self.assertTrue(Route.objects.exists())
from django.test import TestCase from org.models import Organization from ..models import Bus class BusModelTest(TestCase): def setUp(self): self.org = Organization.objects.create( name='Some Org', logo='/media/logos/some-org-logo.jpg', description='We are a familiar condominium', rules='Please check our conduct code page at https://some-url.foo' ) self.bus = Bus.objects.create( name='Bus 1', organization=self.org ) def test_str(self): self.assertEqual('Bus 1', str(self.bus)) def test_can_create(self): self.assertTrue(Bus.objects.exists()) Add some Route model testsfrom django.test import TestCase from org.models import Organization from ..models import Bus, Route class BusModelTest(TestCase): def setUp(self): self.org = Organization.objects.create( name='Some Org', logo='/media/logos/some-org-logo.jpg', description='We are a familiar condominium', rules='Please check our conduct code page at https://some-url.foo' ) self.bus = Bus.objects.create( name='Bus 1', organization=self.org ) def test_str(self): self.assertEqual('Bus 1', str(self.bus)) def test_can_create(self): self.assertTrue(Bus.objects.exists()) class RouteModelTest(TestCase): def setUp(self): self.org = Organization.objects.create( name='Some Org', logo='/media/logos/some-org-logo.jpg', description='We are a familiar condominium', rules='Please check our conduct code page at https://some-url.foo' ) self.route = Route.objects.create( name='Route 1', organization=self.org ) def test_str(self): self.assertEqual('Route 1', str(self.route)) def test_can_create(self): self.assertTrue(Route.objects.exists())
<commit_before>from django.test import TestCase from org.models import Organization from ..models import Bus class BusModelTest(TestCase): def setUp(self): self.org = Organization.objects.create( name='Some Org', logo='/media/logos/some-org-logo.jpg', description='We are a familiar condominium', rules='Please check our conduct code page at https://some-url.foo' ) self.bus = Bus.objects.create( name='Bus 1', organization=self.org ) def test_str(self): self.assertEqual('Bus 1', str(self.bus)) def test_can_create(self): self.assertTrue(Bus.objects.exists()) <commit_msg>Add some Route model tests<commit_after>from django.test import TestCase from org.models import Organization from ..models import Bus, Route class BusModelTest(TestCase): def setUp(self): self.org = Organization.objects.create( name='Some Org', logo='/media/logos/some-org-logo.jpg', description='We are a familiar condominium', rules='Please check our conduct code page at https://some-url.foo' ) self.bus = Bus.objects.create( name='Bus 1', organization=self.org ) def test_str(self): self.assertEqual('Bus 1', str(self.bus)) def test_can_create(self): self.assertTrue(Bus.objects.exists()) class RouteModelTest(TestCase): def setUp(self): self.org = Organization.objects.create( name='Some Org', logo='/media/logos/some-org-logo.jpg', description='We are a familiar condominium', rules='Please check our conduct code page at https://some-url.foo' ) self.route = Route.objects.create( name='Route 1', organization=self.org ) def test_str(self): self.assertEqual('Route 1', str(self.route)) def test_can_create(self): self.assertTrue(Route.objects.exists())
ce5e322367a15198bdbea9d32401b8c779d0e4bf
config.py
config.py
#! /usr/bin/env python import os import warnings import yaml class Config(object): config_fname = "configuration.yaml" def __init__(self, config_fname=None): config_fname = config_fname or self.config_fname fo = open(config_fname, "r") blob = fo.read() fo.close() self.config = yaml.load(blob) def __getattr__(self, attrname): if attrname == "slack_name": warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" % self.config_fname, DeprecationWarning) return self.config[attrname] # This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME SLACK_NAME = os.getenv("SLACK_NAME") if SLACK_NAME is None: SLACK_NAME = Config().slack_name
#! /usr/bin/env python import os import warnings import yaml class Config(object): config_fname = "configuration.yaml" def __init__(self, config_fname=None): config_fname = config_fname or self.config_fname fo = open(config_fname, "r") blob = fo.read() fo.close() self.config = yaml.load(blob) def __getattr__(self, attrname): if attrname == "slack_name": warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" % self.config_fname, DeprecationWarning) return self.config[attrname] def get(self, attrname, fallback=None): try: return self.config[attrname] except KeyError: return fallback # This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME SLACK_NAME = os.getenv("SLACK_NAME") if SLACK_NAME is None: SLACK_NAME = Config().slack_name
Add Config.get() to skip KeyErrors
Add Config.get() to skip KeyErrors Adds common `dict.get()` pattern to our own Config class, to enable use of fallbacks or `None`, as appropriate.
Python
apache-2.0
rossrader/destalinator
#! /usr/bin/env python import os import warnings import yaml class Config(object): config_fname = "configuration.yaml" def __init__(self, config_fname=None): config_fname = config_fname or self.config_fname fo = open(config_fname, "r") blob = fo.read() fo.close() self.config = yaml.load(blob) def __getattr__(self, attrname): if attrname == "slack_name": warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" % self.config_fname, DeprecationWarning) return self.config[attrname] # This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME SLACK_NAME = os.getenv("SLACK_NAME") if SLACK_NAME is None: SLACK_NAME = Config().slack_name Add Config.get() to skip KeyErrors Adds common `dict.get()` pattern to our own Config class, to enable use of fallbacks or `None`, as appropriate.
#! /usr/bin/env python import os import warnings import yaml class Config(object): config_fname = "configuration.yaml" def __init__(self, config_fname=None): config_fname = config_fname or self.config_fname fo = open(config_fname, "r") blob = fo.read() fo.close() self.config = yaml.load(blob) def __getattr__(self, attrname): if attrname == "slack_name": warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" % self.config_fname, DeprecationWarning) return self.config[attrname] def get(self, attrname, fallback=None): try: return self.config[attrname] except KeyError: return fallback # This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME SLACK_NAME = os.getenv("SLACK_NAME") if SLACK_NAME is None: SLACK_NAME = Config().slack_name
<commit_before>#! /usr/bin/env python import os import warnings import yaml class Config(object): config_fname = "configuration.yaml" def __init__(self, config_fname=None): config_fname = config_fname or self.config_fname fo = open(config_fname, "r") blob = fo.read() fo.close() self.config = yaml.load(blob) def __getattr__(self, attrname): if attrname == "slack_name": warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" % self.config_fname, DeprecationWarning) return self.config[attrname] # This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME SLACK_NAME = os.getenv("SLACK_NAME") if SLACK_NAME is None: SLACK_NAME = Config().slack_name <commit_msg>Add Config.get() to skip KeyErrors Adds common `dict.get()` pattern to our own Config class, to enable use of fallbacks or `None`, as appropriate.<commit_after>
#! /usr/bin/env python import os import warnings import yaml class Config(object): config_fname = "configuration.yaml" def __init__(self, config_fname=None): config_fname = config_fname or self.config_fname fo = open(config_fname, "r") blob = fo.read() fo.close() self.config = yaml.load(blob) def __getattr__(self, attrname): if attrname == "slack_name": warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" % self.config_fname, DeprecationWarning) return self.config[attrname] def get(self, attrname, fallback=None): try: return self.config[attrname] except KeyError: return fallback # This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME SLACK_NAME = os.getenv("SLACK_NAME") if SLACK_NAME is None: SLACK_NAME = Config().slack_name
#! /usr/bin/env python import os import warnings import yaml class Config(object): config_fname = "configuration.yaml" def __init__(self, config_fname=None): config_fname = config_fname or self.config_fname fo = open(config_fname, "r") blob = fo.read() fo.close() self.config = yaml.load(blob) def __getattr__(self, attrname): if attrname == "slack_name": warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" % self.config_fname, DeprecationWarning) return self.config[attrname] # This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME SLACK_NAME = os.getenv("SLACK_NAME") if SLACK_NAME is None: SLACK_NAME = Config().slack_name Add Config.get() to skip KeyErrors Adds common `dict.get()` pattern to our own Config class, to enable use of fallbacks or `None`, as appropriate.#! /usr/bin/env python import os import warnings import yaml class Config(object): config_fname = "configuration.yaml" def __init__(self, config_fname=None): config_fname = config_fname or self.config_fname fo = open(config_fname, "r") blob = fo.read() fo.close() self.config = yaml.load(blob) def __getattr__(self, attrname): if attrname == "slack_name": warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" % self.config_fname, DeprecationWarning) return self.config[attrname] def get(self, attrname, fallback=None): try: return self.config[attrname] except KeyError: return fallback # This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME SLACK_NAME = os.getenv("SLACK_NAME") if SLACK_NAME is None: SLACK_NAME = Config().slack_name
<commit_before>#! /usr/bin/env python import os import warnings import yaml class Config(object): config_fname = "configuration.yaml" def __init__(self, config_fname=None): config_fname = config_fname or self.config_fname fo = open(config_fname, "r") blob = fo.read() fo.close() self.config = yaml.load(blob) def __getattr__(self, attrname): if attrname == "slack_name": warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" % self.config_fname, DeprecationWarning) return self.config[attrname] # This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME SLACK_NAME = os.getenv("SLACK_NAME") if SLACK_NAME is None: SLACK_NAME = Config().slack_name <commit_msg>Add Config.get() to skip KeyErrors Adds common `dict.get()` pattern to our own Config class, to enable use of fallbacks or `None`, as appropriate.<commit_after>#! /usr/bin/env python import os import warnings import yaml class Config(object): config_fname = "configuration.yaml" def __init__(self, config_fname=None): config_fname = config_fname or self.config_fname fo = open(config_fname, "r") blob = fo.read() fo.close() self.config = yaml.load(blob) def __getattr__(self, attrname): if attrname == "slack_name": warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" % self.config_fname, DeprecationWarning) return self.config[attrname] def get(self, attrname, fallback=None): try: return self.config[attrname] except KeyError: return fallback # This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME SLACK_NAME = os.getenv("SLACK_NAME") if SLACK_NAME is None: SLACK_NAME = Config().slack_name
e63e2ddb84a8716da1568f82119db46f9d723a11
students/urls.py
students/urls.py
from django.conf.urls import include, url from . import views app_name = "students" urlpatterns = [ url(r'^home/$', views.home, name='home'), url(r'^booking/$', views.booking, name='booking'), url(r'^booking/list/$', views.booking_list, name='list_booking'), url(r'^booking/(?P<booking_id>[\d]+)/delete/$', views.booking_delete, name='delete_booking'), # TODO: overidden registration urls come before the include below url(r'^accounts/register/$', views.ExclusiveRegistrationView.as_view(), name='registration_register'), url(r'^accounts/', include('registration.backends.simple.urls')), ]
from django.conf.urls import include, url from . import views app_name = "students" urlpatterns = [ url(r'^home/$', views.home, name='home'), url(r'^booking/$', views.booking, name='booking'), url(r'^booking/list/$', views.booking_list, name='list_booking'), url(r'^booking/listall/(?P<booking_date>\d{2}\.{1}[a-zA-Z]+\.{1}\d{4})/$', views.booking_listall, name='listall_booking'), url(r'^booking/(?P<booking_id>[\d]+)/delete/$', views.booking_delete, name='delete_booking'), # TODO: overidden registration urls come before the include below url(r'^accounts/register/$', views.ExclusiveRegistrationView.as_view(), name='registration_register'), url(r'^accounts/', include('registration.backends.simple.urls')), ]
Add url for 'list all bookings' view.
Add url for 'list all bookings' view.
Python
mit
muhummadPatel/raspied,muhummadPatel/raspied,muhummadPatel/raspied
from django.conf.urls import include, url from . import views app_name = "students" urlpatterns = [ url(r'^home/$', views.home, name='home'), url(r'^booking/$', views.booking, name='booking'), url(r'^booking/list/$', views.booking_list, name='list_booking'), url(r'^booking/(?P<booking_id>[\d]+)/delete/$', views.booking_delete, name='delete_booking'), # TODO: overidden registration urls come before the include below url(r'^accounts/register/$', views.ExclusiveRegistrationView.as_view(), name='registration_register'), url(r'^accounts/', include('registration.backends.simple.urls')), ] Add url for 'list all bookings' view.
from django.conf.urls import include, url from . import views app_name = "students" urlpatterns = [ url(r'^home/$', views.home, name='home'), url(r'^booking/$', views.booking, name='booking'), url(r'^booking/list/$', views.booking_list, name='list_booking'), url(r'^booking/listall/(?P<booking_date>\d{2}\.{1}[a-zA-Z]+\.{1}\d{4})/$', views.booking_listall, name='listall_booking'), url(r'^booking/(?P<booking_id>[\d]+)/delete/$', views.booking_delete, name='delete_booking'), # TODO: overidden registration urls come before the include below url(r'^accounts/register/$', views.ExclusiveRegistrationView.as_view(), name='registration_register'), url(r'^accounts/', include('registration.backends.simple.urls')), ]
<commit_before>from django.conf.urls import include, url from . import views app_name = "students" urlpatterns = [ url(r'^home/$', views.home, name='home'), url(r'^booking/$', views.booking, name='booking'), url(r'^booking/list/$', views.booking_list, name='list_booking'), url(r'^booking/(?P<booking_id>[\d]+)/delete/$', views.booking_delete, name='delete_booking'), # TODO: overidden registration urls come before the include below url(r'^accounts/register/$', views.ExclusiveRegistrationView.as_view(), name='registration_register'), url(r'^accounts/', include('registration.backends.simple.urls')), ] <commit_msg>Add url for 'list all bookings' view.<commit_after>
from django.conf.urls import include, url from . import views app_name = "students" urlpatterns = [ url(r'^home/$', views.home, name='home'), url(r'^booking/$', views.booking, name='booking'), url(r'^booking/list/$', views.booking_list, name='list_booking'), url(r'^booking/listall/(?P<booking_date>\d{2}\.{1}[a-zA-Z]+\.{1}\d{4})/$', views.booking_listall, name='listall_booking'), url(r'^booking/(?P<booking_id>[\d]+)/delete/$', views.booking_delete, name='delete_booking'), # TODO: overidden registration urls come before the include below url(r'^accounts/register/$', views.ExclusiveRegistrationView.as_view(), name='registration_register'), url(r'^accounts/', include('registration.backends.simple.urls')), ]
from django.conf.urls import include, url from . import views app_name = "students" urlpatterns = [ url(r'^home/$', views.home, name='home'), url(r'^booking/$', views.booking, name='booking'), url(r'^booking/list/$', views.booking_list, name='list_booking'), url(r'^booking/(?P<booking_id>[\d]+)/delete/$', views.booking_delete, name='delete_booking'), # TODO: overidden registration urls come before the include below url(r'^accounts/register/$', views.ExclusiveRegistrationView.as_view(), name='registration_register'), url(r'^accounts/', include('registration.backends.simple.urls')), ] Add url for 'list all bookings' view.from django.conf.urls import include, url from . import views app_name = "students" urlpatterns = [ url(r'^home/$', views.home, name='home'), url(r'^booking/$', views.booking, name='booking'), url(r'^booking/list/$', views.booking_list, name='list_booking'), url(r'^booking/listall/(?P<booking_date>\d{2}\.{1}[a-zA-Z]+\.{1}\d{4})/$', views.booking_listall, name='listall_booking'), url(r'^booking/(?P<booking_id>[\d]+)/delete/$', views.booking_delete, name='delete_booking'), # TODO: overidden registration urls come before the include below url(r'^accounts/register/$', views.ExclusiveRegistrationView.as_view(), name='registration_register'), url(r'^accounts/', include('registration.backends.simple.urls')), ]
<commit_before>from django.conf.urls import include, url from . import views app_name = "students" urlpatterns = [ url(r'^home/$', views.home, name='home'), url(r'^booking/$', views.booking, name='booking'), url(r'^booking/list/$', views.booking_list, name='list_booking'), url(r'^booking/(?P<booking_id>[\d]+)/delete/$', views.booking_delete, name='delete_booking'), # TODO: overidden registration urls come before the include below url(r'^accounts/register/$', views.ExclusiveRegistrationView.as_view(), name='registration_register'), url(r'^accounts/', include('registration.backends.simple.urls')), ] <commit_msg>Add url for 'list all bookings' view.<commit_after>from django.conf.urls import include, url from . import views app_name = "students" urlpatterns = [ url(r'^home/$', views.home, name='home'), url(r'^booking/$', views.booking, name='booking'), url(r'^booking/list/$', views.booking_list, name='list_booking'), url(r'^booking/listall/(?P<booking_date>\d{2}\.{1}[a-zA-Z]+\.{1}\d{4})/$', views.booking_listall, name='listall_booking'), url(r'^booking/(?P<booking_id>[\d]+)/delete/$', views.booking_delete, name='delete_booking'), # TODO: overidden registration urls come before the include below url(r'^accounts/register/$', views.ExclusiveRegistrationView.as_view(), name='registration_register'), url(r'^accounts/', include('registration.backends.simple.urls')), ]
35af07bc99c7527b84e11a8632bfb396823326f3
backlog/__init__.py
backlog/__init__.py
__version__ = (0, 2, 2, '', 0) def get_version(): version = '%d.%d.%d' % __version__[0:3] if __version__[3]: version = '%s-%s%s' % (version, __version__[3], (__version__[4] and str(__version__[4])) or '') return version
__version__ = (0, 2, 3, 'dev', 0) def get_version(): version = '%d.%d.%d' % __version__[0:3] if __version__[3]: version = '%s-%s%s' % (version, __version__[3], (__version__[4] and str(__version__[4])) or '') return version
Set the next patch release number
Set the next patch release number
Python
bsd-3-clause
jszakmeister/trac-backlog,jszakmeister/trac-backlog
__version__ = (0, 2, 2, '', 0) def get_version(): version = '%d.%d.%d' % __version__[0:3] if __version__[3]: version = '%s-%s%s' % (version, __version__[3], (__version__[4] and str(__version__[4])) or '') return version Set the next patch release number
__version__ = (0, 2, 3, 'dev', 0) def get_version(): version = '%d.%d.%d' % __version__[0:3] if __version__[3]: version = '%s-%s%s' % (version, __version__[3], (__version__[4] and str(__version__[4])) or '') return version
<commit_before>__version__ = (0, 2, 2, '', 0) def get_version(): version = '%d.%d.%d' % __version__[0:3] if __version__[3]: version = '%s-%s%s' % (version, __version__[3], (__version__[4] and str(__version__[4])) or '') return version <commit_msg>Set the next patch release number<commit_after>
__version__ = (0, 2, 3, 'dev', 0) def get_version(): version = '%d.%d.%d' % __version__[0:3] if __version__[3]: version = '%s-%s%s' % (version, __version__[3], (__version__[4] and str(__version__[4])) or '') return version
__version__ = (0, 2, 2, '', 0) def get_version(): version = '%d.%d.%d' % __version__[0:3] if __version__[3]: version = '%s-%s%s' % (version, __version__[3], (__version__[4] and str(__version__[4])) or '') return version Set the next patch release number__version__ = (0, 2, 3, 'dev', 0) def get_version(): version = '%d.%d.%d' % __version__[0:3] if __version__[3]: version = '%s-%s%s' % (version, __version__[3], (__version__[4] and str(__version__[4])) or '') return version
<commit_before>__version__ = (0, 2, 2, '', 0) def get_version(): version = '%d.%d.%d' % __version__[0:3] if __version__[3]: version = '%s-%s%s' % (version, __version__[3], (__version__[4] and str(__version__[4])) or '') return version <commit_msg>Set the next patch release number<commit_after>__version__ = (0, 2, 3, 'dev', 0) def get_version(): version = '%d.%d.%d' % __version__[0:3] if __version__[3]: version = '%s-%s%s' % (version, __version__[3], (__version__[4] and str(__version__[4])) or '') return version
a138d7126acd1418e4bec47aeecf5a96076d1acf
djangae/contrib/backup/urls.py
djangae/contrib/backup/urls.py
from django.conf.urls import include, url from . import views urlpatterns = ( url( '^create-datastore-backup$', views.create_datastore_backup, name="create_datastore_backup" ), )
from django.conf.urls import url from . import views urlpatterns = ( url( '^create-datastore-backup/?$', views.create_datastore_backup, name="create_datastore_backup" ), )
Fix the backup url to match the docs (and retain backwards compatibility)
Fix the backup url to match the docs (and retain backwards compatibility)
Python
bsd-3-clause
potatolondon/djangae,potatolondon/djangae
from django.conf.urls import include, url from . import views urlpatterns = ( url( '^create-datastore-backup$', views.create_datastore_backup, name="create_datastore_backup" ), ) Fix the backup url to match the docs (and retain backwards compatibility)
from django.conf.urls import url from . import views urlpatterns = ( url( '^create-datastore-backup/?$', views.create_datastore_backup, name="create_datastore_backup" ), )
<commit_before>from django.conf.urls import include, url from . import views urlpatterns = ( url( '^create-datastore-backup$', views.create_datastore_backup, name="create_datastore_backup" ), ) <commit_msg>Fix the backup url to match the docs (and retain backwards compatibility)<commit_after>
from django.conf.urls import url from . import views urlpatterns = ( url( '^create-datastore-backup/?$', views.create_datastore_backup, name="create_datastore_backup" ), )
from django.conf.urls import include, url from . import views urlpatterns = ( url( '^create-datastore-backup$', views.create_datastore_backup, name="create_datastore_backup" ), ) Fix the backup url to match the docs (and retain backwards compatibility)from django.conf.urls import url from . import views urlpatterns = ( url( '^create-datastore-backup/?$', views.create_datastore_backup, name="create_datastore_backup" ), )
<commit_before>from django.conf.urls import include, url from . import views urlpatterns = ( url( '^create-datastore-backup$', views.create_datastore_backup, name="create_datastore_backup" ), ) <commit_msg>Fix the backup url to match the docs (and retain backwards compatibility)<commit_after>from django.conf.urls import url from . import views urlpatterns = ( url( '^create-datastore-backup/?$', views.create_datastore_backup, name="create_datastore_backup" ), )
9c2efa3df7d39ef6724fb031d0bb674eb7195b2e
tv-script-generation/helper.py
tv-script-generation/helper.py
import os import pickle def load_data(path): """ Load Dataset from File """ input_file = os.path.join(path) with open(input_file, "r") as f: data = f.read() return data def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables): """ Preprocess Text Data """ text = load_data(dataset_path) token_dict = token_lookup() for key, token in token_dict.items(): text = text.replace(key, ' {} '.format(token)) text = text.lower() text = text.split() vocab_to_int, int_to_vocab = create_lookup_tables(text) int_text = [vocab_to_int[word] for word in text] pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('preprocess.p', 'wb')) def load_preprocess(): """ Load the Preprocessed Training data and return them in batches of <batch_size> or less """ return pickle.load(open('preprocess.p', mode='rb')) def save_params(params): """ Save parameters to file """ pickle.dump(params, open('params.p', 'wb')) def load_params(): """ Load parameters from file """ return pickle.load(open('params.p', mode='rb'))
import os import pickle def load_data(path): """ Load Dataset from File """ input_file = os.path.join(path) with open(input_file, "r") as f: data = f.read() return data def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables): """ Preprocess Text Data """ text = load_data(dataset_path) # Ignore notice, since we don't use it for analysing the data text = text[81:] token_dict = token_lookup() for key, token in token_dict.items(): text = text.replace(key, ' {} '.format(token)) text = text.lower() text = text.split() vocab_to_int, int_to_vocab = create_lookup_tables(text) int_text = [vocab_to_int[word] for word in text] pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('preprocess.p', 'wb')) def load_preprocess(): """ Load the Preprocessed Training data and return them in batches of <batch_size> or less """ return pickle.load(open('preprocess.p', mode='rb')) def save_params(params): """ Save parameters to file """ pickle.dump(params, open('params.p', 'wb')) def load_params(): """ Load parameters from file """ return pickle.load(open('params.p', mode='rb'))
Remove copyright notice during preprocessing
Remove copyright notice during preprocessing
Python
mit
elenduuche/deep-learning,elenduuche/deep-learning
import os import pickle def load_data(path): """ Load Dataset from File """ input_file = os.path.join(path) with open(input_file, "r") as f: data = f.read() return data def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables): """ Preprocess Text Data """ text = load_data(dataset_path) token_dict = token_lookup() for key, token in token_dict.items(): text = text.replace(key, ' {} '.format(token)) text = text.lower() text = text.split() vocab_to_int, int_to_vocab = create_lookup_tables(text) int_text = [vocab_to_int[word] for word in text] pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('preprocess.p', 'wb')) def load_preprocess(): """ Load the Preprocessed Training data and return them in batches of <batch_size> or less """ return pickle.load(open('preprocess.p', mode='rb')) def save_params(params): """ Save parameters to file """ pickle.dump(params, open('params.p', 'wb')) def load_params(): """ Load parameters from file """ return pickle.load(open('params.p', mode='rb')) Remove copyright notice during preprocessing
import os import pickle def load_data(path): """ Load Dataset from File """ input_file = os.path.join(path) with open(input_file, "r") as f: data = f.read() return data def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables): """ Preprocess Text Data """ text = load_data(dataset_path) # Ignore notice, since we don't use it for analysing the data text = text[81:] token_dict = token_lookup() for key, token in token_dict.items(): text = text.replace(key, ' {} '.format(token)) text = text.lower() text = text.split() vocab_to_int, int_to_vocab = create_lookup_tables(text) int_text = [vocab_to_int[word] for word in text] pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('preprocess.p', 'wb')) def load_preprocess(): """ Load the Preprocessed Training data and return them in batches of <batch_size> or less """ return pickle.load(open('preprocess.p', mode='rb')) def save_params(params): """ Save parameters to file """ pickle.dump(params, open('params.p', 'wb')) def load_params(): """ Load parameters from file """ return pickle.load(open('params.p', mode='rb'))
<commit_before>import os import pickle def load_data(path): """ Load Dataset from File """ input_file = os.path.join(path) with open(input_file, "r") as f: data = f.read() return data def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables): """ Preprocess Text Data """ text = load_data(dataset_path) token_dict = token_lookup() for key, token in token_dict.items(): text = text.replace(key, ' {} '.format(token)) text = text.lower() text = text.split() vocab_to_int, int_to_vocab = create_lookup_tables(text) int_text = [vocab_to_int[word] for word in text] pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('preprocess.p', 'wb')) def load_preprocess(): """ Load the Preprocessed Training data and return them in batches of <batch_size> or less """ return pickle.load(open('preprocess.p', mode='rb')) def save_params(params): """ Save parameters to file """ pickle.dump(params, open('params.p', 'wb')) def load_params(): """ Load parameters from file """ return pickle.load(open('params.p', mode='rb')) <commit_msg>Remove copyright notice during preprocessing<commit_after>
import os import pickle def load_data(path): """ Load Dataset from File """ input_file = os.path.join(path) with open(input_file, "r") as f: data = f.read() return data def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables): """ Preprocess Text Data """ text = load_data(dataset_path) # Ignore notice, since we don't use it for analysing the data text = text[81:] token_dict = token_lookup() for key, token in token_dict.items(): text = text.replace(key, ' {} '.format(token)) text = text.lower() text = text.split() vocab_to_int, int_to_vocab = create_lookup_tables(text) int_text = [vocab_to_int[word] for word in text] pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('preprocess.p', 'wb')) def load_preprocess(): """ Load the Preprocessed Training data and return them in batches of <batch_size> or less """ return pickle.load(open('preprocess.p', mode='rb')) def save_params(params): """ Save parameters to file """ pickle.dump(params, open('params.p', 'wb')) def load_params(): """ Load parameters from file """ return pickle.load(open('params.p', mode='rb'))
import os import pickle def load_data(path): """ Load Dataset from File """ input_file = os.path.join(path) with open(input_file, "r") as f: data = f.read() return data def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables): """ Preprocess Text Data """ text = load_data(dataset_path) token_dict = token_lookup() for key, token in token_dict.items(): text = text.replace(key, ' {} '.format(token)) text = text.lower() text = text.split() vocab_to_int, int_to_vocab = create_lookup_tables(text) int_text = [vocab_to_int[word] for word in text] pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('preprocess.p', 'wb')) def load_preprocess(): """ Load the Preprocessed Training data and return them in batches of <batch_size> or less """ return pickle.load(open('preprocess.p', mode='rb')) def save_params(params): """ Save parameters to file """ pickle.dump(params, open('params.p', 'wb')) def load_params(): """ Load parameters from file """ return pickle.load(open('params.p', mode='rb')) Remove copyright notice during preprocessingimport os import pickle def load_data(path): """ Load Dataset from File """ input_file = os.path.join(path) with open(input_file, "r") as f: data = f.read() return data def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables): """ Preprocess Text Data """ text = load_data(dataset_path) # Ignore notice, since we don't use it for analysing the data text = text[81:] token_dict = token_lookup() for key, token in token_dict.items(): text = text.replace(key, ' {} '.format(token)) text = text.lower() text = text.split() vocab_to_int, int_to_vocab = create_lookup_tables(text) int_text = [vocab_to_int[word] for word in text] pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('preprocess.p', 'wb')) def load_preprocess(): """ Load the Preprocessed Training data and return them in batches of <batch_size> or less """ return pickle.load(open('preprocess.p', mode='rb')) def save_params(params): """ Save parameters to file """ pickle.dump(params, open('params.p', 'wb')) def load_params(): """ Load parameters from file """ return pickle.load(open('params.p', mode='rb'))
<commit_before>import os import pickle def load_data(path): """ Load Dataset from File """ input_file = os.path.join(path) with open(input_file, "r") as f: data = f.read() return data def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables): """ Preprocess Text Data """ text = load_data(dataset_path) token_dict = token_lookup() for key, token in token_dict.items(): text = text.replace(key, ' {} '.format(token)) text = text.lower() text = text.split() vocab_to_int, int_to_vocab = create_lookup_tables(text) int_text = [vocab_to_int[word] for word in text] pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('preprocess.p', 'wb')) def load_preprocess(): """ Load the Preprocessed Training data and return them in batches of <batch_size> or less """ return pickle.load(open('preprocess.p', mode='rb')) def save_params(params): """ Save parameters to file """ pickle.dump(params, open('params.p', 'wb')) def load_params(): """ Load parameters from file """ return pickle.load(open('params.p', mode='rb')) <commit_msg>Remove copyright notice during preprocessing<commit_after>import os import pickle def load_data(path): """ Load Dataset from File """ input_file = os.path.join(path) with open(input_file, "r") as f: data = f.read() return data def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables): """ Preprocess Text Data """ text = load_data(dataset_path) # Ignore notice, since we don't use it for analysing the data text = text[81:] token_dict = token_lookup() for key, token in token_dict.items(): text = text.replace(key, ' {} '.format(token)) text = text.lower() text = text.split() vocab_to_int, int_to_vocab = create_lookup_tables(text) int_text = [vocab_to_int[word] for word in text] pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('preprocess.p', 'wb')) def load_preprocess(): """ Load the Preprocessed Training data and return them in batches of <batch_size> or less """ return pickle.load(open('preprocess.p', mode='rb')) def save_params(params): """ Save parameters to file """ pickle.dump(params, open('params.p', 'wb')) def load_params(): """ Load parameters from file """ return pickle.load(open('params.p', mode='rb'))
6bc25787dec8530b20db0a43b754c04f0170b9d8
symfit/api.py
symfit/api.py
# Overwrite behavior of sympy objects to make more sense for this project. import symfit.core.operators # Expose useful objects. from symfit.core.fit import ( Fit, Model, Constraint, ODEModel, ModelError, CallableModel, CallableNumericalModel ) from symfit.core.fit_results import FitResults from symfit.core.argument import Variable, Parameter from symfit.core.support import variables, parameters, D # Expose the sympy API from sympy import *
# Overwrite behavior of sympy objects to make more sense for this project. import symfit.core.operators # Expose useful objects. from symfit.core.fit import ( Fit, Model, Constraint, ODEModel, ModelError, CallableModel, CallableNumericalModel, GradientModel ) from symfit.core.fit_results import FitResults from symfit.core.argument import Variable, Parameter from symfit.core.support import variables, parameters, D # Expose the sympy API from sympy import *
Add GradientModel to the API
Add GradientModel to the API
Python
mit
tBuLi/symfit
# Overwrite behavior of sympy objects to make more sense for this project. import symfit.core.operators # Expose useful objects. from symfit.core.fit import ( Fit, Model, Constraint, ODEModel, ModelError, CallableModel, CallableNumericalModel ) from symfit.core.fit_results import FitResults from symfit.core.argument import Variable, Parameter from symfit.core.support import variables, parameters, D # Expose the sympy API from sympy import *Add GradientModel to the API
# Overwrite behavior of sympy objects to make more sense for this project. import symfit.core.operators # Expose useful objects. from symfit.core.fit import ( Fit, Model, Constraint, ODEModel, ModelError, CallableModel, CallableNumericalModel, GradientModel ) from symfit.core.fit_results import FitResults from symfit.core.argument import Variable, Parameter from symfit.core.support import variables, parameters, D # Expose the sympy API from sympy import *
<commit_before># Overwrite behavior of sympy objects to make more sense for this project. import symfit.core.operators # Expose useful objects. from symfit.core.fit import ( Fit, Model, Constraint, ODEModel, ModelError, CallableModel, CallableNumericalModel ) from symfit.core.fit_results import FitResults from symfit.core.argument import Variable, Parameter from symfit.core.support import variables, parameters, D # Expose the sympy API from sympy import *<commit_msg>Add GradientModel to the API<commit_after>
# Overwrite behavior of sympy objects to make more sense for this project. import symfit.core.operators # Expose useful objects. from symfit.core.fit import ( Fit, Model, Constraint, ODEModel, ModelError, CallableModel, CallableNumericalModel, GradientModel ) from symfit.core.fit_results import FitResults from symfit.core.argument import Variable, Parameter from symfit.core.support import variables, parameters, D # Expose the sympy API from sympy import *
# Overwrite behavior of sympy objects to make more sense for this project. import symfit.core.operators # Expose useful objects. from symfit.core.fit import ( Fit, Model, Constraint, ODEModel, ModelError, CallableModel, CallableNumericalModel ) from symfit.core.fit_results import FitResults from symfit.core.argument import Variable, Parameter from symfit.core.support import variables, parameters, D # Expose the sympy API from sympy import *Add GradientModel to the API# Overwrite behavior of sympy objects to make more sense for this project. import symfit.core.operators # Expose useful objects. from symfit.core.fit import ( Fit, Model, Constraint, ODEModel, ModelError, CallableModel, CallableNumericalModel, GradientModel ) from symfit.core.fit_results import FitResults from symfit.core.argument import Variable, Parameter from symfit.core.support import variables, parameters, D # Expose the sympy API from sympy import *
<commit_before># Overwrite behavior of sympy objects to make more sense for this project. import symfit.core.operators # Expose useful objects. from symfit.core.fit import ( Fit, Model, Constraint, ODEModel, ModelError, CallableModel, CallableNumericalModel ) from symfit.core.fit_results import FitResults from symfit.core.argument import Variable, Parameter from symfit.core.support import variables, parameters, D # Expose the sympy API from sympy import *<commit_msg>Add GradientModel to the API<commit_after># Overwrite behavior of sympy objects to make more sense for this project. import symfit.core.operators # Expose useful objects. from symfit.core.fit import ( Fit, Model, Constraint, ODEModel, ModelError, CallableModel, CallableNumericalModel, GradientModel ) from symfit.core.fit_results import FitResults from symfit.core.argument import Variable, Parameter from symfit.core.support import variables, parameters, D # Expose the sympy API from sympy import *
169b5ec57404360d0c9c1c438aa357f62f61b9cf
contrib/chatops/actions/format_result.py
contrib/chatops/actions/format_result.py
import jinja2 import six import os from st2actions.runners.pythonrunner import Action from st2client.client import Client class FormatResultAction(Action): def __init__(self, config): super(FormatResultAction, self).__init__(config) api_url = os.environ.get('ST2_ACTION_API_URL', None) token = os.environ.get('ST2_ACTION_AUTH_TOKEN', None) self.client = Client(api_url=api_url, token=token) self.jinja = jinja2.Environment(trim_blocks=True, lstrip_blocks=True) self.jinja.tests['in'] = lambda item, list: item in list path = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(path, 'templates/default.j2'), 'r') as f: self.default_template = f.read() def run(self, execution): context = { 'six': six, 'execution': execution } template = self.default_template alias_id = execution['context'].get('action_alias_ref', {}).get('id', None) if alias_id: alias = self.client.managers['ActionAlias'].get_by_id(alias_id) context.update({ 'alias': alias }) result = getattr(alias, 'result', None) if result: enabled = result.get('enabled', True) if enabled and 'format' in alias.result: template = alias.result['format'] return self.jinja.from_string(template).render(context)
import jinja2 import six import os from st2actions.runners.pythonrunner import Action from st2client.client import Client class FormatResultAction(Action): def __init__(self, config): super(FormatResultAction, self).__init__(config) api_url = os.environ.get('ST2_ACTION_API_URL', None) token = os.environ.get('ST2_ACTION_AUTH_TOKEN', None) self.client = Client(api_url=api_url, token=token) self.jinja = jinja2.Environment(trim_blocks=True, lstrip_blocks=True) self.jinja.tests['in'] = lambda item, list: item in list path = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(path, 'templates/default.j2'), 'r') as f: self.default_template = f.read() def run(self, execution): context = { 'six': six, 'execution': execution } template = self.default_template alias_id = execution['context'].get('action_alias_ref', {}).get('id', None) if alias_id: alias = self.client.managers['ActionAlias'].get_by_id(alias_id) context.update({ 'alias': alias }) result = getattr(alias, 'result', None) if result: if not result.get('enabled', True): return "" if 'format' in alias.result: template = alias.result['format'] return self.jinja.from_string(template).render(context)
Return empty string if result output is disabled
Return empty string if result output is disabled
Python
apache-2.0
StackStorm/st2,pixelrebel/st2,emedvedev/st2,peak6/st2,Plexxi/st2,Plexxi/st2,lakshmi-kannan/st2,lakshmi-kannan/st2,punalpatel/st2,emedvedev/st2,dennybaa/st2,punalpatel/st2,nzlosh/st2,nzlosh/st2,peak6/st2,peak6/st2,StackStorm/st2,armab/st2,StackStorm/st2,punalpatel/st2,emedvedev/st2,nzlosh/st2,Plexxi/st2,tonybaloney/st2,armab/st2,tonybaloney/st2,nzlosh/st2,armab/st2,dennybaa/st2,lakshmi-kannan/st2,pixelrebel/st2,Plexxi/st2,pixelrebel/st2,StackStorm/st2,tonybaloney/st2,dennybaa/st2
import jinja2 import six import os from st2actions.runners.pythonrunner import Action from st2client.client import Client class FormatResultAction(Action): def __init__(self, config): super(FormatResultAction, self).__init__(config) api_url = os.environ.get('ST2_ACTION_API_URL', None) token = os.environ.get('ST2_ACTION_AUTH_TOKEN', None) self.client = Client(api_url=api_url, token=token) self.jinja = jinja2.Environment(trim_blocks=True, lstrip_blocks=True) self.jinja.tests['in'] = lambda item, list: item in list path = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(path, 'templates/default.j2'), 'r') as f: self.default_template = f.read() def run(self, execution): context = { 'six': six, 'execution': execution } template = self.default_template alias_id = execution['context'].get('action_alias_ref', {}).get('id', None) if alias_id: alias = self.client.managers['ActionAlias'].get_by_id(alias_id) context.update({ 'alias': alias }) result = getattr(alias, 'result', None) if result: enabled = result.get('enabled', True) if enabled and 'format' in alias.result: template = alias.result['format'] return self.jinja.from_string(template).render(context) Return empty string if result output is disabled
import jinja2 import six import os from st2actions.runners.pythonrunner import Action from st2client.client import Client class FormatResultAction(Action): def __init__(self, config): super(FormatResultAction, self).__init__(config) api_url = os.environ.get('ST2_ACTION_API_URL', None) token = os.environ.get('ST2_ACTION_AUTH_TOKEN', None) self.client = Client(api_url=api_url, token=token) self.jinja = jinja2.Environment(trim_blocks=True, lstrip_blocks=True) self.jinja.tests['in'] = lambda item, list: item in list path = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(path, 'templates/default.j2'), 'r') as f: self.default_template = f.read() def run(self, execution): context = { 'six': six, 'execution': execution } template = self.default_template alias_id = execution['context'].get('action_alias_ref', {}).get('id', None) if alias_id: alias = self.client.managers['ActionAlias'].get_by_id(alias_id) context.update({ 'alias': alias }) result = getattr(alias, 'result', None) if result: if not result.get('enabled', True): return "" if 'format' in alias.result: template = alias.result['format'] return self.jinja.from_string(template).render(context)
<commit_before>import jinja2 import six import os from st2actions.runners.pythonrunner import Action from st2client.client import Client class FormatResultAction(Action): def __init__(self, config): super(FormatResultAction, self).__init__(config) api_url = os.environ.get('ST2_ACTION_API_URL', None) token = os.environ.get('ST2_ACTION_AUTH_TOKEN', None) self.client = Client(api_url=api_url, token=token) self.jinja = jinja2.Environment(trim_blocks=True, lstrip_blocks=True) self.jinja.tests['in'] = lambda item, list: item in list path = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(path, 'templates/default.j2'), 'r') as f: self.default_template = f.read() def run(self, execution): context = { 'six': six, 'execution': execution } template = self.default_template alias_id = execution['context'].get('action_alias_ref', {}).get('id', None) if alias_id: alias = self.client.managers['ActionAlias'].get_by_id(alias_id) context.update({ 'alias': alias }) result = getattr(alias, 'result', None) if result: enabled = result.get('enabled', True) if enabled and 'format' in alias.result: template = alias.result['format'] return self.jinja.from_string(template).render(context) <commit_msg>Return empty string if result output is disabled<commit_after>
import jinja2 import six import os from st2actions.runners.pythonrunner import Action from st2client.client import Client class FormatResultAction(Action): def __init__(self, config): super(FormatResultAction, self).__init__(config) api_url = os.environ.get('ST2_ACTION_API_URL', None) token = os.environ.get('ST2_ACTION_AUTH_TOKEN', None) self.client = Client(api_url=api_url, token=token) self.jinja = jinja2.Environment(trim_blocks=True, lstrip_blocks=True) self.jinja.tests['in'] = lambda item, list: item in list path = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(path, 'templates/default.j2'), 'r') as f: self.default_template = f.read() def run(self, execution): context = { 'six': six, 'execution': execution } template = self.default_template alias_id = execution['context'].get('action_alias_ref', {}).get('id', None) if alias_id: alias = self.client.managers['ActionAlias'].get_by_id(alias_id) context.update({ 'alias': alias }) result = getattr(alias, 'result', None) if result: if not result.get('enabled', True): return "" if 'format' in alias.result: template = alias.result['format'] return self.jinja.from_string(template).render(context)
import jinja2 import six import os from st2actions.runners.pythonrunner import Action from st2client.client import Client class FormatResultAction(Action): def __init__(self, config): super(FormatResultAction, self).__init__(config) api_url = os.environ.get('ST2_ACTION_API_URL', None) token = os.environ.get('ST2_ACTION_AUTH_TOKEN', None) self.client = Client(api_url=api_url, token=token) self.jinja = jinja2.Environment(trim_blocks=True, lstrip_blocks=True) self.jinja.tests['in'] = lambda item, list: item in list path = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(path, 'templates/default.j2'), 'r') as f: self.default_template = f.read() def run(self, execution): context = { 'six': six, 'execution': execution } template = self.default_template alias_id = execution['context'].get('action_alias_ref', {}).get('id', None) if alias_id: alias = self.client.managers['ActionAlias'].get_by_id(alias_id) context.update({ 'alias': alias }) result = getattr(alias, 'result', None) if result: enabled = result.get('enabled', True) if enabled and 'format' in alias.result: template = alias.result['format'] return self.jinja.from_string(template).render(context) Return empty string if result output is disabledimport jinja2 import six import os from st2actions.runners.pythonrunner import Action from st2client.client import Client class FormatResultAction(Action): def __init__(self, config): super(FormatResultAction, self).__init__(config) api_url = os.environ.get('ST2_ACTION_API_URL', None) token = os.environ.get('ST2_ACTION_AUTH_TOKEN', None) self.client = Client(api_url=api_url, token=token) self.jinja = jinja2.Environment(trim_blocks=True, lstrip_blocks=True) self.jinja.tests['in'] = lambda item, list: item in list path = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(path, 'templates/default.j2'), 'r') as f: self.default_template = f.read() def run(self, execution): context = { 'six': six, 'execution': execution } template = self.default_template alias_id = execution['context'].get('action_alias_ref', {}).get('id', None) if alias_id: alias = self.client.managers['ActionAlias'].get_by_id(alias_id) context.update({ 'alias': alias }) result = getattr(alias, 'result', None) if result: if not result.get('enabled', True): return "" if 'format' in alias.result: template = alias.result['format'] return self.jinja.from_string(template).render(context)
<commit_before>import jinja2 import six import os from st2actions.runners.pythonrunner import Action from st2client.client import Client class FormatResultAction(Action): def __init__(self, config): super(FormatResultAction, self).__init__(config) api_url = os.environ.get('ST2_ACTION_API_URL', None) token = os.environ.get('ST2_ACTION_AUTH_TOKEN', None) self.client = Client(api_url=api_url, token=token) self.jinja = jinja2.Environment(trim_blocks=True, lstrip_blocks=True) self.jinja.tests['in'] = lambda item, list: item in list path = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(path, 'templates/default.j2'), 'r') as f: self.default_template = f.read() def run(self, execution): context = { 'six': six, 'execution': execution } template = self.default_template alias_id = execution['context'].get('action_alias_ref', {}).get('id', None) if alias_id: alias = self.client.managers['ActionAlias'].get_by_id(alias_id) context.update({ 'alias': alias }) result = getattr(alias, 'result', None) if result: enabled = result.get('enabled', True) if enabled and 'format' in alias.result: template = alias.result['format'] return self.jinja.from_string(template).render(context) <commit_msg>Return empty string if result output is disabled<commit_after>import jinja2 import six import os from st2actions.runners.pythonrunner import Action from st2client.client import Client class FormatResultAction(Action): def __init__(self, config): super(FormatResultAction, self).__init__(config) api_url = os.environ.get('ST2_ACTION_API_URL', None) token = os.environ.get('ST2_ACTION_AUTH_TOKEN', None) self.client = Client(api_url=api_url, token=token) self.jinja = jinja2.Environment(trim_blocks=True, lstrip_blocks=True) self.jinja.tests['in'] = lambda item, list: item in list path = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(path, 'templates/default.j2'), 'r') as f: self.default_template = f.read() def run(self, execution): context = { 'six': six, 'execution': execution } template = self.default_template alias_id = execution['context'].get('action_alias_ref', {}).get('id', None) if alias_id: alias = self.client.managers['ActionAlias'].get_by_id(alias_id) context.update({ 'alias': alias }) result = getattr(alias, 'result', None) if result: if not result.get('enabled', True): return "" if 'format' in alias.result: template = alias.result['format'] return self.jinja.from_string(template).render(context)
42f2b69639b34644f42507bc65d399f423e348ef
tests/grammar_unified_tests.py
tests/grammar_unified_tests.py
from unittest import TestCase from regparser.grammar.unified import * class GrammarCommonTests(TestCase): def test_depth1_p(self): text = '(c)(2)(ii)(A)(<E T="03">2</E>)' result = depth1_p.parseString(text) self.assertEqual('c', result.p1) self.assertEqual('2', result.p2) self.assertEqual('ii', result.p3) self.assertEqual('A', result.p4) self.assertEqual('2', result.p5)
# -*- coding: utf-8 -*- from unittest import TestCase from regparser.grammar.unified import * class GrammarCommonTests(TestCase): def test_depth1_p(self): text = '(c)(2)(ii)(A)(<E T="03">2</E>)' result = depth1_p.parseString(text) self.assertEqual('c', result.p1) self.assertEqual('2', result.p2) self.assertEqual('ii', result.p3) self.assertEqual('A', result.p4) self.assertEqual('2', result.p5) def test_marker_comment(self): texts = [u'comment § 1004.3-4-i', u'comment 1004.3-4-i', u'comment 3-4-i',] for t in texts: result = marker_comment.parseString(t) self.assertEqual("3", result.section) self.assertEqual("4", result.c1)
Add tests for marker_comment from ascott1/appendix-ref
Add tests for marker_comment from ascott1/appendix-ref
Python
cc0-1.0
grapesmoker/regulations-parser,willbarton/regulations-parser,adderall/regulations-parser
from unittest import TestCase from regparser.grammar.unified import * class GrammarCommonTests(TestCase): def test_depth1_p(self): text = '(c)(2)(ii)(A)(<E T="03">2</E>)' result = depth1_p.parseString(text) self.assertEqual('c', result.p1) self.assertEqual('2', result.p2) self.assertEqual('ii', result.p3) self.assertEqual('A', result.p4) self.assertEqual('2', result.p5) Add tests for marker_comment from ascott1/appendix-ref
# -*- coding: utf-8 -*- from unittest import TestCase from regparser.grammar.unified import * class GrammarCommonTests(TestCase): def test_depth1_p(self): text = '(c)(2)(ii)(A)(<E T="03">2</E>)' result = depth1_p.parseString(text) self.assertEqual('c', result.p1) self.assertEqual('2', result.p2) self.assertEqual('ii', result.p3) self.assertEqual('A', result.p4) self.assertEqual('2', result.p5) def test_marker_comment(self): texts = [u'comment § 1004.3-4-i', u'comment 1004.3-4-i', u'comment 3-4-i',] for t in texts: result = marker_comment.parseString(t) self.assertEqual("3", result.section) self.assertEqual("4", result.c1)
<commit_before>from unittest import TestCase from regparser.grammar.unified import * class GrammarCommonTests(TestCase): def test_depth1_p(self): text = '(c)(2)(ii)(A)(<E T="03">2</E>)' result = depth1_p.parseString(text) self.assertEqual('c', result.p1) self.assertEqual('2', result.p2) self.assertEqual('ii', result.p3) self.assertEqual('A', result.p4) self.assertEqual('2', result.p5) <commit_msg>Add tests for marker_comment from ascott1/appendix-ref<commit_after>
# -*- coding: utf-8 -*- from unittest import TestCase from regparser.grammar.unified import * class GrammarCommonTests(TestCase): def test_depth1_p(self): text = '(c)(2)(ii)(A)(<E T="03">2</E>)' result = depth1_p.parseString(text) self.assertEqual('c', result.p1) self.assertEqual('2', result.p2) self.assertEqual('ii', result.p3) self.assertEqual('A', result.p4) self.assertEqual('2', result.p5) def test_marker_comment(self): texts = [u'comment § 1004.3-4-i', u'comment 1004.3-4-i', u'comment 3-4-i',] for t in texts: result = marker_comment.parseString(t) self.assertEqual("3", result.section) self.assertEqual("4", result.c1)
from unittest import TestCase from regparser.grammar.unified import * class GrammarCommonTests(TestCase): def test_depth1_p(self): text = '(c)(2)(ii)(A)(<E T="03">2</E>)' result = depth1_p.parseString(text) self.assertEqual('c', result.p1) self.assertEqual('2', result.p2) self.assertEqual('ii', result.p3) self.assertEqual('A', result.p4) self.assertEqual('2', result.p5) Add tests for marker_comment from ascott1/appendix-ref# -*- coding: utf-8 -*- from unittest import TestCase from regparser.grammar.unified import * class GrammarCommonTests(TestCase): def test_depth1_p(self): text = '(c)(2)(ii)(A)(<E T="03">2</E>)' result = depth1_p.parseString(text) self.assertEqual('c', result.p1) self.assertEqual('2', result.p2) self.assertEqual('ii', result.p3) self.assertEqual('A', result.p4) self.assertEqual('2', result.p5) def test_marker_comment(self): texts = [u'comment § 1004.3-4-i', u'comment 1004.3-4-i', u'comment 3-4-i',] for t in texts: result = marker_comment.parseString(t) self.assertEqual("3", result.section) self.assertEqual("4", result.c1)
<commit_before>from unittest import TestCase from regparser.grammar.unified import * class GrammarCommonTests(TestCase): def test_depth1_p(self): text = '(c)(2)(ii)(A)(<E T="03">2</E>)' result = depth1_p.parseString(text) self.assertEqual('c', result.p1) self.assertEqual('2', result.p2) self.assertEqual('ii', result.p3) self.assertEqual('A', result.p4) self.assertEqual('2', result.p5) <commit_msg>Add tests for marker_comment from ascott1/appendix-ref<commit_after># -*- coding: utf-8 -*- from unittest import TestCase from regparser.grammar.unified import * class GrammarCommonTests(TestCase): def test_depth1_p(self): text = '(c)(2)(ii)(A)(<E T="03">2</E>)' result = depth1_p.parseString(text) self.assertEqual('c', result.p1) self.assertEqual('2', result.p2) self.assertEqual('ii', result.p3) self.assertEqual('A', result.p4) self.assertEqual('2', result.p5) def test_marker_comment(self): texts = [u'comment § 1004.3-4-i', u'comment 1004.3-4-i', u'comment 3-4-i',] for t in texts: result = marker_comment.parseString(t) self.assertEqual("3", result.section) self.assertEqual("4", result.c1)
33ed550e08f405ee1a93123c12f05c0daaa13ad2
dthm4kaiako/config/__init__.py
dthm4kaiako/config/__init__.py
"""Configuration for Django system.""" __version__ = "0.18.4" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] )
"""Configuration for Django system.""" __version__ = "0.18.5" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] )
Increment version number to 0.18.5
Increment version number to 0.18.5
Python
mit
uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers
"""Configuration for Django system.""" __version__ = "0.18.4" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] ) Increment version number to 0.18.5
"""Configuration for Django system.""" __version__ = "0.18.5" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] )
<commit_before>"""Configuration for Django system.""" __version__ = "0.18.4" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] ) <commit_msg>Increment version number to 0.18.5<commit_after>
"""Configuration for Django system.""" __version__ = "0.18.5" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] )
"""Configuration for Django system.""" __version__ = "0.18.4" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] ) Increment version number to 0.18.5"""Configuration for Django system.""" __version__ = "0.18.5" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] )
<commit_before>"""Configuration for Django system.""" __version__ = "0.18.4" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] ) <commit_msg>Increment version number to 0.18.5<commit_after>"""Configuration for Django system.""" __version__ = "0.18.5" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] )
bcf4f87e3690986827d8d34eea5e7edfc03485e2
cassandra_migrate/test/test_cql.py
cassandra_migrate/test/test_cql.py
from __future__ import unicode_literals import pytest from cassandra_migrate.cql import CqlSplitter @pytest.mark.parametrize('cql,statements', [ # Two statements, with whitespace (''' CREATE TABLE hello; CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, no whitespace ('''CREATE TABLE hello;CREATE TABLE world;''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, with line and block comments (''' // comment -- comment CREATE TABLE hello; /* comment; comment */ CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Statements with semicolons inside strings (''' CREATE TABLE 'hello;'; CREATE TABLE "world;" ''', ["CREATE TABLE 'hello;'", 'CREATE TABLE "world;"']) ]) def test_cql_split(cql, statements): result = CqlSplitter.split(cql.strip()) assert result == statements
from __future__ import unicode_literals import pytest from cassandra_migrate.cql import CqlSplitter @pytest.mark.parametrize('cql,statements', [ # Two statements, with whitespace (''' CREATE TABLE hello; CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, no whitespace ('''CREATE TABLE hello;CREATE TABLE world;''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, with line and block comments (''' // comment -- comment CREATE TABLE hello; /* comment; comment */ CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Statements with semicolons inside strings (''' CREATE TABLE 'hello;'; CREATE TABLE "world;" ''', ["CREATE TABLE 'hello;'", 'CREATE TABLE "world;"']), # Double-dollar-sign quoted strings, as reported in PR #24 ('INSERT INTO test (test) VALUES ' '($$Pesky semicolon here ;Hello$$);', ["INSERT INTO test (test) VALUES ($$Pesky semicolon here ;Hello$$)"]) ]) def test_cql_split(cql, statements): result = CqlSplitter.split(cql.strip()) assert result == statements
Add CQL-splitting test case for double-dollar-sign strings
Add CQL-splitting test case for double-dollar-sign strings
Python
mit
Cobliteam/cassandra-migrate,Cobliteam/cassandra-migrate
from __future__ import unicode_literals import pytest from cassandra_migrate.cql import CqlSplitter @pytest.mark.parametrize('cql,statements', [ # Two statements, with whitespace (''' CREATE TABLE hello; CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, no whitespace ('''CREATE TABLE hello;CREATE TABLE world;''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, with line and block comments (''' // comment -- comment CREATE TABLE hello; /* comment; comment */ CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Statements with semicolons inside strings (''' CREATE TABLE 'hello;'; CREATE TABLE "world;" ''', ["CREATE TABLE 'hello;'", 'CREATE TABLE "world;"']) ]) def test_cql_split(cql, statements): result = CqlSplitter.split(cql.strip()) assert result == statements Add CQL-splitting test case for double-dollar-sign strings
from __future__ import unicode_literals import pytest from cassandra_migrate.cql import CqlSplitter @pytest.mark.parametrize('cql,statements', [ # Two statements, with whitespace (''' CREATE TABLE hello; CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, no whitespace ('''CREATE TABLE hello;CREATE TABLE world;''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, with line and block comments (''' // comment -- comment CREATE TABLE hello; /* comment; comment */ CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Statements with semicolons inside strings (''' CREATE TABLE 'hello;'; CREATE TABLE "world;" ''', ["CREATE TABLE 'hello;'", 'CREATE TABLE "world;"']), # Double-dollar-sign quoted strings, as reported in PR #24 ('INSERT INTO test (test) VALUES ' '($$Pesky semicolon here ;Hello$$);', ["INSERT INTO test (test) VALUES ($$Pesky semicolon here ;Hello$$)"]) ]) def test_cql_split(cql, statements): result = CqlSplitter.split(cql.strip()) assert result == statements
<commit_before>from __future__ import unicode_literals import pytest from cassandra_migrate.cql import CqlSplitter @pytest.mark.parametrize('cql,statements', [ # Two statements, with whitespace (''' CREATE TABLE hello; CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, no whitespace ('''CREATE TABLE hello;CREATE TABLE world;''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, with line and block comments (''' // comment -- comment CREATE TABLE hello; /* comment; comment */ CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Statements with semicolons inside strings (''' CREATE TABLE 'hello;'; CREATE TABLE "world;" ''', ["CREATE TABLE 'hello;'", 'CREATE TABLE "world;"']) ]) def test_cql_split(cql, statements): result = CqlSplitter.split(cql.strip()) assert result == statements <commit_msg>Add CQL-splitting test case for double-dollar-sign strings<commit_after>
from __future__ import unicode_literals import pytest from cassandra_migrate.cql import CqlSplitter @pytest.mark.parametrize('cql,statements', [ # Two statements, with whitespace (''' CREATE TABLE hello; CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, no whitespace ('''CREATE TABLE hello;CREATE TABLE world;''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, with line and block comments (''' // comment -- comment CREATE TABLE hello; /* comment; comment */ CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Statements with semicolons inside strings (''' CREATE TABLE 'hello;'; CREATE TABLE "world;" ''', ["CREATE TABLE 'hello;'", 'CREATE TABLE "world;"']), # Double-dollar-sign quoted strings, as reported in PR #24 ('INSERT INTO test (test) VALUES ' '($$Pesky semicolon here ;Hello$$);', ["INSERT INTO test (test) VALUES ($$Pesky semicolon here ;Hello$$)"]) ]) def test_cql_split(cql, statements): result = CqlSplitter.split(cql.strip()) assert result == statements
from __future__ import unicode_literals import pytest from cassandra_migrate.cql import CqlSplitter @pytest.mark.parametrize('cql,statements', [ # Two statements, with whitespace (''' CREATE TABLE hello; CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, no whitespace ('''CREATE TABLE hello;CREATE TABLE world;''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, with line and block comments (''' // comment -- comment CREATE TABLE hello; /* comment; comment */ CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Statements with semicolons inside strings (''' CREATE TABLE 'hello;'; CREATE TABLE "world;" ''', ["CREATE TABLE 'hello;'", 'CREATE TABLE "world;"']) ]) def test_cql_split(cql, statements): result = CqlSplitter.split(cql.strip()) assert result == statements Add CQL-splitting test case for double-dollar-sign stringsfrom __future__ import unicode_literals import pytest from cassandra_migrate.cql import CqlSplitter @pytest.mark.parametrize('cql,statements', [ # Two statements, with whitespace (''' CREATE TABLE hello; CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, no whitespace ('''CREATE TABLE hello;CREATE TABLE world;''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, with line and block comments (''' // comment -- comment CREATE TABLE hello; /* comment; comment */ CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Statements with semicolons inside strings (''' CREATE TABLE 'hello;'; CREATE TABLE "world;" ''', ["CREATE TABLE 'hello;'", 'CREATE TABLE "world;"']), # Double-dollar-sign quoted strings, as reported in PR #24 ('INSERT INTO test (test) VALUES ' '($$Pesky semicolon here ;Hello$$);', ["INSERT INTO test (test) VALUES ($$Pesky semicolon here ;Hello$$)"]) ]) def test_cql_split(cql, statements): result = CqlSplitter.split(cql.strip()) assert result == statements
<commit_before>from __future__ import unicode_literals import pytest from cassandra_migrate.cql import CqlSplitter @pytest.mark.parametrize('cql,statements', [ # Two statements, with whitespace (''' CREATE TABLE hello; CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, no whitespace ('''CREATE TABLE hello;CREATE TABLE world;''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, with line and block comments (''' // comment -- comment CREATE TABLE hello; /* comment; comment */ CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Statements with semicolons inside strings (''' CREATE TABLE 'hello;'; CREATE TABLE "world;" ''', ["CREATE TABLE 'hello;'", 'CREATE TABLE "world;"']) ]) def test_cql_split(cql, statements): result = CqlSplitter.split(cql.strip()) assert result == statements <commit_msg>Add CQL-splitting test case for double-dollar-sign strings<commit_after>from __future__ import unicode_literals import pytest from cassandra_migrate.cql import CqlSplitter @pytest.mark.parametrize('cql,statements', [ # Two statements, with whitespace (''' CREATE TABLE hello; CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, no whitespace ('''CREATE TABLE hello;CREATE TABLE world;''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Two statements, with line and block comments (''' // comment -- comment CREATE TABLE hello; /* comment; comment */ CREATE TABLE world; ''', ['CREATE TABLE hello', 'CREATE TABLE world']), # Statements with semicolons inside strings (''' CREATE TABLE 'hello;'; CREATE TABLE "world;" ''', ["CREATE TABLE 'hello;'", 'CREATE TABLE "world;"']), # Double-dollar-sign quoted strings, as reported in PR #24 ('INSERT INTO test (test) VALUES ' '($$Pesky semicolon here ;Hello$$);', ["INSERT INTO test (test) VALUES ($$Pesky semicolon here ;Hello$$)"]) ]) def test_cql_split(cql, statements): result = CqlSplitter.split(cql.strip()) assert result == statements
0f981d86802706edb78b7d76f6c4b68198876032
tests/steps/express-install.py
tests/steps/express-install.py
#!/usr/bin/python from __future__ import unicode_literals import libvirt from general import libvirt_domain_get_val, libvirt_domain_get_context def libvirt_domain_get_install_state(title): state = None conn = libvirt.openReadOnly(None) doms = conn.listAllDomains() for dom in doms: try: dom0 = conn.lookupByName(dom.name()) # Annoyiingly, libvirt prints its own error message here except libvirt.libvirtError: print("Domain %s is not running" % name) ctx = libvirt_domain_get_context(dom0) if libvirt_domain_get_val(ctx, "/domain/title") == title: return libvirt_domain_get_val(ctx, "/domain/metadata/*/os-state") return None
#!/usr/bin/python from __future__ import unicode_literals import libvirt from time import sleep from general import libvirt_domain_get_val, libvirt_domain_get_context def libvirt_domain_get_install_state(title): state = None conn = libvirt.openReadOnly(None) doms = conn.listAllDomains() for dom in doms: try: dom0 = conn.lookupByName(dom.name()) # Annoyiingly, libvirt prints its own error message here except libvirt.libvirtError: print("Domain %s is not running" % name) ctx = libvirt_domain_get_context(dom0) if libvirt_domain_get_val(ctx, "/domain/title") == title: return libvirt_domain_get_val(ctx, "/domain/metadata/*/os-state") return None @step('Installation of "{machine}" is finished in "{max_time}" minutes') def check_finished_installation(context, machine, max_time): minutes = 0 state = None while minutes < max_time: state = libvirt_domain_get_install_state(machine) if state == 'installed': break else: sleep(60) assert state == 'installed', "%s is not installed but still in %s after %s minutes" %(machine, state, max_time)
Add "Installation finished check" step
tests: Add "Installation finished check" step Step that asks libvirt every minute if VM state is installed. Step fails after specified amount of time, if not. https://bugzilla.gnome.org/show_bug.cgi?id=748006
Python
lgpl-2.1
vbenes/gnome-boxes,vbenes/gnome-boxes
#!/usr/bin/python from __future__ import unicode_literals import libvirt from general import libvirt_domain_get_val, libvirt_domain_get_context def libvirt_domain_get_install_state(title): state = None conn = libvirt.openReadOnly(None) doms = conn.listAllDomains() for dom in doms: try: dom0 = conn.lookupByName(dom.name()) # Annoyiingly, libvirt prints its own error message here except libvirt.libvirtError: print("Domain %s is not running" % name) ctx = libvirt_domain_get_context(dom0) if libvirt_domain_get_val(ctx, "/domain/title") == title: return libvirt_domain_get_val(ctx, "/domain/metadata/*/os-state") return None tests: Add "Installation finished check" step Step that asks libvirt every minute if VM state is installed. Step fails after specified amount of time, if not. https://bugzilla.gnome.org/show_bug.cgi?id=748006
#!/usr/bin/python from __future__ import unicode_literals import libvirt from time import sleep from general import libvirt_domain_get_val, libvirt_domain_get_context def libvirt_domain_get_install_state(title): state = None conn = libvirt.openReadOnly(None) doms = conn.listAllDomains() for dom in doms: try: dom0 = conn.lookupByName(dom.name()) # Annoyiingly, libvirt prints its own error message here except libvirt.libvirtError: print("Domain %s is not running" % name) ctx = libvirt_domain_get_context(dom0) if libvirt_domain_get_val(ctx, "/domain/title") == title: return libvirt_domain_get_val(ctx, "/domain/metadata/*/os-state") return None @step('Installation of "{machine}" is finished in "{max_time}" minutes') def check_finished_installation(context, machine, max_time): minutes = 0 state = None while minutes < max_time: state = libvirt_domain_get_install_state(machine) if state == 'installed': break else: sleep(60) assert state == 'installed', "%s is not installed but still in %s after %s minutes" %(machine, state, max_time)
<commit_before>#!/usr/bin/python from __future__ import unicode_literals import libvirt from general import libvirt_domain_get_val, libvirt_domain_get_context def libvirt_domain_get_install_state(title): state = None conn = libvirt.openReadOnly(None) doms = conn.listAllDomains() for dom in doms: try: dom0 = conn.lookupByName(dom.name()) # Annoyiingly, libvirt prints its own error message here except libvirt.libvirtError: print("Domain %s is not running" % name) ctx = libvirt_domain_get_context(dom0) if libvirt_domain_get_val(ctx, "/domain/title") == title: return libvirt_domain_get_val(ctx, "/domain/metadata/*/os-state") return None <commit_msg>tests: Add "Installation finished check" step Step that asks libvirt every minute if VM state is installed. Step fails after specified amount of time, if not. https://bugzilla.gnome.org/show_bug.cgi?id=748006<commit_after>
#!/usr/bin/python from __future__ import unicode_literals import libvirt from time import sleep from general import libvirt_domain_get_val, libvirt_domain_get_context def libvirt_domain_get_install_state(title): state = None conn = libvirt.openReadOnly(None) doms = conn.listAllDomains() for dom in doms: try: dom0 = conn.lookupByName(dom.name()) # Annoyiingly, libvirt prints its own error message here except libvirt.libvirtError: print("Domain %s is not running" % name) ctx = libvirt_domain_get_context(dom0) if libvirt_domain_get_val(ctx, "/domain/title") == title: return libvirt_domain_get_val(ctx, "/domain/metadata/*/os-state") return None @step('Installation of "{machine}" is finished in "{max_time}" minutes') def check_finished_installation(context, machine, max_time): minutes = 0 state = None while minutes < max_time: state = libvirt_domain_get_install_state(machine) if state == 'installed': break else: sleep(60) assert state == 'installed', "%s is not installed but still in %s after %s minutes" %(machine, state, max_time)
#!/usr/bin/python from __future__ import unicode_literals import libvirt from general import libvirt_domain_get_val, libvirt_domain_get_context def libvirt_domain_get_install_state(title): state = None conn = libvirt.openReadOnly(None) doms = conn.listAllDomains() for dom in doms: try: dom0 = conn.lookupByName(dom.name()) # Annoyiingly, libvirt prints its own error message here except libvirt.libvirtError: print("Domain %s is not running" % name) ctx = libvirt_domain_get_context(dom0) if libvirt_domain_get_val(ctx, "/domain/title") == title: return libvirt_domain_get_val(ctx, "/domain/metadata/*/os-state") return None tests: Add "Installation finished check" step Step that asks libvirt every minute if VM state is installed. Step fails after specified amount of time, if not. https://bugzilla.gnome.org/show_bug.cgi?id=748006#!/usr/bin/python from __future__ import unicode_literals import libvirt from time import sleep from general import libvirt_domain_get_val, libvirt_domain_get_context def libvirt_domain_get_install_state(title): state = None conn = libvirt.openReadOnly(None) doms = conn.listAllDomains() for dom in doms: try: dom0 = conn.lookupByName(dom.name()) # Annoyiingly, libvirt prints its own error message here except libvirt.libvirtError: print("Domain %s is not running" % name) ctx = libvirt_domain_get_context(dom0) if libvirt_domain_get_val(ctx, "/domain/title") == title: return libvirt_domain_get_val(ctx, "/domain/metadata/*/os-state") return None @step('Installation of "{machine}" is finished in "{max_time}" minutes') def check_finished_installation(context, machine, max_time): minutes = 0 state = None while minutes < max_time: state = libvirt_domain_get_install_state(machine) if state == 'installed': break else: sleep(60) assert state == 'installed', "%s is not installed but still in %s after %s minutes" %(machine, state, max_time)
<commit_before>#!/usr/bin/python from __future__ import unicode_literals import libvirt from general import libvirt_domain_get_val, libvirt_domain_get_context def libvirt_domain_get_install_state(title): state = None conn = libvirt.openReadOnly(None) doms = conn.listAllDomains() for dom in doms: try: dom0 = conn.lookupByName(dom.name()) # Annoyiingly, libvirt prints its own error message here except libvirt.libvirtError: print("Domain %s is not running" % name) ctx = libvirt_domain_get_context(dom0) if libvirt_domain_get_val(ctx, "/domain/title") == title: return libvirt_domain_get_val(ctx, "/domain/metadata/*/os-state") return None <commit_msg>tests: Add "Installation finished check" step Step that asks libvirt every minute if VM state is installed. Step fails after specified amount of time, if not. https://bugzilla.gnome.org/show_bug.cgi?id=748006<commit_after>#!/usr/bin/python from __future__ import unicode_literals import libvirt from time import sleep from general import libvirt_domain_get_val, libvirt_domain_get_context def libvirt_domain_get_install_state(title): state = None conn = libvirt.openReadOnly(None) doms = conn.listAllDomains() for dom in doms: try: dom0 = conn.lookupByName(dom.name()) # Annoyiingly, libvirt prints its own error message here except libvirt.libvirtError: print("Domain %s is not running" % name) ctx = libvirt_domain_get_context(dom0) if libvirt_domain_get_val(ctx, "/domain/title") == title: return libvirt_domain_get_val(ctx, "/domain/metadata/*/os-state") return None @step('Installation of "{machine}" is finished in "{max_time}" minutes') def check_finished_installation(context, machine, max_time): minutes = 0 state = None while minutes < max_time: state = libvirt_domain_get_install_state(machine) if state == 'installed': break else: sleep(60) assert state == 'installed', "%s is not installed but still in %s after %s minutes" %(machine, state, max_time)
46017b7c1f480f5cb94ca0ef380b0666f8b77d0f
helevents/models.py
helevents/models.py
from django.db import models from helusers.models import AbstractUser class User(AbstractUser): def __str__(self): return ' - '.join([super().__str__(), self.get_display_name(), self.email]) def get_display_name(self): return '{0} {1}'.format(self.first_name, self.last_name).strip() def get_default_organization(self): return self.admin_organizations.order_by('created_time').first()
from django.db import models from helusers.models import AbstractUser class User(AbstractUser): def __str__(self): return ' - '.join([self.get_display_name(), self.email]) def get_display_name(self): return '{0} {1}'.format(self.first_name, self.last_name).strip() def get_default_organization(self): return self.admin_organizations.order_by('created_time').first()
Remove uuid display from user string
Remove uuid display from user string
Python
mit
City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents
from django.db import models from helusers.models import AbstractUser class User(AbstractUser): def __str__(self): return ' - '.join([super().__str__(), self.get_display_name(), self.email]) def get_display_name(self): return '{0} {1}'.format(self.first_name, self.last_name).strip() def get_default_organization(self): return self.admin_organizations.order_by('created_time').first() Remove uuid display from user string
from django.db import models from helusers.models import AbstractUser class User(AbstractUser): def __str__(self): return ' - '.join([self.get_display_name(), self.email]) def get_display_name(self): return '{0} {1}'.format(self.first_name, self.last_name).strip() def get_default_organization(self): return self.admin_organizations.order_by('created_time').first()
<commit_before>from django.db import models from helusers.models import AbstractUser class User(AbstractUser): def __str__(self): return ' - '.join([super().__str__(), self.get_display_name(), self.email]) def get_display_name(self): return '{0} {1}'.format(self.first_name, self.last_name).strip() def get_default_organization(self): return self.admin_organizations.order_by('created_time').first() <commit_msg>Remove uuid display from user string<commit_after>
from django.db import models from helusers.models import AbstractUser class User(AbstractUser): def __str__(self): return ' - '.join([self.get_display_name(), self.email]) def get_display_name(self): return '{0} {1}'.format(self.first_name, self.last_name).strip() def get_default_organization(self): return self.admin_organizations.order_by('created_time').first()
from django.db import models from helusers.models import AbstractUser class User(AbstractUser): def __str__(self): return ' - '.join([super().__str__(), self.get_display_name(), self.email]) def get_display_name(self): return '{0} {1}'.format(self.first_name, self.last_name).strip() def get_default_organization(self): return self.admin_organizations.order_by('created_time').first() Remove uuid display from user stringfrom django.db import models from helusers.models import AbstractUser class User(AbstractUser): def __str__(self): return ' - '.join([self.get_display_name(), self.email]) def get_display_name(self): return '{0} {1}'.format(self.first_name, self.last_name).strip() def get_default_organization(self): return self.admin_organizations.order_by('created_time').first()
<commit_before>from django.db import models from helusers.models import AbstractUser class User(AbstractUser): def __str__(self): return ' - '.join([super().__str__(), self.get_display_name(), self.email]) def get_display_name(self): return '{0} {1}'.format(self.first_name, self.last_name).strip() def get_default_organization(self): return self.admin_organizations.order_by('created_time').first() <commit_msg>Remove uuid display from user string<commit_after>from django.db import models from helusers.models import AbstractUser class User(AbstractUser): def __str__(self): return ' - '.join([self.get_display_name(), self.email]) def get_display_name(self): return '{0} {1}'.format(self.first_name, self.last_name).strip() def get_default_organization(self): return self.admin_organizations.order_by('created_time').first()
8eb4f1e660de74837c7d05b1ee9076a58a551093
test/python_api/default-constructor/sb_stringlist.py
test/python_api/default-constructor/sb_stringlist.py
""" Fuzz tests an object after the default construction to make sure it does not crash lldb. """ import sys import lldb def fuzz_obj(obj): obj.AppendString("another string") obj.AppendList(None, 0) obj.AppendList(lldb.SBStringList()) obj.GetSize() obj.GetStringAtIndex(0xffffffff) obj.Clear() for str in obj: print str
""" Fuzz tests an object after the default construction to make sure it does not crash lldb. """ import sys import lldb def fuzz_obj(obj): obj.AppendString("another string") obj.AppendString(None) obj.AppendList(None, 0) obj.AppendList(lldb.SBStringList()) obj.GetSize() obj.GetStringAtIndex(0xffffffff) obj.Clear() for str in obj: print str
Add fuzz call to SBStringList.AppendString(None). LLDB should not crash.
Add fuzz call to SBStringList.AppendString(None). LLDB should not crash. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@146935 91177308-0d34-0410-b5e6-96231b3b80d8
Python
apache-2.0
llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb
""" Fuzz tests an object after the default construction to make sure it does not crash lldb. """ import sys import lldb def fuzz_obj(obj): obj.AppendString("another string") obj.AppendList(None, 0) obj.AppendList(lldb.SBStringList()) obj.GetSize() obj.GetStringAtIndex(0xffffffff) obj.Clear() for str in obj: print str Add fuzz call to SBStringList.AppendString(None). LLDB should not crash. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@146935 91177308-0d34-0410-b5e6-96231b3b80d8
""" Fuzz tests an object after the default construction to make sure it does not crash lldb. """ import sys import lldb def fuzz_obj(obj): obj.AppendString("another string") obj.AppendString(None) obj.AppendList(None, 0) obj.AppendList(lldb.SBStringList()) obj.GetSize() obj.GetStringAtIndex(0xffffffff) obj.Clear() for str in obj: print str
<commit_before>""" Fuzz tests an object after the default construction to make sure it does not crash lldb. """ import sys import lldb def fuzz_obj(obj): obj.AppendString("another string") obj.AppendList(None, 0) obj.AppendList(lldb.SBStringList()) obj.GetSize() obj.GetStringAtIndex(0xffffffff) obj.Clear() for str in obj: print str <commit_msg>Add fuzz call to SBStringList.AppendString(None). LLDB should not crash. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@146935 91177308-0d34-0410-b5e6-96231b3b80d8<commit_after>
""" Fuzz tests an object after the default construction to make sure it does not crash lldb. """ import sys import lldb def fuzz_obj(obj): obj.AppendString("another string") obj.AppendString(None) obj.AppendList(None, 0) obj.AppendList(lldb.SBStringList()) obj.GetSize() obj.GetStringAtIndex(0xffffffff) obj.Clear() for str in obj: print str
""" Fuzz tests an object after the default construction to make sure it does not crash lldb. """ import sys import lldb def fuzz_obj(obj): obj.AppendString("another string") obj.AppendList(None, 0) obj.AppendList(lldb.SBStringList()) obj.GetSize() obj.GetStringAtIndex(0xffffffff) obj.Clear() for str in obj: print str Add fuzz call to SBStringList.AppendString(None). LLDB should not crash. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@146935 91177308-0d34-0410-b5e6-96231b3b80d8""" Fuzz tests an object after the default construction to make sure it does not crash lldb. """ import sys import lldb def fuzz_obj(obj): obj.AppendString("another string") obj.AppendString(None) obj.AppendList(None, 0) obj.AppendList(lldb.SBStringList()) obj.GetSize() obj.GetStringAtIndex(0xffffffff) obj.Clear() for str in obj: print str
<commit_before>""" Fuzz tests an object after the default construction to make sure it does not crash lldb. """ import sys import lldb def fuzz_obj(obj): obj.AppendString("another string") obj.AppendList(None, 0) obj.AppendList(lldb.SBStringList()) obj.GetSize() obj.GetStringAtIndex(0xffffffff) obj.Clear() for str in obj: print str <commit_msg>Add fuzz call to SBStringList.AppendString(None). LLDB should not crash. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@146935 91177308-0d34-0410-b5e6-96231b3b80d8<commit_after>""" Fuzz tests an object after the default construction to make sure it does not crash lldb. """ import sys import lldb def fuzz_obj(obj): obj.AppendString("another string") obj.AppendString(None) obj.AppendList(None, 0) obj.AppendList(lldb.SBStringList()) obj.GetSize() obj.GetStringAtIndex(0xffffffff) obj.Clear() for str in obj: print str
ae00c60510e28c0852ac6ad14bab86563b5e1399
mica/common.py
mica/common.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Common definitions for Mica subpackages """ import os class MissingDataError(Exception): pass FLIGHT_MICA_ARCHIVE = os.path.join(os.environ['SKA'], 'data', 'mica', 'archive') # The MICA_ARCHIVE env. var can be a colon-delimited path, which allows # packages using pyyaks context files to see files within multiple trees. # This can be convenient for testing and development. Normally the flight # path is put last so that the test path is preferred if available. MICA_ARCHIVE_PATH = os.environ.get('MICA_ARCHIVE', FLIGHT_MICA_ARCHIVE) # Most of the existing subpackages just expect a single path, which should # be the test path (first one) if defined that way. MICA_ARCHIVE = MICA_ARCHIVE_PATH.split(':')[-1]
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Common definitions for Mica subpackages """ import os class MissingDataError(Exception): pass FLIGHT_MICA_ARCHIVE = os.path.join(os.environ['SKA'], 'data', 'mica', 'archive') # The MICA_ARCHIVE env. var can be a colon-delimited path, which allows # packages using pyyaks context files to see files within multiple trees. # This can be convenient for testing and development. Normally the flight # path is put last so that the test path is preferred if available. MICA_ARCHIVE_PATH = os.environ.get('MICA_ARCHIVE', FLIGHT_MICA_ARCHIVE) # Most of the existing subpackages just expect a single path, which should # be the test path (first one) if defined that way. MICA_ARCHIVE = MICA_ARCHIVE_PATH.split(os.pathsep)[-1]
Use os.pathsep instead of ':' for windows compat
Use os.pathsep instead of ':' for windows compat
Python
bsd-3-clause
sot/mica,sot/mica
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Common definitions for Mica subpackages """ import os class MissingDataError(Exception): pass FLIGHT_MICA_ARCHIVE = os.path.join(os.environ['SKA'], 'data', 'mica', 'archive') # The MICA_ARCHIVE env. var can be a colon-delimited path, which allows # packages using pyyaks context files to see files within multiple trees. # This can be convenient for testing and development. Normally the flight # path is put last so that the test path is preferred if available. MICA_ARCHIVE_PATH = os.environ.get('MICA_ARCHIVE', FLIGHT_MICA_ARCHIVE) # Most of the existing subpackages just expect a single path, which should # be the test path (first one) if defined that way. MICA_ARCHIVE = MICA_ARCHIVE_PATH.split(':')[-1] Use os.pathsep instead of ':' for windows compat
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Common definitions for Mica subpackages """ import os class MissingDataError(Exception): pass FLIGHT_MICA_ARCHIVE = os.path.join(os.environ['SKA'], 'data', 'mica', 'archive') # The MICA_ARCHIVE env. var can be a colon-delimited path, which allows # packages using pyyaks context files to see files within multiple trees. # This can be convenient for testing and development. Normally the flight # path is put last so that the test path is preferred if available. MICA_ARCHIVE_PATH = os.environ.get('MICA_ARCHIVE', FLIGHT_MICA_ARCHIVE) # Most of the existing subpackages just expect a single path, which should # be the test path (first one) if defined that way. MICA_ARCHIVE = MICA_ARCHIVE_PATH.split(os.pathsep)[-1]
<commit_before># Licensed under a 3-clause BSD style license - see LICENSE.rst """ Common definitions for Mica subpackages """ import os class MissingDataError(Exception): pass FLIGHT_MICA_ARCHIVE = os.path.join(os.environ['SKA'], 'data', 'mica', 'archive') # The MICA_ARCHIVE env. var can be a colon-delimited path, which allows # packages using pyyaks context files to see files within multiple trees. # This can be convenient for testing and development. Normally the flight # path is put last so that the test path is preferred if available. MICA_ARCHIVE_PATH = os.environ.get('MICA_ARCHIVE', FLIGHT_MICA_ARCHIVE) # Most of the existing subpackages just expect a single path, which should # be the test path (first one) if defined that way. MICA_ARCHIVE = MICA_ARCHIVE_PATH.split(':')[-1] <commit_msg>Use os.pathsep instead of ':' for windows compat<commit_after>
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Common definitions for Mica subpackages """ import os class MissingDataError(Exception): pass FLIGHT_MICA_ARCHIVE = os.path.join(os.environ['SKA'], 'data', 'mica', 'archive') # The MICA_ARCHIVE env. var can be a colon-delimited path, which allows # packages using pyyaks context files to see files within multiple trees. # This can be convenient for testing and development. Normally the flight # path is put last so that the test path is preferred if available. MICA_ARCHIVE_PATH = os.environ.get('MICA_ARCHIVE', FLIGHT_MICA_ARCHIVE) # Most of the existing subpackages just expect a single path, which should # be the test path (first one) if defined that way. MICA_ARCHIVE = MICA_ARCHIVE_PATH.split(os.pathsep)[-1]
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Common definitions for Mica subpackages """ import os class MissingDataError(Exception): pass FLIGHT_MICA_ARCHIVE = os.path.join(os.environ['SKA'], 'data', 'mica', 'archive') # The MICA_ARCHIVE env. var can be a colon-delimited path, which allows # packages using pyyaks context files to see files within multiple trees. # This can be convenient for testing and development. Normally the flight # path is put last so that the test path is preferred if available. MICA_ARCHIVE_PATH = os.environ.get('MICA_ARCHIVE', FLIGHT_MICA_ARCHIVE) # Most of the existing subpackages just expect a single path, which should # be the test path (first one) if defined that way. MICA_ARCHIVE = MICA_ARCHIVE_PATH.split(':')[-1] Use os.pathsep instead of ':' for windows compat# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Common definitions for Mica subpackages """ import os class MissingDataError(Exception): pass FLIGHT_MICA_ARCHIVE = os.path.join(os.environ['SKA'], 'data', 'mica', 'archive') # The MICA_ARCHIVE env. var can be a colon-delimited path, which allows # packages using pyyaks context files to see files within multiple trees. # This can be convenient for testing and development. Normally the flight # path is put last so that the test path is preferred if available. MICA_ARCHIVE_PATH = os.environ.get('MICA_ARCHIVE', FLIGHT_MICA_ARCHIVE) # Most of the existing subpackages just expect a single path, which should # be the test path (first one) if defined that way. MICA_ARCHIVE = MICA_ARCHIVE_PATH.split(os.pathsep)[-1]
<commit_before># Licensed under a 3-clause BSD style license - see LICENSE.rst """ Common definitions for Mica subpackages """ import os class MissingDataError(Exception): pass FLIGHT_MICA_ARCHIVE = os.path.join(os.environ['SKA'], 'data', 'mica', 'archive') # The MICA_ARCHIVE env. var can be a colon-delimited path, which allows # packages using pyyaks context files to see files within multiple trees. # This can be convenient for testing and development. Normally the flight # path is put last so that the test path is preferred if available. MICA_ARCHIVE_PATH = os.environ.get('MICA_ARCHIVE', FLIGHT_MICA_ARCHIVE) # Most of the existing subpackages just expect a single path, which should # be the test path (first one) if defined that way. MICA_ARCHIVE = MICA_ARCHIVE_PATH.split(':')[-1] <commit_msg>Use os.pathsep instead of ':' for windows compat<commit_after># Licensed under a 3-clause BSD style license - see LICENSE.rst """ Common definitions for Mica subpackages """ import os class MissingDataError(Exception): pass FLIGHT_MICA_ARCHIVE = os.path.join(os.environ['SKA'], 'data', 'mica', 'archive') # The MICA_ARCHIVE env. var can be a colon-delimited path, which allows # packages using pyyaks context files to see files within multiple trees. # This can be convenient for testing and development. Normally the flight # path is put last so that the test path is preferred if available. MICA_ARCHIVE_PATH = os.environ.get('MICA_ARCHIVE', FLIGHT_MICA_ARCHIVE) # Most of the existing subpackages just expect a single path, which should # be the test path (first one) if defined that way. MICA_ARCHIVE = MICA_ARCHIVE_PATH.split(os.pathsep)[-1]
c04d8dfaf3b4fcbddedb0973a501609ffb9472f6
simpleflow/settings/__init__.py
simpleflow/settings/__init__.py
import sys from future.utils import iteritems from . import base def put_setting(key, value): setattr(sys.modules[__name__], key, value) _keys.add(key) def configure(dct): for k, v in iteritems(dct): put_setting(k, v) # initialize a list of settings names _keys = set() # look for settings and initialize them configure(base.load())
from pprint import pformat import sys from future.utils import iteritems from . import base def put_setting(key, value): setattr(sys.modules[__name__], key, value) _keys.add(key) def configure(dct): for k, v in iteritems(dct): put_setting(k, v) def print_settings(): for key in sorted(_keys): value = getattr(sys.modules[__name__], key) print("{}={}".format(key, pformat(value))) # initialize a list of settings names _keys = set() # look for settings and initialize them configure(base.load())
Add utility method to print all settings
Add utility method to print all settings
Python
mit
botify-labs/simpleflow,botify-labs/simpleflow
import sys from future.utils import iteritems from . import base def put_setting(key, value): setattr(sys.modules[__name__], key, value) _keys.add(key) def configure(dct): for k, v in iteritems(dct): put_setting(k, v) # initialize a list of settings names _keys = set() # look for settings and initialize them configure(base.load()) Add utility method to print all settings
from pprint import pformat import sys from future.utils import iteritems from . import base def put_setting(key, value): setattr(sys.modules[__name__], key, value) _keys.add(key) def configure(dct): for k, v in iteritems(dct): put_setting(k, v) def print_settings(): for key in sorted(_keys): value = getattr(sys.modules[__name__], key) print("{}={}".format(key, pformat(value))) # initialize a list of settings names _keys = set() # look for settings and initialize them configure(base.load())
<commit_before>import sys from future.utils import iteritems from . import base def put_setting(key, value): setattr(sys.modules[__name__], key, value) _keys.add(key) def configure(dct): for k, v in iteritems(dct): put_setting(k, v) # initialize a list of settings names _keys = set() # look for settings and initialize them configure(base.load()) <commit_msg>Add utility method to print all settings<commit_after>
from pprint import pformat import sys from future.utils import iteritems from . import base def put_setting(key, value): setattr(sys.modules[__name__], key, value) _keys.add(key) def configure(dct): for k, v in iteritems(dct): put_setting(k, v) def print_settings(): for key in sorted(_keys): value = getattr(sys.modules[__name__], key) print("{}={}".format(key, pformat(value))) # initialize a list of settings names _keys = set() # look for settings and initialize them configure(base.load())
import sys from future.utils import iteritems from . import base def put_setting(key, value): setattr(sys.modules[__name__], key, value) _keys.add(key) def configure(dct): for k, v in iteritems(dct): put_setting(k, v) # initialize a list of settings names _keys = set() # look for settings and initialize them configure(base.load()) Add utility method to print all settingsfrom pprint import pformat import sys from future.utils import iteritems from . import base def put_setting(key, value): setattr(sys.modules[__name__], key, value) _keys.add(key) def configure(dct): for k, v in iteritems(dct): put_setting(k, v) def print_settings(): for key in sorted(_keys): value = getattr(sys.modules[__name__], key) print("{}={}".format(key, pformat(value))) # initialize a list of settings names _keys = set() # look for settings and initialize them configure(base.load())
<commit_before>import sys from future.utils import iteritems from . import base def put_setting(key, value): setattr(sys.modules[__name__], key, value) _keys.add(key) def configure(dct): for k, v in iteritems(dct): put_setting(k, v) # initialize a list of settings names _keys = set() # look for settings and initialize them configure(base.load()) <commit_msg>Add utility method to print all settings<commit_after>from pprint import pformat import sys from future.utils import iteritems from . import base def put_setting(key, value): setattr(sys.modules[__name__], key, value) _keys.add(key) def configure(dct): for k, v in iteritems(dct): put_setting(k, v) def print_settings(): for key in sorted(_keys): value = getattr(sys.modules[__name__], key) print("{}={}".format(key, pformat(value))) # initialize a list of settings names _keys = set() # look for settings and initialize them configure(base.load())
db02cadeb115bf3f7a8dd9be40d8a62d75d3559f
corehq/apps/hqwebapp/middleware.py
corehq/apps/hqwebapp/middleware.py
from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN from corehq.util.soft_assert import soft_assert from django.conf import settings class HQCsrfViewMiddleWare(CsrfViewMiddleware): def _reject(self, request, reason): if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]: warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\ "Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\ "Read more here https://github.com/dimagi/commcare-hq/pull/9227".format( url=request.path ) _assert = soft_assert(notify_admins=True, exponential_backoff=True) _assert(False, warning) return self._accept(request) else: return super(HQCsrfViewMiddleWare, self)._reject(request, reason)
import logging from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN from django.conf import settings logger = logging.getLogger('') class HQCsrfViewMiddleWare(CsrfViewMiddleware): def _reject(self, request, reason): if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]: warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\ "Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\ "Read more here https://github.com/dimagi/commcare-hq/pull/9227".format( url=request.path ) logger.error(warning) return self._accept(request) else: return super(HQCsrfViewMiddleWare, self)._reject(request, reason)
Revert "Revert "log to file, don't email""
Revert "Revert "log to file, don't email"" This reverts commit 95245bb7fab6efe5a72cb8abbf4380a26b72a720.
Python
bsd-3-clause
qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq
from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN from corehq.util.soft_assert import soft_assert from django.conf import settings class HQCsrfViewMiddleWare(CsrfViewMiddleware): def _reject(self, request, reason): if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]: warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\ "Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\ "Read more here https://github.com/dimagi/commcare-hq/pull/9227".format( url=request.path ) _assert = soft_assert(notify_admins=True, exponential_backoff=True) _assert(False, warning) return self._accept(request) else: return super(HQCsrfViewMiddleWare, self)._reject(request, reason) Revert "Revert "log to file, don't email"" This reverts commit 95245bb7fab6efe5a72cb8abbf4380a26b72a720.
import logging from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN from django.conf import settings logger = logging.getLogger('') class HQCsrfViewMiddleWare(CsrfViewMiddleware): def _reject(self, request, reason): if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]: warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\ "Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\ "Read more here https://github.com/dimagi/commcare-hq/pull/9227".format( url=request.path ) logger.error(warning) return self._accept(request) else: return super(HQCsrfViewMiddleWare, self)._reject(request, reason)
<commit_before>from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN from corehq.util.soft_assert import soft_assert from django.conf import settings class HQCsrfViewMiddleWare(CsrfViewMiddleware): def _reject(self, request, reason): if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]: warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\ "Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\ "Read more here https://github.com/dimagi/commcare-hq/pull/9227".format( url=request.path ) _assert = soft_assert(notify_admins=True, exponential_backoff=True) _assert(False, warning) return self._accept(request) else: return super(HQCsrfViewMiddleWare, self)._reject(request, reason) <commit_msg>Revert "Revert "log to file, don't email"" This reverts commit 95245bb7fab6efe5a72cb8abbf4380a26b72a720.<commit_after>
import logging from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN from django.conf import settings logger = logging.getLogger('') class HQCsrfViewMiddleWare(CsrfViewMiddleware): def _reject(self, request, reason): if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]: warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\ "Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\ "Read more here https://github.com/dimagi/commcare-hq/pull/9227".format( url=request.path ) logger.error(warning) return self._accept(request) else: return super(HQCsrfViewMiddleWare, self)._reject(request, reason)
from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN from corehq.util.soft_assert import soft_assert from django.conf import settings class HQCsrfViewMiddleWare(CsrfViewMiddleware): def _reject(self, request, reason): if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]: warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\ "Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\ "Read more here https://github.com/dimagi/commcare-hq/pull/9227".format( url=request.path ) _assert = soft_assert(notify_admins=True, exponential_backoff=True) _assert(False, warning) return self._accept(request) else: return super(HQCsrfViewMiddleWare, self)._reject(request, reason) Revert "Revert "log to file, don't email"" This reverts commit 95245bb7fab6efe5a72cb8abbf4380a26b72a720.import logging from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN from django.conf import settings logger = logging.getLogger('') class HQCsrfViewMiddleWare(CsrfViewMiddleware): def _reject(self, request, reason): if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]: warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\ "Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\ "Read more here https://github.com/dimagi/commcare-hq/pull/9227".format( url=request.path ) logger.error(warning) return self._accept(request) else: return super(HQCsrfViewMiddleWare, self)._reject(request, reason)
<commit_before>from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN from corehq.util.soft_assert import soft_assert from django.conf import settings class HQCsrfViewMiddleWare(CsrfViewMiddleware): def _reject(self, request, reason): if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]: warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\ "Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\ "Read more here https://github.com/dimagi/commcare-hq/pull/9227".format( url=request.path ) _assert = soft_assert(notify_admins=True, exponential_backoff=True) _assert(False, warning) return self._accept(request) else: return super(HQCsrfViewMiddleWare, self)._reject(request, reason) <commit_msg>Revert "Revert "log to file, don't email"" This reverts commit 95245bb7fab6efe5a72cb8abbf4380a26b72a720.<commit_after>import logging from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN from django.conf import settings logger = logging.getLogger('') class HQCsrfViewMiddleWare(CsrfViewMiddleware): def _reject(self, request, reason): if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]: warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\ "Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\ "Read more here https://github.com/dimagi/commcare-hq/pull/9227".format( url=request.path ) logger.error(warning) return self._accept(request) else: return super(HQCsrfViewMiddleWare, self)._reject(request, reason)
eef7f3797a6228c9e06717c3be49801a10b457a5
registries/views.py
registries/views.py
from django.http import HttpResponse from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.response import Response from registries.models import Organization from registries.serializers import DrillerListSerializer, DrillerSerializer class APIDrillerListCreateView(ListCreateAPIView): queryset = Organization.objects.all().select_related('province_state') serializer_class = DrillerSerializer def list(self, request): queryset = self.get_queryset() serializer = DrillerListSerializer(queryset, many=True) return Response(serializer.data) class APIDrillerRetrieveUpdateDestroyView(RetrieveUpdateDestroyAPIView): queryset = Organization.objects.all() lookup_field = "org_guid" serializer_class = DrillerSerializer # Create your views here. def index(request): return HttpResponse("TEST: Driller Register app home index.")
from django.http import HttpResponse from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.response import Response from registries.models import Organization from registries.serializers import DrillerListSerializer, DrillerSerializer class APIDrillerListCreateView(ListCreateAPIView): """ get: Return a list of all registered drilling organizations post: Create a new drilling organization instance """ queryset = Organization.objects.all().select_related('province_state') serializer_class = DrillerSerializer def list(self, request): queryset = self.get_queryset() serializer = DrillerListSerializer(queryset, many=True) return Response(serializer.data) class APIDrillerRetrieveUpdateDestroyView(RetrieveUpdateDestroyAPIView): """ get: Return the specified drilling organization patch: Updates the specified drilling organization with the fields/values provided in the request body delete: Removes the specified drilling organization record """ queryset = Organization.objects.all() lookup_field = "org_guid" serializer_class = DrillerSerializer # Create your views here. def index(request): return HttpResponse("TEST: Driller Register app home index.")
Add docstrings to view classes
Add docstrings to view classes
Python
apache-2.0
bcgov/gwells,rstens/gwells,rstens/gwells,rstens/gwells,bcgov/gwells,bcgov/gwells,bcgov/gwells,rstens/gwells
from django.http import HttpResponse from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.response import Response from registries.models import Organization from registries.serializers import DrillerListSerializer, DrillerSerializer class APIDrillerListCreateView(ListCreateAPIView): queryset = Organization.objects.all().select_related('province_state') serializer_class = DrillerSerializer def list(self, request): queryset = self.get_queryset() serializer = DrillerListSerializer(queryset, many=True) return Response(serializer.data) class APIDrillerRetrieveUpdateDestroyView(RetrieveUpdateDestroyAPIView): queryset = Organization.objects.all() lookup_field = "org_guid" serializer_class = DrillerSerializer # Create your views here. def index(request): return HttpResponse("TEST: Driller Register app home index.") Add docstrings to view classes
from django.http import HttpResponse from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.response import Response from registries.models import Organization from registries.serializers import DrillerListSerializer, DrillerSerializer class APIDrillerListCreateView(ListCreateAPIView): """ get: Return a list of all registered drilling organizations post: Create a new drilling organization instance """ queryset = Organization.objects.all().select_related('province_state') serializer_class = DrillerSerializer def list(self, request): queryset = self.get_queryset() serializer = DrillerListSerializer(queryset, many=True) return Response(serializer.data) class APIDrillerRetrieveUpdateDestroyView(RetrieveUpdateDestroyAPIView): """ get: Return the specified drilling organization patch: Updates the specified drilling organization with the fields/values provided in the request body delete: Removes the specified drilling organization record """ queryset = Organization.objects.all() lookup_field = "org_guid" serializer_class = DrillerSerializer # Create your views here. def index(request): return HttpResponse("TEST: Driller Register app home index.")
<commit_before>from django.http import HttpResponse from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.response import Response from registries.models import Organization from registries.serializers import DrillerListSerializer, DrillerSerializer class APIDrillerListCreateView(ListCreateAPIView): queryset = Organization.objects.all().select_related('province_state') serializer_class = DrillerSerializer def list(self, request): queryset = self.get_queryset() serializer = DrillerListSerializer(queryset, many=True) return Response(serializer.data) class APIDrillerRetrieveUpdateDestroyView(RetrieveUpdateDestroyAPIView): queryset = Organization.objects.all() lookup_field = "org_guid" serializer_class = DrillerSerializer # Create your views here. def index(request): return HttpResponse("TEST: Driller Register app home index.") <commit_msg>Add docstrings to view classes<commit_after>
from django.http import HttpResponse from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.response import Response from registries.models import Organization from registries.serializers import DrillerListSerializer, DrillerSerializer class APIDrillerListCreateView(ListCreateAPIView): """ get: Return a list of all registered drilling organizations post: Create a new drilling organization instance """ queryset = Organization.objects.all().select_related('province_state') serializer_class = DrillerSerializer def list(self, request): queryset = self.get_queryset() serializer = DrillerListSerializer(queryset, many=True) return Response(serializer.data) class APIDrillerRetrieveUpdateDestroyView(RetrieveUpdateDestroyAPIView): """ get: Return the specified drilling organization patch: Updates the specified drilling organization with the fields/values provided in the request body delete: Removes the specified drilling organization record """ queryset = Organization.objects.all() lookup_field = "org_guid" serializer_class = DrillerSerializer # Create your views here. def index(request): return HttpResponse("TEST: Driller Register app home index.")
from django.http import HttpResponse from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.response import Response from registries.models import Organization from registries.serializers import DrillerListSerializer, DrillerSerializer class APIDrillerListCreateView(ListCreateAPIView): queryset = Organization.objects.all().select_related('province_state') serializer_class = DrillerSerializer def list(self, request): queryset = self.get_queryset() serializer = DrillerListSerializer(queryset, many=True) return Response(serializer.data) class APIDrillerRetrieveUpdateDestroyView(RetrieveUpdateDestroyAPIView): queryset = Organization.objects.all() lookup_field = "org_guid" serializer_class = DrillerSerializer # Create your views here. def index(request): return HttpResponse("TEST: Driller Register app home index.") Add docstrings to view classesfrom django.http import HttpResponse from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.response import Response from registries.models import Organization from registries.serializers import DrillerListSerializer, DrillerSerializer class APIDrillerListCreateView(ListCreateAPIView): """ get: Return a list of all registered drilling organizations post: Create a new drilling organization instance """ queryset = Organization.objects.all().select_related('province_state') serializer_class = DrillerSerializer def list(self, request): queryset = self.get_queryset() serializer = DrillerListSerializer(queryset, many=True) return Response(serializer.data) class APIDrillerRetrieveUpdateDestroyView(RetrieveUpdateDestroyAPIView): """ get: Return the specified drilling organization patch: Updates the specified drilling organization with the fields/values provided in the request body delete: Removes the specified drilling organization record """ queryset = Organization.objects.all() lookup_field = "org_guid" serializer_class = DrillerSerializer # Create your views here. def index(request): return HttpResponse("TEST: Driller Register app home index.")
<commit_before>from django.http import HttpResponse from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.response import Response from registries.models import Organization from registries.serializers import DrillerListSerializer, DrillerSerializer class APIDrillerListCreateView(ListCreateAPIView): queryset = Organization.objects.all().select_related('province_state') serializer_class = DrillerSerializer def list(self, request): queryset = self.get_queryset() serializer = DrillerListSerializer(queryset, many=True) return Response(serializer.data) class APIDrillerRetrieveUpdateDestroyView(RetrieveUpdateDestroyAPIView): queryset = Organization.objects.all() lookup_field = "org_guid" serializer_class = DrillerSerializer # Create your views here. def index(request): return HttpResponse("TEST: Driller Register app home index.") <commit_msg>Add docstrings to view classes<commit_after>from django.http import HttpResponse from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.response import Response from registries.models import Organization from registries.serializers import DrillerListSerializer, DrillerSerializer class APIDrillerListCreateView(ListCreateAPIView): """ get: Return a list of all registered drilling organizations post: Create a new drilling organization instance """ queryset = Organization.objects.all().select_related('province_state') serializer_class = DrillerSerializer def list(self, request): queryset = self.get_queryset() serializer = DrillerListSerializer(queryset, many=True) return Response(serializer.data) class APIDrillerRetrieveUpdateDestroyView(RetrieveUpdateDestroyAPIView): """ get: Return the specified drilling organization patch: Updates the specified drilling organization with the fields/values provided in the request body delete: Removes the specified drilling organization record """ queryset = Organization.objects.all() lookup_field = "org_guid" serializer_class = DrillerSerializer # Create your views here. def index(request): return HttpResponse("TEST: Driller Register app home index.")
3902e8183a9b5aab416b3574c3c415d9cc5c1740
src/test/test_location_info.py
src/test/test_location_info.py
import pytest import pytz from astral import LocationInfo class TestLocationInfo: def test_Default(self): loc = LocationInfo() assert loc.name == "Greenwich" assert loc.region == "England" assert loc.timezone == "Europe/London" assert loc.latitude == pytest.approx(51.4733, abs=0.001) assert loc.longitude == pytest.approx(-0.0008333, abs=0.000001) def test_bad_latitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", "i", 2) def test_bad_longitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", 2, "i") def test_timezone_group(self): li = LocationInfo() assert li.timezone_group == "Europe" def test_tzinfo(self, new_delhi): assert new_delhi.tzinfo == pytz.timezone("Asia/Kolkata")
import pytest import pytz from astral import LocationInfo class TestLocationInfo: def test_Default(self): loc = LocationInfo() assert loc.name == "Greenwich" assert loc.region == "England" assert loc.timezone == "Europe/London" assert loc.latitude == pytest.approx(51.4733, abs=0.001) assert loc.longitude == pytest.approx(-0.0008333, abs=0.000001) def test_bad_latitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", "i", 2) def test_bad_longitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", 2, "i") def test_timezone_group(self): li = LocationInfo() assert li.timezone_group == "Europe" def test_tzinfo(self, new_delhi_info): assert new_delhi_info.tzinfo == pytz.timezone("Asia/Kolkata")
Make sure we're testing the right function!
Make sure we're testing the right function!
Python
apache-2.0
sffjunkie/astral,sffjunkie/astral
import pytest import pytz from astral import LocationInfo class TestLocationInfo: def test_Default(self): loc = LocationInfo() assert loc.name == "Greenwich" assert loc.region == "England" assert loc.timezone == "Europe/London" assert loc.latitude == pytest.approx(51.4733, abs=0.001) assert loc.longitude == pytest.approx(-0.0008333, abs=0.000001) def test_bad_latitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", "i", 2) def test_bad_longitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", 2, "i") def test_timezone_group(self): li = LocationInfo() assert li.timezone_group == "Europe" def test_tzinfo(self, new_delhi): assert new_delhi.tzinfo == pytz.timezone("Asia/Kolkata") Make sure we're testing the right function!
import pytest import pytz from astral import LocationInfo class TestLocationInfo: def test_Default(self): loc = LocationInfo() assert loc.name == "Greenwich" assert loc.region == "England" assert loc.timezone == "Europe/London" assert loc.latitude == pytest.approx(51.4733, abs=0.001) assert loc.longitude == pytest.approx(-0.0008333, abs=0.000001) def test_bad_latitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", "i", 2) def test_bad_longitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", 2, "i") def test_timezone_group(self): li = LocationInfo() assert li.timezone_group == "Europe" def test_tzinfo(self, new_delhi_info): assert new_delhi_info.tzinfo == pytz.timezone("Asia/Kolkata")
<commit_before>import pytest import pytz from astral import LocationInfo class TestLocationInfo: def test_Default(self): loc = LocationInfo() assert loc.name == "Greenwich" assert loc.region == "England" assert loc.timezone == "Europe/London" assert loc.latitude == pytest.approx(51.4733, abs=0.001) assert loc.longitude == pytest.approx(-0.0008333, abs=0.000001) def test_bad_latitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", "i", 2) def test_bad_longitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", 2, "i") def test_timezone_group(self): li = LocationInfo() assert li.timezone_group == "Europe" def test_tzinfo(self, new_delhi): assert new_delhi.tzinfo == pytz.timezone("Asia/Kolkata") <commit_msg>Make sure we're testing the right function!<commit_after>
import pytest import pytz from astral import LocationInfo class TestLocationInfo: def test_Default(self): loc = LocationInfo() assert loc.name == "Greenwich" assert loc.region == "England" assert loc.timezone == "Europe/London" assert loc.latitude == pytest.approx(51.4733, abs=0.001) assert loc.longitude == pytest.approx(-0.0008333, abs=0.000001) def test_bad_latitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", "i", 2) def test_bad_longitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", 2, "i") def test_timezone_group(self): li = LocationInfo() assert li.timezone_group == "Europe" def test_tzinfo(self, new_delhi_info): assert new_delhi_info.tzinfo == pytz.timezone("Asia/Kolkata")
import pytest import pytz from astral import LocationInfo class TestLocationInfo: def test_Default(self): loc = LocationInfo() assert loc.name == "Greenwich" assert loc.region == "England" assert loc.timezone == "Europe/London" assert loc.latitude == pytest.approx(51.4733, abs=0.001) assert loc.longitude == pytest.approx(-0.0008333, abs=0.000001) def test_bad_latitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", "i", 2) def test_bad_longitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", 2, "i") def test_timezone_group(self): li = LocationInfo() assert li.timezone_group == "Europe" def test_tzinfo(self, new_delhi): assert new_delhi.tzinfo == pytz.timezone("Asia/Kolkata") Make sure we're testing the right function!import pytest import pytz from astral import LocationInfo class TestLocationInfo: def test_Default(self): loc = LocationInfo() assert loc.name == "Greenwich" assert loc.region == "England" assert loc.timezone == "Europe/London" assert loc.latitude == pytest.approx(51.4733, abs=0.001) assert loc.longitude == pytest.approx(-0.0008333, abs=0.000001) def test_bad_latitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", "i", 2) def test_bad_longitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", 2, "i") def test_timezone_group(self): li = LocationInfo() assert li.timezone_group == "Europe" def test_tzinfo(self, new_delhi_info): assert new_delhi_info.tzinfo == pytz.timezone("Asia/Kolkata")
<commit_before>import pytest import pytz from astral import LocationInfo class TestLocationInfo: def test_Default(self): loc = LocationInfo() assert loc.name == "Greenwich" assert loc.region == "England" assert loc.timezone == "Europe/London" assert loc.latitude == pytest.approx(51.4733, abs=0.001) assert loc.longitude == pytest.approx(-0.0008333, abs=0.000001) def test_bad_latitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", "i", 2) def test_bad_longitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", 2, "i") def test_timezone_group(self): li = LocationInfo() assert li.timezone_group == "Europe" def test_tzinfo(self, new_delhi): assert new_delhi.tzinfo == pytz.timezone("Asia/Kolkata") <commit_msg>Make sure we're testing the right function!<commit_after>import pytest import pytz from astral import LocationInfo class TestLocationInfo: def test_Default(self): loc = LocationInfo() assert loc.name == "Greenwich" assert loc.region == "England" assert loc.timezone == "Europe/London" assert loc.latitude == pytest.approx(51.4733, abs=0.001) assert loc.longitude == pytest.approx(-0.0008333, abs=0.000001) def test_bad_latitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", "i", 2) def test_bad_longitude(self): with pytest.raises(ValueError): LocationInfo("A place", "Somewhere", "Europe/London", 2, "i") def test_timezone_group(self): li = LocationInfo() assert li.timezone_group == "Europe" def test_tzinfo(self, new_delhi_info): assert new_delhi_info.tzinfo == pytz.timezone("Asia/Kolkata")
17bbc99919b4c799f0bee94d4dac458aab7d695a
common/imagenet_server/main.py
common/imagenet_server/main.py
#!/usr/bin/python import logging import os import cv2 import numpy as np import image_getter def main(): # Configure root logger. root = logging.getLogger() root.setLevel(logging.DEBUG) file_handler = logging.FileHandler("test_image_getter.log") file_handler.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) formatter = logging.Formatter("%(name)s@%(asctime)s: " + "[%(levelname)s] %(message)s") file_handler.setFormatter(formatter) stream_handler.setFormatter(formatter) root.addHandler(file_handler) root.addHandler(stream_handler) root.info("Starting...") getter = image_getter.FilteredImageGetter("ilsvrc12_urls.txt", "image_cache", 10, preload_batches=2) for x in range(0, 3): batch = getter.get_random_test_batch() print batch[1] print len(batch[1]) i = 0 for image in batch[0]: print "Showing image: %d" % (i) i += 1 cv2.imshow("test", np.transpose(image, (1, 2, 0))) cv2.waitKey(0) main()
#!/usr/bin/python import logging def _configure_logging(): """ Configure logging handlers. """ # Configure root logger. root = logging.getLogger() root.setLevel(logging.DEBUG) file_handler = logging.FileHandler("test_image_getter.log") file_handler.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) formatter = logging.Formatter("%(name)s@%(asctime)s: " + "[%(levelname)s] %(message)s") file_handler.setFormatter(formatter) stream_handler.setFormatter(formatter) root.addHandler(file_handler) root.addHandler(stream_handler) # Some modules need logging configured immediately to work. _configure_logging() import os import cv2 import numpy as np import image_getter def main(): logging.info("Starting...") getter = image_getter.FilteredImageGetter("ilsvrc12_urls.txt", "image_cache", 10, preload_batches=2) for x in range(0, 3): batch = getter.get_random_train_batch() print batch[1] print len(batch[1]) i = 0 for image in batch[0]: print "Showing image: %d" % (i) i += 1 cv2.imshow("test", np.transpose(image, (1, 2, 0))) cv2.waitKey(0) main()
Make imagenet server tester logging better.
Make imagenet server tester logging better.
Python
mit
djpetti/rpinets,djpetti/rpinets
#!/usr/bin/python import logging import os import cv2 import numpy as np import image_getter def main(): # Configure root logger. root = logging.getLogger() root.setLevel(logging.DEBUG) file_handler = logging.FileHandler("test_image_getter.log") file_handler.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) formatter = logging.Formatter("%(name)s@%(asctime)s: " + "[%(levelname)s] %(message)s") file_handler.setFormatter(formatter) stream_handler.setFormatter(formatter) root.addHandler(file_handler) root.addHandler(stream_handler) root.info("Starting...") getter = image_getter.FilteredImageGetter("ilsvrc12_urls.txt", "image_cache", 10, preload_batches=2) for x in range(0, 3): batch = getter.get_random_test_batch() print batch[1] print len(batch[1]) i = 0 for image in batch[0]: print "Showing image: %d" % (i) i += 1 cv2.imshow("test", np.transpose(image, (1, 2, 0))) cv2.waitKey(0) main() Make imagenet server tester logging better.
#!/usr/bin/python import logging def _configure_logging(): """ Configure logging handlers. """ # Configure root logger. root = logging.getLogger() root.setLevel(logging.DEBUG) file_handler = logging.FileHandler("test_image_getter.log") file_handler.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) formatter = logging.Formatter("%(name)s@%(asctime)s: " + "[%(levelname)s] %(message)s") file_handler.setFormatter(formatter) stream_handler.setFormatter(formatter) root.addHandler(file_handler) root.addHandler(stream_handler) # Some modules need logging configured immediately to work. _configure_logging() import os import cv2 import numpy as np import image_getter def main(): logging.info("Starting...") getter = image_getter.FilteredImageGetter("ilsvrc12_urls.txt", "image_cache", 10, preload_batches=2) for x in range(0, 3): batch = getter.get_random_train_batch() print batch[1] print len(batch[1]) i = 0 for image in batch[0]: print "Showing image: %d" % (i) i += 1 cv2.imshow("test", np.transpose(image, (1, 2, 0))) cv2.waitKey(0) main()
<commit_before>#!/usr/bin/python import logging import os import cv2 import numpy as np import image_getter def main(): # Configure root logger. root = logging.getLogger() root.setLevel(logging.DEBUG) file_handler = logging.FileHandler("test_image_getter.log") file_handler.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) formatter = logging.Formatter("%(name)s@%(asctime)s: " + "[%(levelname)s] %(message)s") file_handler.setFormatter(formatter) stream_handler.setFormatter(formatter) root.addHandler(file_handler) root.addHandler(stream_handler) root.info("Starting...") getter = image_getter.FilteredImageGetter("ilsvrc12_urls.txt", "image_cache", 10, preload_batches=2) for x in range(0, 3): batch = getter.get_random_test_batch() print batch[1] print len(batch[1]) i = 0 for image in batch[0]: print "Showing image: %d" % (i) i += 1 cv2.imshow("test", np.transpose(image, (1, 2, 0))) cv2.waitKey(0) main() <commit_msg>Make imagenet server tester logging better.<commit_after>
#!/usr/bin/python import logging def _configure_logging(): """ Configure logging handlers. """ # Configure root logger. root = logging.getLogger() root.setLevel(logging.DEBUG) file_handler = logging.FileHandler("test_image_getter.log") file_handler.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) formatter = logging.Formatter("%(name)s@%(asctime)s: " + "[%(levelname)s] %(message)s") file_handler.setFormatter(formatter) stream_handler.setFormatter(formatter) root.addHandler(file_handler) root.addHandler(stream_handler) # Some modules need logging configured immediately to work. _configure_logging() import os import cv2 import numpy as np import image_getter def main(): logging.info("Starting...") getter = image_getter.FilteredImageGetter("ilsvrc12_urls.txt", "image_cache", 10, preload_batches=2) for x in range(0, 3): batch = getter.get_random_train_batch() print batch[1] print len(batch[1]) i = 0 for image in batch[0]: print "Showing image: %d" % (i) i += 1 cv2.imshow("test", np.transpose(image, (1, 2, 0))) cv2.waitKey(0) main()
#!/usr/bin/python import logging import os import cv2 import numpy as np import image_getter def main(): # Configure root logger. root = logging.getLogger() root.setLevel(logging.DEBUG) file_handler = logging.FileHandler("test_image_getter.log") file_handler.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) formatter = logging.Formatter("%(name)s@%(asctime)s: " + "[%(levelname)s] %(message)s") file_handler.setFormatter(formatter) stream_handler.setFormatter(formatter) root.addHandler(file_handler) root.addHandler(stream_handler) root.info("Starting...") getter = image_getter.FilteredImageGetter("ilsvrc12_urls.txt", "image_cache", 10, preload_batches=2) for x in range(0, 3): batch = getter.get_random_test_batch() print batch[1] print len(batch[1]) i = 0 for image in batch[0]: print "Showing image: %d" % (i) i += 1 cv2.imshow("test", np.transpose(image, (1, 2, 0))) cv2.waitKey(0) main() Make imagenet server tester logging better.#!/usr/bin/python import logging def _configure_logging(): """ Configure logging handlers. """ # Configure root logger. root = logging.getLogger() root.setLevel(logging.DEBUG) file_handler = logging.FileHandler("test_image_getter.log") file_handler.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) formatter = logging.Formatter("%(name)s@%(asctime)s: " + "[%(levelname)s] %(message)s") file_handler.setFormatter(formatter) stream_handler.setFormatter(formatter) root.addHandler(file_handler) root.addHandler(stream_handler) # Some modules need logging configured immediately to work. _configure_logging() import os import cv2 import numpy as np import image_getter def main(): logging.info("Starting...") getter = image_getter.FilteredImageGetter("ilsvrc12_urls.txt", "image_cache", 10, preload_batches=2) for x in range(0, 3): batch = getter.get_random_train_batch() print batch[1] print len(batch[1]) i = 0 for image in batch[0]: print "Showing image: %d" % (i) i += 1 cv2.imshow("test", np.transpose(image, (1, 2, 0))) cv2.waitKey(0) main()
<commit_before>#!/usr/bin/python import logging import os import cv2 import numpy as np import image_getter def main(): # Configure root logger. root = logging.getLogger() root.setLevel(logging.DEBUG) file_handler = logging.FileHandler("test_image_getter.log") file_handler.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) formatter = logging.Formatter("%(name)s@%(asctime)s: " + "[%(levelname)s] %(message)s") file_handler.setFormatter(formatter) stream_handler.setFormatter(formatter) root.addHandler(file_handler) root.addHandler(stream_handler) root.info("Starting...") getter = image_getter.FilteredImageGetter("ilsvrc12_urls.txt", "image_cache", 10, preload_batches=2) for x in range(0, 3): batch = getter.get_random_test_batch() print batch[1] print len(batch[1]) i = 0 for image in batch[0]: print "Showing image: %d" % (i) i += 1 cv2.imshow("test", np.transpose(image, (1, 2, 0))) cv2.waitKey(0) main() <commit_msg>Make imagenet server tester logging better.<commit_after>#!/usr/bin/python import logging def _configure_logging(): """ Configure logging handlers. """ # Configure root logger. root = logging.getLogger() root.setLevel(logging.DEBUG) file_handler = logging.FileHandler("test_image_getter.log") file_handler.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) formatter = logging.Formatter("%(name)s@%(asctime)s: " + "[%(levelname)s] %(message)s") file_handler.setFormatter(formatter) stream_handler.setFormatter(formatter) root.addHandler(file_handler) root.addHandler(stream_handler) # Some modules need logging configured immediately to work. _configure_logging() import os import cv2 import numpy as np import image_getter def main(): logging.info("Starting...") getter = image_getter.FilteredImageGetter("ilsvrc12_urls.txt", "image_cache", 10, preload_batches=2) for x in range(0, 3): batch = getter.get_random_train_batch() print batch[1] print len(batch[1]) i = 0 for image in batch[0]: print "Showing image: %d" % (i) i += 1 cv2.imshow("test", np.transpose(image, (1, 2, 0))) cv2.waitKey(0) main()
a31e62f2a981f7662aee8a35ad195252a542d08d
plugins/say.py
plugins/say.py
from motobot import command, action @command('say') def say_command(bot, message, database): masters = [ "Moto-chan", "Motoko11", "Akahige", "betholas", "Baradium", "Cold_slither", "Drahken" ] if message.nick.lower() not in [x.lower() for x in masters]: return "Check your privilege!" else: args = message.message.split(' ')[1:] if len(args) < 2: return "You must specify both a channel and a message" else: channel = args[0] message = ' '.join(args[1:]) if message.startswith('/me '): message = action(message[4:]) bot.send('PRIVMSG {} :{}'.format(channel, message))
from motobot import command, action @command('say') def say_command(bot, message, database): masters = [ "Moto-chan", "Motoko11", "MotoNyan", "Akahige", "betholas", "Baradium", "Cold_slither", "Drahken" ] if message.nick.lower() not in [x.lower() for x in masters]: return "Check your privilege!" else: args = message.message.split(' ')[1:] if len(args) < 2: return "You must specify both a channel and a message" else: channel = args[0] message = ' '.join(args[1:]) if message.startswith('/me '): message = action(message[4:]) bot.send('PRIVMSG {} :{}'.format(channel, message))
Add MotoNyan to mad hax
Add MotoNyan to mad hax
Python
mit
Motoko11/MotoBot
from motobot import command, action @command('say') def say_command(bot, message, database): masters = [ "Moto-chan", "Motoko11", "Akahige", "betholas", "Baradium", "Cold_slither", "Drahken" ] if message.nick.lower() not in [x.lower() for x in masters]: return "Check your privilege!" else: args = message.message.split(' ')[1:] if len(args) < 2: return "You must specify both a channel and a message" else: channel = args[0] message = ' '.join(args[1:]) if message.startswith('/me '): message = action(message[4:]) bot.send('PRIVMSG {} :{}'.format(channel, message)) Add MotoNyan to mad hax
from motobot import command, action @command('say') def say_command(bot, message, database): masters = [ "Moto-chan", "Motoko11", "MotoNyan", "Akahige", "betholas", "Baradium", "Cold_slither", "Drahken" ] if message.nick.lower() not in [x.lower() for x in masters]: return "Check your privilege!" else: args = message.message.split(' ')[1:] if len(args) < 2: return "You must specify both a channel and a message" else: channel = args[0] message = ' '.join(args[1:]) if message.startswith('/me '): message = action(message[4:]) bot.send('PRIVMSG {} :{}'.format(channel, message))
<commit_before>from motobot import command, action @command('say') def say_command(bot, message, database): masters = [ "Moto-chan", "Motoko11", "Akahige", "betholas", "Baradium", "Cold_slither", "Drahken" ] if message.nick.lower() not in [x.lower() for x in masters]: return "Check your privilege!" else: args = message.message.split(' ')[1:] if len(args) < 2: return "You must specify both a channel and a message" else: channel = args[0] message = ' '.join(args[1:]) if message.startswith('/me '): message = action(message[4:]) bot.send('PRIVMSG {} :{}'.format(channel, message)) <commit_msg>Add MotoNyan to mad hax<commit_after>
from motobot import command, action @command('say') def say_command(bot, message, database): masters = [ "Moto-chan", "Motoko11", "MotoNyan", "Akahige", "betholas", "Baradium", "Cold_slither", "Drahken" ] if message.nick.lower() not in [x.lower() for x in masters]: return "Check your privilege!" else: args = message.message.split(' ')[1:] if len(args) < 2: return "You must specify both a channel and a message" else: channel = args[0] message = ' '.join(args[1:]) if message.startswith('/me '): message = action(message[4:]) bot.send('PRIVMSG {} :{}'.format(channel, message))
from motobot import command, action @command('say') def say_command(bot, message, database): masters = [ "Moto-chan", "Motoko11", "Akahige", "betholas", "Baradium", "Cold_slither", "Drahken" ] if message.nick.lower() not in [x.lower() for x in masters]: return "Check your privilege!" else: args = message.message.split(' ')[1:] if len(args) < 2: return "You must specify both a channel and a message" else: channel = args[0] message = ' '.join(args[1:]) if message.startswith('/me '): message = action(message[4:]) bot.send('PRIVMSG {} :{}'.format(channel, message)) Add MotoNyan to mad haxfrom motobot import command, action @command('say') def say_command(bot, message, database): masters = [ "Moto-chan", "Motoko11", "MotoNyan", "Akahige", "betholas", "Baradium", "Cold_slither", "Drahken" ] if message.nick.lower() not in [x.lower() for x in masters]: return "Check your privilege!" else: args = message.message.split(' ')[1:] if len(args) < 2: return "You must specify both a channel and a message" else: channel = args[0] message = ' '.join(args[1:]) if message.startswith('/me '): message = action(message[4:]) bot.send('PRIVMSG {} :{}'.format(channel, message))
<commit_before>from motobot import command, action @command('say') def say_command(bot, message, database): masters = [ "Moto-chan", "Motoko11", "Akahige", "betholas", "Baradium", "Cold_slither", "Drahken" ] if message.nick.lower() not in [x.lower() for x in masters]: return "Check your privilege!" else: args = message.message.split(' ')[1:] if len(args) < 2: return "You must specify both a channel and a message" else: channel = args[0] message = ' '.join(args[1:]) if message.startswith('/me '): message = action(message[4:]) bot.send('PRIVMSG {} :{}'.format(channel, message)) <commit_msg>Add MotoNyan to mad hax<commit_after>from motobot import command, action @command('say') def say_command(bot, message, database): masters = [ "Moto-chan", "Motoko11", "MotoNyan", "Akahige", "betholas", "Baradium", "Cold_slither", "Drahken" ] if message.nick.lower() not in [x.lower() for x in masters]: return "Check your privilege!" else: args = message.message.split(' ')[1:] if len(args) < 2: return "You must specify both a channel and a message" else: channel = args[0] message = ' '.join(args[1:]) if message.startswith('/me '): message = action(message[4:]) bot.send('PRIVMSG {} :{}'.format(channel, message))
662101e89943fe62b7036894140272e2f9ea4f78
ibmcnx/test/test.py
ibmcnx/test/test.py
import ibmcnx.test.loadFunction loadFilesService() FilesPolicyService.browse( "title", "true", 1, 25 )
import ibmcnx.test.loadFunction ibmcnx.test.loadFunction.loadFilesService() FilesPolicyService.browse( "title", "true", 1, 25 )
Customize scripts to work with menu
Customize scripts to work with menu
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
import ibmcnx.test.loadFunction loadFilesService() FilesPolicyService.browse( "title", "true", 1, 25 ) Customize scripts to work with menu
import ibmcnx.test.loadFunction ibmcnx.test.loadFunction.loadFilesService() FilesPolicyService.browse( "title", "true", 1, 25 )
<commit_before>import ibmcnx.test.loadFunction loadFilesService() FilesPolicyService.browse( "title", "true", 1, 25 ) <commit_msg>Customize scripts to work with menu<commit_after>
import ibmcnx.test.loadFunction ibmcnx.test.loadFunction.loadFilesService() FilesPolicyService.browse( "title", "true", 1, 25 )
import ibmcnx.test.loadFunction loadFilesService() FilesPolicyService.browse( "title", "true", 1, 25 ) Customize scripts to work with menuimport ibmcnx.test.loadFunction ibmcnx.test.loadFunction.loadFilesService() FilesPolicyService.browse( "title", "true", 1, 25 )
<commit_before>import ibmcnx.test.loadFunction loadFilesService() FilesPolicyService.browse( "title", "true", 1, 25 ) <commit_msg>Customize scripts to work with menu<commit_after>import ibmcnx.test.loadFunction ibmcnx.test.loadFunction.loadFilesService() FilesPolicyService.browse( "title", "true", 1, 25 )
61c87725b1b6a4c5294b630df4c8c018d9db73a8
ingestors/worker.py
ingestors/worker.py
import logging from followthemoney import model from servicelayer.worker import Worker from servicelayer.jobs import JobStage as Stage from ingestors.manager import Manager log = logging.getLogger(__name__) class IngestWorker(Worker): """A long running task runner that uses Redis as a task queue""" def dispatch_next(self, stage, context, entities): next_stage = context.get('next_stage') if next_stage is None: return next_queue = Stage(stage.conn, next_stage, stage.job.id, stage.dataset, priority=stage.priority) log.info("Sending %s entities to: %s", len(entities), next_stage) for entity_id in entities: next_queue.queue_task({'entity_id': entity_id}, context) def handle(self, stage, payload, context): manager = Manager(stage, context) entity = model.get_proxy(payload) log.debug("Ingest: %r", entity) manager.ingest_entity(entity) manager.close() self.dispatch_next(stage, context, manager.emitted)
import logging from followthemoney import model from servicelayer.worker import Worker from servicelayer.jobs import JobStage as Stage from ingestors.manager import Manager log = logging.getLogger(__name__) class IngestWorker(Worker): """A long running task runner that uses Redis as a task queue""" def dispatch_next(self, stage, context, entities): next_stage = context.get('next_stage') if next_stage is None: return next_queue = Stage(stage.conn, next_stage, stage.job.id, stage.dataset, priority=stage.priority) log.info("Sending %s entities to: %s", len(entities), next_stage) for entity_id in entities: next_queue.queue_task({'entity_id': entity_id}, context) def handle(self, task): manager = Manager(task.stage, task.context) entity = model.get_proxy(task.payload) log.debug("Ingest: %r", entity) manager.ingest_entity(entity) manager.close() self.dispatch_next(task.stage, task.context, manager.emitted)
Remove job when done and match servicelayer api
Remove job when done and match servicelayer api
Python
mit
alephdata/ingestors
import logging from followthemoney import model from servicelayer.worker import Worker from servicelayer.jobs import JobStage as Stage from ingestors.manager import Manager log = logging.getLogger(__name__) class IngestWorker(Worker): """A long running task runner that uses Redis as a task queue""" def dispatch_next(self, stage, context, entities): next_stage = context.get('next_stage') if next_stage is None: return next_queue = Stage(stage.conn, next_stage, stage.job.id, stage.dataset, priority=stage.priority) log.info("Sending %s entities to: %s", len(entities), next_stage) for entity_id in entities: next_queue.queue_task({'entity_id': entity_id}, context) def handle(self, stage, payload, context): manager = Manager(stage, context) entity = model.get_proxy(payload) log.debug("Ingest: %r", entity) manager.ingest_entity(entity) manager.close() self.dispatch_next(stage, context, manager.emitted) Remove job when done and match servicelayer api
import logging from followthemoney import model from servicelayer.worker import Worker from servicelayer.jobs import JobStage as Stage from ingestors.manager import Manager log = logging.getLogger(__name__) class IngestWorker(Worker): """A long running task runner that uses Redis as a task queue""" def dispatch_next(self, stage, context, entities): next_stage = context.get('next_stage') if next_stage is None: return next_queue = Stage(stage.conn, next_stage, stage.job.id, stage.dataset, priority=stage.priority) log.info("Sending %s entities to: %s", len(entities), next_stage) for entity_id in entities: next_queue.queue_task({'entity_id': entity_id}, context) def handle(self, task): manager = Manager(task.stage, task.context) entity = model.get_proxy(task.payload) log.debug("Ingest: %r", entity) manager.ingest_entity(entity) manager.close() self.dispatch_next(task.stage, task.context, manager.emitted)
<commit_before>import logging from followthemoney import model from servicelayer.worker import Worker from servicelayer.jobs import JobStage as Stage from ingestors.manager import Manager log = logging.getLogger(__name__) class IngestWorker(Worker): """A long running task runner that uses Redis as a task queue""" def dispatch_next(self, stage, context, entities): next_stage = context.get('next_stage') if next_stage is None: return next_queue = Stage(stage.conn, next_stage, stage.job.id, stage.dataset, priority=stage.priority) log.info("Sending %s entities to: %s", len(entities), next_stage) for entity_id in entities: next_queue.queue_task({'entity_id': entity_id}, context) def handle(self, stage, payload, context): manager = Manager(stage, context) entity = model.get_proxy(payload) log.debug("Ingest: %r", entity) manager.ingest_entity(entity) manager.close() self.dispatch_next(stage, context, manager.emitted) <commit_msg>Remove job when done and match servicelayer api<commit_after>
import logging from followthemoney import model from servicelayer.worker import Worker from servicelayer.jobs import JobStage as Stage from ingestors.manager import Manager log = logging.getLogger(__name__) class IngestWorker(Worker): """A long running task runner that uses Redis as a task queue""" def dispatch_next(self, stage, context, entities): next_stage = context.get('next_stage') if next_stage is None: return next_queue = Stage(stage.conn, next_stage, stage.job.id, stage.dataset, priority=stage.priority) log.info("Sending %s entities to: %s", len(entities), next_stage) for entity_id in entities: next_queue.queue_task({'entity_id': entity_id}, context) def handle(self, task): manager = Manager(task.stage, task.context) entity = model.get_proxy(task.payload) log.debug("Ingest: %r", entity) manager.ingest_entity(entity) manager.close() self.dispatch_next(task.stage, task.context, manager.emitted)
import logging from followthemoney import model from servicelayer.worker import Worker from servicelayer.jobs import JobStage as Stage from ingestors.manager import Manager log = logging.getLogger(__name__) class IngestWorker(Worker): """A long running task runner that uses Redis as a task queue""" def dispatch_next(self, stage, context, entities): next_stage = context.get('next_stage') if next_stage is None: return next_queue = Stage(stage.conn, next_stage, stage.job.id, stage.dataset, priority=stage.priority) log.info("Sending %s entities to: %s", len(entities), next_stage) for entity_id in entities: next_queue.queue_task({'entity_id': entity_id}, context) def handle(self, stage, payload, context): manager = Manager(stage, context) entity = model.get_proxy(payload) log.debug("Ingest: %r", entity) manager.ingest_entity(entity) manager.close() self.dispatch_next(stage, context, manager.emitted) Remove job when done and match servicelayer apiimport logging from followthemoney import model from servicelayer.worker import Worker from servicelayer.jobs import JobStage as Stage from ingestors.manager import Manager log = logging.getLogger(__name__) class IngestWorker(Worker): """A long running task runner that uses Redis as a task queue""" def dispatch_next(self, stage, context, entities): next_stage = context.get('next_stage') if next_stage is None: return next_queue = Stage(stage.conn, next_stage, stage.job.id, stage.dataset, priority=stage.priority) log.info("Sending %s entities to: %s", len(entities), next_stage) for entity_id in entities: next_queue.queue_task({'entity_id': entity_id}, context) def handle(self, task): manager = Manager(task.stage, task.context) entity = model.get_proxy(task.payload) log.debug("Ingest: %r", entity) manager.ingest_entity(entity) manager.close() self.dispatch_next(task.stage, task.context, manager.emitted)
<commit_before>import logging from followthemoney import model from servicelayer.worker import Worker from servicelayer.jobs import JobStage as Stage from ingestors.manager import Manager log = logging.getLogger(__name__) class IngestWorker(Worker): """A long running task runner that uses Redis as a task queue""" def dispatch_next(self, stage, context, entities): next_stage = context.get('next_stage') if next_stage is None: return next_queue = Stage(stage.conn, next_stage, stage.job.id, stage.dataset, priority=stage.priority) log.info("Sending %s entities to: %s", len(entities), next_stage) for entity_id in entities: next_queue.queue_task({'entity_id': entity_id}, context) def handle(self, stage, payload, context): manager = Manager(stage, context) entity = model.get_proxy(payload) log.debug("Ingest: %r", entity) manager.ingest_entity(entity) manager.close() self.dispatch_next(stage, context, manager.emitted) <commit_msg>Remove job when done and match servicelayer api<commit_after>import logging from followthemoney import model from servicelayer.worker import Worker from servicelayer.jobs import JobStage as Stage from ingestors.manager import Manager log = logging.getLogger(__name__) class IngestWorker(Worker): """A long running task runner that uses Redis as a task queue""" def dispatch_next(self, stage, context, entities): next_stage = context.get('next_stage') if next_stage is None: return next_queue = Stage(stage.conn, next_stage, stage.job.id, stage.dataset, priority=stage.priority) log.info("Sending %s entities to: %s", len(entities), next_stage) for entity_id in entities: next_queue.queue_task({'entity_id': entity_id}, context) def handle(self, task): manager = Manager(task.stage, task.context) entity = model.get_proxy(task.payload) log.debug("Ingest: %r", entity) manager.ingest_entity(entity) manager.close() self.dispatch_next(task.stage, task.context, manager.emitted)
89b463c5ce29e89bfcf444de9a8d73bc1ad78fc8
omop_harvest/migrations/0003_avocado_metadata_migration.py
omop_harvest/migrations/0003_avocado_metadata_migration.py
# -*- coding: utf-8 -*- from south.v2 import DataMigration class Migration(DataMigration): def forwards(self, orm): "Perform a 'safe' load using Avocado's backup utilities." from avocado.core import backup backup.safe_load(u'0001_avocado_metadata', backup_path=None, using='default') def backwards(self, orm): "No backwards migration applicable." pass
# -*- coding: utf-8 -*- from south.v2 import DataMigration class Migration(DataMigration): depends_on = ( ("avocado", "0031_auto__add_field_dataquery_tree__add_field_datacontext_tree"), ) def forwards(self, orm): "Perform a 'safe' load using Avocado's backup utilities." from avocado.core import backup backup.safe_load(u'0001_avocado_metadata', backup_path=None, using='default') def backwards(self, orm): "No backwards migration applicable." pass
Add avocado dependency to metadata migration.
Add avocado dependency to metadata migration. Signed-off-by: Aaron Browne <a437ff1f67cf5e38cd2f6119addad5bba3897ae0@gmail.com>
Python
bsd-2-clause
chop-dbhi/omop_harvest,chop-dbhi/omop_harvest,chop-dbhi/omop_harvest
# -*- coding: utf-8 -*- from south.v2 import DataMigration class Migration(DataMigration): def forwards(self, orm): "Perform a 'safe' load using Avocado's backup utilities." from avocado.core import backup backup.safe_load(u'0001_avocado_metadata', backup_path=None, using='default') def backwards(self, orm): "No backwards migration applicable." pass Add avocado dependency to metadata migration. Signed-off-by: Aaron Browne <a437ff1f67cf5e38cd2f6119addad5bba3897ae0@gmail.com>
# -*- coding: utf-8 -*- from south.v2 import DataMigration class Migration(DataMigration): depends_on = ( ("avocado", "0031_auto__add_field_dataquery_tree__add_field_datacontext_tree"), ) def forwards(self, orm): "Perform a 'safe' load using Avocado's backup utilities." from avocado.core import backup backup.safe_load(u'0001_avocado_metadata', backup_path=None, using='default') def backwards(self, orm): "No backwards migration applicable." pass
<commit_before># -*- coding: utf-8 -*- from south.v2 import DataMigration class Migration(DataMigration): def forwards(self, orm): "Perform a 'safe' load using Avocado's backup utilities." from avocado.core import backup backup.safe_load(u'0001_avocado_metadata', backup_path=None, using='default') def backwards(self, orm): "No backwards migration applicable." pass <commit_msg>Add avocado dependency to metadata migration. Signed-off-by: Aaron Browne <a437ff1f67cf5e38cd2f6119addad5bba3897ae0@gmail.com><commit_after>
# -*- coding: utf-8 -*- from south.v2 import DataMigration class Migration(DataMigration): depends_on = ( ("avocado", "0031_auto__add_field_dataquery_tree__add_field_datacontext_tree"), ) def forwards(self, orm): "Perform a 'safe' load using Avocado's backup utilities." from avocado.core import backup backup.safe_load(u'0001_avocado_metadata', backup_path=None, using='default') def backwards(self, orm): "No backwards migration applicable." pass
# -*- coding: utf-8 -*- from south.v2 import DataMigration class Migration(DataMigration): def forwards(self, orm): "Perform a 'safe' load using Avocado's backup utilities." from avocado.core import backup backup.safe_load(u'0001_avocado_metadata', backup_path=None, using='default') def backwards(self, orm): "No backwards migration applicable." pass Add avocado dependency to metadata migration. Signed-off-by: Aaron Browne <a437ff1f67cf5e38cd2f6119addad5bba3897ae0@gmail.com># -*- coding: utf-8 -*- from south.v2 import DataMigration class Migration(DataMigration): depends_on = ( ("avocado", "0031_auto__add_field_dataquery_tree__add_field_datacontext_tree"), ) def forwards(self, orm): "Perform a 'safe' load using Avocado's backup utilities." from avocado.core import backup backup.safe_load(u'0001_avocado_metadata', backup_path=None, using='default') def backwards(self, orm): "No backwards migration applicable." pass
<commit_before># -*- coding: utf-8 -*- from south.v2 import DataMigration class Migration(DataMigration): def forwards(self, orm): "Perform a 'safe' load using Avocado's backup utilities." from avocado.core import backup backup.safe_load(u'0001_avocado_metadata', backup_path=None, using='default') def backwards(self, orm): "No backwards migration applicable." pass <commit_msg>Add avocado dependency to metadata migration. Signed-off-by: Aaron Browne <a437ff1f67cf5e38cd2f6119addad5bba3897ae0@gmail.com><commit_after># -*- coding: utf-8 -*- from south.v2 import DataMigration class Migration(DataMigration): depends_on = ( ("avocado", "0031_auto__add_field_dataquery_tree__add_field_datacontext_tree"), ) def forwards(self, orm): "Perform a 'safe' load using Avocado's backup utilities." from avocado.core import backup backup.safe_load(u'0001_avocado_metadata', backup_path=None, using='default') def backwards(self, orm): "No backwards migration applicable." pass