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
2adbbe6c7291dd79784bd3a1e5702945435fa436
phasortoolbox/__init__.py
phasortoolbox/__init__.py
#!/usr/bin/env python3 import asyncio from .parser import Parser, PcapParser from .client import Client from .pdc import PDC import logging logging.getLogger(__name__).addHandler(logging.NullHandler())
#!/usr/bin/env python3 import asyncio from .synchrophasor import Synchrophasor from .parser import Parser, PcapParser from .client import Client from .pdc import PDC import logging logging.getLogger(__name__).addHandler(logging.NullHandler())
Put Synchrophasor in a seperate file
Put Synchrophasor in a seperate file
Python
mit
sonusz/PhasorToolBox
#!/usr/bin/env python3 import asyncio from .parser import Parser, PcapParser from .client import Client from .pdc import PDC import logging logging.getLogger(__name__).addHandler(logging.NullHandler()) Put Synchrophasor in a seperate file
#!/usr/bin/env python3 import asyncio from .synchrophasor import Synchrophasor from .parser import Parser, PcapParser from .client import Client from .pdc import PDC import logging logging.getLogger(__name__).addHandler(logging.NullHandler())
<commit_before>#!/usr/bin/env python3 import asyncio from .parser import Parser, PcapParser from .client import Client from .pdc import PDC import logging logging.getLogger(__name__).addHandler(logging.NullHandler()) <commit_msg>Put Synchrophasor in a seperate file<commit_after>
#!/usr/bin/env python3 import asyncio from .synchrophasor import Synchrophasor from .parser import Parser, PcapParser from .client import Client from .pdc import PDC import logging logging.getLogger(__name__).addHandler(logging.NullHandler())
#!/usr/bin/env python3 import asyncio from .parser import Parser, PcapParser from .client import Client from .pdc import PDC import logging logging.getLogger(__name__).addHandler(logging.NullHandler()) Put Synchrophasor in a seperate file#!/usr/bin/env python3 import asyncio from .synchrophasor import Synchrophasor from .parser import Parser, PcapParser from .client import Client from .pdc import PDC import logging logging.getLogger(__name__).addHandler(logging.NullHandler())
<commit_before>#!/usr/bin/env python3 import asyncio from .parser import Parser, PcapParser from .client import Client from .pdc import PDC import logging logging.getLogger(__name__).addHandler(logging.NullHandler()) <commit_msg>Put Synchrophasor in a seperate file<commit_after>#!/usr/bin/env python3 import asyncio from .synchrophasor import Synchrophasor from .parser import Parser, PcapParser from .client import Client from .pdc import PDC import logging logging.getLogger(__name__).addHandler(logging.NullHandler())
1bbc1fab976dd63e6a2f05aa35117dc74db40652
private_messages/forms.py
private_messages/forms.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from django_select2.fields import HeavySelect2MultipleChoiceField from pybb import util from private_messages.models import PrivateMessage class MessageForm(forms.ModelForm): parent = forms.UUIDField(required=False, widget=forms.HiddenInput) receivers = HeavySelect2MultipleChoiceField(data_view='private_messages:receivers_json') class Meta(object): model = PrivateMessage fields = ('receivers', 'subject', 'body', 'parent') widgets = { 'body': util.get_markup_engine().get_widget_cls(), } labels = { 'receivers': _('To'), }
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.contrib.auth import get_user_model from django.utils.translation import ugettext_lazy as _ from django_select2.fields import HeavyModelSelect2MultipleChoiceField from pybb import util from private_messages.models import PrivateMessage User = get_user_model() class MessageForm(forms.ModelForm): parent = forms.UUIDField(required=False, widget=forms.HiddenInput) receivers = HeavyModelSelect2MultipleChoiceField( data_view='private_messages:receivers_json', queryset=User.objects.all()) class Meta(object): model = PrivateMessage fields = ('receivers', 'subject', 'body', 'parent') widgets = { 'body': util.get_markup_engine().get_widget_cls(), } labels = { 'receivers': _('To'), }
Use ModelSelectField. Javascript still broken for some reason.
Use ModelSelectField. Javascript still broken for some reason.
Python
mit
skolsuper/pybbm_private_messages,skolsuper/pybbm_private_messages,skolsuper/pybbm_private_messages
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from django_select2.fields import HeavySelect2MultipleChoiceField from pybb import util from private_messages.models import PrivateMessage class MessageForm(forms.ModelForm): parent = forms.UUIDField(required=False, widget=forms.HiddenInput) receivers = HeavySelect2MultipleChoiceField(data_view='private_messages:receivers_json') class Meta(object): model = PrivateMessage fields = ('receivers', 'subject', 'body', 'parent') widgets = { 'body': util.get_markup_engine().get_widget_cls(), } labels = { 'receivers': _('To'), } Use ModelSelectField. Javascript still broken for some reason.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.contrib.auth import get_user_model from django.utils.translation import ugettext_lazy as _ from django_select2.fields import HeavyModelSelect2MultipleChoiceField from pybb import util from private_messages.models import PrivateMessage User = get_user_model() class MessageForm(forms.ModelForm): parent = forms.UUIDField(required=False, widget=forms.HiddenInput) receivers = HeavyModelSelect2MultipleChoiceField( data_view='private_messages:receivers_json', queryset=User.objects.all()) class Meta(object): model = PrivateMessage fields = ('receivers', 'subject', 'body', 'parent') widgets = { 'body': util.get_markup_engine().get_widget_cls(), } labels = { 'receivers': _('To'), }
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from django_select2.fields import HeavySelect2MultipleChoiceField from pybb import util from private_messages.models import PrivateMessage class MessageForm(forms.ModelForm): parent = forms.UUIDField(required=False, widget=forms.HiddenInput) receivers = HeavySelect2MultipleChoiceField(data_view='private_messages:receivers_json') class Meta(object): model = PrivateMessage fields = ('receivers', 'subject', 'body', 'parent') widgets = { 'body': util.get_markup_engine().get_widget_cls(), } labels = { 'receivers': _('To'), } <commit_msg>Use ModelSelectField. Javascript still broken for some reason.<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.contrib.auth import get_user_model from django.utils.translation import ugettext_lazy as _ from django_select2.fields import HeavyModelSelect2MultipleChoiceField from pybb import util from private_messages.models import PrivateMessage User = get_user_model() class MessageForm(forms.ModelForm): parent = forms.UUIDField(required=False, widget=forms.HiddenInput) receivers = HeavyModelSelect2MultipleChoiceField( data_view='private_messages:receivers_json', queryset=User.objects.all()) class Meta(object): model = PrivateMessage fields = ('receivers', 'subject', 'body', 'parent') widgets = { 'body': util.get_markup_engine().get_widget_cls(), } labels = { 'receivers': _('To'), }
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from django_select2.fields import HeavySelect2MultipleChoiceField from pybb import util from private_messages.models import PrivateMessage class MessageForm(forms.ModelForm): parent = forms.UUIDField(required=False, widget=forms.HiddenInput) receivers = HeavySelect2MultipleChoiceField(data_view='private_messages:receivers_json') class Meta(object): model = PrivateMessage fields = ('receivers', 'subject', 'body', 'parent') widgets = { 'body': util.get_markup_engine().get_widget_cls(), } labels = { 'receivers': _('To'), } Use ModelSelectField. Javascript still broken for some reason.# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.contrib.auth import get_user_model from django.utils.translation import ugettext_lazy as _ from django_select2.fields import HeavyModelSelect2MultipleChoiceField from pybb import util from private_messages.models import PrivateMessage User = get_user_model() class MessageForm(forms.ModelForm): parent = forms.UUIDField(required=False, widget=forms.HiddenInput) receivers = HeavyModelSelect2MultipleChoiceField( data_view='private_messages:receivers_json', queryset=User.objects.all()) class Meta(object): model = PrivateMessage fields = ('receivers', 'subject', 'body', 'parent') widgets = { 'body': util.get_markup_engine().get_widget_cls(), } labels = { 'receivers': _('To'), }
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from django_select2.fields import HeavySelect2MultipleChoiceField from pybb import util from private_messages.models import PrivateMessage class MessageForm(forms.ModelForm): parent = forms.UUIDField(required=False, widget=forms.HiddenInput) receivers = HeavySelect2MultipleChoiceField(data_view='private_messages:receivers_json') class Meta(object): model = PrivateMessage fields = ('receivers', 'subject', 'body', 'parent') widgets = { 'body': util.get_markup_engine().get_widget_cls(), } labels = { 'receivers': _('To'), } <commit_msg>Use ModelSelectField. Javascript still broken for some reason.<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.contrib.auth import get_user_model from django.utils.translation import ugettext_lazy as _ from django_select2.fields import HeavyModelSelect2MultipleChoiceField from pybb import util from private_messages.models import PrivateMessage User = get_user_model() class MessageForm(forms.ModelForm): parent = forms.UUIDField(required=False, widget=forms.HiddenInput) receivers = HeavyModelSelect2MultipleChoiceField( data_view='private_messages:receivers_json', queryset=User.objects.all()) class Meta(object): model = PrivateMessage fields = ('receivers', 'subject', 'body', 'parent') widgets = { 'body': util.get_markup_engine().get_widget_cls(), } labels = { 'receivers': _('To'), }
f1d3d2f5543c0e847c4b2051c04837cb3586846e
emission/analysis/plotting/leaflet_osm/our_plotter.py
emission/analysis/plotting/leaflet_osm/our_plotter.py
import pandas as pd import folium def get_map_list(df, potential_splits): mapList = [] potential_splits_list = list(potential_splits) for start, end in zip(potential_splits_list, potential_splits_list[1:]): trip = df[start:end] currMap = folium.Map([trip.mLatitude.mean(), trip.mLongitude.mean()]) plot_point = lambda row: currMap.simple_marker([row['mLatitude'], row['mLongitude']], popup='%s' % row) trip.apply(plot_point, axis=1) currMap.line(zip(list(trip.mLatitude), list(trip.mLongitude))) mapList.append(currMap) return mapList
import pandas as pd import folium def df_to_string_list(df): """ Convert the input df into a list of strings, suitable for using as popups in a map. This is a utility function. """ print "Converting df with size %s to string list" % df.shape[0] array_list = df.as_matrix().tolist() return [str(line) for line in array_list] def get_map_list(df, potential_splits): mapList = [] potential_splits_list = list(potential_splits) for start, end in zip(potential_splits_list, potential_splits_list[1:]): trip = df[start:end] currMap = folium.Map([trip.mLatitude.mean(), trip.mLongitude.mean()]) currMap.div_markers(trip[['mLatitude', 'mLongitude']].as_matrix().tolist(), df_to_string_list(trip[['mLatitude', 'mLongitude', 'formatted_time', 'mAccuracy']])) currMap.line(trip[['mLatitude', 'mLongitude']].as_matrix().tolist()) mapList.append(currMap) return mapList
Enhance our plotter to use the new div_markers code
Enhance our plotter to use the new div_markers code And to generate popups correctly
Python
bsd-3-clause
yw374cornell/e-mission-server,joshzarrabi/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,joshzarrabi/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,yw374cornell/e-mission-server,joshzarrabi/e-mission-server,yw374cornell/e-mission-server,shankari/e-mission-server,yw374cornell/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,joshzarrabi/e-mission-server
import pandas as pd import folium def get_map_list(df, potential_splits): mapList = [] potential_splits_list = list(potential_splits) for start, end in zip(potential_splits_list, potential_splits_list[1:]): trip = df[start:end] currMap = folium.Map([trip.mLatitude.mean(), trip.mLongitude.mean()]) plot_point = lambda row: currMap.simple_marker([row['mLatitude'], row['mLongitude']], popup='%s' % row) trip.apply(plot_point, axis=1) currMap.line(zip(list(trip.mLatitude), list(trip.mLongitude))) mapList.append(currMap) return mapList Enhance our plotter to use the new div_markers code And to generate popups correctly
import pandas as pd import folium def df_to_string_list(df): """ Convert the input df into a list of strings, suitable for using as popups in a map. This is a utility function. """ print "Converting df with size %s to string list" % df.shape[0] array_list = df.as_matrix().tolist() return [str(line) for line in array_list] def get_map_list(df, potential_splits): mapList = [] potential_splits_list = list(potential_splits) for start, end in zip(potential_splits_list, potential_splits_list[1:]): trip = df[start:end] currMap = folium.Map([trip.mLatitude.mean(), trip.mLongitude.mean()]) currMap.div_markers(trip[['mLatitude', 'mLongitude']].as_matrix().tolist(), df_to_string_list(trip[['mLatitude', 'mLongitude', 'formatted_time', 'mAccuracy']])) currMap.line(trip[['mLatitude', 'mLongitude']].as_matrix().tolist()) mapList.append(currMap) return mapList
<commit_before>import pandas as pd import folium def get_map_list(df, potential_splits): mapList = [] potential_splits_list = list(potential_splits) for start, end in zip(potential_splits_list, potential_splits_list[1:]): trip = df[start:end] currMap = folium.Map([trip.mLatitude.mean(), trip.mLongitude.mean()]) plot_point = lambda row: currMap.simple_marker([row['mLatitude'], row['mLongitude']], popup='%s' % row) trip.apply(plot_point, axis=1) currMap.line(zip(list(trip.mLatitude), list(trip.mLongitude))) mapList.append(currMap) return mapList <commit_msg>Enhance our plotter to use the new div_markers code And to generate popups correctly<commit_after>
import pandas as pd import folium def df_to_string_list(df): """ Convert the input df into a list of strings, suitable for using as popups in a map. This is a utility function. """ print "Converting df with size %s to string list" % df.shape[0] array_list = df.as_matrix().tolist() return [str(line) for line in array_list] def get_map_list(df, potential_splits): mapList = [] potential_splits_list = list(potential_splits) for start, end in zip(potential_splits_list, potential_splits_list[1:]): trip = df[start:end] currMap = folium.Map([trip.mLatitude.mean(), trip.mLongitude.mean()]) currMap.div_markers(trip[['mLatitude', 'mLongitude']].as_matrix().tolist(), df_to_string_list(trip[['mLatitude', 'mLongitude', 'formatted_time', 'mAccuracy']])) currMap.line(trip[['mLatitude', 'mLongitude']].as_matrix().tolist()) mapList.append(currMap) return mapList
import pandas as pd import folium def get_map_list(df, potential_splits): mapList = [] potential_splits_list = list(potential_splits) for start, end in zip(potential_splits_list, potential_splits_list[1:]): trip = df[start:end] currMap = folium.Map([trip.mLatitude.mean(), trip.mLongitude.mean()]) plot_point = lambda row: currMap.simple_marker([row['mLatitude'], row['mLongitude']], popup='%s' % row) trip.apply(plot_point, axis=1) currMap.line(zip(list(trip.mLatitude), list(trip.mLongitude))) mapList.append(currMap) return mapList Enhance our plotter to use the new div_markers code And to generate popups correctlyimport pandas as pd import folium def df_to_string_list(df): """ Convert the input df into a list of strings, suitable for using as popups in a map. This is a utility function. """ print "Converting df with size %s to string list" % df.shape[0] array_list = df.as_matrix().tolist() return [str(line) for line in array_list] def get_map_list(df, potential_splits): mapList = [] potential_splits_list = list(potential_splits) for start, end in zip(potential_splits_list, potential_splits_list[1:]): trip = df[start:end] currMap = folium.Map([trip.mLatitude.mean(), trip.mLongitude.mean()]) currMap.div_markers(trip[['mLatitude', 'mLongitude']].as_matrix().tolist(), df_to_string_list(trip[['mLatitude', 'mLongitude', 'formatted_time', 'mAccuracy']])) currMap.line(trip[['mLatitude', 'mLongitude']].as_matrix().tolist()) mapList.append(currMap) return mapList
<commit_before>import pandas as pd import folium def get_map_list(df, potential_splits): mapList = [] potential_splits_list = list(potential_splits) for start, end in zip(potential_splits_list, potential_splits_list[1:]): trip = df[start:end] currMap = folium.Map([trip.mLatitude.mean(), trip.mLongitude.mean()]) plot_point = lambda row: currMap.simple_marker([row['mLatitude'], row['mLongitude']], popup='%s' % row) trip.apply(plot_point, axis=1) currMap.line(zip(list(trip.mLatitude), list(trip.mLongitude))) mapList.append(currMap) return mapList <commit_msg>Enhance our plotter to use the new div_markers code And to generate popups correctly<commit_after>import pandas as pd import folium def df_to_string_list(df): """ Convert the input df into a list of strings, suitable for using as popups in a map. This is a utility function. """ print "Converting df with size %s to string list" % df.shape[0] array_list = df.as_matrix().tolist() return [str(line) for line in array_list] def get_map_list(df, potential_splits): mapList = [] potential_splits_list = list(potential_splits) for start, end in zip(potential_splits_list, potential_splits_list[1:]): trip = df[start:end] currMap = folium.Map([trip.mLatitude.mean(), trip.mLongitude.mean()]) currMap.div_markers(trip[['mLatitude', 'mLongitude']].as_matrix().tolist(), df_to_string_list(trip[['mLatitude', 'mLongitude', 'formatted_time', 'mAccuracy']])) currMap.line(trip[['mLatitude', 'mLongitude']].as_matrix().tolist()) mapList.append(currMap) return mapList
93700dba921c6bffe77f2eaadc2d7ece5dde03e5
tests/__init__.py
tests/__init__.py
from bsAbstimmungen import setup_logging setup_logging('tests/test-logging.json')
from bsAbstimmungen.utils import setup_logging setup_logging('tests/test-logging.json')
Fix error caused by moving function setup_logging
Fix error caused by moving function setup_logging
Python
mit
raphiz/bsAbstimmungen,raphiz/bsAbstimmungen
from bsAbstimmungen import setup_logging setup_logging('tests/test-logging.json') Fix error caused by moving function setup_logging
from bsAbstimmungen.utils import setup_logging setup_logging('tests/test-logging.json')
<commit_before>from bsAbstimmungen import setup_logging setup_logging('tests/test-logging.json') <commit_msg>Fix error caused by moving function setup_logging<commit_after>
from bsAbstimmungen.utils import setup_logging setup_logging('tests/test-logging.json')
from bsAbstimmungen import setup_logging setup_logging('tests/test-logging.json') Fix error caused by moving function setup_loggingfrom bsAbstimmungen.utils import setup_logging setup_logging('tests/test-logging.json')
<commit_before>from bsAbstimmungen import setup_logging setup_logging('tests/test-logging.json') <commit_msg>Fix error caused by moving function setup_logging<commit_after>from bsAbstimmungen.utils import setup_logging setup_logging('tests/test-logging.json')
19dd810c5acb35ce5d7565ee57a55ae725194bd1
mvp/integration.py
mvp/integration.py
# -*- coding: utf-8 -*- class Integration(object): name = None description = None icon = None banner = None requires_confirmation = False enabled_by_default = False columns = 1 def __init__(self): self.set_enabled(self.enabled_by_default) def fields(self): '''Return a list of fields. Example: return [ { 'name': 'StringField', 'type': 'str', 'default': None, 'options': [...], 'required': False, }, ... ] ''' return NotImplemented def on_filename_changed(self, form, value): return NotImplemented def set_enabled(self, value): '''Returns True if the integration was successfully enabled''' if value: return self._on_enable() else: return self._on_disable() def _on_enable(self): self.enabled = self.on_enable() return self.enabled def on_enable(self): '''Return True to enable integration and False to disable''' return True def _on_disable(self): self.enabled = not self.on_disable() return self.enabled def on_disable(self): '''Return True to disable integration and False to enable''' return True def before_playblast(self, data): return NotImplemented def after_playblast(self, data): return NotImplemented
# -*- coding: utf-8 -*- class Integration(object): name = None description = None icon = None banner = None requires_confirmation = False enabled_by_default = False columns = 1 def __init__(self): self.set_enabled(self.enabled_by_default) def fields(self): '''Return a list of fields. Example: return [ { 'name': 'StringField', 'type': 'str', 'default': None, 'options': [...], 'required': False, }, ... ] ''' return NotImplemented def on_filename_changed(self, form, value): return NotImplemented def set_enabled(self, value): '''Returns True if the integration was successfully enabled''' if value: return self._on_enable() else: return self._on_disable() def _on_enable(self): self.enabled = self.on_enable() return self.enabled def on_enable(self): '''Return True to enable integration and False to disable''' return True def _on_disable(self): self.enabled = not self.on_disable() return self.enabled def on_disable(self): '''Return True to disable integration and False to enable''' return True def before_playblast(self, form, data): '''Runs before playblasting.''' return NotImplemented def after_playblast(self, form, data): '''Runs after playblasting.''' return NotImplemented def finalize(self, form, data): '''Runs after entire playblast process is finished. Unlike after_playblast, this method will only run ONCE after all playblasting is finished. So, when playblasting multiple render layers you can use this to execute after all of those render layers have completed rendering. Arguments: form: The Form object including render options data: List of renders that were output ''' return NotImplemented
Add finalize method to Integration.
Add finalize method to Integration.
Python
mit
danbradham/mvp
# -*- coding: utf-8 -*- class Integration(object): name = None description = None icon = None banner = None requires_confirmation = False enabled_by_default = False columns = 1 def __init__(self): self.set_enabled(self.enabled_by_default) def fields(self): '''Return a list of fields. Example: return [ { 'name': 'StringField', 'type': 'str', 'default': None, 'options': [...], 'required': False, }, ... ] ''' return NotImplemented def on_filename_changed(self, form, value): return NotImplemented def set_enabled(self, value): '''Returns True if the integration was successfully enabled''' if value: return self._on_enable() else: return self._on_disable() def _on_enable(self): self.enabled = self.on_enable() return self.enabled def on_enable(self): '''Return True to enable integration and False to disable''' return True def _on_disable(self): self.enabled = not self.on_disable() return self.enabled def on_disable(self): '''Return True to disable integration and False to enable''' return True def before_playblast(self, data): return NotImplemented def after_playblast(self, data): return NotImplemented Add finalize method to Integration.
# -*- coding: utf-8 -*- class Integration(object): name = None description = None icon = None banner = None requires_confirmation = False enabled_by_default = False columns = 1 def __init__(self): self.set_enabled(self.enabled_by_default) def fields(self): '''Return a list of fields. Example: return [ { 'name': 'StringField', 'type': 'str', 'default': None, 'options': [...], 'required': False, }, ... ] ''' return NotImplemented def on_filename_changed(self, form, value): return NotImplemented def set_enabled(self, value): '''Returns True if the integration was successfully enabled''' if value: return self._on_enable() else: return self._on_disable() def _on_enable(self): self.enabled = self.on_enable() return self.enabled def on_enable(self): '''Return True to enable integration and False to disable''' return True def _on_disable(self): self.enabled = not self.on_disable() return self.enabled def on_disable(self): '''Return True to disable integration and False to enable''' return True def before_playblast(self, form, data): '''Runs before playblasting.''' return NotImplemented def after_playblast(self, form, data): '''Runs after playblasting.''' return NotImplemented def finalize(self, form, data): '''Runs after entire playblast process is finished. Unlike after_playblast, this method will only run ONCE after all playblasting is finished. So, when playblasting multiple render layers you can use this to execute after all of those render layers have completed rendering. Arguments: form: The Form object including render options data: List of renders that were output ''' return NotImplemented
<commit_before># -*- coding: utf-8 -*- class Integration(object): name = None description = None icon = None banner = None requires_confirmation = False enabled_by_default = False columns = 1 def __init__(self): self.set_enabled(self.enabled_by_default) def fields(self): '''Return a list of fields. Example: return [ { 'name': 'StringField', 'type': 'str', 'default': None, 'options': [...], 'required': False, }, ... ] ''' return NotImplemented def on_filename_changed(self, form, value): return NotImplemented def set_enabled(self, value): '''Returns True if the integration was successfully enabled''' if value: return self._on_enable() else: return self._on_disable() def _on_enable(self): self.enabled = self.on_enable() return self.enabled def on_enable(self): '''Return True to enable integration and False to disable''' return True def _on_disable(self): self.enabled = not self.on_disable() return self.enabled def on_disable(self): '''Return True to disable integration and False to enable''' return True def before_playblast(self, data): return NotImplemented def after_playblast(self, data): return NotImplemented <commit_msg>Add finalize method to Integration.<commit_after>
# -*- coding: utf-8 -*- class Integration(object): name = None description = None icon = None banner = None requires_confirmation = False enabled_by_default = False columns = 1 def __init__(self): self.set_enabled(self.enabled_by_default) def fields(self): '''Return a list of fields. Example: return [ { 'name': 'StringField', 'type': 'str', 'default': None, 'options': [...], 'required': False, }, ... ] ''' return NotImplemented def on_filename_changed(self, form, value): return NotImplemented def set_enabled(self, value): '''Returns True if the integration was successfully enabled''' if value: return self._on_enable() else: return self._on_disable() def _on_enable(self): self.enabled = self.on_enable() return self.enabled def on_enable(self): '''Return True to enable integration and False to disable''' return True def _on_disable(self): self.enabled = not self.on_disable() return self.enabled def on_disable(self): '''Return True to disable integration and False to enable''' return True def before_playblast(self, form, data): '''Runs before playblasting.''' return NotImplemented def after_playblast(self, form, data): '''Runs after playblasting.''' return NotImplemented def finalize(self, form, data): '''Runs after entire playblast process is finished. Unlike after_playblast, this method will only run ONCE after all playblasting is finished. So, when playblasting multiple render layers you can use this to execute after all of those render layers have completed rendering. Arguments: form: The Form object including render options data: List of renders that were output ''' return NotImplemented
# -*- coding: utf-8 -*- class Integration(object): name = None description = None icon = None banner = None requires_confirmation = False enabled_by_default = False columns = 1 def __init__(self): self.set_enabled(self.enabled_by_default) def fields(self): '''Return a list of fields. Example: return [ { 'name': 'StringField', 'type': 'str', 'default': None, 'options': [...], 'required': False, }, ... ] ''' return NotImplemented def on_filename_changed(self, form, value): return NotImplemented def set_enabled(self, value): '''Returns True if the integration was successfully enabled''' if value: return self._on_enable() else: return self._on_disable() def _on_enable(self): self.enabled = self.on_enable() return self.enabled def on_enable(self): '''Return True to enable integration and False to disable''' return True def _on_disable(self): self.enabled = not self.on_disable() return self.enabled def on_disable(self): '''Return True to disable integration and False to enable''' return True def before_playblast(self, data): return NotImplemented def after_playblast(self, data): return NotImplemented Add finalize method to Integration.# -*- coding: utf-8 -*- class Integration(object): name = None description = None icon = None banner = None requires_confirmation = False enabled_by_default = False columns = 1 def __init__(self): self.set_enabled(self.enabled_by_default) def fields(self): '''Return a list of fields. Example: return [ { 'name': 'StringField', 'type': 'str', 'default': None, 'options': [...], 'required': False, }, ... ] ''' return NotImplemented def on_filename_changed(self, form, value): return NotImplemented def set_enabled(self, value): '''Returns True if the integration was successfully enabled''' if value: return self._on_enable() else: return self._on_disable() def _on_enable(self): self.enabled = self.on_enable() return self.enabled def on_enable(self): '''Return True to enable integration and False to disable''' return True def _on_disable(self): self.enabled = not self.on_disable() return self.enabled def on_disable(self): '''Return True to disable integration and False to enable''' return True def before_playblast(self, form, data): '''Runs before playblasting.''' return NotImplemented def after_playblast(self, form, data): '''Runs after playblasting.''' return NotImplemented def finalize(self, form, data): '''Runs after entire playblast process is finished. Unlike after_playblast, this method will only run ONCE after all playblasting is finished. So, when playblasting multiple render layers you can use this to execute after all of those render layers have completed rendering. Arguments: form: The Form object including render options data: List of renders that were output ''' return NotImplemented
<commit_before># -*- coding: utf-8 -*- class Integration(object): name = None description = None icon = None banner = None requires_confirmation = False enabled_by_default = False columns = 1 def __init__(self): self.set_enabled(self.enabled_by_default) def fields(self): '''Return a list of fields. Example: return [ { 'name': 'StringField', 'type': 'str', 'default': None, 'options': [...], 'required': False, }, ... ] ''' return NotImplemented def on_filename_changed(self, form, value): return NotImplemented def set_enabled(self, value): '''Returns True if the integration was successfully enabled''' if value: return self._on_enable() else: return self._on_disable() def _on_enable(self): self.enabled = self.on_enable() return self.enabled def on_enable(self): '''Return True to enable integration and False to disable''' return True def _on_disable(self): self.enabled = not self.on_disable() return self.enabled def on_disable(self): '''Return True to disable integration and False to enable''' return True def before_playblast(self, data): return NotImplemented def after_playblast(self, data): return NotImplemented <commit_msg>Add finalize method to Integration.<commit_after># -*- coding: utf-8 -*- class Integration(object): name = None description = None icon = None banner = None requires_confirmation = False enabled_by_default = False columns = 1 def __init__(self): self.set_enabled(self.enabled_by_default) def fields(self): '''Return a list of fields. Example: return [ { 'name': 'StringField', 'type': 'str', 'default': None, 'options': [...], 'required': False, }, ... ] ''' return NotImplemented def on_filename_changed(self, form, value): return NotImplemented def set_enabled(self, value): '''Returns True if the integration was successfully enabled''' if value: return self._on_enable() else: return self._on_disable() def _on_enable(self): self.enabled = self.on_enable() return self.enabled def on_enable(self): '''Return True to enable integration and False to disable''' return True def _on_disable(self): self.enabled = not self.on_disable() return self.enabled def on_disable(self): '''Return True to disable integration and False to enable''' return True def before_playblast(self, form, data): '''Runs before playblasting.''' return NotImplemented def after_playblast(self, form, data): '''Runs after playblasting.''' return NotImplemented def finalize(self, form, data): '''Runs after entire playblast process is finished. Unlike after_playblast, this method will only run ONCE after all playblasting is finished. So, when playblasting multiple render layers you can use this to execute after all of those render layers have completed rendering. Arguments: form: The Form object including render options data: List of renders that were output ''' return NotImplemented
c970cab38d846c4774aee52e52c23ed2452af96a
openfisca_france_data/tests/base.py
openfisca_france_data/tests/base.py
# -*- coding: utf-8 -*- from openfisca_core.tools import assert_near from openfisca_france.tests.base import get_cached_composed_reform, get_cached_reform from .. import france_data_tax_benefit_system, FranceDataTaxBenefitSystem __all__ = [ 'assert_near', 'france_data_tax_benefit_system', 'FranceDataTaxBenefitSystem', 'get_cached_composed_reform', 'get_cached_reform', ]
# -*- coding: utf-8 -*- from openfisca_core.tools import assert_near from openfisca_france.tests.base import get_cached_composed_reform, get_cached_reform from .. import france_data_tax_benefit_system __all__ = [ 'assert_near', 'france_data_tax_benefit_system', 'get_cached_composed_reform', 'get_cached_reform', ]
Remove unused and buggy import
Remove unused and buggy import
Python
agpl-3.0
openfisca/openfisca-france-data,openfisca/openfisca-france-data,openfisca/openfisca-france-data
# -*- coding: utf-8 -*- from openfisca_core.tools import assert_near from openfisca_france.tests.base import get_cached_composed_reform, get_cached_reform from .. import france_data_tax_benefit_system, FranceDataTaxBenefitSystem __all__ = [ 'assert_near', 'france_data_tax_benefit_system', 'FranceDataTaxBenefitSystem', 'get_cached_composed_reform', 'get_cached_reform', ] Remove unused and buggy import
# -*- coding: utf-8 -*- from openfisca_core.tools import assert_near from openfisca_france.tests.base import get_cached_composed_reform, get_cached_reform from .. import france_data_tax_benefit_system __all__ = [ 'assert_near', 'france_data_tax_benefit_system', 'get_cached_composed_reform', 'get_cached_reform', ]
<commit_before># -*- coding: utf-8 -*- from openfisca_core.tools import assert_near from openfisca_france.tests.base import get_cached_composed_reform, get_cached_reform from .. import france_data_tax_benefit_system, FranceDataTaxBenefitSystem __all__ = [ 'assert_near', 'france_data_tax_benefit_system', 'FranceDataTaxBenefitSystem', 'get_cached_composed_reform', 'get_cached_reform', ] <commit_msg>Remove unused and buggy import<commit_after>
# -*- coding: utf-8 -*- from openfisca_core.tools import assert_near from openfisca_france.tests.base import get_cached_composed_reform, get_cached_reform from .. import france_data_tax_benefit_system __all__ = [ 'assert_near', 'france_data_tax_benefit_system', 'get_cached_composed_reform', 'get_cached_reform', ]
# -*- coding: utf-8 -*- from openfisca_core.tools import assert_near from openfisca_france.tests.base import get_cached_composed_reform, get_cached_reform from .. import france_data_tax_benefit_system, FranceDataTaxBenefitSystem __all__ = [ 'assert_near', 'france_data_tax_benefit_system', 'FranceDataTaxBenefitSystem', 'get_cached_composed_reform', 'get_cached_reform', ] Remove unused and buggy import# -*- coding: utf-8 -*- from openfisca_core.tools import assert_near from openfisca_france.tests.base import get_cached_composed_reform, get_cached_reform from .. import france_data_tax_benefit_system __all__ = [ 'assert_near', 'france_data_tax_benefit_system', 'get_cached_composed_reform', 'get_cached_reform', ]
<commit_before># -*- coding: utf-8 -*- from openfisca_core.tools import assert_near from openfisca_france.tests.base import get_cached_composed_reform, get_cached_reform from .. import france_data_tax_benefit_system, FranceDataTaxBenefitSystem __all__ = [ 'assert_near', 'france_data_tax_benefit_system', 'FranceDataTaxBenefitSystem', 'get_cached_composed_reform', 'get_cached_reform', ] <commit_msg>Remove unused and buggy import<commit_after># -*- coding: utf-8 -*- from openfisca_core.tools import assert_near from openfisca_france.tests.base import get_cached_composed_reform, get_cached_reform from .. import france_data_tax_benefit_system __all__ = [ 'assert_near', 'france_data_tax_benefit_system', 'get_cached_composed_reform', 'get_cached_reform', ]
151599602b9d626ebcfe5ae6960ea216b767fec2
setuptools/distutils_patch.py
setuptools/distutils_patch.py
""" Ensure that the local copy of distutils is preferred over stdlib. See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 for more motivation. """ import sys import importlib from os.path import dirname sys.path.insert(0, dirname(dirname(__file__))) importlib.import_module('distutils') sys.path.pop(0)
""" Ensure that the local copy of distutils is preferred over stdlib. See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 for more motivation. """ import sys import importlib import contextlib from os.path import dirname @contextlib.contextmanager def patch_sys_path(): orig = sys.path[:] sys.path[:] = [dirname(dirname(__file__))] try: yield finally: sys.path[:] = orig if 'distutils' in sys.path: raise RuntimeError("Distutils must not be imported before setuptools") with patch_sys_path(): importlib.import_module('distutils')
Update distutils patch to monkeypatch all paths from sys.path to ensure that distutils is never imported except from the same path as setuptools. Assert that 'distutils' is not already in sys.modules.
Update distutils patch to monkeypatch all paths from sys.path to ensure that distutils is never imported except from the same path as setuptools. Assert that 'distutils' is not already in sys.modules.
Python
mit
pypa/setuptools,pypa/setuptools,pypa/setuptools
""" Ensure that the local copy of distutils is preferred over stdlib. See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 for more motivation. """ import sys import importlib from os.path import dirname sys.path.insert(0, dirname(dirname(__file__))) importlib.import_module('distutils') sys.path.pop(0) Update distutils patch to monkeypatch all paths from sys.path to ensure that distutils is never imported except from the same path as setuptools. Assert that 'distutils' is not already in sys.modules.
""" Ensure that the local copy of distutils is preferred over stdlib. See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 for more motivation. """ import sys import importlib import contextlib from os.path import dirname @contextlib.contextmanager def patch_sys_path(): orig = sys.path[:] sys.path[:] = [dirname(dirname(__file__))] try: yield finally: sys.path[:] = orig if 'distutils' in sys.path: raise RuntimeError("Distutils must not be imported before setuptools") with patch_sys_path(): importlib.import_module('distutils')
<commit_before>""" Ensure that the local copy of distutils is preferred over stdlib. See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 for more motivation. """ import sys import importlib from os.path import dirname sys.path.insert(0, dirname(dirname(__file__))) importlib.import_module('distutils') sys.path.pop(0) <commit_msg>Update distutils patch to monkeypatch all paths from sys.path to ensure that distutils is never imported except from the same path as setuptools. Assert that 'distutils' is not already in sys.modules.<commit_after>
""" Ensure that the local copy of distutils is preferred over stdlib. See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 for more motivation. """ import sys import importlib import contextlib from os.path import dirname @contextlib.contextmanager def patch_sys_path(): orig = sys.path[:] sys.path[:] = [dirname(dirname(__file__))] try: yield finally: sys.path[:] = orig if 'distutils' in sys.path: raise RuntimeError("Distutils must not be imported before setuptools") with patch_sys_path(): importlib.import_module('distutils')
""" Ensure that the local copy of distutils is preferred over stdlib. See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 for more motivation. """ import sys import importlib from os.path import dirname sys.path.insert(0, dirname(dirname(__file__))) importlib.import_module('distutils') sys.path.pop(0) Update distutils patch to monkeypatch all paths from sys.path to ensure that distutils is never imported except from the same path as setuptools. Assert that 'distutils' is not already in sys.modules.""" Ensure that the local copy of distutils is preferred over stdlib. See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 for more motivation. """ import sys import importlib import contextlib from os.path import dirname @contextlib.contextmanager def patch_sys_path(): orig = sys.path[:] sys.path[:] = [dirname(dirname(__file__))] try: yield finally: sys.path[:] = orig if 'distutils' in sys.path: raise RuntimeError("Distutils must not be imported before setuptools") with patch_sys_path(): importlib.import_module('distutils')
<commit_before>""" Ensure that the local copy of distutils is preferred over stdlib. See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 for more motivation. """ import sys import importlib from os.path import dirname sys.path.insert(0, dirname(dirname(__file__))) importlib.import_module('distutils') sys.path.pop(0) <commit_msg>Update distutils patch to monkeypatch all paths from sys.path to ensure that distutils is never imported except from the same path as setuptools. Assert that 'distutils' is not already in sys.modules.<commit_after>""" Ensure that the local copy of distutils is preferred over stdlib. See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 for more motivation. """ import sys import importlib import contextlib from os.path import dirname @contextlib.contextmanager def patch_sys_path(): orig = sys.path[:] sys.path[:] = [dirname(dirname(__file__))] try: yield finally: sys.path[:] = orig if 'distutils' in sys.path: raise RuntimeError("Distutils must not be imported before setuptools") with patch_sys_path(): importlib.import_module('distutils')
de23099e04d0a5823d6917f6f991d66e25b9002b
django_medusa/management/commands/staticsitegen.py
django_medusa/management/commands/staticsitegen.py
from django.core.management.base import BaseCommand from django_medusa.renderers import StaticSiteRenderer from django_medusa.utils import get_static_renderers class Command(BaseCommand): can_import_settings = True help = 'Looks for \'renderers.py\' in each INSTALLED_APP, which defines '\ 'a class for processing one or more URL paths into static files.' def handle(self, *args, **options): StaticSiteRenderer.initialize_output() for Renderer in get_static_renderers(): r = Renderer() r.generate() StaticSiteRenderer.finalize_output()
from django.conf import settings from django.core.management.base import BaseCommand from django.core.urlresolvers import set_script_prefix from django_medusa.renderers import StaticSiteRenderer from django_medusa.utils import get_static_renderers class Command(BaseCommand): can_import_settings = True help = 'Looks for \'renderers.py\' in each INSTALLED_APP, which defines '\ 'a class for processing one or more URL paths into static files.' def handle(self, *args, **options): StaticSiteRenderer.initialize_output() url_prefix = getattr(settings, 'MEDUSA_URL_PREFIX') if url_prefix is not None: set_script_prefix(url_prefix) for Renderer in get_static_renderers(): r = Renderer() r.generate() StaticSiteRenderer.finalize_output()
Add support for rendering with a URL prefix
Add support for rendering with a URL prefix This adds an optional MEDUSA_URL_PREFIX setting option that causes Django's URL reversing to render URLS prefixed with this string. This is necessary when hosting Django projects on a URI path other than /, as a proper WSGI environment is not present to tell Django what URL prefix to use.
Python
mit
hyperair/django-medusa
from django.core.management.base import BaseCommand from django_medusa.renderers import StaticSiteRenderer from django_medusa.utils import get_static_renderers class Command(BaseCommand): can_import_settings = True help = 'Looks for \'renderers.py\' in each INSTALLED_APP, which defines '\ 'a class for processing one or more URL paths into static files.' def handle(self, *args, **options): StaticSiteRenderer.initialize_output() for Renderer in get_static_renderers(): r = Renderer() r.generate() StaticSiteRenderer.finalize_output() Add support for rendering with a URL prefix This adds an optional MEDUSA_URL_PREFIX setting option that causes Django's URL reversing to render URLS prefixed with this string. This is necessary when hosting Django projects on a URI path other than /, as a proper WSGI environment is not present to tell Django what URL prefix to use.
from django.conf import settings from django.core.management.base import BaseCommand from django.core.urlresolvers import set_script_prefix from django_medusa.renderers import StaticSiteRenderer from django_medusa.utils import get_static_renderers class Command(BaseCommand): can_import_settings = True help = 'Looks for \'renderers.py\' in each INSTALLED_APP, which defines '\ 'a class for processing one or more URL paths into static files.' def handle(self, *args, **options): StaticSiteRenderer.initialize_output() url_prefix = getattr(settings, 'MEDUSA_URL_PREFIX') if url_prefix is not None: set_script_prefix(url_prefix) for Renderer in get_static_renderers(): r = Renderer() r.generate() StaticSiteRenderer.finalize_output()
<commit_before>from django.core.management.base import BaseCommand from django_medusa.renderers import StaticSiteRenderer from django_medusa.utils import get_static_renderers class Command(BaseCommand): can_import_settings = True help = 'Looks for \'renderers.py\' in each INSTALLED_APP, which defines '\ 'a class for processing one or more URL paths into static files.' def handle(self, *args, **options): StaticSiteRenderer.initialize_output() for Renderer in get_static_renderers(): r = Renderer() r.generate() StaticSiteRenderer.finalize_output() <commit_msg>Add support for rendering with a URL prefix This adds an optional MEDUSA_URL_PREFIX setting option that causes Django's URL reversing to render URLS prefixed with this string. This is necessary when hosting Django projects on a URI path other than /, as a proper WSGI environment is not present to tell Django what URL prefix to use.<commit_after>
from django.conf import settings from django.core.management.base import BaseCommand from django.core.urlresolvers import set_script_prefix from django_medusa.renderers import StaticSiteRenderer from django_medusa.utils import get_static_renderers class Command(BaseCommand): can_import_settings = True help = 'Looks for \'renderers.py\' in each INSTALLED_APP, which defines '\ 'a class for processing one or more URL paths into static files.' def handle(self, *args, **options): StaticSiteRenderer.initialize_output() url_prefix = getattr(settings, 'MEDUSA_URL_PREFIX') if url_prefix is not None: set_script_prefix(url_prefix) for Renderer in get_static_renderers(): r = Renderer() r.generate() StaticSiteRenderer.finalize_output()
from django.core.management.base import BaseCommand from django_medusa.renderers import StaticSiteRenderer from django_medusa.utils import get_static_renderers class Command(BaseCommand): can_import_settings = True help = 'Looks for \'renderers.py\' in each INSTALLED_APP, which defines '\ 'a class for processing one or more URL paths into static files.' def handle(self, *args, **options): StaticSiteRenderer.initialize_output() for Renderer in get_static_renderers(): r = Renderer() r.generate() StaticSiteRenderer.finalize_output() Add support for rendering with a URL prefix This adds an optional MEDUSA_URL_PREFIX setting option that causes Django's URL reversing to render URLS prefixed with this string. This is necessary when hosting Django projects on a URI path other than /, as a proper WSGI environment is not present to tell Django what URL prefix to use.from django.conf import settings from django.core.management.base import BaseCommand from django.core.urlresolvers import set_script_prefix from django_medusa.renderers import StaticSiteRenderer from django_medusa.utils import get_static_renderers class Command(BaseCommand): can_import_settings = True help = 'Looks for \'renderers.py\' in each INSTALLED_APP, which defines '\ 'a class for processing one or more URL paths into static files.' def handle(self, *args, **options): StaticSiteRenderer.initialize_output() url_prefix = getattr(settings, 'MEDUSA_URL_PREFIX') if url_prefix is not None: set_script_prefix(url_prefix) for Renderer in get_static_renderers(): r = Renderer() r.generate() StaticSiteRenderer.finalize_output()
<commit_before>from django.core.management.base import BaseCommand from django_medusa.renderers import StaticSiteRenderer from django_medusa.utils import get_static_renderers class Command(BaseCommand): can_import_settings = True help = 'Looks for \'renderers.py\' in each INSTALLED_APP, which defines '\ 'a class for processing one or more URL paths into static files.' def handle(self, *args, **options): StaticSiteRenderer.initialize_output() for Renderer in get_static_renderers(): r = Renderer() r.generate() StaticSiteRenderer.finalize_output() <commit_msg>Add support for rendering with a URL prefix This adds an optional MEDUSA_URL_PREFIX setting option that causes Django's URL reversing to render URLS prefixed with this string. This is necessary when hosting Django projects on a URI path other than /, as a proper WSGI environment is not present to tell Django what URL prefix to use.<commit_after>from django.conf import settings from django.core.management.base import BaseCommand from django.core.urlresolvers import set_script_prefix from django_medusa.renderers import StaticSiteRenderer from django_medusa.utils import get_static_renderers class Command(BaseCommand): can_import_settings = True help = 'Looks for \'renderers.py\' in each INSTALLED_APP, which defines '\ 'a class for processing one or more URL paths into static files.' def handle(self, *args, **options): StaticSiteRenderer.initialize_output() url_prefix = getattr(settings, 'MEDUSA_URL_PREFIX') if url_prefix is not None: set_script_prefix(url_prefix) for Renderer in get_static_renderers(): r = Renderer() r.generate() StaticSiteRenderer.finalize_output()
dc67190ae855de30f0ee33f4d8b34462d44667e9
nightreads/urls.py
nightreads/urls.py
"""nightreads URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from nightreads.user_manager import urls as user_manager_urls urlpatterns = [ url(r'^user/', include(user_manager_urls, namespace='user')), url(r'^admin/', admin.site.urls), ]
"""nightreads URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from nightreads.user_manager import urls as user_manager_urls urlpatterns = [ url(r'^users/', include(user_manager_urls, namespace='users')), url(r'^admin/', admin.site.urls), ]
Change URL scheme `user` to `users`
Change URL scheme `user` to `users`
Python
mit
avinassh/nightreads,avinassh/nightreads
"""nightreads URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from nightreads.user_manager import urls as user_manager_urls urlpatterns = [ url(r'^user/', include(user_manager_urls, namespace='user')), url(r'^admin/', admin.site.urls), ] Change URL scheme `user` to `users`
"""nightreads URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from nightreads.user_manager import urls as user_manager_urls urlpatterns = [ url(r'^users/', include(user_manager_urls, namespace='users')), url(r'^admin/', admin.site.urls), ]
<commit_before>"""nightreads URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from nightreads.user_manager import urls as user_manager_urls urlpatterns = [ url(r'^user/', include(user_manager_urls, namespace='user')), url(r'^admin/', admin.site.urls), ] <commit_msg>Change URL scheme `user` to `users`<commit_after>
"""nightreads URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from nightreads.user_manager import urls as user_manager_urls urlpatterns = [ url(r'^users/', include(user_manager_urls, namespace='users')), url(r'^admin/', admin.site.urls), ]
"""nightreads URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from nightreads.user_manager import urls as user_manager_urls urlpatterns = [ url(r'^user/', include(user_manager_urls, namespace='user')), url(r'^admin/', admin.site.urls), ] Change URL scheme `user` to `users`"""nightreads URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from nightreads.user_manager import urls as user_manager_urls urlpatterns = [ url(r'^users/', include(user_manager_urls, namespace='users')), url(r'^admin/', admin.site.urls), ]
<commit_before>"""nightreads URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from nightreads.user_manager import urls as user_manager_urls urlpatterns = [ url(r'^user/', include(user_manager_urls, namespace='user')), url(r'^admin/', admin.site.urls), ] <commit_msg>Change URL scheme `user` to `users`<commit_after>"""nightreads URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from nightreads.user_manager import urls as user_manager_urls urlpatterns = [ url(r'^users/', include(user_manager_urls, namespace='users')), url(r'^admin/', admin.site.urls), ]
28770cf4d0995697f7b2c8edad7a56fb8aeabea5
Sendy.py
Sendy.py
# coding: utf-8 # ! /usr/bin/python __author__ = 'Shahariar Rabby' # # Sendy # ### Importing Send mail file # In[6]: from Sendmail import * # ** Take user email, text plan massage, HTML file ** # In[7]: TO_EMAIL = raw_input("Enter reciver email : ") #Taking Reciver email as input subject = raw_input("Enter Mail Subject : ") #taking mail subject text = raw_input("Enter Plain message(or html format) : ") #Taking plane massage as input filename = raw_input('Enter file name with location(if any) : ') try: file = open(filename,'r') #reading HTML format message html = file.read() except: html = text # **Calling send mail and sending mail ** # In[8]: Send_Mail(login(),TO_EMAIL=TO_EMAIL,text=text,html=html,subject=subject)
# coding: utf-8 # ! /usr/bin/python __author__ = 'Shahariar Rabby' # This will read details and send email to clint # # Sendy # ### Importing Send mail file # In[6]: from Sendmail import * # ** Take user email, text plan massage, HTML file ** # In[7]: TO_EMAIL = raw_input("Enter reciver email : ") #Taking Reciver email as input subject = raw_input("Enter Mail Subject : ") #taking mail subject text = raw_input("Enter Plain message(or html format) : ") #Taking plane massage as input filename = raw_input('Enter file name with location(if any) : ') try: file = open(filename,'r') #reading HTML format message html = file.read() except: html = text # **Calling send mail and sending mail ** # In[8]: Send_Mail(login(),TO_EMAIL=TO_EMAIL,text=text,html=html,subject=subject)
Send email to client working
Send email to client working
Python
mit
shahariarrabby/Mail_Server
# coding: utf-8 # ! /usr/bin/python __author__ = 'Shahariar Rabby' # # Sendy # ### Importing Send mail file # In[6]: from Sendmail import * # ** Take user email, text plan massage, HTML file ** # In[7]: TO_EMAIL = raw_input("Enter reciver email : ") #Taking Reciver email as input subject = raw_input("Enter Mail Subject : ") #taking mail subject text = raw_input("Enter Plain message(or html format) : ") #Taking plane massage as input filename = raw_input('Enter file name with location(if any) : ') try: file = open(filename,'r') #reading HTML format message html = file.read() except: html = text # **Calling send mail and sending mail ** # In[8]: Send_Mail(login(),TO_EMAIL=TO_EMAIL,text=text,html=html,subject=subject) Send email to client working
# coding: utf-8 # ! /usr/bin/python __author__ = 'Shahariar Rabby' # This will read details and send email to clint # # Sendy # ### Importing Send mail file # In[6]: from Sendmail import * # ** Take user email, text plan massage, HTML file ** # In[7]: TO_EMAIL = raw_input("Enter reciver email : ") #Taking Reciver email as input subject = raw_input("Enter Mail Subject : ") #taking mail subject text = raw_input("Enter Plain message(or html format) : ") #Taking plane massage as input filename = raw_input('Enter file name with location(if any) : ') try: file = open(filename,'r') #reading HTML format message html = file.read() except: html = text # **Calling send mail and sending mail ** # In[8]: Send_Mail(login(),TO_EMAIL=TO_EMAIL,text=text,html=html,subject=subject)
<commit_before># coding: utf-8 # ! /usr/bin/python __author__ = 'Shahariar Rabby' # # Sendy # ### Importing Send mail file # In[6]: from Sendmail import * # ** Take user email, text plan massage, HTML file ** # In[7]: TO_EMAIL = raw_input("Enter reciver email : ") #Taking Reciver email as input subject = raw_input("Enter Mail Subject : ") #taking mail subject text = raw_input("Enter Plain message(or html format) : ") #Taking plane massage as input filename = raw_input('Enter file name with location(if any) : ') try: file = open(filename,'r') #reading HTML format message html = file.read() except: html = text # **Calling send mail and sending mail ** # In[8]: Send_Mail(login(),TO_EMAIL=TO_EMAIL,text=text,html=html,subject=subject) <commit_msg>Send email to client working<commit_after>
# coding: utf-8 # ! /usr/bin/python __author__ = 'Shahariar Rabby' # This will read details and send email to clint # # Sendy # ### Importing Send mail file # In[6]: from Sendmail import * # ** Take user email, text plan massage, HTML file ** # In[7]: TO_EMAIL = raw_input("Enter reciver email : ") #Taking Reciver email as input subject = raw_input("Enter Mail Subject : ") #taking mail subject text = raw_input("Enter Plain message(or html format) : ") #Taking plane massage as input filename = raw_input('Enter file name with location(if any) : ') try: file = open(filename,'r') #reading HTML format message html = file.read() except: html = text # **Calling send mail and sending mail ** # In[8]: Send_Mail(login(),TO_EMAIL=TO_EMAIL,text=text,html=html,subject=subject)
# coding: utf-8 # ! /usr/bin/python __author__ = 'Shahariar Rabby' # # Sendy # ### Importing Send mail file # In[6]: from Sendmail import * # ** Take user email, text plan massage, HTML file ** # In[7]: TO_EMAIL = raw_input("Enter reciver email : ") #Taking Reciver email as input subject = raw_input("Enter Mail Subject : ") #taking mail subject text = raw_input("Enter Plain message(or html format) : ") #Taking plane massage as input filename = raw_input('Enter file name with location(if any) : ') try: file = open(filename,'r') #reading HTML format message html = file.read() except: html = text # **Calling send mail and sending mail ** # In[8]: Send_Mail(login(),TO_EMAIL=TO_EMAIL,text=text,html=html,subject=subject) Send email to client working# coding: utf-8 # ! /usr/bin/python __author__ = 'Shahariar Rabby' # This will read details and send email to clint # # Sendy # ### Importing Send mail file # In[6]: from Sendmail import * # ** Take user email, text plan massage, HTML file ** # In[7]: TO_EMAIL = raw_input("Enter reciver email : ") #Taking Reciver email as input subject = raw_input("Enter Mail Subject : ") #taking mail subject text = raw_input("Enter Plain message(or html format) : ") #Taking plane massage as input filename = raw_input('Enter file name with location(if any) : ') try: file = open(filename,'r') #reading HTML format message html = file.read() except: html = text # **Calling send mail and sending mail ** # In[8]: Send_Mail(login(),TO_EMAIL=TO_EMAIL,text=text,html=html,subject=subject)
<commit_before># coding: utf-8 # ! /usr/bin/python __author__ = 'Shahariar Rabby' # # Sendy # ### Importing Send mail file # In[6]: from Sendmail import * # ** Take user email, text plan massage, HTML file ** # In[7]: TO_EMAIL = raw_input("Enter reciver email : ") #Taking Reciver email as input subject = raw_input("Enter Mail Subject : ") #taking mail subject text = raw_input("Enter Plain message(or html format) : ") #Taking plane massage as input filename = raw_input('Enter file name with location(if any) : ') try: file = open(filename,'r') #reading HTML format message html = file.read() except: html = text # **Calling send mail and sending mail ** # In[8]: Send_Mail(login(),TO_EMAIL=TO_EMAIL,text=text,html=html,subject=subject) <commit_msg>Send email to client working<commit_after># coding: utf-8 # ! /usr/bin/python __author__ = 'Shahariar Rabby' # This will read details and send email to clint # # Sendy # ### Importing Send mail file # In[6]: from Sendmail import * # ** Take user email, text plan massage, HTML file ** # In[7]: TO_EMAIL = raw_input("Enter reciver email : ") #Taking Reciver email as input subject = raw_input("Enter Mail Subject : ") #taking mail subject text = raw_input("Enter Plain message(or html format) : ") #Taking plane massage as input filename = raw_input('Enter file name with location(if any) : ') try: file = open(filename,'r') #reading HTML format message html = file.read() except: html = text # **Calling send mail and sending mail ** # In[8]: Send_Mail(login(),TO_EMAIL=TO_EMAIL,text=text,html=html,subject=subject)
0cb45bbc1c7b6b5f1a2722e85159b97c8a555e0c
examples/providers/factory_deep_init_injections.py
examples/providers/factory_deep_init_injections.py
"""`Factory` providers deep init injections example.""" from dependency_injector import providers class Regularizer: def __init__(self, alpha): self.alpha = alpha class Loss: def __init__(self, regularizer): self.regularizer = regularizer class ClassificationTask: def __init__(self, loss): self.loss = loss class Algorithm: def __init__(self, task): self.task = task algorithm_factory = providers.Factory( Algorithm, task=providers.Factory( ClassificationTask, loss=providers.Factory( Loss, regularizer=providers.Factory( Regularizer, ), ), ), ) if __name__ == '__main__': algorithm_1 = algorithm_factory(task__loss__regularizer__alpha=0.5) assert algorithm_1.task.loss.regularizer.alpha == 0.5 algorithm_2 = algorithm_factory(task__loss__regularizer__alpha=0.7) assert algorithm_2.task.loss.regularizer.alpha == 0.7 algorithm_3 = algorithm_factory(task__loss__regularizer=Regularizer(alpha=0.8)) assert algorithm_3.task.loss.regularizer.alpha == 0.8
"""`Factory` providers - building a complex object graph with deep init injections example.""" from dependency_injector import providers class Regularizer: def __init__(self, alpha): self.alpha = alpha class Loss: def __init__(self, regularizer): self.regularizer = regularizer class ClassificationTask: def __init__(self, loss): self.loss = loss class Algorithm: def __init__(self, task): self.task = task algorithm_factory = providers.Factory( Algorithm, task=providers.Factory( ClassificationTask, loss=providers.Factory( Loss, regularizer=providers.Factory( Regularizer, ), ), ), ) if __name__ == '__main__': algorithm_1 = algorithm_factory(task__loss__regularizer__alpha=0.5) assert algorithm_1.task.loss.regularizer.alpha == 0.5 algorithm_2 = algorithm_factory(task__loss__regularizer__alpha=0.7) assert algorithm_2.task.loss.regularizer.alpha == 0.7 algorithm_3 = algorithm_factory(task__loss__regularizer=Regularizer(alpha=0.8)) assert algorithm_3.task.loss.regularizer.alpha == 0.8
Update the docblock of the example
Update the docblock of the example
Python
bsd-3-clause
ets-labs/dependency_injector,rmk135/dependency_injector,ets-labs/python-dependency-injector,rmk135/objects
"""`Factory` providers deep init injections example.""" from dependency_injector import providers class Regularizer: def __init__(self, alpha): self.alpha = alpha class Loss: def __init__(self, regularizer): self.regularizer = regularizer class ClassificationTask: def __init__(self, loss): self.loss = loss class Algorithm: def __init__(self, task): self.task = task algorithm_factory = providers.Factory( Algorithm, task=providers.Factory( ClassificationTask, loss=providers.Factory( Loss, regularizer=providers.Factory( Regularizer, ), ), ), ) if __name__ == '__main__': algorithm_1 = algorithm_factory(task__loss__regularizer__alpha=0.5) assert algorithm_1.task.loss.regularizer.alpha == 0.5 algorithm_2 = algorithm_factory(task__loss__regularizer__alpha=0.7) assert algorithm_2.task.loss.regularizer.alpha == 0.7 algorithm_3 = algorithm_factory(task__loss__regularizer=Regularizer(alpha=0.8)) assert algorithm_3.task.loss.regularizer.alpha == 0.8 Update the docblock of the example
"""`Factory` providers - building a complex object graph with deep init injections example.""" from dependency_injector import providers class Regularizer: def __init__(self, alpha): self.alpha = alpha class Loss: def __init__(self, regularizer): self.regularizer = regularizer class ClassificationTask: def __init__(self, loss): self.loss = loss class Algorithm: def __init__(self, task): self.task = task algorithm_factory = providers.Factory( Algorithm, task=providers.Factory( ClassificationTask, loss=providers.Factory( Loss, regularizer=providers.Factory( Regularizer, ), ), ), ) if __name__ == '__main__': algorithm_1 = algorithm_factory(task__loss__regularizer__alpha=0.5) assert algorithm_1.task.loss.regularizer.alpha == 0.5 algorithm_2 = algorithm_factory(task__loss__regularizer__alpha=0.7) assert algorithm_2.task.loss.regularizer.alpha == 0.7 algorithm_3 = algorithm_factory(task__loss__regularizer=Regularizer(alpha=0.8)) assert algorithm_3.task.loss.regularizer.alpha == 0.8
<commit_before>"""`Factory` providers deep init injections example.""" from dependency_injector import providers class Regularizer: def __init__(self, alpha): self.alpha = alpha class Loss: def __init__(self, regularizer): self.regularizer = regularizer class ClassificationTask: def __init__(self, loss): self.loss = loss class Algorithm: def __init__(self, task): self.task = task algorithm_factory = providers.Factory( Algorithm, task=providers.Factory( ClassificationTask, loss=providers.Factory( Loss, regularizer=providers.Factory( Regularizer, ), ), ), ) if __name__ == '__main__': algorithm_1 = algorithm_factory(task__loss__regularizer__alpha=0.5) assert algorithm_1.task.loss.regularizer.alpha == 0.5 algorithm_2 = algorithm_factory(task__loss__regularizer__alpha=0.7) assert algorithm_2.task.loss.regularizer.alpha == 0.7 algorithm_3 = algorithm_factory(task__loss__regularizer=Regularizer(alpha=0.8)) assert algorithm_3.task.loss.regularizer.alpha == 0.8 <commit_msg>Update the docblock of the example<commit_after>
"""`Factory` providers - building a complex object graph with deep init injections example.""" from dependency_injector import providers class Regularizer: def __init__(self, alpha): self.alpha = alpha class Loss: def __init__(self, regularizer): self.regularizer = regularizer class ClassificationTask: def __init__(self, loss): self.loss = loss class Algorithm: def __init__(self, task): self.task = task algorithm_factory = providers.Factory( Algorithm, task=providers.Factory( ClassificationTask, loss=providers.Factory( Loss, regularizer=providers.Factory( Regularizer, ), ), ), ) if __name__ == '__main__': algorithm_1 = algorithm_factory(task__loss__regularizer__alpha=0.5) assert algorithm_1.task.loss.regularizer.alpha == 0.5 algorithm_2 = algorithm_factory(task__loss__regularizer__alpha=0.7) assert algorithm_2.task.loss.regularizer.alpha == 0.7 algorithm_3 = algorithm_factory(task__loss__regularizer=Regularizer(alpha=0.8)) assert algorithm_3.task.loss.regularizer.alpha == 0.8
"""`Factory` providers deep init injections example.""" from dependency_injector import providers class Regularizer: def __init__(self, alpha): self.alpha = alpha class Loss: def __init__(self, regularizer): self.regularizer = regularizer class ClassificationTask: def __init__(self, loss): self.loss = loss class Algorithm: def __init__(self, task): self.task = task algorithm_factory = providers.Factory( Algorithm, task=providers.Factory( ClassificationTask, loss=providers.Factory( Loss, regularizer=providers.Factory( Regularizer, ), ), ), ) if __name__ == '__main__': algorithm_1 = algorithm_factory(task__loss__regularizer__alpha=0.5) assert algorithm_1.task.loss.regularizer.alpha == 0.5 algorithm_2 = algorithm_factory(task__loss__regularizer__alpha=0.7) assert algorithm_2.task.loss.regularizer.alpha == 0.7 algorithm_3 = algorithm_factory(task__loss__regularizer=Regularizer(alpha=0.8)) assert algorithm_3.task.loss.regularizer.alpha == 0.8 Update the docblock of the example"""`Factory` providers - building a complex object graph with deep init injections example.""" from dependency_injector import providers class Regularizer: def __init__(self, alpha): self.alpha = alpha class Loss: def __init__(self, regularizer): self.regularizer = regularizer class ClassificationTask: def __init__(self, loss): self.loss = loss class Algorithm: def __init__(self, task): self.task = task algorithm_factory = providers.Factory( Algorithm, task=providers.Factory( ClassificationTask, loss=providers.Factory( Loss, regularizer=providers.Factory( Regularizer, ), ), ), ) if __name__ == '__main__': algorithm_1 = algorithm_factory(task__loss__regularizer__alpha=0.5) assert algorithm_1.task.loss.regularizer.alpha == 0.5 algorithm_2 = algorithm_factory(task__loss__regularizer__alpha=0.7) assert algorithm_2.task.loss.regularizer.alpha == 0.7 algorithm_3 = algorithm_factory(task__loss__regularizer=Regularizer(alpha=0.8)) assert algorithm_3.task.loss.regularizer.alpha == 0.8
<commit_before>"""`Factory` providers deep init injections example.""" from dependency_injector import providers class Regularizer: def __init__(self, alpha): self.alpha = alpha class Loss: def __init__(self, regularizer): self.regularizer = regularizer class ClassificationTask: def __init__(self, loss): self.loss = loss class Algorithm: def __init__(self, task): self.task = task algorithm_factory = providers.Factory( Algorithm, task=providers.Factory( ClassificationTask, loss=providers.Factory( Loss, regularizer=providers.Factory( Regularizer, ), ), ), ) if __name__ == '__main__': algorithm_1 = algorithm_factory(task__loss__regularizer__alpha=0.5) assert algorithm_1.task.loss.regularizer.alpha == 0.5 algorithm_2 = algorithm_factory(task__loss__regularizer__alpha=0.7) assert algorithm_2.task.loss.regularizer.alpha == 0.7 algorithm_3 = algorithm_factory(task__loss__regularizer=Regularizer(alpha=0.8)) assert algorithm_3.task.loss.regularizer.alpha == 0.8 <commit_msg>Update the docblock of the example<commit_after>"""`Factory` providers - building a complex object graph with deep init injections example.""" from dependency_injector import providers class Regularizer: def __init__(self, alpha): self.alpha = alpha class Loss: def __init__(self, regularizer): self.regularizer = regularizer class ClassificationTask: def __init__(self, loss): self.loss = loss class Algorithm: def __init__(self, task): self.task = task algorithm_factory = providers.Factory( Algorithm, task=providers.Factory( ClassificationTask, loss=providers.Factory( Loss, regularizer=providers.Factory( Regularizer, ), ), ), ) if __name__ == '__main__': algorithm_1 = algorithm_factory(task__loss__regularizer__alpha=0.5) assert algorithm_1.task.loss.regularizer.alpha == 0.5 algorithm_2 = algorithm_factory(task__loss__regularizer__alpha=0.7) assert algorithm_2.task.loss.regularizer.alpha == 0.7 algorithm_3 = algorithm_factory(task__loss__regularizer=Regularizer(alpha=0.8)) assert algorithm_3.task.loss.regularizer.alpha == 0.8
e908a2c62be1d937a68b5c602b8cae02633685f7
csunplugged/general/management/commands/updatedata.py
csunplugged/general/management/commands/updatedata.py
"""Module for the custom Django updatedata command.""" from django.core import management class Command(management.base.BaseCommand): """Required command class for the custom Django updatedata command.""" help = "Update all data from content folders for all applications" def add_arguments(self, parser): """Add optional parameter to updatedata command.""" parser.add_argument( "--lite-load", action="store_true", dest="lite_load", help="Perform lite load (only load key content)", ) def handle(self, *args, **options): """Automatically called when the updatedata command is given.""" lite_load = options.get("lite_load") management.call_command("flush", interactive=False) management.call_command("loadresources", lite_load=lite_load) management.call_command("loadtopics", lite_load=lite_load) management.call_command("loadgeneralpages", lite_load=lite_load) management.call_command("loadclassicpages", lite_load=lite_load) management.call_command("loadactivities", lite_load=lite_load) management.call_command("rebuild_search_indexes")
"""Module for the custom Django updatedata command.""" from django.core import management class Command(management.base.BaseCommand): """Required command class for the custom Django updatedata command.""" help = "Update all data from content folders for all applications" def add_arguments(self, parser): """Add optional parameter to updatedata command.""" parser.add_argument( "--lite-load", action="store_true", dest="lite_load", help="Perform lite load (only load key content)", ) def handle(self, *args, **options): """Automatically called when the updatedata command is given.""" lite_load = options.get("lite_load") management.call_command("flush", interactive=False) management.call_command("loadresources", lite_load=lite_load) management.call_command("loadtopics", lite_load=lite_load) management.call_command("loadgeneralpages", lite_load=lite_load) management.call_command("loadclassicpages", lite_load=lite_load) management.call_command("loadactivities", lite_load=lite_load) management.call_command("load_at_a_distance_data", lite_load=lite_load) management.call_command("rebuild_search_indexes")
Load at a distance content in updatadata command
Load at a distance content in updatadata command
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
"""Module for the custom Django updatedata command.""" from django.core import management class Command(management.base.BaseCommand): """Required command class for the custom Django updatedata command.""" help = "Update all data from content folders for all applications" def add_arguments(self, parser): """Add optional parameter to updatedata command.""" parser.add_argument( "--lite-load", action="store_true", dest="lite_load", help="Perform lite load (only load key content)", ) def handle(self, *args, **options): """Automatically called when the updatedata command is given.""" lite_load = options.get("lite_load") management.call_command("flush", interactive=False) management.call_command("loadresources", lite_load=lite_load) management.call_command("loadtopics", lite_load=lite_load) management.call_command("loadgeneralpages", lite_load=lite_load) management.call_command("loadclassicpages", lite_load=lite_load) management.call_command("loadactivities", lite_load=lite_load) management.call_command("rebuild_search_indexes") Load at a distance content in updatadata command
"""Module for the custom Django updatedata command.""" from django.core import management class Command(management.base.BaseCommand): """Required command class for the custom Django updatedata command.""" help = "Update all data from content folders for all applications" def add_arguments(self, parser): """Add optional parameter to updatedata command.""" parser.add_argument( "--lite-load", action="store_true", dest="lite_load", help="Perform lite load (only load key content)", ) def handle(self, *args, **options): """Automatically called when the updatedata command is given.""" lite_load = options.get("lite_load") management.call_command("flush", interactive=False) management.call_command("loadresources", lite_load=lite_load) management.call_command("loadtopics", lite_load=lite_load) management.call_command("loadgeneralpages", lite_load=lite_load) management.call_command("loadclassicpages", lite_load=lite_load) management.call_command("loadactivities", lite_load=lite_load) management.call_command("load_at_a_distance_data", lite_load=lite_load) management.call_command("rebuild_search_indexes")
<commit_before>"""Module for the custom Django updatedata command.""" from django.core import management class Command(management.base.BaseCommand): """Required command class for the custom Django updatedata command.""" help = "Update all data from content folders for all applications" def add_arguments(self, parser): """Add optional parameter to updatedata command.""" parser.add_argument( "--lite-load", action="store_true", dest="lite_load", help="Perform lite load (only load key content)", ) def handle(self, *args, **options): """Automatically called when the updatedata command is given.""" lite_load = options.get("lite_load") management.call_command("flush", interactive=False) management.call_command("loadresources", lite_load=lite_load) management.call_command("loadtopics", lite_load=lite_load) management.call_command("loadgeneralpages", lite_load=lite_load) management.call_command("loadclassicpages", lite_load=lite_load) management.call_command("loadactivities", lite_load=lite_load) management.call_command("rebuild_search_indexes") <commit_msg>Load at a distance content in updatadata command<commit_after>
"""Module for the custom Django updatedata command.""" from django.core import management class Command(management.base.BaseCommand): """Required command class for the custom Django updatedata command.""" help = "Update all data from content folders for all applications" def add_arguments(self, parser): """Add optional parameter to updatedata command.""" parser.add_argument( "--lite-load", action="store_true", dest="lite_load", help="Perform lite load (only load key content)", ) def handle(self, *args, **options): """Automatically called when the updatedata command is given.""" lite_load = options.get("lite_load") management.call_command("flush", interactive=False) management.call_command("loadresources", lite_load=lite_load) management.call_command("loadtopics", lite_load=lite_load) management.call_command("loadgeneralpages", lite_load=lite_load) management.call_command("loadclassicpages", lite_load=lite_load) management.call_command("loadactivities", lite_load=lite_load) management.call_command("load_at_a_distance_data", lite_load=lite_load) management.call_command("rebuild_search_indexes")
"""Module for the custom Django updatedata command.""" from django.core import management class Command(management.base.BaseCommand): """Required command class for the custom Django updatedata command.""" help = "Update all data from content folders for all applications" def add_arguments(self, parser): """Add optional parameter to updatedata command.""" parser.add_argument( "--lite-load", action="store_true", dest="lite_load", help="Perform lite load (only load key content)", ) def handle(self, *args, **options): """Automatically called when the updatedata command is given.""" lite_load = options.get("lite_load") management.call_command("flush", interactive=False) management.call_command("loadresources", lite_load=lite_load) management.call_command("loadtopics", lite_load=lite_load) management.call_command("loadgeneralpages", lite_load=lite_load) management.call_command("loadclassicpages", lite_load=lite_load) management.call_command("loadactivities", lite_load=lite_load) management.call_command("rebuild_search_indexes") Load at a distance content in updatadata command"""Module for the custom Django updatedata command.""" from django.core import management class Command(management.base.BaseCommand): """Required command class for the custom Django updatedata command.""" help = "Update all data from content folders for all applications" def add_arguments(self, parser): """Add optional parameter to updatedata command.""" parser.add_argument( "--lite-load", action="store_true", dest="lite_load", help="Perform lite load (only load key content)", ) def handle(self, *args, **options): """Automatically called when the updatedata command is given.""" lite_load = options.get("lite_load") management.call_command("flush", interactive=False) management.call_command("loadresources", lite_load=lite_load) management.call_command("loadtopics", lite_load=lite_load) management.call_command("loadgeneralpages", lite_load=lite_load) management.call_command("loadclassicpages", lite_load=lite_load) management.call_command("loadactivities", lite_load=lite_load) management.call_command("load_at_a_distance_data", lite_load=lite_load) management.call_command("rebuild_search_indexes")
<commit_before>"""Module for the custom Django updatedata command.""" from django.core import management class Command(management.base.BaseCommand): """Required command class for the custom Django updatedata command.""" help = "Update all data from content folders for all applications" def add_arguments(self, parser): """Add optional parameter to updatedata command.""" parser.add_argument( "--lite-load", action="store_true", dest="lite_load", help="Perform lite load (only load key content)", ) def handle(self, *args, **options): """Automatically called when the updatedata command is given.""" lite_load = options.get("lite_load") management.call_command("flush", interactive=False) management.call_command("loadresources", lite_load=lite_load) management.call_command("loadtopics", lite_load=lite_load) management.call_command("loadgeneralpages", lite_load=lite_load) management.call_command("loadclassicpages", lite_load=lite_load) management.call_command("loadactivities", lite_load=lite_load) management.call_command("rebuild_search_indexes") <commit_msg>Load at a distance content in updatadata command<commit_after>"""Module for the custom Django updatedata command.""" from django.core import management class Command(management.base.BaseCommand): """Required command class for the custom Django updatedata command.""" help = "Update all data from content folders for all applications" def add_arguments(self, parser): """Add optional parameter to updatedata command.""" parser.add_argument( "--lite-load", action="store_true", dest="lite_load", help="Perform lite load (only load key content)", ) def handle(self, *args, **options): """Automatically called when the updatedata command is given.""" lite_load = options.get("lite_load") management.call_command("flush", interactive=False) management.call_command("loadresources", lite_load=lite_load) management.call_command("loadtopics", lite_load=lite_load) management.call_command("loadgeneralpages", lite_load=lite_load) management.call_command("loadclassicpages", lite_load=lite_load) management.call_command("loadactivities", lite_load=lite_load) management.call_command("load_at_a_distance_data", lite_load=lite_load) management.call_command("rebuild_search_indexes")
047c95e255d6aac31651e3a95e2045de0b4888e2
flask_app.py
flask_app.py
import json from flask import abort from flask import Flask from flask_caching import Cache from flask_cors import CORS import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) @app.route('/') def display_available(): content = ('<html>' + '<head>' + '<title>Restaurant Menu Parser</title>' + '</head>' + '<body>' + '<p><a href="ki">Campus Solna (KI)</a></p>' + '<p><a href="uu">Campus Uppsala (BMC)</a></p>' + '</body>' + '</html>') return content @app.route('/api/restaurants') @cache.cached(timeout=3600) def api_list_restaurants(): return json.dumps(main.list_restaurants()) @app.route('/api/restaurant/<name>') @cache.cached(timeout=3600) def api_get_restaurant(name): data = main.get_restaurant(name) if not data: abort(404) return json.dumps(data) @app.route('/ki') @cache.cached(timeout=3600) def make_menu_ki(): return main.gen_ki_menu() @app.route('/uu') @cache.cached(timeout=3600) def make_menu_uu(): return main.gen_uu_menu()
from flask import Flask, abort, jsonify from flask_caching import Cache from flask_cors import CORS import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) @app.route('/') def display_available(): content = ('<html>' + '<head>' + '<title>Restaurant Menu Parser</title>' + '</head>' + '<body>' + '<p><a href="ki">Campus Solna (KI)</a></p>' + '<p><a href="uu">Campus Uppsala (BMC)</a></p>' + '</body>' + '</html>') return content @app.route('/api/restaurants') @cache.cached(timeout=3600) def api_list_restaurants(): return jsonify(main.list_restaurants()) @app.route('/api/restaurant/<name>') @cache.cached(timeout=3600) def api_get_restaurant(name): data = main.get_restaurant(name) if not data: abort(404) return jsonify(data) @app.route('/ki') @cache.cached(timeout=3600) def make_menu_ki(): return main.gen_ki_menu() @app.route('/uu') @cache.cached(timeout=3600) def make_menu_uu(): return main.gen_uu_menu()
Make a real json response.
Make a real json response.
Python
bsd-3-clause
talavis/kimenu
import json from flask import abort from flask import Flask from flask_caching import Cache from flask_cors import CORS import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) @app.route('/') def display_available(): content = ('<html>' + '<head>' + '<title>Restaurant Menu Parser</title>' + '</head>' + '<body>' + '<p><a href="ki">Campus Solna (KI)</a></p>' + '<p><a href="uu">Campus Uppsala (BMC)</a></p>' + '</body>' + '</html>') return content @app.route('/api/restaurants') @cache.cached(timeout=3600) def api_list_restaurants(): return json.dumps(main.list_restaurants()) @app.route('/api/restaurant/<name>') @cache.cached(timeout=3600) def api_get_restaurant(name): data = main.get_restaurant(name) if not data: abort(404) return json.dumps(data) @app.route('/ki') @cache.cached(timeout=3600) def make_menu_ki(): return main.gen_ki_menu() @app.route('/uu') @cache.cached(timeout=3600) def make_menu_uu(): return main.gen_uu_menu() Make a real json response.
from flask import Flask, abort, jsonify from flask_caching import Cache from flask_cors import CORS import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) @app.route('/') def display_available(): content = ('<html>' + '<head>' + '<title>Restaurant Menu Parser</title>' + '</head>' + '<body>' + '<p><a href="ki">Campus Solna (KI)</a></p>' + '<p><a href="uu">Campus Uppsala (BMC)</a></p>' + '</body>' + '</html>') return content @app.route('/api/restaurants') @cache.cached(timeout=3600) def api_list_restaurants(): return jsonify(main.list_restaurants()) @app.route('/api/restaurant/<name>') @cache.cached(timeout=3600) def api_get_restaurant(name): data = main.get_restaurant(name) if not data: abort(404) return jsonify(data) @app.route('/ki') @cache.cached(timeout=3600) def make_menu_ki(): return main.gen_ki_menu() @app.route('/uu') @cache.cached(timeout=3600) def make_menu_uu(): return main.gen_uu_menu()
<commit_before>import json from flask import abort from flask import Flask from flask_caching import Cache from flask_cors import CORS import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) @app.route('/') def display_available(): content = ('<html>' + '<head>' + '<title>Restaurant Menu Parser</title>' + '</head>' + '<body>' + '<p><a href="ki">Campus Solna (KI)</a></p>' + '<p><a href="uu">Campus Uppsala (BMC)</a></p>' + '</body>' + '</html>') return content @app.route('/api/restaurants') @cache.cached(timeout=3600) def api_list_restaurants(): return json.dumps(main.list_restaurants()) @app.route('/api/restaurant/<name>') @cache.cached(timeout=3600) def api_get_restaurant(name): data = main.get_restaurant(name) if not data: abort(404) return json.dumps(data) @app.route('/ki') @cache.cached(timeout=3600) def make_menu_ki(): return main.gen_ki_menu() @app.route('/uu') @cache.cached(timeout=3600) def make_menu_uu(): return main.gen_uu_menu() <commit_msg>Make a real json response.<commit_after>
from flask import Flask, abort, jsonify from flask_caching import Cache from flask_cors import CORS import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) @app.route('/') def display_available(): content = ('<html>' + '<head>' + '<title>Restaurant Menu Parser</title>' + '</head>' + '<body>' + '<p><a href="ki">Campus Solna (KI)</a></p>' + '<p><a href="uu">Campus Uppsala (BMC)</a></p>' + '</body>' + '</html>') return content @app.route('/api/restaurants') @cache.cached(timeout=3600) def api_list_restaurants(): return jsonify(main.list_restaurants()) @app.route('/api/restaurant/<name>') @cache.cached(timeout=3600) def api_get_restaurant(name): data = main.get_restaurant(name) if not data: abort(404) return jsonify(data) @app.route('/ki') @cache.cached(timeout=3600) def make_menu_ki(): return main.gen_ki_menu() @app.route('/uu') @cache.cached(timeout=3600) def make_menu_uu(): return main.gen_uu_menu()
import json from flask import abort from flask import Flask from flask_caching import Cache from flask_cors import CORS import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) @app.route('/') def display_available(): content = ('<html>' + '<head>' + '<title>Restaurant Menu Parser</title>' + '</head>' + '<body>' + '<p><a href="ki">Campus Solna (KI)</a></p>' + '<p><a href="uu">Campus Uppsala (BMC)</a></p>' + '</body>' + '</html>') return content @app.route('/api/restaurants') @cache.cached(timeout=3600) def api_list_restaurants(): return json.dumps(main.list_restaurants()) @app.route('/api/restaurant/<name>') @cache.cached(timeout=3600) def api_get_restaurant(name): data = main.get_restaurant(name) if not data: abort(404) return json.dumps(data) @app.route('/ki') @cache.cached(timeout=3600) def make_menu_ki(): return main.gen_ki_menu() @app.route('/uu') @cache.cached(timeout=3600) def make_menu_uu(): return main.gen_uu_menu() Make a real json response.from flask import Flask, abort, jsonify from flask_caching import Cache from flask_cors import CORS import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) @app.route('/') def display_available(): content = ('<html>' + '<head>' + '<title>Restaurant Menu Parser</title>' + '</head>' + '<body>' + '<p><a href="ki">Campus Solna (KI)</a></p>' + '<p><a href="uu">Campus Uppsala (BMC)</a></p>' + '</body>' + '</html>') return content @app.route('/api/restaurants') @cache.cached(timeout=3600) def api_list_restaurants(): return jsonify(main.list_restaurants()) @app.route('/api/restaurant/<name>') @cache.cached(timeout=3600) def api_get_restaurant(name): data = main.get_restaurant(name) if not data: abort(404) return jsonify(data) @app.route('/ki') @cache.cached(timeout=3600) def make_menu_ki(): return main.gen_ki_menu() @app.route('/uu') @cache.cached(timeout=3600) def make_menu_uu(): return main.gen_uu_menu()
<commit_before>import json from flask import abort from flask import Flask from flask_caching import Cache from flask_cors import CORS import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) @app.route('/') def display_available(): content = ('<html>' + '<head>' + '<title>Restaurant Menu Parser</title>' + '</head>' + '<body>' + '<p><a href="ki">Campus Solna (KI)</a></p>' + '<p><a href="uu">Campus Uppsala (BMC)</a></p>' + '</body>' + '</html>') return content @app.route('/api/restaurants') @cache.cached(timeout=3600) def api_list_restaurants(): return json.dumps(main.list_restaurants()) @app.route('/api/restaurant/<name>') @cache.cached(timeout=3600) def api_get_restaurant(name): data = main.get_restaurant(name) if not data: abort(404) return json.dumps(data) @app.route('/ki') @cache.cached(timeout=3600) def make_menu_ki(): return main.gen_ki_menu() @app.route('/uu') @cache.cached(timeout=3600) def make_menu_uu(): return main.gen_uu_menu() <commit_msg>Make a real json response.<commit_after>from flask import Flask, abort, jsonify from flask_caching import Cache from flask_cors import CORS import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) @app.route('/') def display_available(): content = ('<html>' + '<head>' + '<title>Restaurant Menu Parser</title>' + '</head>' + '<body>' + '<p><a href="ki">Campus Solna (KI)</a></p>' + '<p><a href="uu">Campus Uppsala (BMC)</a></p>' + '</body>' + '</html>') return content @app.route('/api/restaurants') @cache.cached(timeout=3600) def api_list_restaurants(): return jsonify(main.list_restaurants()) @app.route('/api/restaurant/<name>') @cache.cached(timeout=3600) def api_get_restaurant(name): data = main.get_restaurant(name) if not data: abort(404) return jsonify(data) @app.route('/ki') @cache.cached(timeout=3600) def make_menu_ki(): return main.gen_ki_menu() @app.route('/uu') @cache.cached(timeout=3600) def make_menu_uu(): return main.gen_uu_menu()
df2bf7cc95f38d9e6605dcc91e56b28502063b6a
apps/faqs/admin.py
apps/faqs/admin.py
from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin from django.contrib import admin from .models import Category, Faq @admin.register(Faq) class FaqAdmin(SearchMetaBaseAdmin): """ Admin settings for the Faq model """ prepopulated_fields = {"url_title": ("question",)} filter_horizontal = ("categories",) fieldsets = ( (None, { "fields": ( "page", "question", "url_title", "answer", "categories", "order", ) }), SearchMetaBaseAdmin.PUBLICATION_FIELDS, SearchMetaBaseAdmin.SEO_FIELDS, ) @admin.register(Category) class CategoryAdmin(PageBaseAdmin): """ Admin settings for the FAQ Category model. """ prepopulated_fields = {"url_title": ("title",)} fieldsets = ( PageBaseAdmin.TITLE_FIELDS, ("Content", { "fields": ("content_primary",), }), PageBaseAdmin.PUBLICATION_FIELDS, PageBaseAdmin.NAVIGATION_FIELDS, PageBaseAdmin.SEO_FIELDS, )
from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin from django.contrib import admin from .models import Category, Faq @admin.register(Faq) class FaqAdmin(SearchMetaBaseAdmin): """ Admin settings for the Faq model """ prepopulated_fields = {"url_title": ("question",)} filter_horizontal = ("categories",) fieldsets = ( (None, { "fields": ["page", "question", "url_title", "answer", "categories", "order"] }), SearchMetaBaseAdmin.PUBLICATION_FIELDS, SearchMetaBaseAdmin.SEO_FIELDS, ) @admin.register(Category) class CategoryAdmin(PageBaseAdmin): """ Admin settings for the FAQ Category model. """ prepopulated_fields = { "slug": ("title",) } fieldsets = ( PageBaseAdmin.TITLE_FIELDS, ("Content", { "fields": ("content_primary",), }), PageBaseAdmin.PUBLICATION_FIELDS, PageBaseAdmin.NAVIGATION_FIELDS, PageBaseAdmin.SEO_FIELDS, )
Fix usage of `url_title` in CategoryAdmin.
Fix usage of `url_title` in CategoryAdmin.
Python
mit
onespacemedia/cms-faqs,onespacemedia/cms-faqs
from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin from django.contrib import admin from .models import Category, Faq @admin.register(Faq) class FaqAdmin(SearchMetaBaseAdmin): """ Admin settings for the Faq model """ prepopulated_fields = {"url_title": ("question",)} filter_horizontal = ("categories",) fieldsets = ( (None, { "fields": ( "page", "question", "url_title", "answer", "categories", "order", ) }), SearchMetaBaseAdmin.PUBLICATION_FIELDS, SearchMetaBaseAdmin.SEO_FIELDS, ) @admin.register(Category) class CategoryAdmin(PageBaseAdmin): """ Admin settings for the FAQ Category model. """ prepopulated_fields = {"url_title": ("title",)} fieldsets = ( PageBaseAdmin.TITLE_FIELDS, ("Content", { "fields": ("content_primary",), }), PageBaseAdmin.PUBLICATION_FIELDS, PageBaseAdmin.NAVIGATION_FIELDS, PageBaseAdmin.SEO_FIELDS, ) Fix usage of `url_title` in CategoryAdmin.
from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin from django.contrib import admin from .models import Category, Faq @admin.register(Faq) class FaqAdmin(SearchMetaBaseAdmin): """ Admin settings for the Faq model """ prepopulated_fields = {"url_title": ("question",)} filter_horizontal = ("categories",) fieldsets = ( (None, { "fields": ["page", "question", "url_title", "answer", "categories", "order"] }), SearchMetaBaseAdmin.PUBLICATION_FIELDS, SearchMetaBaseAdmin.SEO_FIELDS, ) @admin.register(Category) class CategoryAdmin(PageBaseAdmin): """ Admin settings for the FAQ Category model. """ prepopulated_fields = { "slug": ("title",) } fieldsets = ( PageBaseAdmin.TITLE_FIELDS, ("Content", { "fields": ("content_primary",), }), PageBaseAdmin.PUBLICATION_FIELDS, PageBaseAdmin.NAVIGATION_FIELDS, PageBaseAdmin.SEO_FIELDS, )
<commit_before>from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin from django.contrib import admin from .models import Category, Faq @admin.register(Faq) class FaqAdmin(SearchMetaBaseAdmin): """ Admin settings for the Faq model """ prepopulated_fields = {"url_title": ("question",)} filter_horizontal = ("categories",) fieldsets = ( (None, { "fields": ( "page", "question", "url_title", "answer", "categories", "order", ) }), SearchMetaBaseAdmin.PUBLICATION_FIELDS, SearchMetaBaseAdmin.SEO_FIELDS, ) @admin.register(Category) class CategoryAdmin(PageBaseAdmin): """ Admin settings for the FAQ Category model. """ prepopulated_fields = {"url_title": ("title",)} fieldsets = ( PageBaseAdmin.TITLE_FIELDS, ("Content", { "fields": ("content_primary",), }), PageBaseAdmin.PUBLICATION_FIELDS, PageBaseAdmin.NAVIGATION_FIELDS, PageBaseAdmin.SEO_FIELDS, ) <commit_msg>Fix usage of `url_title` in CategoryAdmin.<commit_after>
from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin from django.contrib import admin from .models import Category, Faq @admin.register(Faq) class FaqAdmin(SearchMetaBaseAdmin): """ Admin settings for the Faq model """ prepopulated_fields = {"url_title": ("question",)} filter_horizontal = ("categories",) fieldsets = ( (None, { "fields": ["page", "question", "url_title", "answer", "categories", "order"] }), SearchMetaBaseAdmin.PUBLICATION_FIELDS, SearchMetaBaseAdmin.SEO_FIELDS, ) @admin.register(Category) class CategoryAdmin(PageBaseAdmin): """ Admin settings for the FAQ Category model. """ prepopulated_fields = { "slug": ("title",) } fieldsets = ( PageBaseAdmin.TITLE_FIELDS, ("Content", { "fields": ("content_primary",), }), PageBaseAdmin.PUBLICATION_FIELDS, PageBaseAdmin.NAVIGATION_FIELDS, PageBaseAdmin.SEO_FIELDS, )
from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin from django.contrib import admin from .models import Category, Faq @admin.register(Faq) class FaqAdmin(SearchMetaBaseAdmin): """ Admin settings for the Faq model """ prepopulated_fields = {"url_title": ("question",)} filter_horizontal = ("categories",) fieldsets = ( (None, { "fields": ( "page", "question", "url_title", "answer", "categories", "order", ) }), SearchMetaBaseAdmin.PUBLICATION_FIELDS, SearchMetaBaseAdmin.SEO_FIELDS, ) @admin.register(Category) class CategoryAdmin(PageBaseAdmin): """ Admin settings for the FAQ Category model. """ prepopulated_fields = {"url_title": ("title",)} fieldsets = ( PageBaseAdmin.TITLE_FIELDS, ("Content", { "fields": ("content_primary",), }), PageBaseAdmin.PUBLICATION_FIELDS, PageBaseAdmin.NAVIGATION_FIELDS, PageBaseAdmin.SEO_FIELDS, ) Fix usage of `url_title` in CategoryAdmin.from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin from django.contrib import admin from .models import Category, Faq @admin.register(Faq) class FaqAdmin(SearchMetaBaseAdmin): """ Admin settings for the Faq model """ prepopulated_fields = {"url_title": ("question",)} filter_horizontal = ("categories",) fieldsets = ( (None, { "fields": ["page", "question", "url_title", "answer", "categories", "order"] }), SearchMetaBaseAdmin.PUBLICATION_FIELDS, SearchMetaBaseAdmin.SEO_FIELDS, ) @admin.register(Category) class CategoryAdmin(PageBaseAdmin): """ Admin settings for the FAQ Category model. """ prepopulated_fields = { "slug": ("title",) } fieldsets = ( PageBaseAdmin.TITLE_FIELDS, ("Content", { "fields": ("content_primary",), }), PageBaseAdmin.PUBLICATION_FIELDS, PageBaseAdmin.NAVIGATION_FIELDS, PageBaseAdmin.SEO_FIELDS, )
<commit_before>from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin from django.contrib import admin from .models import Category, Faq @admin.register(Faq) class FaqAdmin(SearchMetaBaseAdmin): """ Admin settings for the Faq model """ prepopulated_fields = {"url_title": ("question",)} filter_horizontal = ("categories",) fieldsets = ( (None, { "fields": ( "page", "question", "url_title", "answer", "categories", "order", ) }), SearchMetaBaseAdmin.PUBLICATION_FIELDS, SearchMetaBaseAdmin.SEO_FIELDS, ) @admin.register(Category) class CategoryAdmin(PageBaseAdmin): """ Admin settings for the FAQ Category model. """ prepopulated_fields = {"url_title": ("title",)} fieldsets = ( PageBaseAdmin.TITLE_FIELDS, ("Content", { "fields": ("content_primary",), }), PageBaseAdmin.PUBLICATION_FIELDS, PageBaseAdmin.NAVIGATION_FIELDS, PageBaseAdmin.SEO_FIELDS, ) <commit_msg>Fix usage of `url_title` in CategoryAdmin.<commit_after>from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin from django.contrib import admin from .models import Category, Faq @admin.register(Faq) class FaqAdmin(SearchMetaBaseAdmin): """ Admin settings for the Faq model """ prepopulated_fields = {"url_title": ("question",)} filter_horizontal = ("categories",) fieldsets = ( (None, { "fields": ["page", "question", "url_title", "answer", "categories", "order"] }), SearchMetaBaseAdmin.PUBLICATION_FIELDS, SearchMetaBaseAdmin.SEO_FIELDS, ) @admin.register(Category) class CategoryAdmin(PageBaseAdmin): """ Admin settings for the FAQ Category model. """ prepopulated_fields = { "slug": ("title",) } fieldsets = ( PageBaseAdmin.TITLE_FIELDS, ("Content", { "fields": ("content_primary",), }), PageBaseAdmin.PUBLICATION_FIELDS, PageBaseAdmin.NAVIGATION_FIELDS, PageBaseAdmin.SEO_FIELDS, )
6050b32ddb812e32da08fd15f210d9d9ee794a42
first-program.py
first-program.py
# Python program for Programming for Everybody (Getting Started with Python) by University of Michigan - Charles Severance # Task 1 Python code with single print statement but not print hello world print "It is a great feeling to code in Python"
# Python program for Programming for Everybody (Getting Started with Python) by University of Michigan - Charles Severance # Task 1 Python code with single print statement but not print hello world print "It is a great feeling to code in Python" print "Hello World!"
Print Hello World in Python
Print Hello World in Python
Python
mit
rahulbohra/Python-Basic
# Python program for Programming for Everybody (Getting Started with Python) by University of Michigan - Charles Severance # Task 1 Python code with single print statement but not print hello world print "It is a great feeling to code in Python" Print Hello World in Python
# Python program for Programming for Everybody (Getting Started with Python) by University of Michigan - Charles Severance # Task 1 Python code with single print statement but not print hello world print "It is a great feeling to code in Python" print "Hello World!"
<commit_before># Python program for Programming for Everybody (Getting Started with Python) by University of Michigan - Charles Severance # Task 1 Python code with single print statement but not print hello world print "It is a great feeling to code in Python" <commit_msg>Print Hello World in Python<commit_after>
# Python program for Programming for Everybody (Getting Started with Python) by University of Michigan - Charles Severance # Task 1 Python code with single print statement but not print hello world print "It is a great feeling to code in Python" print "Hello World!"
# Python program for Programming for Everybody (Getting Started with Python) by University of Michigan - Charles Severance # Task 1 Python code with single print statement but not print hello world print "It is a great feeling to code in Python" Print Hello World in Python# Python program for Programming for Everybody (Getting Started with Python) by University of Michigan - Charles Severance # Task 1 Python code with single print statement but not print hello world print "It is a great feeling to code in Python" print "Hello World!"
<commit_before># Python program for Programming for Everybody (Getting Started with Python) by University of Michigan - Charles Severance # Task 1 Python code with single print statement but not print hello world print "It is a great feeling to code in Python" <commit_msg>Print Hello World in Python<commit_after># Python program for Programming for Everybody (Getting Started with Python) by University of Michigan - Charles Severance # Task 1 Python code with single print statement but not print hello world print "It is a great feeling to code in Python" print "Hello World!"
88abdf5365977a47abaa0d0a8f3275e4635c8378
singleuser/user-config.py
singleuser/user-config.py
import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'rb') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) del f # Clean up temp variables, since pwb issues a warning otherwise # to help people catch misspelt config del custom_path # Things that should be non-easily-overridable usernames[family]['*'] = os.environ['JPY_USER'] # If OAuth integration is available, take it if 'CLIENT_ID' in os.environ: authenticate['*'] = ( os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'], os.environ['ACCESS_KEY'], os.environ['ACCESS_SECRET'] )
import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'rb') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) del f # Clean up temp variables, since pwb issues a warning otherwise # to help people catch misspelt config del custom_path # Things that should be non-easily-overridable for fam in ( 'wikipedia', 'commons', 'meta', 'wikiboots', 'wikimedia', 'wikiquote', 'wikisource', 'wikisource', 'wiktionary', 'wikiversity', 'wikidata', 'mediawiki' ): usernames[fam]['*'] = os.environ['JPY_USER'] del fam # If OAuth integration is available, take it if 'CLIENT_ID' in os.environ: authenticate['*'] = ( os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'], os.environ['ACCESS_KEY'], os.environ['ACCESS_SECRET'] )
Fix OAuth integration for all wiki families
Fix OAuth integration for all wiki families Earlier you needed to edit config file to set family to whatever you were working on, even if you constructed a Site object referring to other website. This would cause funky errors about 'Logged in as X, expected None' errors. Fix by listing almost all the families people will want to use!
Python
mit
yuvipanda/paws,yuvipanda/paws
import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'rb') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) del f # Clean up temp variables, since pwb issues a warning otherwise # to help people catch misspelt config del custom_path # Things that should be non-easily-overridable usernames[family]['*'] = os.environ['JPY_USER'] # If OAuth integration is available, take it if 'CLIENT_ID' in os.environ: authenticate['*'] = ( os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'], os.environ['ACCESS_KEY'], os.environ['ACCESS_SECRET'] ) Fix OAuth integration for all wiki families Earlier you needed to edit config file to set family to whatever you were working on, even if you constructed a Site object referring to other website. This would cause funky errors about 'Logged in as X, expected None' errors. Fix by listing almost all the families people will want to use!
import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'rb') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) del f # Clean up temp variables, since pwb issues a warning otherwise # to help people catch misspelt config del custom_path # Things that should be non-easily-overridable for fam in ( 'wikipedia', 'commons', 'meta', 'wikiboots', 'wikimedia', 'wikiquote', 'wikisource', 'wikisource', 'wiktionary', 'wikiversity', 'wikidata', 'mediawiki' ): usernames[fam]['*'] = os.environ['JPY_USER'] del fam # If OAuth integration is available, take it if 'CLIENT_ID' in os.environ: authenticate['*'] = ( os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'], os.environ['ACCESS_KEY'], os.environ['ACCESS_SECRET'] )
<commit_before>import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'rb') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) del f # Clean up temp variables, since pwb issues a warning otherwise # to help people catch misspelt config del custom_path # Things that should be non-easily-overridable usernames[family]['*'] = os.environ['JPY_USER'] # If OAuth integration is available, take it if 'CLIENT_ID' in os.environ: authenticate['*'] = ( os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'], os.environ['ACCESS_KEY'], os.environ['ACCESS_SECRET'] ) <commit_msg>Fix OAuth integration for all wiki families Earlier you needed to edit config file to set family to whatever you were working on, even if you constructed a Site object referring to other website. This would cause funky errors about 'Logged in as X, expected None' errors. Fix by listing almost all the families people will want to use!<commit_after>
import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'rb') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) del f # Clean up temp variables, since pwb issues a warning otherwise # to help people catch misspelt config del custom_path # Things that should be non-easily-overridable for fam in ( 'wikipedia', 'commons', 'meta', 'wikiboots', 'wikimedia', 'wikiquote', 'wikisource', 'wikisource', 'wiktionary', 'wikiversity', 'wikidata', 'mediawiki' ): usernames[fam]['*'] = os.environ['JPY_USER'] del fam # If OAuth integration is available, take it if 'CLIENT_ID' in os.environ: authenticate['*'] = ( os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'], os.environ['ACCESS_KEY'], os.environ['ACCESS_SECRET'] )
import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'rb') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) del f # Clean up temp variables, since pwb issues a warning otherwise # to help people catch misspelt config del custom_path # Things that should be non-easily-overridable usernames[family]['*'] = os.environ['JPY_USER'] # If OAuth integration is available, take it if 'CLIENT_ID' in os.environ: authenticate['*'] = ( os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'], os.environ['ACCESS_KEY'], os.environ['ACCESS_SECRET'] ) Fix OAuth integration for all wiki families Earlier you needed to edit config file to set family to whatever you were working on, even if you constructed a Site object referring to other website. This would cause funky errors about 'Logged in as X, expected None' errors. Fix by listing almost all the families people will want to use!import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'rb') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) del f # Clean up temp variables, since pwb issues a warning otherwise # to help people catch misspelt config del custom_path # Things that should be non-easily-overridable for fam in ( 'wikipedia', 'commons', 'meta', 'wikiboots', 'wikimedia', 'wikiquote', 'wikisource', 'wikisource', 'wiktionary', 'wikiversity', 'wikidata', 'mediawiki' ): usernames[fam]['*'] = os.environ['JPY_USER'] del fam # If OAuth integration is available, take it if 'CLIENT_ID' in os.environ: authenticate['*'] = ( os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'], os.environ['ACCESS_KEY'], os.environ['ACCESS_SECRET'] )
<commit_before>import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'rb') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) del f # Clean up temp variables, since pwb issues a warning otherwise # to help people catch misspelt config del custom_path # Things that should be non-easily-overridable usernames[family]['*'] = os.environ['JPY_USER'] # If OAuth integration is available, take it if 'CLIENT_ID' in os.environ: authenticate['*'] = ( os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'], os.environ['ACCESS_KEY'], os.environ['ACCESS_SECRET'] ) <commit_msg>Fix OAuth integration for all wiki families Earlier you needed to edit config file to set family to whatever you were working on, even if you constructed a Site object referring to other website. This would cause funky errors about 'Logged in as X, expected None' errors. Fix by listing almost all the families people will want to use!<commit_after>import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'rb') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) del f # Clean up temp variables, since pwb issues a warning otherwise # to help people catch misspelt config del custom_path # Things that should be non-easily-overridable for fam in ( 'wikipedia', 'commons', 'meta', 'wikiboots', 'wikimedia', 'wikiquote', 'wikisource', 'wikisource', 'wiktionary', 'wikiversity', 'wikidata', 'mediawiki' ): usernames[fam]['*'] = os.environ['JPY_USER'] del fam # If OAuth integration is available, take it if 'CLIENT_ID' in os.environ: authenticate['*'] = ( os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'], os.environ['ACCESS_KEY'], os.environ['ACCESS_SECRET'] )
294dabd8cc6bfc7e004a1a0dde9b40e9535d4b19
organizer/views.py
organizer/views.py
from django.http.response import HttpResponse from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request, slug): tag = Tag.objects.get(slug__iexact=slug) template = loader.get_template( 'organizer/tag_detail.html') context = Context({'tag': tag}) return HttpResponse(template.render(context))
from django.http.response import ( Http404, HttpResponse) from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request, slug): try: tag = Tag.objects.get(slug__iexact=slug) except Tag.DoesNotExist: raise Http404 template = loader.get_template( 'organizer/tag_detail.html') context = Context({'tag': tag}) return HttpResponse(template.render(context))
Raise 404 Error if no Tag exists.
Ch05: Raise 404 Error if no Tag exists.
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
from django.http.response import HttpResponse from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request, slug): tag = Tag.objects.get(slug__iexact=slug) template = loader.get_template( 'organizer/tag_detail.html') context = Context({'tag': tag}) return HttpResponse(template.render(context)) Ch05: Raise 404 Error if no Tag exists.
from django.http.response import ( Http404, HttpResponse) from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request, slug): try: tag = Tag.objects.get(slug__iexact=slug) except Tag.DoesNotExist: raise Http404 template = loader.get_template( 'organizer/tag_detail.html') context = Context({'tag': tag}) return HttpResponse(template.render(context))
<commit_before>from django.http.response import HttpResponse from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request, slug): tag = Tag.objects.get(slug__iexact=slug) template = loader.get_template( 'organizer/tag_detail.html') context = Context({'tag': tag}) return HttpResponse(template.render(context)) <commit_msg>Ch05: Raise 404 Error if no Tag exists.<commit_after>
from django.http.response import ( Http404, HttpResponse) from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request, slug): try: tag = Tag.objects.get(slug__iexact=slug) except Tag.DoesNotExist: raise Http404 template = loader.get_template( 'organizer/tag_detail.html') context = Context({'tag': tag}) return HttpResponse(template.render(context))
from django.http.response import HttpResponse from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request, slug): tag = Tag.objects.get(slug__iexact=slug) template = loader.get_template( 'organizer/tag_detail.html') context = Context({'tag': tag}) return HttpResponse(template.render(context)) Ch05: Raise 404 Error if no Tag exists.from django.http.response import ( Http404, HttpResponse) from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request, slug): try: tag = Tag.objects.get(slug__iexact=slug) except Tag.DoesNotExist: raise Http404 template = loader.get_template( 'organizer/tag_detail.html') context = Context({'tag': tag}) return HttpResponse(template.render(context))
<commit_before>from django.http.response import HttpResponse from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request, slug): tag = Tag.objects.get(slug__iexact=slug) template = loader.get_template( 'organizer/tag_detail.html') context = Context({'tag': tag}) return HttpResponse(template.render(context)) <commit_msg>Ch05: Raise 404 Error if no Tag exists.<commit_after>from django.http.response import ( Http404, HttpResponse) from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request, slug): try: tag = Tag.objects.get(slug__iexact=slug) except Tag.DoesNotExist: raise Http404 template = loader.get_template( 'organizer/tag_detail.html') context = Context({'tag': tag}) return HttpResponse(template.render(context))
a95c3bff0065ed5612a0786e7d8fd3e43fe71ff7
src/som/interpreter/ast/nodes/message/super_node.py
src/som/interpreter/ast/nodes/message/super_node.py
from .abstract_node import AbstractMessageNode class SuperMessageNode(AbstractMessageNode): def __init__(self, selector, receiver, args, super_class, source_section = None): AbstractMessageNode.__init__(self, selector, None, receiver, args, source_section) self._method = None self._super_class = super_class self._selector = selector def execute(self, frame): if self._method is None: method = self._super_class.lookup_invokable(self._selector) if not method: raise Exception("Not yet implemented") self._method = method rcvr, args = self._evaluate_rcvr_and_args(frame) return self._method.invoke(rcvr, args)
from .abstract_node import AbstractMessageNode class SuperMessageNode(AbstractMessageNode): _immutable_fields_ = ['_method?', '_super_class', '_selector'] def __init__(self, selector, receiver, args, super_class, source_section = None): AbstractMessageNode.__init__(self, selector, None, receiver, args, source_section) self._method = None self._super_class = super_class self._selector = selector def execute(self, frame): if self._method is None: method = self._super_class.lookup_invokable(self._selector) if not method: raise Exception("Not yet implemented") self._method = method rcvr, args = self._evaluate_rcvr_and_args(frame) return self._method.invoke(rcvr, args)
Declare immutable fields in SuperMessageNode
Declare immutable fields in SuperMessageNode Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
Python
mit
SOM-st/PySOM,SOM-st/PySOM,smarr/PySOM,smarr/PySOM
from .abstract_node import AbstractMessageNode class SuperMessageNode(AbstractMessageNode): def __init__(self, selector, receiver, args, super_class, source_section = None): AbstractMessageNode.__init__(self, selector, None, receiver, args, source_section) self._method = None self._super_class = super_class self._selector = selector def execute(self, frame): if self._method is None: method = self._super_class.lookup_invokable(self._selector) if not method: raise Exception("Not yet implemented") self._method = method rcvr, args = self._evaluate_rcvr_and_args(frame) return self._method.invoke(rcvr, args) Declare immutable fields in SuperMessageNode Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
from .abstract_node import AbstractMessageNode class SuperMessageNode(AbstractMessageNode): _immutable_fields_ = ['_method?', '_super_class', '_selector'] def __init__(self, selector, receiver, args, super_class, source_section = None): AbstractMessageNode.__init__(self, selector, None, receiver, args, source_section) self._method = None self._super_class = super_class self._selector = selector def execute(self, frame): if self._method is None: method = self._super_class.lookup_invokable(self._selector) if not method: raise Exception("Not yet implemented") self._method = method rcvr, args = self._evaluate_rcvr_and_args(frame) return self._method.invoke(rcvr, args)
<commit_before>from .abstract_node import AbstractMessageNode class SuperMessageNode(AbstractMessageNode): def __init__(self, selector, receiver, args, super_class, source_section = None): AbstractMessageNode.__init__(self, selector, None, receiver, args, source_section) self._method = None self._super_class = super_class self._selector = selector def execute(self, frame): if self._method is None: method = self._super_class.lookup_invokable(self._selector) if not method: raise Exception("Not yet implemented") self._method = method rcvr, args = self._evaluate_rcvr_and_args(frame) return self._method.invoke(rcvr, args) <commit_msg>Declare immutable fields in SuperMessageNode Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de><commit_after>
from .abstract_node import AbstractMessageNode class SuperMessageNode(AbstractMessageNode): _immutable_fields_ = ['_method?', '_super_class', '_selector'] def __init__(self, selector, receiver, args, super_class, source_section = None): AbstractMessageNode.__init__(self, selector, None, receiver, args, source_section) self._method = None self._super_class = super_class self._selector = selector def execute(self, frame): if self._method is None: method = self._super_class.lookup_invokable(self._selector) if not method: raise Exception("Not yet implemented") self._method = method rcvr, args = self._evaluate_rcvr_and_args(frame) return self._method.invoke(rcvr, args)
from .abstract_node import AbstractMessageNode class SuperMessageNode(AbstractMessageNode): def __init__(self, selector, receiver, args, super_class, source_section = None): AbstractMessageNode.__init__(self, selector, None, receiver, args, source_section) self._method = None self._super_class = super_class self._selector = selector def execute(self, frame): if self._method is None: method = self._super_class.lookup_invokable(self._selector) if not method: raise Exception("Not yet implemented") self._method = method rcvr, args = self._evaluate_rcvr_and_args(frame) return self._method.invoke(rcvr, args) Declare immutable fields in SuperMessageNode Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>from .abstract_node import AbstractMessageNode class SuperMessageNode(AbstractMessageNode): _immutable_fields_ = ['_method?', '_super_class', '_selector'] def __init__(self, selector, receiver, args, super_class, source_section = None): AbstractMessageNode.__init__(self, selector, None, receiver, args, source_section) self._method = None self._super_class = super_class self._selector = selector def execute(self, frame): if self._method is None: method = self._super_class.lookup_invokable(self._selector) if not method: raise Exception("Not yet implemented") self._method = method rcvr, args = self._evaluate_rcvr_and_args(frame) return self._method.invoke(rcvr, args)
<commit_before>from .abstract_node import AbstractMessageNode class SuperMessageNode(AbstractMessageNode): def __init__(self, selector, receiver, args, super_class, source_section = None): AbstractMessageNode.__init__(self, selector, None, receiver, args, source_section) self._method = None self._super_class = super_class self._selector = selector def execute(self, frame): if self._method is None: method = self._super_class.lookup_invokable(self._selector) if not method: raise Exception("Not yet implemented") self._method = method rcvr, args = self._evaluate_rcvr_and_args(frame) return self._method.invoke(rcvr, args) <commit_msg>Declare immutable fields in SuperMessageNode Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de><commit_after>from .abstract_node import AbstractMessageNode class SuperMessageNode(AbstractMessageNode): _immutable_fields_ = ['_method?', '_super_class', '_selector'] def __init__(self, selector, receiver, args, super_class, source_section = None): AbstractMessageNode.__init__(self, selector, None, receiver, args, source_section) self._method = None self._super_class = super_class self._selector = selector def execute(self, frame): if self._method is None: method = self._super_class.lookup_invokable(self._selector) if not method: raise Exception("Not yet implemented") self._method = method rcvr, args = self._evaluate_rcvr_and_args(frame) return self._method.invoke(rcvr, args)
5bcc4ae60f89fbcadad234e0d6b9a755d28aab5d
pavement.py
pavement.py
import subprocess from paver.easy import * def call(*args, **kwargs): return subprocess.call(args, **kwargs) @task def build(): """Package up the app.""" call('palm-package', '.') @task def halt(): call('palm-launch', '--device=emulator', '-c', 'org.markpasc.paperplain') @task @needs('halt') def uninstall(): call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain') @task @needs('build', 'uninstall') def push(): """Reinstall the app and start it.""" call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk') call('palm-launch', '--device=emulator', 'org.markpasc.paperplain') @task def tail(): """Follow the device's log.""" call('palm-log', '--device=emulator', '--system-log-level', 'info') call('palm-log', '--device=emulator', '-f', 'org.markpasc.paperplain')
import subprocess from paver.easy import * def call(*args, **kwargs): return subprocess.call(args, **kwargs) @task def build(): """Package up the app.""" call('palm-package', '.') @task def halt(): call('palm-launch', '--device=emulator', '-c', 'org.markpasc.paperplain') @task @needs('halt') def uninstall(): call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain') @task @needs('build', 'uninstall') def push(): """Reinstall the app and start it.""" call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk') call('palm-launch', '--device=emulator', 'org.markpasc.paperplain') @task def tail(): """Follow the device's log.""" call('palm-log', '--device=emulator', '--system-log-level', 'info') try: call('palm-log', '--device=emulator', '-f', 'org.markpasc.paperplain') except KeyboardInterrupt: print
Handle ctrl-C-ing out of palm-log
Handle ctrl-C-ing out of palm-log
Python
mit
markpasc/paperplain,markpasc/paperplain
import subprocess from paver.easy import * def call(*args, **kwargs): return subprocess.call(args, **kwargs) @task def build(): """Package up the app.""" call('palm-package', '.') @task def halt(): call('palm-launch', '--device=emulator', '-c', 'org.markpasc.paperplain') @task @needs('halt') def uninstall(): call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain') @task @needs('build', 'uninstall') def push(): """Reinstall the app and start it.""" call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk') call('palm-launch', '--device=emulator', 'org.markpasc.paperplain') @task def tail(): """Follow the device's log.""" call('palm-log', '--device=emulator', '--system-log-level', 'info') call('palm-log', '--device=emulator', '-f', 'org.markpasc.paperplain') Handle ctrl-C-ing out of palm-log
import subprocess from paver.easy import * def call(*args, **kwargs): return subprocess.call(args, **kwargs) @task def build(): """Package up the app.""" call('palm-package', '.') @task def halt(): call('palm-launch', '--device=emulator', '-c', 'org.markpasc.paperplain') @task @needs('halt') def uninstall(): call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain') @task @needs('build', 'uninstall') def push(): """Reinstall the app and start it.""" call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk') call('palm-launch', '--device=emulator', 'org.markpasc.paperplain') @task def tail(): """Follow the device's log.""" call('palm-log', '--device=emulator', '--system-log-level', 'info') try: call('palm-log', '--device=emulator', '-f', 'org.markpasc.paperplain') except KeyboardInterrupt: print
<commit_before>import subprocess from paver.easy import * def call(*args, **kwargs): return subprocess.call(args, **kwargs) @task def build(): """Package up the app.""" call('palm-package', '.') @task def halt(): call('palm-launch', '--device=emulator', '-c', 'org.markpasc.paperplain') @task @needs('halt') def uninstall(): call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain') @task @needs('build', 'uninstall') def push(): """Reinstall the app and start it.""" call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk') call('palm-launch', '--device=emulator', 'org.markpasc.paperplain') @task def tail(): """Follow the device's log.""" call('palm-log', '--device=emulator', '--system-log-level', 'info') call('palm-log', '--device=emulator', '-f', 'org.markpasc.paperplain') <commit_msg>Handle ctrl-C-ing out of palm-log<commit_after>
import subprocess from paver.easy import * def call(*args, **kwargs): return subprocess.call(args, **kwargs) @task def build(): """Package up the app.""" call('palm-package', '.') @task def halt(): call('palm-launch', '--device=emulator', '-c', 'org.markpasc.paperplain') @task @needs('halt') def uninstall(): call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain') @task @needs('build', 'uninstall') def push(): """Reinstall the app and start it.""" call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk') call('palm-launch', '--device=emulator', 'org.markpasc.paperplain') @task def tail(): """Follow the device's log.""" call('palm-log', '--device=emulator', '--system-log-level', 'info') try: call('palm-log', '--device=emulator', '-f', 'org.markpasc.paperplain') except KeyboardInterrupt: print
import subprocess from paver.easy import * def call(*args, **kwargs): return subprocess.call(args, **kwargs) @task def build(): """Package up the app.""" call('palm-package', '.') @task def halt(): call('palm-launch', '--device=emulator', '-c', 'org.markpasc.paperplain') @task @needs('halt') def uninstall(): call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain') @task @needs('build', 'uninstall') def push(): """Reinstall the app and start it.""" call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk') call('palm-launch', '--device=emulator', 'org.markpasc.paperplain') @task def tail(): """Follow the device's log.""" call('palm-log', '--device=emulator', '--system-log-level', 'info') call('palm-log', '--device=emulator', '-f', 'org.markpasc.paperplain') Handle ctrl-C-ing out of palm-logimport subprocess from paver.easy import * def call(*args, **kwargs): return subprocess.call(args, **kwargs) @task def build(): """Package up the app.""" call('palm-package', '.') @task def halt(): call('palm-launch', '--device=emulator', '-c', 'org.markpasc.paperplain') @task @needs('halt') def uninstall(): call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain') @task @needs('build', 'uninstall') def push(): """Reinstall the app and start it.""" call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk') call('palm-launch', '--device=emulator', 'org.markpasc.paperplain') @task def tail(): """Follow the device's log.""" call('palm-log', '--device=emulator', '--system-log-level', 'info') try: call('palm-log', '--device=emulator', '-f', 'org.markpasc.paperplain') except KeyboardInterrupt: print
<commit_before>import subprocess from paver.easy import * def call(*args, **kwargs): return subprocess.call(args, **kwargs) @task def build(): """Package up the app.""" call('palm-package', '.') @task def halt(): call('palm-launch', '--device=emulator', '-c', 'org.markpasc.paperplain') @task @needs('halt') def uninstall(): call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain') @task @needs('build', 'uninstall') def push(): """Reinstall the app and start it.""" call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk') call('palm-launch', '--device=emulator', 'org.markpasc.paperplain') @task def tail(): """Follow the device's log.""" call('palm-log', '--device=emulator', '--system-log-level', 'info') call('palm-log', '--device=emulator', '-f', 'org.markpasc.paperplain') <commit_msg>Handle ctrl-C-ing out of palm-log<commit_after>import subprocess from paver.easy import * def call(*args, **kwargs): return subprocess.call(args, **kwargs) @task def build(): """Package up the app.""" call('palm-package', '.') @task def halt(): call('palm-launch', '--device=emulator', '-c', 'org.markpasc.paperplain') @task @needs('halt') def uninstall(): call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain') @task @needs('build', 'uninstall') def push(): """Reinstall the app and start it.""" call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk') call('palm-launch', '--device=emulator', 'org.markpasc.paperplain') @task def tail(): """Follow the device's log.""" call('palm-log', '--device=emulator', '--system-log-level', 'info') try: call('palm-log', '--device=emulator', '-f', 'org.markpasc.paperplain') except KeyboardInterrupt: print
14b1648b96064363a833c496da38e62ffc9dbbcb
external_tools/src/main/python/images/common.py
external_tools/src/main/python/images/common.py
#!/usr/bin/python #splitString='images/clean/impc/' splitString='images/holding_area/impc/'
#!/usr/bin/python splitString='images/clean/impc/'
Revert splitString to former value
Revert splitString to former value
Python
apache-2.0
mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData
#!/usr/bin/python #splitString='images/clean/impc/' splitString='images/holding_area/impc/' Revert splitString to former value
#!/usr/bin/python splitString='images/clean/impc/'
<commit_before>#!/usr/bin/python #splitString='images/clean/impc/' splitString='images/holding_area/impc/' <commit_msg>Revert splitString to former value<commit_after>
#!/usr/bin/python splitString='images/clean/impc/'
#!/usr/bin/python #splitString='images/clean/impc/' splitString='images/holding_area/impc/' Revert splitString to former value#!/usr/bin/python splitString='images/clean/impc/'
<commit_before>#!/usr/bin/python #splitString='images/clean/impc/' splitString='images/holding_area/impc/' <commit_msg>Revert splitString to former value<commit_after>#!/usr/bin/python splitString='images/clean/impc/'
bb104ac04e27e3354c4aebee7a0ca7e539232490
regparser/commands/outline_depths.py
regparser/commands/outline_depths.py
import logging from regparser.tree.depth import optional_rules from regparser.tree.depth.derive import derive_depths import click logger = logging.getLogger(__name__) @click.command() @click.argument('markers', type=click.STRING, required=True) def outline_depths(markers) -> None: """ Infer an outline's structure. Return a list of outline depths for a given list of space-separated markers. """ # Input is space-separated. marker_list = markers.split(' ') all_solutions = derive_depths( marker_list, [optional_rules.limit_sequence_gap(1)] ) depths = {tuple(str(a.depth) for a in s) for s in all_solutions}.pop() # Expected output is space-separated. formatted_output = ' '.join(depths) print(formatted_output) if __name__ == '__main__': """Enable running this command directly. E.g., `$ python regparser/commands/outline_depths.py`. This can save 1.5 seconds or more of startup time. """ outline_depths()
import logging from regparser.tree.depth import optional_rules from regparser.tree.depth.derive import derive_depths import click logger = logging.getLogger(__name__) @click.command() @click.argument('markers', type=click.STRING, required=True) def outline_depths(markers) -> None: """ Infer an outline's structure. Return a list of outline depths for a given list of space-separated markers. """ # Input is space-separated. marker_list = markers.split(' ') all_solutions = derive_depths( marker_list, [optional_rules.limit_sequence_gap(1)] ) depths = {tuple(str(a.depth) for a in s) for s in all_solutions}.pop() # Expected output is space-separated. formatted_output = ' '.join(depths) click.echo(formatted_output) if __name__ == '__main__': """Enable running this command directly. E.g., `$ python regparser/commands/outline_depths.py`. This can save 1.5 seconds or more of startup time. """ outline_depths()
Use click.echo() for python 2.7 compatibility
Use click.echo() for python 2.7 compatibility
Python
cc0-1.0
eregs/regulations-parser,tadhg-ohiggins/regulations-parser,eregs/regulations-parser,tadhg-ohiggins/regulations-parser
import logging from regparser.tree.depth import optional_rules from regparser.tree.depth.derive import derive_depths import click logger = logging.getLogger(__name__) @click.command() @click.argument('markers', type=click.STRING, required=True) def outline_depths(markers) -> None: """ Infer an outline's structure. Return a list of outline depths for a given list of space-separated markers. """ # Input is space-separated. marker_list = markers.split(' ') all_solutions = derive_depths( marker_list, [optional_rules.limit_sequence_gap(1)] ) depths = {tuple(str(a.depth) for a in s) for s in all_solutions}.pop() # Expected output is space-separated. formatted_output = ' '.join(depths) print(formatted_output) if __name__ == '__main__': """Enable running this command directly. E.g., `$ python regparser/commands/outline_depths.py`. This can save 1.5 seconds or more of startup time. """ outline_depths() Use click.echo() for python 2.7 compatibility
import logging from regparser.tree.depth import optional_rules from regparser.tree.depth.derive import derive_depths import click logger = logging.getLogger(__name__) @click.command() @click.argument('markers', type=click.STRING, required=True) def outline_depths(markers) -> None: """ Infer an outline's structure. Return a list of outline depths for a given list of space-separated markers. """ # Input is space-separated. marker_list = markers.split(' ') all_solutions = derive_depths( marker_list, [optional_rules.limit_sequence_gap(1)] ) depths = {tuple(str(a.depth) for a in s) for s in all_solutions}.pop() # Expected output is space-separated. formatted_output = ' '.join(depths) click.echo(formatted_output) if __name__ == '__main__': """Enable running this command directly. E.g., `$ python regparser/commands/outline_depths.py`. This can save 1.5 seconds or more of startup time. """ outline_depths()
<commit_before>import logging from regparser.tree.depth import optional_rules from regparser.tree.depth.derive import derive_depths import click logger = logging.getLogger(__name__) @click.command() @click.argument('markers', type=click.STRING, required=True) def outline_depths(markers) -> None: """ Infer an outline's structure. Return a list of outline depths for a given list of space-separated markers. """ # Input is space-separated. marker_list = markers.split(' ') all_solutions = derive_depths( marker_list, [optional_rules.limit_sequence_gap(1)] ) depths = {tuple(str(a.depth) for a in s) for s in all_solutions}.pop() # Expected output is space-separated. formatted_output = ' '.join(depths) print(formatted_output) if __name__ == '__main__': """Enable running this command directly. E.g., `$ python regparser/commands/outline_depths.py`. This can save 1.5 seconds or more of startup time. """ outline_depths() <commit_msg>Use click.echo() for python 2.7 compatibility<commit_after>
import logging from regparser.tree.depth import optional_rules from regparser.tree.depth.derive import derive_depths import click logger = logging.getLogger(__name__) @click.command() @click.argument('markers', type=click.STRING, required=True) def outline_depths(markers) -> None: """ Infer an outline's structure. Return a list of outline depths for a given list of space-separated markers. """ # Input is space-separated. marker_list = markers.split(' ') all_solutions = derive_depths( marker_list, [optional_rules.limit_sequence_gap(1)] ) depths = {tuple(str(a.depth) for a in s) for s in all_solutions}.pop() # Expected output is space-separated. formatted_output = ' '.join(depths) click.echo(formatted_output) if __name__ == '__main__': """Enable running this command directly. E.g., `$ python regparser/commands/outline_depths.py`. This can save 1.5 seconds or more of startup time. """ outline_depths()
import logging from regparser.tree.depth import optional_rules from regparser.tree.depth.derive import derive_depths import click logger = logging.getLogger(__name__) @click.command() @click.argument('markers', type=click.STRING, required=True) def outline_depths(markers) -> None: """ Infer an outline's structure. Return a list of outline depths for a given list of space-separated markers. """ # Input is space-separated. marker_list = markers.split(' ') all_solutions = derive_depths( marker_list, [optional_rules.limit_sequence_gap(1)] ) depths = {tuple(str(a.depth) for a in s) for s in all_solutions}.pop() # Expected output is space-separated. formatted_output = ' '.join(depths) print(formatted_output) if __name__ == '__main__': """Enable running this command directly. E.g., `$ python regparser/commands/outline_depths.py`. This can save 1.5 seconds or more of startup time. """ outline_depths() Use click.echo() for python 2.7 compatibilityimport logging from regparser.tree.depth import optional_rules from regparser.tree.depth.derive import derive_depths import click logger = logging.getLogger(__name__) @click.command() @click.argument('markers', type=click.STRING, required=True) def outline_depths(markers) -> None: """ Infer an outline's structure. Return a list of outline depths for a given list of space-separated markers. """ # Input is space-separated. marker_list = markers.split(' ') all_solutions = derive_depths( marker_list, [optional_rules.limit_sequence_gap(1)] ) depths = {tuple(str(a.depth) for a in s) for s in all_solutions}.pop() # Expected output is space-separated. formatted_output = ' '.join(depths) click.echo(formatted_output) if __name__ == '__main__': """Enable running this command directly. E.g., `$ python regparser/commands/outline_depths.py`. This can save 1.5 seconds or more of startup time. """ outline_depths()
<commit_before>import logging from regparser.tree.depth import optional_rules from regparser.tree.depth.derive import derive_depths import click logger = logging.getLogger(__name__) @click.command() @click.argument('markers', type=click.STRING, required=True) def outline_depths(markers) -> None: """ Infer an outline's structure. Return a list of outline depths for a given list of space-separated markers. """ # Input is space-separated. marker_list = markers.split(' ') all_solutions = derive_depths( marker_list, [optional_rules.limit_sequence_gap(1)] ) depths = {tuple(str(a.depth) for a in s) for s in all_solutions}.pop() # Expected output is space-separated. formatted_output = ' '.join(depths) print(formatted_output) if __name__ == '__main__': """Enable running this command directly. E.g., `$ python regparser/commands/outline_depths.py`. This can save 1.5 seconds or more of startup time. """ outline_depths() <commit_msg>Use click.echo() for python 2.7 compatibility<commit_after>import logging from regparser.tree.depth import optional_rules from regparser.tree.depth.derive import derive_depths import click logger = logging.getLogger(__name__) @click.command() @click.argument('markers', type=click.STRING, required=True) def outline_depths(markers) -> None: """ Infer an outline's structure. Return a list of outline depths for a given list of space-separated markers. """ # Input is space-separated. marker_list = markers.split(' ') all_solutions = derive_depths( marker_list, [optional_rules.limit_sequence_gap(1)] ) depths = {tuple(str(a.depth) for a in s) for s in all_solutions}.pop() # Expected output is space-separated. formatted_output = ' '.join(depths) click.echo(formatted_output) if __name__ == '__main__': """Enable running this command directly. E.g., `$ python regparser/commands/outline_depths.py`. This can save 1.5 seconds or more of startup time. """ outline_depths()
9da303e48820e95e1bfd206f1c0372f896dac6ec
draftjs_exporter/constants.py
draftjs_exporter/constants.py
from __future__ import absolute_import, unicode_literals # http://stackoverflow.com/a/22723724/1798491 class Enum(object): def __init__(self, tuple_list): self.tuple_list = tuple_list def __getattr__(self, name): if name not in self.tuple_list: raise AttributeError("'Enum' has no attribute '{}'".format(name)) return name # https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js class BLOCK_TYPES: UNSTYLED = 'unstyled' HEADER_ONE = 'header-one' HEADER_TWO = 'header-two' HEADER_THREE = 'header-three' HEADER_FOUR = 'header-four' HEADER_FIVE = 'header-five' HEADER_SIX = 'header-six' UNORDERED_LIST_ITEM = 'unordered-list-item' ORDERED_LIST_ITEM = 'ordered-list-item' BLOCKQUOTE = 'blockquote' PULLQUOTE = 'pullquote' CODE = 'code-block' ATOMIC = 'atomic' HORIZONTAL_RULE = 'horizontal-rule' ENTITY_TYPES = Enum(('LINK', 'IMAGE', 'TOKEN')) INLINE_STYLES = Enum(('BOLD', 'CODE', 'ITALIC', 'STRIKETHROUGH', 'UNDERLINE'))
from __future__ import absolute_import, unicode_literals # http://stackoverflow.com/a/22723724/1798491 class Enum(object): def __init__(self, *elements): self.elements = tuple(elements) def __getattr__(self, name): if name not in self.elements: raise AttributeError("'Enum' has no attribute '{}'".format(name)) return name # https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js class BLOCK_TYPES: UNSTYLED = 'unstyled' HEADER_ONE = 'header-one' HEADER_TWO = 'header-two' HEADER_THREE = 'header-three' HEADER_FOUR = 'header-four' HEADER_FIVE = 'header-five' HEADER_SIX = 'header-six' UNORDERED_LIST_ITEM = 'unordered-list-item' ORDERED_LIST_ITEM = 'ordered-list-item' BLOCKQUOTE = 'blockquote' PULLQUOTE = 'pullquote' CODE = 'code-block' ATOMIC = 'atomic' HORIZONTAL_RULE = 'horizontal-rule' ENTITY_TYPES = Enum('LINK', 'IMAGE', 'TOKEN') INLINE_STYLES = Enum('BOLD', 'CODE', 'ITALIC', 'STRIKETHROUGH', 'UNDERLINE')
Allow enum to be created more easily
Allow enum to be created more easily
Python
mit
springload/draftjs_exporter,springload/draftjs_exporter,springload/draftjs_exporter
from __future__ import absolute_import, unicode_literals # http://stackoverflow.com/a/22723724/1798491 class Enum(object): def __init__(self, tuple_list): self.tuple_list = tuple_list def __getattr__(self, name): if name not in self.tuple_list: raise AttributeError("'Enum' has no attribute '{}'".format(name)) return name # https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js class BLOCK_TYPES: UNSTYLED = 'unstyled' HEADER_ONE = 'header-one' HEADER_TWO = 'header-two' HEADER_THREE = 'header-three' HEADER_FOUR = 'header-four' HEADER_FIVE = 'header-five' HEADER_SIX = 'header-six' UNORDERED_LIST_ITEM = 'unordered-list-item' ORDERED_LIST_ITEM = 'ordered-list-item' BLOCKQUOTE = 'blockquote' PULLQUOTE = 'pullquote' CODE = 'code-block' ATOMIC = 'atomic' HORIZONTAL_RULE = 'horizontal-rule' ENTITY_TYPES = Enum(('LINK', 'IMAGE', 'TOKEN')) INLINE_STYLES = Enum(('BOLD', 'CODE', 'ITALIC', 'STRIKETHROUGH', 'UNDERLINE')) Allow enum to be created more easily
from __future__ import absolute_import, unicode_literals # http://stackoverflow.com/a/22723724/1798491 class Enum(object): def __init__(self, *elements): self.elements = tuple(elements) def __getattr__(self, name): if name not in self.elements: raise AttributeError("'Enum' has no attribute '{}'".format(name)) return name # https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js class BLOCK_TYPES: UNSTYLED = 'unstyled' HEADER_ONE = 'header-one' HEADER_TWO = 'header-two' HEADER_THREE = 'header-three' HEADER_FOUR = 'header-four' HEADER_FIVE = 'header-five' HEADER_SIX = 'header-six' UNORDERED_LIST_ITEM = 'unordered-list-item' ORDERED_LIST_ITEM = 'ordered-list-item' BLOCKQUOTE = 'blockquote' PULLQUOTE = 'pullquote' CODE = 'code-block' ATOMIC = 'atomic' HORIZONTAL_RULE = 'horizontal-rule' ENTITY_TYPES = Enum('LINK', 'IMAGE', 'TOKEN') INLINE_STYLES = Enum('BOLD', 'CODE', 'ITALIC', 'STRIKETHROUGH', 'UNDERLINE')
<commit_before>from __future__ import absolute_import, unicode_literals # http://stackoverflow.com/a/22723724/1798491 class Enum(object): def __init__(self, tuple_list): self.tuple_list = tuple_list def __getattr__(self, name): if name not in self.tuple_list: raise AttributeError("'Enum' has no attribute '{}'".format(name)) return name # https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js class BLOCK_TYPES: UNSTYLED = 'unstyled' HEADER_ONE = 'header-one' HEADER_TWO = 'header-two' HEADER_THREE = 'header-three' HEADER_FOUR = 'header-four' HEADER_FIVE = 'header-five' HEADER_SIX = 'header-six' UNORDERED_LIST_ITEM = 'unordered-list-item' ORDERED_LIST_ITEM = 'ordered-list-item' BLOCKQUOTE = 'blockquote' PULLQUOTE = 'pullquote' CODE = 'code-block' ATOMIC = 'atomic' HORIZONTAL_RULE = 'horizontal-rule' ENTITY_TYPES = Enum(('LINK', 'IMAGE', 'TOKEN')) INLINE_STYLES = Enum(('BOLD', 'CODE', 'ITALIC', 'STRIKETHROUGH', 'UNDERLINE')) <commit_msg>Allow enum to be created more easily<commit_after>
from __future__ import absolute_import, unicode_literals # http://stackoverflow.com/a/22723724/1798491 class Enum(object): def __init__(self, *elements): self.elements = tuple(elements) def __getattr__(self, name): if name not in self.elements: raise AttributeError("'Enum' has no attribute '{}'".format(name)) return name # https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js class BLOCK_TYPES: UNSTYLED = 'unstyled' HEADER_ONE = 'header-one' HEADER_TWO = 'header-two' HEADER_THREE = 'header-three' HEADER_FOUR = 'header-four' HEADER_FIVE = 'header-five' HEADER_SIX = 'header-six' UNORDERED_LIST_ITEM = 'unordered-list-item' ORDERED_LIST_ITEM = 'ordered-list-item' BLOCKQUOTE = 'blockquote' PULLQUOTE = 'pullquote' CODE = 'code-block' ATOMIC = 'atomic' HORIZONTAL_RULE = 'horizontal-rule' ENTITY_TYPES = Enum('LINK', 'IMAGE', 'TOKEN') INLINE_STYLES = Enum('BOLD', 'CODE', 'ITALIC', 'STRIKETHROUGH', 'UNDERLINE')
from __future__ import absolute_import, unicode_literals # http://stackoverflow.com/a/22723724/1798491 class Enum(object): def __init__(self, tuple_list): self.tuple_list = tuple_list def __getattr__(self, name): if name not in self.tuple_list: raise AttributeError("'Enum' has no attribute '{}'".format(name)) return name # https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js class BLOCK_TYPES: UNSTYLED = 'unstyled' HEADER_ONE = 'header-one' HEADER_TWO = 'header-two' HEADER_THREE = 'header-three' HEADER_FOUR = 'header-four' HEADER_FIVE = 'header-five' HEADER_SIX = 'header-six' UNORDERED_LIST_ITEM = 'unordered-list-item' ORDERED_LIST_ITEM = 'ordered-list-item' BLOCKQUOTE = 'blockquote' PULLQUOTE = 'pullquote' CODE = 'code-block' ATOMIC = 'atomic' HORIZONTAL_RULE = 'horizontal-rule' ENTITY_TYPES = Enum(('LINK', 'IMAGE', 'TOKEN')) INLINE_STYLES = Enum(('BOLD', 'CODE', 'ITALIC', 'STRIKETHROUGH', 'UNDERLINE')) Allow enum to be created more easilyfrom __future__ import absolute_import, unicode_literals # http://stackoverflow.com/a/22723724/1798491 class Enum(object): def __init__(self, *elements): self.elements = tuple(elements) def __getattr__(self, name): if name not in self.elements: raise AttributeError("'Enum' has no attribute '{}'".format(name)) return name # https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js class BLOCK_TYPES: UNSTYLED = 'unstyled' HEADER_ONE = 'header-one' HEADER_TWO = 'header-two' HEADER_THREE = 'header-three' HEADER_FOUR = 'header-four' HEADER_FIVE = 'header-five' HEADER_SIX = 'header-six' UNORDERED_LIST_ITEM = 'unordered-list-item' ORDERED_LIST_ITEM = 'ordered-list-item' BLOCKQUOTE = 'blockquote' PULLQUOTE = 'pullquote' CODE = 'code-block' ATOMIC = 'atomic' HORIZONTAL_RULE = 'horizontal-rule' ENTITY_TYPES = Enum('LINK', 'IMAGE', 'TOKEN') INLINE_STYLES = Enum('BOLD', 'CODE', 'ITALIC', 'STRIKETHROUGH', 'UNDERLINE')
<commit_before>from __future__ import absolute_import, unicode_literals # http://stackoverflow.com/a/22723724/1798491 class Enum(object): def __init__(self, tuple_list): self.tuple_list = tuple_list def __getattr__(self, name): if name not in self.tuple_list: raise AttributeError("'Enum' has no attribute '{}'".format(name)) return name # https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js class BLOCK_TYPES: UNSTYLED = 'unstyled' HEADER_ONE = 'header-one' HEADER_TWO = 'header-two' HEADER_THREE = 'header-three' HEADER_FOUR = 'header-four' HEADER_FIVE = 'header-five' HEADER_SIX = 'header-six' UNORDERED_LIST_ITEM = 'unordered-list-item' ORDERED_LIST_ITEM = 'ordered-list-item' BLOCKQUOTE = 'blockquote' PULLQUOTE = 'pullquote' CODE = 'code-block' ATOMIC = 'atomic' HORIZONTAL_RULE = 'horizontal-rule' ENTITY_TYPES = Enum(('LINK', 'IMAGE', 'TOKEN')) INLINE_STYLES = Enum(('BOLD', 'CODE', 'ITALIC', 'STRIKETHROUGH', 'UNDERLINE')) <commit_msg>Allow enum to be created more easily<commit_after>from __future__ import absolute_import, unicode_literals # http://stackoverflow.com/a/22723724/1798491 class Enum(object): def __init__(self, *elements): self.elements = tuple(elements) def __getattr__(self, name): if name not in self.elements: raise AttributeError("'Enum' has no attribute '{}'".format(name)) return name # https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js class BLOCK_TYPES: UNSTYLED = 'unstyled' HEADER_ONE = 'header-one' HEADER_TWO = 'header-two' HEADER_THREE = 'header-three' HEADER_FOUR = 'header-four' HEADER_FIVE = 'header-five' HEADER_SIX = 'header-six' UNORDERED_LIST_ITEM = 'unordered-list-item' ORDERED_LIST_ITEM = 'ordered-list-item' BLOCKQUOTE = 'blockquote' PULLQUOTE = 'pullquote' CODE = 'code-block' ATOMIC = 'atomic' HORIZONTAL_RULE = 'horizontal-rule' ENTITY_TYPES = Enum('LINK', 'IMAGE', 'TOKEN') INLINE_STYLES = Enum('BOLD', 'CODE', 'ITALIC', 'STRIKETHROUGH', 'UNDERLINE')
70a251ba27641e3c0425c659bb900e17f0f423dd
scripts/create_initial_admin_user.py
scripts/create_initial_admin_user.py
#!/usr/bin/env python """Create an initial user with admin privileges to begin BYCEPS setup. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import click from byceps.database import db from byceps.services.user import creation_service as user_creation_service from byceps.util.system import get_config_filename_from_env_or_exit from _util import app_context @click.command() @click.option('--screen_name', prompt=True) @click.option('--email_address', prompt=True) @click.option('--password', prompt=True, hide_input=True) def execute(screen_name, email_address, password): click.echo('Creating user "{}" ... '.format(screen_name), nl=False) user = _create_user(screen_name, email_address, password) click.secho('done.', fg='green') def _create_user(screen_name, email_address, password): try: user = user_creation_service \ .create_basic_user(screen_name, email_address, password) except ValueError as e: raise click.UsageError(e) user.enabled = True db.session.add(user) db.session.commit() return user if __name__ == '__main__': config_filename = get_config_filename_from_env_or_exit() with app_context(config_filename): execute()
#!/usr/bin/env python """Create an initial user with admin privileges to begin BYCEPS setup. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import click from byceps.services.user import creation_service as user_creation_service from byceps.services.user import service as user_service from byceps.util.system import get_config_filename_from_env_or_exit from _util import app_context @click.command() @click.option('--screen_name', prompt=True) @click.option('--email_address', prompt=True) @click.option('--password', prompt=True, hide_input=True) def execute(screen_name, email_address, password): click.echo('Creating user "{}" ... '.format(screen_name), nl=False) user = _create_user(screen_name, email_address, password) user_service.enable_user(user.id, user.id) click.secho('done.', fg='green') def _create_user(screen_name, email_address, password): try: return user_creation_service \ .create_basic_user(screen_name, email_address, password) except ValueError as e: raise click.UsageError(e) if __name__ == '__main__': config_filename = get_config_filename_from_env_or_exit() with app_context(config_filename): execute()
Enable initial user via service so that an event gets written
Enable initial user via service so that an event gets written
Python
bsd-3-clause
homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps
#!/usr/bin/env python """Create an initial user with admin privileges to begin BYCEPS setup. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import click from byceps.database import db from byceps.services.user import creation_service as user_creation_service from byceps.util.system import get_config_filename_from_env_or_exit from _util import app_context @click.command() @click.option('--screen_name', prompt=True) @click.option('--email_address', prompt=True) @click.option('--password', prompt=True, hide_input=True) def execute(screen_name, email_address, password): click.echo('Creating user "{}" ... '.format(screen_name), nl=False) user = _create_user(screen_name, email_address, password) click.secho('done.', fg='green') def _create_user(screen_name, email_address, password): try: user = user_creation_service \ .create_basic_user(screen_name, email_address, password) except ValueError as e: raise click.UsageError(e) user.enabled = True db.session.add(user) db.session.commit() return user if __name__ == '__main__': config_filename = get_config_filename_from_env_or_exit() with app_context(config_filename): execute() Enable initial user via service so that an event gets written
#!/usr/bin/env python """Create an initial user with admin privileges to begin BYCEPS setup. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import click from byceps.services.user import creation_service as user_creation_service from byceps.services.user import service as user_service from byceps.util.system import get_config_filename_from_env_or_exit from _util import app_context @click.command() @click.option('--screen_name', prompt=True) @click.option('--email_address', prompt=True) @click.option('--password', prompt=True, hide_input=True) def execute(screen_name, email_address, password): click.echo('Creating user "{}" ... '.format(screen_name), nl=False) user = _create_user(screen_name, email_address, password) user_service.enable_user(user.id, user.id) click.secho('done.', fg='green') def _create_user(screen_name, email_address, password): try: return user_creation_service \ .create_basic_user(screen_name, email_address, password) except ValueError as e: raise click.UsageError(e) if __name__ == '__main__': config_filename = get_config_filename_from_env_or_exit() with app_context(config_filename): execute()
<commit_before>#!/usr/bin/env python """Create an initial user with admin privileges to begin BYCEPS setup. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import click from byceps.database import db from byceps.services.user import creation_service as user_creation_service from byceps.util.system import get_config_filename_from_env_or_exit from _util import app_context @click.command() @click.option('--screen_name', prompt=True) @click.option('--email_address', prompt=True) @click.option('--password', prompt=True, hide_input=True) def execute(screen_name, email_address, password): click.echo('Creating user "{}" ... '.format(screen_name), nl=False) user = _create_user(screen_name, email_address, password) click.secho('done.', fg='green') def _create_user(screen_name, email_address, password): try: user = user_creation_service \ .create_basic_user(screen_name, email_address, password) except ValueError as e: raise click.UsageError(e) user.enabled = True db.session.add(user) db.session.commit() return user if __name__ == '__main__': config_filename = get_config_filename_from_env_or_exit() with app_context(config_filename): execute() <commit_msg>Enable initial user via service so that an event gets written<commit_after>
#!/usr/bin/env python """Create an initial user with admin privileges to begin BYCEPS setup. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import click from byceps.services.user import creation_service as user_creation_service from byceps.services.user import service as user_service from byceps.util.system import get_config_filename_from_env_or_exit from _util import app_context @click.command() @click.option('--screen_name', prompt=True) @click.option('--email_address', prompt=True) @click.option('--password', prompt=True, hide_input=True) def execute(screen_name, email_address, password): click.echo('Creating user "{}" ... '.format(screen_name), nl=False) user = _create_user(screen_name, email_address, password) user_service.enable_user(user.id, user.id) click.secho('done.', fg='green') def _create_user(screen_name, email_address, password): try: return user_creation_service \ .create_basic_user(screen_name, email_address, password) except ValueError as e: raise click.UsageError(e) if __name__ == '__main__': config_filename = get_config_filename_from_env_or_exit() with app_context(config_filename): execute()
#!/usr/bin/env python """Create an initial user with admin privileges to begin BYCEPS setup. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import click from byceps.database import db from byceps.services.user import creation_service as user_creation_service from byceps.util.system import get_config_filename_from_env_or_exit from _util import app_context @click.command() @click.option('--screen_name', prompt=True) @click.option('--email_address', prompt=True) @click.option('--password', prompt=True, hide_input=True) def execute(screen_name, email_address, password): click.echo('Creating user "{}" ... '.format(screen_name), nl=False) user = _create_user(screen_name, email_address, password) click.secho('done.', fg='green') def _create_user(screen_name, email_address, password): try: user = user_creation_service \ .create_basic_user(screen_name, email_address, password) except ValueError as e: raise click.UsageError(e) user.enabled = True db.session.add(user) db.session.commit() return user if __name__ == '__main__': config_filename = get_config_filename_from_env_or_exit() with app_context(config_filename): execute() Enable initial user via service so that an event gets written#!/usr/bin/env python """Create an initial user with admin privileges to begin BYCEPS setup. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import click from byceps.services.user import creation_service as user_creation_service from byceps.services.user import service as user_service from byceps.util.system import get_config_filename_from_env_or_exit from _util import app_context @click.command() @click.option('--screen_name', prompt=True) @click.option('--email_address', prompt=True) @click.option('--password', prompt=True, hide_input=True) def execute(screen_name, email_address, password): click.echo('Creating user "{}" ... '.format(screen_name), nl=False) user = _create_user(screen_name, email_address, password) user_service.enable_user(user.id, user.id) click.secho('done.', fg='green') def _create_user(screen_name, email_address, password): try: return user_creation_service \ .create_basic_user(screen_name, email_address, password) except ValueError as e: raise click.UsageError(e) if __name__ == '__main__': config_filename = get_config_filename_from_env_or_exit() with app_context(config_filename): execute()
<commit_before>#!/usr/bin/env python """Create an initial user with admin privileges to begin BYCEPS setup. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import click from byceps.database import db from byceps.services.user import creation_service as user_creation_service from byceps.util.system import get_config_filename_from_env_or_exit from _util import app_context @click.command() @click.option('--screen_name', prompt=True) @click.option('--email_address', prompt=True) @click.option('--password', prompt=True, hide_input=True) def execute(screen_name, email_address, password): click.echo('Creating user "{}" ... '.format(screen_name), nl=False) user = _create_user(screen_name, email_address, password) click.secho('done.', fg='green') def _create_user(screen_name, email_address, password): try: user = user_creation_service \ .create_basic_user(screen_name, email_address, password) except ValueError as e: raise click.UsageError(e) user.enabled = True db.session.add(user) db.session.commit() return user if __name__ == '__main__': config_filename = get_config_filename_from_env_or_exit() with app_context(config_filename): execute() <commit_msg>Enable initial user via service so that an event gets written<commit_after>#!/usr/bin/env python """Create an initial user with admin privileges to begin BYCEPS setup. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import click from byceps.services.user import creation_service as user_creation_service from byceps.services.user import service as user_service from byceps.util.system import get_config_filename_from_env_or_exit from _util import app_context @click.command() @click.option('--screen_name', prompt=True) @click.option('--email_address', prompt=True) @click.option('--password', prompt=True, hide_input=True) def execute(screen_name, email_address, password): click.echo('Creating user "{}" ... '.format(screen_name), nl=False) user = _create_user(screen_name, email_address, password) user_service.enable_user(user.id, user.id) click.secho('done.', fg='green') def _create_user(screen_name, email_address, password): try: return user_creation_service \ .create_basic_user(screen_name, email_address, password) except ValueError as e: raise click.UsageError(e) if __name__ == '__main__': config_filename = get_config_filename_from_env_or_exit() with app_context(config_filename): execute()
65ae8fc33a1fa7297d3e68f7c67ca5c2678e81b7
app/__init__.py
app/__init__.py
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) migrate = Migrate(app, db) # Load Flask-Mail mail = Mail(app) from app import views, models
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail from flask_user import UserManager, SQLAlchemyAdapter app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) migrate = Migrate(app, db) # Load Flask-Mail mail = Mail(app) # Configure user model for Flask-User from app.models import User db_adapter = SQLAlchemyAdapter(db, User) user_manager = UserManager(db_adapter, app) from app import views, models
Set up Flask-User to provide user auth
Set up Flask-User to provide user auth
Python
agpl-3.0
interactomix/iis,interactomix/iis
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) migrate = Migrate(app, db) # Load Flask-Mail mail = Mail(app) from app import views, models Set up Flask-User to provide user auth
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail from flask_user import UserManager, SQLAlchemyAdapter app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) migrate = Migrate(app, db) # Load Flask-Mail mail = Mail(app) # Configure user model for Flask-User from app.models import User db_adapter = SQLAlchemyAdapter(db, User) user_manager = UserManager(db_adapter, app) from app import views, models
<commit_before>from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) migrate = Migrate(app, db) # Load Flask-Mail mail = Mail(app) from app import views, models <commit_msg>Set up Flask-User to provide user auth<commit_after>
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail from flask_user import UserManager, SQLAlchemyAdapter app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) migrate = Migrate(app, db) # Load Flask-Mail mail = Mail(app) # Configure user model for Flask-User from app.models import User db_adapter = SQLAlchemyAdapter(db, User) user_manager = UserManager(db_adapter, app) from app import views, models
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) migrate = Migrate(app, db) # Load Flask-Mail mail = Mail(app) from app import views, models Set up Flask-User to provide user authfrom flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail from flask_user import UserManager, SQLAlchemyAdapter app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) migrate = Migrate(app, db) # Load Flask-Mail mail = Mail(app) # Configure user model for Flask-User from app.models import User db_adapter = SQLAlchemyAdapter(db, User) user_manager = UserManager(db_adapter, app) from app import views, models
<commit_before>from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) migrate = Migrate(app, db) # Load Flask-Mail mail = Mail(app) from app import views, models <commit_msg>Set up Flask-User to provide user auth<commit_after>from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail from flask_user import UserManager, SQLAlchemyAdapter app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) migrate = Migrate(app, db) # Load Flask-Mail mail = Mail(app) # Configure user model for Flask-User from app.models import User db_adapter = SQLAlchemyAdapter(db, User) user_manager = UserManager(db_adapter, app) from app import views, models
d2e82419a8f1b7ead32a43e6a03ebe8093374840
opps/channels/forms.py
opps/channels/forms.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from django.utils.translation import ugettext_lazy as _ from .models import Channel class ChannelAdminForm(forms.ModelForm): layout = forms.ChoiceField(choices=(('default', _('Default')),)) class Meta: model = Channel
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from django.utils.translation import ugettext_lazy as _ from .models import Channel class ChannelAdminForm(forms.ModelForm): layout = forms.ChoiceField(choices=(('default', _('Default')),)) def __init__(self, *args, **kwargs): super(ChannelAdminForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance and instance.pk: self.fields['slug'].widget.attrs['readonly'] = True class Meta: model = Channel
Set slug field readonly after channel create
Set slug field readonly after channel create
Python
mit
williamroot/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps,opps/opps,williamroot/opps,opps/opps,YACOWS/opps,opps/opps,opps/opps,YACOWS/opps
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from django.utils.translation import ugettext_lazy as _ from .models import Channel class ChannelAdminForm(forms.ModelForm): layout = forms.ChoiceField(choices=(('default', _('Default')),)) class Meta: model = Channel Set slug field readonly after channel create
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from django.utils.translation import ugettext_lazy as _ from .models import Channel class ChannelAdminForm(forms.ModelForm): layout = forms.ChoiceField(choices=(('default', _('Default')),)) def __init__(self, *args, **kwargs): super(ChannelAdminForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance and instance.pk: self.fields['slug'].widget.attrs['readonly'] = True class Meta: model = Channel
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from django.utils.translation import ugettext_lazy as _ from .models import Channel class ChannelAdminForm(forms.ModelForm): layout = forms.ChoiceField(choices=(('default', _('Default')),)) class Meta: model = Channel <commit_msg>Set slug field readonly after channel create<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from django.utils.translation import ugettext_lazy as _ from .models import Channel class ChannelAdminForm(forms.ModelForm): layout = forms.ChoiceField(choices=(('default', _('Default')),)) def __init__(self, *args, **kwargs): super(ChannelAdminForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance and instance.pk: self.fields['slug'].widget.attrs['readonly'] = True class Meta: model = Channel
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from django.utils.translation import ugettext_lazy as _ from .models import Channel class ChannelAdminForm(forms.ModelForm): layout = forms.ChoiceField(choices=(('default', _('Default')),)) class Meta: model = Channel Set slug field readonly after channel create#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from django.utils.translation import ugettext_lazy as _ from .models import Channel class ChannelAdminForm(forms.ModelForm): layout = forms.ChoiceField(choices=(('default', _('Default')),)) def __init__(self, *args, **kwargs): super(ChannelAdminForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance and instance.pk: self.fields['slug'].widget.attrs['readonly'] = True class Meta: model = Channel
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from django.utils.translation import ugettext_lazy as _ from .models import Channel class ChannelAdminForm(forms.ModelForm): layout = forms.ChoiceField(choices=(('default', _('Default')),)) class Meta: model = Channel <commit_msg>Set slug field readonly after channel create<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from django.utils.translation import ugettext_lazy as _ from .models import Channel class ChannelAdminForm(forms.ModelForm): layout = forms.ChoiceField(choices=(('default', _('Default')),)) def __init__(self, *args, **kwargs): super(ChannelAdminForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance and instance.pk: self.fields['slug'].widget.attrs['readonly'] = True class Meta: model = Channel
c9284827eeec90a253157286214bc1d17771db24
neutron/tests/api/test_service_type_management.py
neutron/tests/api/test_service_type_management.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_lib import decorators from neutron.tests.api import base from neutron.tests.tempest import test class ServiceTypeManagementTestJSON(base.BaseNetworkTest): @classmethod def resource_setup(cls): super(ServiceTypeManagementTestJSON, cls).resource_setup() if not test.is_extension_enabled('service-type', 'network'): msg = "Neutron Service Type Management not enabled." raise cls.skipException(msg) @decorators.skip_because(bug="1400370") @test.attr(type='smoke') @test.idempotent_id('2cbbeea9-f010-40f6-8df5-4eaa0c918ea6') def test_service_provider_list(self): body = self.client.list_service_providers() self.assertIsInstance(body['service_providers'], list)
# 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 neutron.tests.api import base from neutron.tests.tempest import test class ServiceTypeManagementTest(base.BaseNetworkTest): @classmethod def resource_setup(cls): super(ServiceTypeManagementTest, cls).resource_setup() if not test.is_extension_enabled('service-type', 'network'): msg = "Neutron Service Type Management not enabled." raise cls.skipException(msg) @test.attr(type='smoke') @test.idempotent_id('2cbbeea9-f010-40f6-8df5-4eaa0c918ea6') def test_service_provider_list(self): body = self.client.list_service_providers() self.assertIsInstance(body['service_providers'], list)
Remove skip of service-type management API test
Remove skip of service-type management API test Advanced services split is complete so remove the skip for the service-type management API test. (Yes, there is only one placeholder test. More tests need to be developed.) Also remove the obsolete 'JSON' suffix from the test class. Closes-bug: 1400370 Change-Id: I5b4b8a67b24595568ea13bc400c1f5fce6d40f28
Python
apache-2.0
NeCTAR-RC/neutron,apporc/neutron,takeshineshiro/neutron,mmnelemane/neutron,barnsnake351/neutron,glove747/liberty-neutron,sasukeh/neutron,SamYaple/neutron,dhanunjaya/neutron,swdream/neutron,noironetworks/neutron,bgxavier/neutron,chitr/neutron,eonpatapon/neutron,glove747/liberty-neutron,paninetworks/neutron,antonioUnina/neutron,wenhuizhang/neutron,klmitch/neutron,wolverineav/neutron,suneeth51/neutron,eayunstack/neutron,igor-toga/local-snat,shahbazn/neutron,jerryz1982/neutron,cloudbase/neutron,bigswitch/neutron,vivekanand1101/neutron,wolverineav/neutron,jumpojoy/neutron,JianyuWang/neutron,cisco-openstack/neutron,paninetworks/neutron,openstack/neutron,watonyweng/neutron,bigswitch/neutron,skyddv/neutron,mattt416/neutron,dims/neutron,neoareslinux/neutron,JianyuWang/neutron,huntxu/neutron,skyddv/neutron,yanheven/neutron,adelina-t/neutron,cisco-openstack/neutron,eonpatapon/neutron,SmartInfrastructures/neutron,igor-toga/local-snat,apporc/neutron,mandeepdhami/neutron,antonioUnina/neutron,SmartInfrastructures/neutron,sebrandon1/neutron,bgxavier/neutron,MaximNevrov/neutron,chitr/neutron,SamYaple/neutron,mahak/neutron,jumpojoy/neutron,shahbazn/neutron,asgard-lab/neutron,jacknjzhou/neutron,asgard-lab/neutron,mattt416/neutron,huntxu/neutron,takeshineshiro/neutron,silenci/neutron,JioCloud/neutron,mandeepdhami/neutron,javaos74/neutron,noironetworks/neutron,MaximNevrov/neutron,jerryz1982/neutron,adelina-t/neutron,swdream/neutron,silenci/neutron,barnsnake351/neutron,JioCloud/neutron,mahak/neutron,openstack/neutron,wenhuizhang/neutron,yanheven/neutron,dhanunjaya/neutron,eayunstack/neutron,mmnelemane/neutron,cloudbase/neutron,suneeth51/neutron,sasukeh/neutron,NeCTAR-RC/neutron,klmitch/neutron,vivekanand1101/neutron,jacknjzhou/neutron,watonyweng/neutron,mahak/neutron,sebrandon1/neutron,openstack/neutron,javaos74/neutron,neoareslinux/neutron,dims/neutron
# 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_lib import decorators from neutron.tests.api import base from neutron.tests.tempest import test class ServiceTypeManagementTestJSON(base.BaseNetworkTest): @classmethod def resource_setup(cls): super(ServiceTypeManagementTestJSON, cls).resource_setup() if not test.is_extension_enabled('service-type', 'network'): msg = "Neutron Service Type Management not enabled." raise cls.skipException(msg) @decorators.skip_because(bug="1400370") @test.attr(type='smoke') @test.idempotent_id('2cbbeea9-f010-40f6-8df5-4eaa0c918ea6') def test_service_provider_list(self): body = self.client.list_service_providers() self.assertIsInstance(body['service_providers'], list) Remove skip of service-type management API test Advanced services split is complete so remove the skip for the service-type management API test. (Yes, there is only one placeholder test. More tests need to be developed.) Also remove the obsolete 'JSON' suffix from the test class. Closes-bug: 1400370 Change-Id: I5b4b8a67b24595568ea13bc400c1f5fce6d40f28
# 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 neutron.tests.api import base from neutron.tests.tempest import test class ServiceTypeManagementTest(base.BaseNetworkTest): @classmethod def resource_setup(cls): super(ServiceTypeManagementTest, cls).resource_setup() if not test.is_extension_enabled('service-type', 'network'): msg = "Neutron Service Type Management not enabled." raise cls.skipException(msg) @test.attr(type='smoke') @test.idempotent_id('2cbbeea9-f010-40f6-8df5-4eaa0c918ea6') def test_service_provider_list(self): body = self.client.list_service_providers() self.assertIsInstance(body['service_providers'], list)
<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_lib import decorators from neutron.tests.api import base from neutron.tests.tempest import test class ServiceTypeManagementTestJSON(base.BaseNetworkTest): @classmethod def resource_setup(cls): super(ServiceTypeManagementTestJSON, cls).resource_setup() if not test.is_extension_enabled('service-type', 'network'): msg = "Neutron Service Type Management not enabled." raise cls.skipException(msg) @decorators.skip_because(bug="1400370") @test.attr(type='smoke') @test.idempotent_id('2cbbeea9-f010-40f6-8df5-4eaa0c918ea6') def test_service_provider_list(self): body = self.client.list_service_providers() self.assertIsInstance(body['service_providers'], list) <commit_msg>Remove skip of service-type management API test Advanced services split is complete so remove the skip for the service-type management API test. (Yes, there is only one placeholder test. More tests need to be developed.) Also remove the obsolete 'JSON' suffix from the test class. Closes-bug: 1400370 Change-Id: I5b4b8a67b24595568ea13bc400c1f5fce6d40f28<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 neutron.tests.api import base from neutron.tests.tempest import test class ServiceTypeManagementTest(base.BaseNetworkTest): @classmethod def resource_setup(cls): super(ServiceTypeManagementTest, cls).resource_setup() if not test.is_extension_enabled('service-type', 'network'): msg = "Neutron Service Type Management not enabled." raise cls.skipException(msg) @test.attr(type='smoke') @test.idempotent_id('2cbbeea9-f010-40f6-8df5-4eaa0c918ea6') def test_service_provider_list(self): body = self.client.list_service_providers() self.assertIsInstance(body['service_providers'], list)
# 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_lib import decorators from neutron.tests.api import base from neutron.tests.tempest import test class ServiceTypeManagementTestJSON(base.BaseNetworkTest): @classmethod def resource_setup(cls): super(ServiceTypeManagementTestJSON, cls).resource_setup() if not test.is_extension_enabled('service-type', 'network'): msg = "Neutron Service Type Management not enabled." raise cls.skipException(msg) @decorators.skip_because(bug="1400370") @test.attr(type='smoke') @test.idempotent_id('2cbbeea9-f010-40f6-8df5-4eaa0c918ea6') def test_service_provider_list(self): body = self.client.list_service_providers() self.assertIsInstance(body['service_providers'], list) Remove skip of service-type management API test Advanced services split is complete so remove the skip for the service-type management API test. (Yes, there is only one placeholder test. More tests need to be developed.) Also remove the obsolete 'JSON' suffix from the test class. Closes-bug: 1400370 Change-Id: I5b4b8a67b24595568ea13bc400c1f5fce6d40f28# 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 neutron.tests.api import base from neutron.tests.tempest import test class ServiceTypeManagementTest(base.BaseNetworkTest): @classmethod def resource_setup(cls): super(ServiceTypeManagementTest, cls).resource_setup() if not test.is_extension_enabled('service-type', 'network'): msg = "Neutron Service Type Management not enabled." raise cls.skipException(msg) @test.attr(type='smoke') @test.idempotent_id('2cbbeea9-f010-40f6-8df5-4eaa0c918ea6') def test_service_provider_list(self): body = self.client.list_service_providers() self.assertIsInstance(body['service_providers'], list)
<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_lib import decorators from neutron.tests.api import base from neutron.tests.tempest import test class ServiceTypeManagementTestJSON(base.BaseNetworkTest): @classmethod def resource_setup(cls): super(ServiceTypeManagementTestJSON, cls).resource_setup() if not test.is_extension_enabled('service-type', 'network'): msg = "Neutron Service Type Management not enabled." raise cls.skipException(msg) @decorators.skip_because(bug="1400370") @test.attr(type='smoke') @test.idempotent_id('2cbbeea9-f010-40f6-8df5-4eaa0c918ea6') def test_service_provider_list(self): body = self.client.list_service_providers() self.assertIsInstance(body['service_providers'], list) <commit_msg>Remove skip of service-type management API test Advanced services split is complete so remove the skip for the service-type management API test. (Yes, there is only one placeholder test. More tests need to be developed.) Also remove the obsolete 'JSON' suffix from the test class. Closes-bug: 1400370 Change-Id: I5b4b8a67b24595568ea13bc400c1f5fce6d40f28<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 neutron.tests.api import base from neutron.tests.tempest import test class ServiceTypeManagementTest(base.BaseNetworkTest): @classmethod def resource_setup(cls): super(ServiceTypeManagementTest, cls).resource_setup() if not test.is_extension_enabled('service-type', 'network'): msg = "Neutron Service Type Management not enabled." raise cls.skipException(msg) @test.attr(type='smoke') @test.idempotent_id('2cbbeea9-f010-40f6-8df5-4eaa0c918ea6') def test_service_provider_list(self): body = self.client.list_service_providers() self.assertIsInstance(body['service_providers'], list)
c75a244247988dbce68aa7985241712d8c94a24a
Lib/distutils/command/install_ext.py
Lib/distutils/command/install_ext.py
"""install_ext Implement the Distutils "install_ext" command to install extension modules.""" # created 1999/09/12, Greg Ward __revision__ = "$Id$" from distutils.core import Command from distutils.util import copy_tree class install_ext (Command): description = "install C/C++ extension modules" user_options = [ ('install-dir=', 'd', "directory to install to"), ('build-dir=','b', "build directory (where to install from)"), ] def initialize_options (self): # let the 'install' command dictate our installation directory self.install_dir = None self.build_dir = None def finalize_options (self): self.set_undefined_options ('install', ('build_platlib', 'build_dir'), ('install_platlib', 'install_dir')) def run (self): # Make sure we have built all extension modules first self.run_peer ('build_ext') # Dump the entire "build/platlib" directory (or whatever it really # is; "build/platlib" is the default) to the installation target # (eg. "/usr/local/lib/python1.5/site-packages"). Note that # putting files in the right package dir is already done when we # build. outfiles = self.copy_tree (self.build_dir, self.install_dir) # class InstallExt
"""install_ext Implement the Distutils "install_ext" command to install extension modules.""" # created 1999/09/12, Greg Ward __revision__ = "$Id$" from distutils.core import Command from distutils.util import copy_tree class install_ext (Command): description = "install C/C++ extension modules" user_options = [ ('install-dir=', 'd', "directory to install to"), ('build-dir=','b', "build directory (where to install from)"), ] def initialize_options (self): # let the 'install' command dictate our installation directory self.install_dir = None self.build_dir = None def finalize_options (self): self.set_undefined_options ('install', ('build_lib', 'build_dir'), ('install_lib', 'install_dir')) def run (self): # Make sure we have built all extension modules first self.run_peer ('build_ext') # Dump the entire "build/platlib" directory (or whatever it really # is; "build/platlib" is the default) to the installation target # (eg. "/usr/local/lib/python1.5/site-packages"). Note that # putting files in the right package dir is already done when we # build. outfiles = self.copy_tree (self.build_dir, self.install_dir) # class InstallExt
Fix how we set 'build_dir' and 'install_dir' options from 'install' options -- irrelevant because this file is about to go away, but oh well.
Fix how we set 'build_dir' and 'install_dir' options from 'install' options -- irrelevant because this file is about to go away, but oh well.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
"""install_ext Implement the Distutils "install_ext" command to install extension modules.""" # created 1999/09/12, Greg Ward __revision__ = "$Id$" from distutils.core import Command from distutils.util import copy_tree class install_ext (Command): description = "install C/C++ extension modules" user_options = [ ('install-dir=', 'd', "directory to install to"), ('build-dir=','b', "build directory (where to install from)"), ] def initialize_options (self): # let the 'install' command dictate our installation directory self.install_dir = None self.build_dir = None def finalize_options (self): self.set_undefined_options ('install', ('build_platlib', 'build_dir'), ('install_platlib', 'install_dir')) def run (self): # Make sure we have built all extension modules first self.run_peer ('build_ext') # Dump the entire "build/platlib" directory (or whatever it really # is; "build/platlib" is the default) to the installation target # (eg. "/usr/local/lib/python1.5/site-packages"). Note that # putting files in the right package dir is already done when we # build. outfiles = self.copy_tree (self.build_dir, self.install_dir) # class InstallExt Fix how we set 'build_dir' and 'install_dir' options from 'install' options -- irrelevant because this file is about to go away, but oh well.
"""install_ext Implement the Distutils "install_ext" command to install extension modules.""" # created 1999/09/12, Greg Ward __revision__ = "$Id$" from distutils.core import Command from distutils.util import copy_tree class install_ext (Command): description = "install C/C++ extension modules" user_options = [ ('install-dir=', 'd', "directory to install to"), ('build-dir=','b', "build directory (where to install from)"), ] def initialize_options (self): # let the 'install' command dictate our installation directory self.install_dir = None self.build_dir = None def finalize_options (self): self.set_undefined_options ('install', ('build_lib', 'build_dir'), ('install_lib', 'install_dir')) def run (self): # Make sure we have built all extension modules first self.run_peer ('build_ext') # Dump the entire "build/platlib" directory (or whatever it really # is; "build/platlib" is the default) to the installation target # (eg. "/usr/local/lib/python1.5/site-packages"). Note that # putting files in the right package dir is already done when we # build. outfiles = self.copy_tree (self.build_dir, self.install_dir) # class InstallExt
<commit_before>"""install_ext Implement the Distutils "install_ext" command to install extension modules.""" # created 1999/09/12, Greg Ward __revision__ = "$Id$" from distutils.core import Command from distutils.util import copy_tree class install_ext (Command): description = "install C/C++ extension modules" user_options = [ ('install-dir=', 'd', "directory to install to"), ('build-dir=','b', "build directory (where to install from)"), ] def initialize_options (self): # let the 'install' command dictate our installation directory self.install_dir = None self.build_dir = None def finalize_options (self): self.set_undefined_options ('install', ('build_platlib', 'build_dir'), ('install_platlib', 'install_dir')) def run (self): # Make sure we have built all extension modules first self.run_peer ('build_ext') # Dump the entire "build/platlib" directory (or whatever it really # is; "build/platlib" is the default) to the installation target # (eg. "/usr/local/lib/python1.5/site-packages"). Note that # putting files in the right package dir is already done when we # build. outfiles = self.copy_tree (self.build_dir, self.install_dir) # class InstallExt <commit_msg>Fix how we set 'build_dir' and 'install_dir' options from 'install' options -- irrelevant because this file is about to go away, but oh well.<commit_after>
"""install_ext Implement the Distutils "install_ext" command to install extension modules.""" # created 1999/09/12, Greg Ward __revision__ = "$Id$" from distutils.core import Command from distutils.util import copy_tree class install_ext (Command): description = "install C/C++ extension modules" user_options = [ ('install-dir=', 'd', "directory to install to"), ('build-dir=','b', "build directory (where to install from)"), ] def initialize_options (self): # let the 'install' command dictate our installation directory self.install_dir = None self.build_dir = None def finalize_options (self): self.set_undefined_options ('install', ('build_lib', 'build_dir'), ('install_lib', 'install_dir')) def run (self): # Make sure we have built all extension modules first self.run_peer ('build_ext') # Dump the entire "build/platlib" directory (or whatever it really # is; "build/platlib" is the default) to the installation target # (eg. "/usr/local/lib/python1.5/site-packages"). Note that # putting files in the right package dir is already done when we # build. outfiles = self.copy_tree (self.build_dir, self.install_dir) # class InstallExt
"""install_ext Implement the Distutils "install_ext" command to install extension modules.""" # created 1999/09/12, Greg Ward __revision__ = "$Id$" from distutils.core import Command from distutils.util import copy_tree class install_ext (Command): description = "install C/C++ extension modules" user_options = [ ('install-dir=', 'd', "directory to install to"), ('build-dir=','b', "build directory (where to install from)"), ] def initialize_options (self): # let the 'install' command dictate our installation directory self.install_dir = None self.build_dir = None def finalize_options (self): self.set_undefined_options ('install', ('build_platlib', 'build_dir'), ('install_platlib', 'install_dir')) def run (self): # Make sure we have built all extension modules first self.run_peer ('build_ext') # Dump the entire "build/platlib" directory (or whatever it really # is; "build/platlib" is the default) to the installation target # (eg. "/usr/local/lib/python1.5/site-packages"). Note that # putting files in the right package dir is already done when we # build. outfiles = self.copy_tree (self.build_dir, self.install_dir) # class InstallExt Fix how we set 'build_dir' and 'install_dir' options from 'install' options -- irrelevant because this file is about to go away, but oh well."""install_ext Implement the Distutils "install_ext" command to install extension modules.""" # created 1999/09/12, Greg Ward __revision__ = "$Id$" from distutils.core import Command from distutils.util import copy_tree class install_ext (Command): description = "install C/C++ extension modules" user_options = [ ('install-dir=', 'd', "directory to install to"), ('build-dir=','b', "build directory (where to install from)"), ] def initialize_options (self): # let the 'install' command dictate our installation directory self.install_dir = None self.build_dir = None def finalize_options (self): self.set_undefined_options ('install', ('build_lib', 'build_dir'), ('install_lib', 'install_dir')) def run (self): # Make sure we have built all extension modules first self.run_peer ('build_ext') # Dump the entire "build/platlib" directory (or whatever it really # is; "build/platlib" is the default) to the installation target # (eg. "/usr/local/lib/python1.5/site-packages"). Note that # putting files in the right package dir is already done when we # build. outfiles = self.copy_tree (self.build_dir, self.install_dir) # class InstallExt
<commit_before>"""install_ext Implement the Distutils "install_ext" command to install extension modules.""" # created 1999/09/12, Greg Ward __revision__ = "$Id$" from distutils.core import Command from distutils.util import copy_tree class install_ext (Command): description = "install C/C++ extension modules" user_options = [ ('install-dir=', 'd', "directory to install to"), ('build-dir=','b', "build directory (where to install from)"), ] def initialize_options (self): # let the 'install' command dictate our installation directory self.install_dir = None self.build_dir = None def finalize_options (self): self.set_undefined_options ('install', ('build_platlib', 'build_dir'), ('install_platlib', 'install_dir')) def run (self): # Make sure we have built all extension modules first self.run_peer ('build_ext') # Dump the entire "build/platlib" directory (or whatever it really # is; "build/platlib" is the default) to the installation target # (eg. "/usr/local/lib/python1.5/site-packages"). Note that # putting files in the right package dir is already done when we # build. outfiles = self.copy_tree (self.build_dir, self.install_dir) # class InstallExt <commit_msg>Fix how we set 'build_dir' and 'install_dir' options from 'install' options -- irrelevant because this file is about to go away, but oh well.<commit_after>"""install_ext Implement the Distutils "install_ext" command to install extension modules.""" # created 1999/09/12, Greg Ward __revision__ = "$Id$" from distutils.core import Command from distutils.util import copy_tree class install_ext (Command): description = "install C/C++ extension modules" user_options = [ ('install-dir=', 'd', "directory to install to"), ('build-dir=','b', "build directory (where to install from)"), ] def initialize_options (self): # let the 'install' command dictate our installation directory self.install_dir = None self.build_dir = None def finalize_options (self): self.set_undefined_options ('install', ('build_lib', 'build_dir'), ('install_lib', 'install_dir')) def run (self): # Make sure we have built all extension modules first self.run_peer ('build_ext') # Dump the entire "build/platlib" directory (or whatever it really # is; "build/platlib" is the default) to the installation target # (eg. "/usr/local/lib/python1.5/site-packages"). Note that # putting files in the right package dir is already done when we # build. outfiles = self.copy_tree (self.build_dir, self.install_dir) # class InstallExt
a619d5b35eb88ab71126e53f195190536d71fdb4
orionsdk/swisclient.py
orionsdk/swisclient.py
import requests import json from datetime import datetime def _json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime): serial = obj.isoformat() return serial class SwisClient: def __init__(self, hostname, username, password, verify=False): self.url = "https://{}:17778/SolarWinds/InformationService/v3/Json/".\ format(hostname) self.credentials = (username, password) self.verify = verify def query(self, query, **params): return self._req( "POST", "Query", {'query': query, 'parameters': params}).json() def invoke(self, entity, verb, *args): return self._req( "POST", "Invoke/{}/{}".format(entity, verb), args).json() def create(self, entity, **properties): return self._req( "POST", "Create/" + entity, properties).json() def read(self, uri): return self._req("GET", uri).json() def update(self, uri, **properties): self._req("POST", uri, properties) def delete(self, uri): self._req("DELETE", uri) def _req(self, method, frag, data=None): return requests.request(method, self.url + frag, data=json.dumps(data, default=_json_serial), verify=self.verify, auth=self.credentials, headers={'Content-Type': 'application/json'})
import requests import json from datetime import datetime def _json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime): serial = obj.isoformat() return serial class SwisClient: def __init__(self, hostname, username, password, verify=False): self.url = "https://{}:17778/SolarWinds/InformationService/v3/Json/".\ format(hostname) self.credentials = (username, password) self.verify = verify def query(self, query, **params): return self._req( "POST", "Query", {'query': query, 'parameters': params}).json() def invoke(self, entity, verb, *args): return self._req( "POST", "Invoke/{}/{}".format(entity, verb), args).json() def create(self, entity, **properties): return self._req( "POST", "Create/" + entity, properties).json() def read(self, uri): return self._req("GET", uri).json() def update(self, uri, **properties): self._req("POST", uri, properties) def delete(self, uri): self._req("DELETE", uri) def _req(self, method, frag, data=None): resp = requests.request(method, self.url + frag, data=json.dumps(data, default=_json_serial), verify=self.verify, auth=self.credentials, headers={'Content-Type': 'application/json'}) resp.raise_for_status() return resp
Throw exceptions error responses from server
Throw exceptions error responses from server
Python
apache-2.0
solarwinds/orionsdk-python
import requests import json from datetime import datetime def _json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime): serial = obj.isoformat() return serial class SwisClient: def __init__(self, hostname, username, password, verify=False): self.url = "https://{}:17778/SolarWinds/InformationService/v3/Json/".\ format(hostname) self.credentials = (username, password) self.verify = verify def query(self, query, **params): return self._req( "POST", "Query", {'query': query, 'parameters': params}).json() def invoke(self, entity, verb, *args): return self._req( "POST", "Invoke/{}/{}".format(entity, verb), args).json() def create(self, entity, **properties): return self._req( "POST", "Create/" + entity, properties).json() def read(self, uri): return self._req("GET", uri).json() def update(self, uri, **properties): self._req("POST", uri, properties) def delete(self, uri): self._req("DELETE", uri) def _req(self, method, frag, data=None): return requests.request(method, self.url + frag, data=json.dumps(data, default=_json_serial), verify=self.verify, auth=self.credentials, headers={'Content-Type': 'application/json'}) Throw exceptions error responses from server
import requests import json from datetime import datetime def _json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime): serial = obj.isoformat() return serial class SwisClient: def __init__(self, hostname, username, password, verify=False): self.url = "https://{}:17778/SolarWinds/InformationService/v3/Json/".\ format(hostname) self.credentials = (username, password) self.verify = verify def query(self, query, **params): return self._req( "POST", "Query", {'query': query, 'parameters': params}).json() def invoke(self, entity, verb, *args): return self._req( "POST", "Invoke/{}/{}".format(entity, verb), args).json() def create(self, entity, **properties): return self._req( "POST", "Create/" + entity, properties).json() def read(self, uri): return self._req("GET", uri).json() def update(self, uri, **properties): self._req("POST", uri, properties) def delete(self, uri): self._req("DELETE", uri) def _req(self, method, frag, data=None): resp = requests.request(method, self.url + frag, data=json.dumps(data, default=_json_serial), verify=self.verify, auth=self.credentials, headers={'Content-Type': 'application/json'}) resp.raise_for_status() return resp
<commit_before>import requests import json from datetime import datetime def _json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime): serial = obj.isoformat() return serial class SwisClient: def __init__(self, hostname, username, password, verify=False): self.url = "https://{}:17778/SolarWinds/InformationService/v3/Json/".\ format(hostname) self.credentials = (username, password) self.verify = verify def query(self, query, **params): return self._req( "POST", "Query", {'query': query, 'parameters': params}).json() def invoke(self, entity, verb, *args): return self._req( "POST", "Invoke/{}/{}".format(entity, verb), args).json() def create(self, entity, **properties): return self._req( "POST", "Create/" + entity, properties).json() def read(self, uri): return self._req("GET", uri).json() def update(self, uri, **properties): self._req("POST", uri, properties) def delete(self, uri): self._req("DELETE", uri) def _req(self, method, frag, data=None): return requests.request(method, self.url + frag, data=json.dumps(data, default=_json_serial), verify=self.verify, auth=self.credentials, headers={'Content-Type': 'application/json'}) <commit_msg>Throw exceptions error responses from server<commit_after>
import requests import json from datetime import datetime def _json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime): serial = obj.isoformat() return serial class SwisClient: def __init__(self, hostname, username, password, verify=False): self.url = "https://{}:17778/SolarWinds/InformationService/v3/Json/".\ format(hostname) self.credentials = (username, password) self.verify = verify def query(self, query, **params): return self._req( "POST", "Query", {'query': query, 'parameters': params}).json() def invoke(self, entity, verb, *args): return self._req( "POST", "Invoke/{}/{}".format(entity, verb), args).json() def create(self, entity, **properties): return self._req( "POST", "Create/" + entity, properties).json() def read(self, uri): return self._req("GET", uri).json() def update(self, uri, **properties): self._req("POST", uri, properties) def delete(self, uri): self._req("DELETE", uri) def _req(self, method, frag, data=None): resp = requests.request(method, self.url + frag, data=json.dumps(data, default=_json_serial), verify=self.verify, auth=self.credentials, headers={'Content-Type': 'application/json'}) resp.raise_for_status() return resp
import requests import json from datetime import datetime def _json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime): serial = obj.isoformat() return serial class SwisClient: def __init__(self, hostname, username, password, verify=False): self.url = "https://{}:17778/SolarWinds/InformationService/v3/Json/".\ format(hostname) self.credentials = (username, password) self.verify = verify def query(self, query, **params): return self._req( "POST", "Query", {'query': query, 'parameters': params}).json() def invoke(self, entity, verb, *args): return self._req( "POST", "Invoke/{}/{}".format(entity, verb), args).json() def create(self, entity, **properties): return self._req( "POST", "Create/" + entity, properties).json() def read(self, uri): return self._req("GET", uri).json() def update(self, uri, **properties): self._req("POST", uri, properties) def delete(self, uri): self._req("DELETE", uri) def _req(self, method, frag, data=None): return requests.request(method, self.url + frag, data=json.dumps(data, default=_json_serial), verify=self.verify, auth=self.credentials, headers={'Content-Type': 'application/json'}) Throw exceptions error responses from serverimport requests import json from datetime import datetime def _json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime): serial = obj.isoformat() return serial class SwisClient: def __init__(self, hostname, username, password, verify=False): self.url = "https://{}:17778/SolarWinds/InformationService/v3/Json/".\ format(hostname) self.credentials = (username, password) self.verify = verify def query(self, query, **params): return self._req( "POST", "Query", {'query': query, 'parameters': params}).json() def invoke(self, entity, verb, *args): return self._req( "POST", "Invoke/{}/{}".format(entity, verb), args).json() def create(self, entity, **properties): return self._req( "POST", "Create/" + entity, properties).json() def read(self, uri): return self._req("GET", uri).json() def update(self, uri, **properties): self._req("POST", uri, properties) def delete(self, uri): self._req("DELETE", uri) def _req(self, method, frag, data=None): resp = requests.request(method, self.url + frag, data=json.dumps(data, default=_json_serial), verify=self.verify, auth=self.credentials, headers={'Content-Type': 'application/json'}) resp.raise_for_status() return resp
<commit_before>import requests import json from datetime import datetime def _json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime): serial = obj.isoformat() return serial class SwisClient: def __init__(self, hostname, username, password, verify=False): self.url = "https://{}:17778/SolarWinds/InformationService/v3/Json/".\ format(hostname) self.credentials = (username, password) self.verify = verify def query(self, query, **params): return self._req( "POST", "Query", {'query': query, 'parameters': params}).json() def invoke(self, entity, verb, *args): return self._req( "POST", "Invoke/{}/{}".format(entity, verb), args).json() def create(self, entity, **properties): return self._req( "POST", "Create/" + entity, properties).json() def read(self, uri): return self._req("GET", uri).json() def update(self, uri, **properties): self._req("POST", uri, properties) def delete(self, uri): self._req("DELETE", uri) def _req(self, method, frag, data=None): return requests.request(method, self.url + frag, data=json.dumps(data, default=_json_serial), verify=self.verify, auth=self.credentials, headers={'Content-Type': 'application/json'}) <commit_msg>Throw exceptions error responses from server<commit_after>import requests import json from datetime import datetime def _json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime): serial = obj.isoformat() return serial class SwisClient: def __init__(self, hostname, username, password, verify=False): self.url = "https://{}:17778/SolarWinds/InformationService/v3/Json/".\ format(hostname) self.credentials = (username, password) self.verify = verify def query(self, query, **params): return self._req( "POST", "Query", {'query': query, 'parameters': params}).json() def invoke(self, entity, verb, *args): return self._req( "POST", "Invoke/{}/{}".format(entity, verb), args).json() def create(self, entity, **properties): return self._req( "POST", "Create/" + entity, properties).json() def read(self, uri): return self._req("GET", uri).json() def update(self, uri, **properties): self._req("POST", uri, properties) def delete(self, uri): self._req("DELETE", uri) def _req(self, method, frag, data=None): resp = requests.request(method, self.url + frag, data=json.dumps(data, default=_json_serial), verify=self.verify, auth=self.credentials, headers={'Content-Type': 'application/json'}) resp.raise_for_status() return resp
8e6237288dae3964cdd0a36e747f53f11b285073
callee/__init__.py
callee/__init__.py
""" callee """ __version__ = "0.0.1" __description__ = "Argument matcher for unittest.mock" __author__ = "Karol Kuczmarski" __license__ = "Simplified BSD" from callee.base import And, Or, Not from callee.general import \ Any, ArgThat, IsA, Inherits, InstanceOf, Matching, SubclassOf from callee.strings import Bytes, String, Unicode __all__ = [ 'Not', 'And', 'Or', 'Any', 'Matching', 'ArgThat', 'InstanceOf', 'IsA', 'SubclassOf', 'Inherits', 'String', 'Unicode', 'Bytes', ] # TODO(xion): operator-based matchers (GreaterThan, ShorterThan, etc.) # TODO(xion): collection matchers (lists, sequences, dicts, ...) # TODO(xion): matchers for positional & keyword arguments
""" callee """ __version__ = "0.0.1" __description__ = "Argument matcher for unittest.mock" __author__ = "Karol Kuczmarski" __license__ = "Simplified BSD" from callee.base import And, Or, Not from callee.collections import Dict, List, Mapping, Iterable, Sequence, Set from callee.general import \ Any, ArgThat, IsA, Inherits, InstanceOf, Matching, SubclassOf from callee.strings import Bytes, String, Unicode __all__ = [ 'BaseMatcher', 'Eq', 'Not', 'And', 'Or', 'Iterable', 'Sequence', 'List', 'Set', 'Mapping', 'Dict', 'Any', 'Matching', 'ArgThat', 'Callable', 'Function', 'GeneratorFunction', 'InstanceOf', 'IsA', 'SubclassOf', 'Inherits', 'Type', 'Class', 'String', 'Unicode', 'Bytes', ] # TODO(xion): operator-based matchers (GreaterThan, ShorterThan, etc.) # TODO(xion): matchers for positional & keyword arguments
Include recently added matchers in callee.__all__
Include recently added matchers in callee.__all__
Python
bsd-3-clause
Xion/callee
""" callee """ __version__ = "0.0.1" __description__ = "Argument matcher for unittest.mock" __author__ = "Karol Kuczmarski" __license__ = "Simplified BSD" from callee.base import And, Or, Not from callee.general import \ Any, ArgThat, IsA, Inherits, InstanceOf, Matching, SubclassOf from callee.strings import Bytes, String, Unicode __all__ = [ 'Not', 'And', 'Or', 'Any', 'Matching', 'ArgThat', 'InstanceOf', 'IsA', 'SubclassOf', 'Inherits', 'String', 'Unicode', 'Bytes', ] # TODO(xion): operator-based matchers (GreaterThan, ShorterThan, etc.) # TODO(xion): collection matchers (lists, sequences, dicts, ...) # TODO(xion): matchers for positional & keyword arguments Include recently added matchers in callee.__all__
""" callee """ __version__ = "0.0.1" __description__ = "Argument matcher for unittest.mock" __author__ = "Karol Kuczmarski" __license__ = "Simplified BSD" from callee.base import And, Or, Not from callee.collections import Dict, List, Mapping, Iterable, Sequence, Set from callee.general import \ Any, ArgThat, IsA, Inherits, InstanceOf, Matching, SubclassOf from callee.strings import Bytes, String, Unicode __all__ = [ 'BaseMatcher', 'Eq', 'Not', 'And', 'Or', 'Iterable', 'Sequence', 'List', 'Set', 'Mapping', 'Dict', 'Any', 'Matching', 'ArgThat', 'Callable', 'Function', 'GeneratorFunction', 'InstanceOf', 'IsA', 'SubclassOf', 'Inherits', 'Type', 'Class', 'String', 'Unicode', 'Bytes', ] # TODO(xion): operator-based matchers (GreaterThan, ShorterThan, etc.) # TODO(xion): matchers for positional & keyword arguments
<commit_before>""" callee """ __version__ = "0.0.1" __description__ = "Argument matcher for unittest.mock" __author__ = "Karol Kuczmarski" __license__ = "Simplified BSD" from callee.base import And, Or, Not from callee.general import \ Any, ArgThat, IsA, Inherits, InstanceOf, Matching, SubclassOf from callee.strings import Bytes, String, Unicode __all__ = [ 'Not', 'And', 'Or', 'Any', 'Matching', 'ArgThat', 'InstanceOf', 'IsA', 'SubclassOf', 'Inherits', 'String', 'Unicode', 'Bytes', ] # TODO(xion): operator-based matchers (GreaterThan, ShorterThan, etc.) # TODO(xion): collection matchers (lists, sequences, dicts, ...) # TODO(xion): matchers for positional & keyword arguments <commit_msg>Include recently added matchers in callee.__all__<commit_after>
""" callee """ __version__ = "0.0.1" __description__ = "Argument matcher for unittest.mock" __author__ = "Karol Kuczmarski" __license__ = "Simplified BSD" from callee.base import And, Or, Not from callee.collections import Dict, List, Mapping, Iterable, Sequence, Set from callee.general import \ Any, ArgThat, IsA, Inherits, InstanceOf, Matching, SubclassOf from callee.strings import Bytes, String, Unicode __all__ = [ 'BaseMatcher', 'Eq', 'Not', 'And', 'Or', 'Iterable', 'Sequence', 'List', 'Set', 'Mapping', 'Dict', 'Any', 'Matching', 'ArgThat', 'Callable', 'Function', 'GeneratorFunction', 'InstanceOf', 'IsA', 'SubclassOf', 'Inherits', 'Type', 'Class', 'String', 'Unicode', 'Bytes', ] # TODO(xion): operator-based matchers (GreaterThan, ShorterThan, etc.) # TODO(xion): matchers for positional & keyword arguments
""" callee """ __version__ = "0.0.1" __description__ = "Argument matcher for unittest.mock" __author__ = "Karol Kuczmarski" __license__ = "Simplified BSD" from callee.base import And, Or, Not from callee.general import \ Any, ArgThat, IsA, Inherits, InstanceOf, Matching, SubclassOf from callee.strings import Bytes, String, Unicode __all__ = [ 'Not', 'And', 'Or', 'Any', 'Matching', 'ArgThat', 'InstanceOf', 'IsA', 'SubclassOf', 'Inherits', 'String', 'Unicode', 'Bytes', ] # TODO(xion): operator-based matchers (GreaterThan, ShorterThan, etc.) # TODO(xion): collection matchers (lists, sequences, dicts, ...) # TODO(xion): matchers for positional & keyword arguments Include recently added matchers in callee.__all__""" callee """ __version__ = "0.0.1" __description__ = "Argument matcher for unittest.mock" __author__ = "Karol Kuczmarski" __license__ = "Simplified BSD" from callee.base import And, Or, Not from callee.collections import Dict, List, Mapping, Iterable, Sequence, Set from callee.general import \ Any, ArgThat, IsA, Inherits, InstanceOf, Matching, SubclassOf from callee.strings import Bytes, String, Unicode __all__ = [ 'BaseMatcher', 'Eq', 'Not', 'And', 'Or', 'Iterable', 'Sequence', 'List', 'Set', 'Mapping', 'Dict', 'Any', 'Matching', 'ArgThat', 'Callable', 'Function', 'GeneratorFunction', 'InstanceOf', 'IsA', 'SubclassOf', 'Inherits', 'Type', 'Class', 'String', 'Unicode', 'Bytes', ] # TODO(xion): operator-based matchers (GreaterThan, ShorterThan, etc.) # TODO(xion): matchers for positional & keyword arguments
<commit_before>""" callee """ __version__ = "0.0.1" __description__ = "Argument matcher for unittest.mock" __author__ = "Karol Kuczmarski" __license__ = "Simplified BSD" from callee.base import And, Or, Not from callee.general import \ Any, ArgThat, IsA, Inherits, InstanceOf, Matching, SubclassOf from callee.strings import Bytes, String, Unicode __all__ = [ 'Not', 'And', 'Or', 'Any', 'Matching', 'ArgThat', 'InstanceOf', 'IsA', 'SubclassOf', 'Inherits', 'String', 'Unicode', 'Bytes', ] # TODO(xion): operator-based matchers (GreaterThan, ShorterThan, etc.) # TODO(xion): collection matchers (lists, sequences, dicts, ...) # TODO(xion): matchers for positional & keyword arguments <commit_msg>Include recently added matchers in callee.__all__<commit_after>""" callee """ __version__ = "0.0.1" __description__ = "Argument matcher for unittest.mock" __author__ = "Karol Kuczmarski" __license__ = "Simplified BSD" from callee.base import And, Or, Not from callee.collections import Dict, List, Mapping, Iterable, Sequence, Set from callee.general import \ Any, ArgThat, IsA, Inherits, InstanceOf, Matching, SubclassOf from callee.strings import Bytes, String, Unicode __all__ = [ 'BaseMatcher', 'Eq', 'Not', 'And', 'Or', 'Iterable', 'Sequence', 'List', 'Set', 'Mapping', 'Dict', 'Any', 'Matching', 'ArgThat', 'Callable', 'Function', 'GeneratorFunction', 'InstanceOf', 'IsA', 'SubclassOf', 'Inherits', 'Type', 'Class', 'String', 'Unicode', 'Bytes', ] # TODO(xion): operator-based matchers (GreaterThan, ShorterThan, etc.) # TODO(xion): matchers for positional & keyword arguments
2a2a1c9ad37932bf300caf02419dd55a463d46d1
src/tmod_tools/__main__.py
src/tmod_tools/__main__.py
""" Entrypoint module, in case you use `python -mtmod_tools`. Why does this file exist, and why __main__? For more info, read: - https://www.python.org/dev/peps/pep-0338/ - https://docs.python.org/2/using/cmdline.html#cmdoption-m - https://docs.python.org/3/using/cmdline.html#cmdoption-m """ from tmod_tools.cli import main if __name__ == "__main__": main()
""" Entrypoint module, in case you use `python -mtmod_tools`. Why does this file exist, and why __main__? For more info, read: - https://www.python.org/dev/peps/pep-0338/ - https://docs.python.org/2/using/cmdline.html#cmdoption-m - https://docs.python.org/3/using/cmdline.html#cmdoption-m """ from tmod_tools.cli import main # pragma: no cover if __name__ == "__main__": # pragma: no cover main()
Add nocov for lines that will never normally run
Add nocov for lines that will never normally run
Python
isc
mystfox/python-tmod-tools
""" Entrypoint module, in case you use `python -mtmod_tools`. Why does this file exist, and why __main__? For more info, read: - https://www.python.org/dev/peps/pep-0338/ - https://docs.python.org/2/using/cmdline.html#cmdoption-m - https://docs.python.org/3/using/cmdline.html#cmdoption-m """ from tmod_tools.cli import main if __name__ == "__main__": main() Add nocov for lines that will never normally run
""" Entrypoint module, in case you use `python -mtmod_tools`. Why does this file exist, and why __main__? For more info, read: - https://www.python.org/dev/peps/pep-0338/ - https://docs.python.org/2/using/cmdline.html#cmdoption-m - https://docs.python.org/3/using/cmdline.html#cmdoption-m """ from tmod_tools.cli import main # pragma: no cover if __name__ == "__main__": # pragma: no cover main()
<commit_before>""" Entrypoint module, in case you use `python -mtmod_tools`. Why does this file exist, and why __main__? For more info, read: - https://www.python.org/dev/peps/pep-0338/ - https://docs.python.org/2/using/cmdline.html#cmdoption-m - https://docs.python.org/3/using/cmdline.html#cmdoption-m """ from tmod_tools.cli import main if __name__ == "__main__": main() <commit_msg>Add nocov for lines that will never normally run<commit_after>
""" Entrypoint module, in case you use `python -mtmod_tools`. Why does this file exist, and why __main__? For more info, read: - https://www.python.org/dev/peps/pep-0338/ - https://docs.python.org/2/using/cmdline.html#cmdoption-m - https://docs.python.org/3/using/cmdline.html#cmdoption-m """ from tmod_tools.cli import main # pragma: no cover if __name__ == "__main__": # pragma: no cover main()
""" Entrypoint module, in case you use `python -mtmod_tools`. Why does this file exist, and why __main__? For more info, read: - https://www.python.org/dev/peps/pep-0338/ - https://docs.python.org/2/using/cmdline.html#cmdoption-m - https://docs.python.org/3/using/cmdline.html#cmdoption-m """ from tmod_tools.cli import main if __name__ == "__main__": main() Add nocov for lines that will never normally run""" Entrypoint module, in case you use `python -mtmod_tools`. Why does this file exist, and why __main__? For more info, read: - https://www.python.org/dev/peps/pep-0338/ - https://docs.python.org/2/using/cmdline.html#cmdoption-m - https://docs.python.org/3/using/cmdline.html#cmdoption-m """ from tmod_tools.cli import main # pragma: no cover if __name__ == "__main__": # pragma: no cover main()
<commit_before>""" Entrypoint module, in case you use `python -mtmod_tools`. Why does this file exist, and why __main__? For more info, read: - https://www.python.org/dev/peps/pep-0338/ - https://docs.python.org/2/using/cmdline.html#cmdoption-m - https://docs.python.org/3/using/cmdline.html#cmdoption-m """ from tmod_tools.cli import main if __name__ == "__main__": main() <commit_msg>Add nocov for lines that will never normally run<commit_after>""" Entrypoint module, in case you use `python -mtmod_tools`. Why does this file exist, and why __main__? For more info, read: - https://www.python.org/dev/peps/pep-0338/ - https://docs.python.org/2/using/cmdline.html#cmdoption-m - https://docs.python.org/3/using/cmdline.html#cmdoption-m """ from tmod_tools.cli import main # pragma: no cover if __name__ == "__main__": # pragma: no cover main()
f1372842fa1c3eef11f4e9dbe2b35af02c1c5bf5
mdot_rest/migrations/0003_auto_20150723_1759.py
mdot_rest/migrations/0003_auto_20150723_1759.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('mdot_rest', '0002_auto_20150722_2054'), ] operations = [ migrations.RemoveField( model_name='resourcelink', name='resource', ), migrations.AddField( model_name='resourcelink', name='resource', field=models.ForeignKey(default='', to='mdot_rest.Resource'), preserve_default=False, ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('mdot_rest', '0002_auto_20150722_2054'), ] operations = [ migrations.RemoveField( model_name='resourcelink', name='resource', ), migrations.AddField( model_name='resourcelink', name='resource', field=models.ForeignKey(default=1, to='mdot_rest.Resource'), preserve_default=False, ), ]
Fix the migration so it takes care of bad default for resource links.
Fix the migration so it takes care of bad default for resource links.
Python
apache-2.0
uw-it-aca/mdot-rest,uw-it-aca/mdot-rest
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('mdot_rest', '0002_auto_20150722_2054'), ] operations = [ migrations.RemoveField( model_name='resourcelink', name='resource', ), migrations.AddField( model_name='resourcelink', name='resource', field=models.ForeignKey(default='', to='mdot_rest.Resource'), preserve_default=False, ), ] Fix the migration so it takes care of bad default for resource links.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('mdot_rest', '0002_auto_20150722_2054'), ] operations = [ migrations.RemoveField( model_name='resourcelink', name='resource', ), migrations.AddField( model_name='resourcelink', name='resource', field=models.ForeignKey(default=1, to='mdot_rest.Resource'), preserve_default=False, ), ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('mdot_rest', '0002_auto_20150722_2054'), ] operations = [ migrations.RemoveField( model_name='resourcelink', name='resource', ), migrations.AddField( model_name='resourcelink', name='resource', field=models.ForeignKey(default='', to='mdot_rest.Resource'), preserve_default=False, ), ] <commit_msg>Fix the migration so it takes care of bad default for resource links.<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('mdot_rest', '0002_auto_20150722_2054'), ] operations = [ migrations.RemoveField( model_name='resourcelink', name='resource', ), migrations.AddField( model_name='resourcelink', name='resource', field=models.ForeignKey(default=1, to='mdot_rest.Resource'), preserve_default=False, ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('mdot_rest', '0002_auto_20150722_2054'), ] operations = [ migrations.RemoveField( model_name='resourcelink', name='resource', ), migrations.AddField( model_name='resourcelink', name='resource', field=models.ForeignKey(default='', to='mdot_rest.Resource'), preserve_default=False, ), ] Fix the migration so it takes care of bad default for resource links.# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('mdot_rest', '0002_auto_20150722_2054'), ] operations = [ migrations.RemoveField( model_name='resourcelink', name='resource', ), migrations.AddField( model_name='resourcelink', name='resource', field=models.ForeignKey(default=1, to='mdot_rest.Resource'), preserve_default=False, ), ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('mdot_rest', '0002_auto_20150722_2054'), ] operations = [ migrations.RemoveField( model_name='resourcelink', name='resource', ), migrations.AddField( model_name='resourcelink', name='resource', field=models.ForeignKey(default='', to='mdot_rest.Resource'), preserve_default=False, ), ] <commit_msg>Fix the migration so it takes care of bad default for resource links.<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('mdot_rest', '0002_auto_20150722_2054'), ] operations = [ migrations.RemoveField( model_name='resourcelink', name='resource', ), migrations.AddField( model_name='resourcelink', name='resource', field=models.ForeignKey(default=1, to='mdot_rest.Resource'), preserve_default=False, ), ]
3fd2d1cade716f264b2febc3627b1443a1d3e604
taiga/projects/migrations/0043_auto_20160530_1004.py
taiga/projects/migrations/0043_auto_20160530_1004.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-30 10:04 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0042_auto_20160525_0911'), ] operations = [ migrations.AlterField( model_name='project', name='owner', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='owned_projects', to=settings.AUTH_USER_MODEL, verbose_name='owner'), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-30 10:04 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0040_remove_memberships_of_cancelled_users_acounts'), ] operations = [ migrations.AlterField( model_name='project', name='owner', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='owned_projects', to=settings.AUTH_USER_MODEL, verbose_name='owner'), ), ]
Fix a problem with a migration between master and stable branch
Fix a problem with a migration between master and stable branch
Python
agpl-3.0
taigaio/taiga-back,dayatz/taiga-back,xdevelsistemas/taiga-back-community,taigaio/taiga-back,taigaio/taiga-back,dayatz/taiga-back,dayatz/taiga-back,xdevelsistemas/taiga-back-community,xdevelsistemas/taiga-back-community
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-30 10:04 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0042_auto_20160525_0911'), ] operations = [ migrations.AlterField( model_name='project', name='owner', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='owned_projects', to=settings.AUTH_USER_MODEL, verbose_name='owner'), ), ] Fix a problem with a migration between master and stable branch
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-30 10:04 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0040_remove_memberships_of_cancelled_users_acounts'), ] operations = [ migrations.AlterField( model_name='project', name='owner', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='owned_projects', to=settings.AUTH_USER_MODEL, verbose_name='owner'), ), ]
<commit_before># -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-30 10:04 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0042_auto_20160525_0911'), ] operations = [ migrations.AlterField( model_name='project', name='owner', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='owned_projects', to=settings.AUTH_USER_MODEL, verbose_name='owner'), ), ] <commit_msg>Fix a problem with a migration between master and stable branch<commit_after>
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-30 10:04 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0040_remove_memberships_of_cancelled_users_acounts'), ] operations = [ migrations.AlterField( model_name='project', name='owner', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='owned_projects', to=settings.AUTH_USER_MODEL, verbose_name='owner'), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-30 10:04 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0042_auto_20160525_0911'), ] operations = [ migrations.AlterField( model_name='project', name='owner', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='owned_projects', to=settings.AUTH_USER_MODEL, verbose_name='owner'), ), ] Fix a problem with a migration between master and stable branch# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-30 10:04 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0040_remove_memberships_of_cancelled_users_acounts'), ] operations = [ migrations.AlterField( model_name='project', name='owner', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='owned_projects', to=settings.AUTH_USER_MODEL, verbose_name='owner'), ), ]
<commit_before># -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-30 10:04 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0042_auto_20160525_0911'), ] operations = [ migrations.AlterField( model_name='project', name='owner', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='owned_projects', to=settings.AUTH_USER_MODEL, verbose_name='owner'), ), ] <commit_msg>Fix a problem with a migration between master and stable branch<commit_after># -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-30 10:04 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0040_remove_memberships_of_cancelled_users_acounts'), ] operations = [ migrations.AlterField( model_name='project', name='owner', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='owned_projects', to=settings.AUTH_USER_MODEL, verbose_name='owner'), ), ]
6916a3fb24a12ce3c0261034c1dcaae57a8cd0ee
docs/examples/kernel/task2.py
docs/examples/kernel/task2.py
#!/usr/bin/env python # encoding: utf-8 from IPython.kernel import client import time tc = client.TaskClient() mec = client.MultiEngineClient() mec.execute('import time') for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=False)" print tc.queue_status() for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) for i in range(12): tc.run(client.StringTask('time.sleep(2)')) print "Queue status (vebose=True)" print tc.queue_status(True) qs = tc.queue_status(True) sched = qs['scheduled'] for tid in sched[-4:]: tc.abort(tid) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True)
#!/usr/bin/env python # encoding: utf-8 from IPython.kernel import client import time import sys flush = sys.stdout.flush tc = client.TaskClient() mec = client.MultiEngineClient() mec.execute('import time') for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=False)" print tc.queue_status() flush() for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) flush() for i in range(12): tc.run(client.StringTask('time.sleep(2)')) print "Queue status (vebose=True)" print tc.queue_status(True) flush() qs = tc.queue_status(True) sched = qs['scheduled'] for tid in sched[-4:]: tc.abort(tid) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) flush()
Add stdout flushing statements to example.
Add stdout flushing statements to example. This forces the prints to happen right away, so the example behaves a little more like you'd expect.
Python
bsd-3-clause
ipython/ipython,ipython/ipython
#!/usr/bin/env python # encoding: utf-8 from IPython.kernel import client import time tc = client.TaskClient() mec = client.MultiEngineClient() mec.execute('import time') for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=False)" print tc.queue_status() for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) for i in range(12): tc.run(client.StringTask('time.sleep(2)')) print "Queue status (vebose=True)" print tc.queue_status(True) qs = tc.queue_status(True) sched = qs['scheduled'] for tid in sched[-4:]: tc.abort(tid) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) Add stdout flushing statements to example. This forces the prints to happen right away, so the example behaves a little more like you'd expect.
#!/usr/bin/env python # encoding: utf-8 from IPython.kernel import client import time import sys flush = sys.stdout.flush tc = client.TaskClient() mec = client.MultiEngineClient() mec.execute('import time') for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=False)" print tc.queue_status() flush() for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) flush() for i in range(12): tc.run(client.StringTask('time.sleep(2)')) print "Queue status (vebose=True)" print tc.queue_status(True) flush() qs = tc.queue_status(True) sched = qs['scheduled'] for tid in sched[-4:]: tc.abort(tid) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) flush()
<commit_before>#!/usr/bin/env python # encoding: utf-8 from IPython.kernel import client import time tc = client.TaskClient() mec = client.MultiEngineClient() mec.execute('import time') for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=False)" print tc.queue_status() for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) for i in range(12): tc.run(client.StringTask('time.sleep(2)')) print "Queue status (vebose=True)" print tc.queue_status(True) qs = tc.queue_status(True) sched = qs['scheduled'] for tid in sched[-4:]: tc.abort(tid) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) <commit_msg>Add stdout flushing statements to example. This forces the prints to happen right away, so the example behaves a little more like you'd expect.<commit_after>
#!/usr/bin/env python # encoding: utf-8 from IPython.kernel import client import time import sys flush = sys.stdout.flush tc = client.TaskClient() mec = client.MultiEngineClient() mec.execute('import time') for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=False)" print tc.queue_status() flush() for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) flush() for i in range(12): tc.run(client.StringTask('time.sleep(2)')) print "Queue status (vebose=True)" print tc.queue_status(True) flush() qs = tc.queue_status(True) sched = qs['scheduled'] for tid in sched[-4:]: tc.abort(tid) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) flush()
#!/usr/bin/env python # encoding: utf-8 from IPython.kernel import client import time tc = client.TaskClient() mec = client.MultiEngineClient() mec.execute('import time') for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=False)" print tc.queue_status() for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) for i in range(12): tc.run(client.StringTask('time.sleep(2)')) print "Queue status (vebose=True)" print tc.queue_status(True) qs = tc.queue_status(True) sched = qs['scheduled'] for tid in sched[-4:]: tc.abort(tid) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) Add stdout flushing statements to example. This forces the prints to happen right away, so the example behaves a little more like you'd expect.#!/usr/bin/env python # encoding: utf-8 from IPython.kernel import client import time import sys flush = sys.stdout.flush tc = client.TaskClient() mec = client.MultiEngineClient() mec.execute('import time') for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=False)" print tc.queue_status() flush() for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) flush() for i in range(12): tc.run(client.StringTask('time.sleep(2)')) print "Queue status (vebose=True)" print tc.queue_status(True) flush() qs = tc.queue_status(True) sched = qs['scheduled'] for tid in sched[-4:]: tc.abort(tid) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) flush()
<commit_before>#!/usr/bin/env python # encoding: utf-8 from IPython.kernel import client import time tc = client.TaskClient() mec = client.MultiEngineClient() mec.execute('import time') for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=False)" print tc.queue_status() for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) for i in range(12): tc.run(client.StringTask('time.sleep(2)')) print "Queue status (vebose=True)" print tc.queue_status(True) qs = tc.queue_status(True) sched = qs['scheduled'] for tid in sched[-4:]: tc.abort(tid) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) <commit_msg>Add stdout flushing statements to example. This forces the prints to happen right away, so the example behaves a little more like you'd expect.<commit_after>#!/usr/bin/env python # encoding: utf-8 from IPython.kernel import client import time import sys flush = sys.stdout.flush tc = client.TaskClient() mec = client.MultiEngineClient() mec.execute('import time') for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=False)" print tc.queue_status() flush() for i in range(24): tc.run(client.StringTask('time.sleep(1)')) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) flush() for i in range(12): tc.run(client.StringTask('time.sleep(2)')) print "Queue status (vebose=True)" print tc.queue_status(True) flush() qs = tc.queue_status(True) sched = qs['scheduled'] for tid in sched[-4:]: tc.abort(tid) for i in range(6): time.sleep(1.0) print "Queue status (vebose=True)" print tc.queue_status(True) flush()
f7e85968a3256485276858ebfa9ef9cc538e2ee2
blimp/urls.py
blimp/urls.py
from django.conf.urls import patterns, include from django.views.generic import TemplateView from django.contrib import admin admin.autodiscover() urlpatterns = patterns( # Prefix '', (r'^admin/', include(admin.site.urls)), (r'^api/', include('blimp.router')), (r'', include('blimp.users.urls')), # Catch all URL (r'^', TemplateView.as_view(template_name='index.html')) )
from django.conf.urls import patterns, include from django.views.generic import TemplateView from django.contrib import admin admin.autodiscover() urlpatterns = patterns( # Prefix '', (r'^admin/', include(admin.site.urls)), (r'^api/', include('blimp.router')), (r'', include('blimp.users.urls')), # Catch all URL (r'^.*/$', TemplateView.as_view(template_name='index.html')) )
Fix catch all URL to allow APPEND_SLASH to work
Fix catch all URL to allow APPEND_SLASH to work
Python
agpl-3.0
jessamynsmith/boards-backend,jessamynsmith/boards-backend,GetBlimp/boards-backend
from django.conf.urls import patterns, include from django.views.generic import TemplateView from django.contrib import admin admin.autodiscover() urlpatterns = patterns( # Prefix '', (r'^admin/', include(admin.site.urls)), (r'^api/', include('blimp.router')), (r'', include('blimp.users.urls')), # Catch all URL (r'^', TemplateView.as_view(template_name='index.html')) ) Fix catch all URL to allow APPEND_SLASH to work
from django.conf.urls import patterns, include from django.views.generic import TemplateView from django.contrib import admin admin.autodiscover() urlpatterns = patterns( # Prefix '', (r'^admin/', include(admin.site.urls)), (r'^api/', include('blimp.router')), (r'', include('blimp.users.urls')), # Catch all URL (r'^.*/$', TemplateView.as_view(template_name='index.html')) )
<commit_before>from django.conf.urls import patterns, include from django.views.generic import TemplateView from django.contrib import admin admin.autodiscover() urlpatterns = patterns( # Prefix '', (r'^admin/', include(admin.site.urls)), (r'^api/', include('blimp.router')), (r'', include('blimp.users.urls')), # Catch all URL (r'^', TemplateView.as_view(template_name='index.html')) ) <commit_msg>Fix catch all URL to allow APPEND_SLASH to work<commit_after>
from django.conf.urls import patterns, include from django.views.generic import TemplateView from django.contrib import admin admin.autodiscover() urlpatterns = patterns( # Prefix '', (r'^admin/', include(admin.site.urls)), (r'^api/', include('blimp.router')), (r'', include('blimp.users.urls')), # Catch all URL (r'^.*/$', TemplateView.as_view(template_name='index.html')) )
from django.conf.urls import patterns, include from django.views.generic import TemplateView from django.contrib import admin admin.autodiscover() urlpatterns = patterns( # Prefix '', (r'^admin/', include(admin.site.urls)), (r'^api/', include('blimp.router')), (r'', include('blimp.users.urls')), # Catch all URL (r'^', TemplateView.as_view(template_name='index.html')) ) Fix catch all URL to allow APPEND_SLASH to workfrom django.conf.urls import patterns, include from django.views.generic import TemplateView from django.contrib import admin admin.autodiscover() urlpatterns = patterns( # Prefix '', (r'^admin/', include(admin.site.urls)), (r'^api/', include('blimp.router')), (r'', include('blimp.users.urls')), # Catch all URL (r'^.*/$', TemplateView.as_view(template_name='index.html')) )
<commit_before>from django.conf.urls import patterns, include from django.views.generic import TemplateView from django.contrib import admin admin.autodiscover() urlpatterns = patterns( # Prefix '', (r'^admin/', include(admin.site.urls)), (r'^api/', include('blimp.router')), (r'', include('blimp.users.urls')), # Catch all URL (r'^', TemplateView.as_view(template_name='index.html')) ) <commit_msg>Fix catch all URL to allow APPEND_SLASH to work<commit_after>from django.conf.urls import patterns, include from django.views.generic import TemplateView from django.contrib import admin admin.autodiscover() urlpatterns = patterns( # Prefix '', (r'^admin/', include(admin.site.urls)), (r'^api/', include('blimp.router')), (r'', include('blimp.users.urls')), # Catch all URL (r'^.*/$', TemplateView.as_view(template_name='index.html')) )
306c56883939be640512f3d835b8d3f6b93b4ad7
judge/signals.py
judge/signals.py
from django.core.cache.utils import make_template_fragment_key from django.db.models.signals import post_save from django.dispatch import receiver from django.core.cache import cache from .models import Problem, Contest, Submission, Organization from .caching import update_submission @receiver(post_save, sender=Problem) def problem_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('problem_html', (instance.id,))) cache.delete(make_template_fragment_key('submission_problem', (instance.id,))) cache.delete(make_template_fragment_key('problem_list_group', (instance.group_id,))) @receiver(post_save, sender=Contest) def contest_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('contest_html', (instance.id,))) @receiver(post_save, sender=Submission) def submission_update(sender, instance, **kwargs): update_submission(instance.id) @receiver(post_save, sender=Organization) def organization_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('organization_html', (instance.id,)))
from django.core.cache.utils import make_template_fragment_key from django.db.models.signals import post_save from django.dispatch import receiver from django.core.cache import cache from .models import Problem, Contest, Submission, Organization, Profile from .caching import update_submission @receiver(post_save, sender=Problem) def problem_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('problem_html', (instance.id,))) cache.delete(make_template_fragment_key('submission_problem', (instance.id,))) cache.delete(make_template_fragment_key('problem_list_group', (instance.group_id,))) @receiver(post_save, sender=Profile) def problem_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('user_on_rank', (instance.id,))) cache.delete(make_template_fragment_key('submission_user', (instance.id,))) @receiver(post_save, sender=Contest) def contest_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('contest_html', (instance.id,))) @receiver(post_save, sender=Submission) def submission_update(sender, instance, **kwargs): update_submission(instance.id) @receiver(post_save, sender=Organization) def organization_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('organization_html', (instance.id,)))
Clear cache when user changes info.
Clear cache when user changes info.
Python
agpl-3.0
Minkov/site,monouno/site,DMOJ/site,DMOJ/site,Phoenix1369/site,DMOJ/site,Phoenix1369/site,monouno/site,monouno/site,Phoenix1369/site,Minkov/site,Minkov/site,Phoenix1369/site,Minkov/site,monouno/site,monouno/site,DMOJ/site
from django.core.cache.utils import make_template_fragment_key from django.db.models.signals import post_save from django.dispatch import receiver from django.core.cache import cache from .models import Problem, Contest, Submission, Organization from .caching import update_submission @receiver(post_save, sender=Problem) def problem_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('problem_html', (instance.id,))) cache.delete(make_template_fragment_key('submission_problem', (instance.id,))) cache.delete(make_template_fragment_key('problem_list_group', (instance.group_id,))) @receiver(post_save, sender=Contest) def contest_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('contest_html', (instance.id,))) @receiver(post_save, sender=Submission) def submission_update(sender, instance, **kwargs): update_submission(instance.id) @receiver(post_save, sender=Organization) def organization_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('organization_html', (instance.id,))) Clear cache when user changes info.
from django.core.cache.utils import make_template_fragment_key from django.db.models.signals import post_save from django.dispatch import receiver from django.core.cache import cache from .models import Problem, Contest, Submission, Organization, Profile from .caching import update_submission @receiver(post_save, sender=Problem) def problem_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('problem_html', (instance.id,))) cache.delete(make_template_fragment_key('submission_problem', (instance.id,))) cache.delete(make_template_fragment_key('problem_list_group', (instance.group_id,))) @receiver(post_save, sender=Profile) def problem_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('user_on_rank', (instance.id,))) cache.delete(make_template_fragment_key('submission_user', (instance.id,))) @receiver(post_save, sender=Contest) def contest_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('contest_html', (instance.id,))) @receiver(post_save, sender=Submission) def submission_update(sender, instance, **kwargs): update_submission(instance.id) @receiver(post_save, sender=Organization) def organization_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('organization_html', (instance.id,)))
<commit_before>from django.core.cache.utils import make_template_fragment_key from django.db.models.signals import post_save from django.dispatch import receiver from django.core.cache import cache from .models import Problem, Contest, Submission, Organization from .caching import update_submission @receiver(post_save, sender=Problem) def problem_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('problem_html', (instance.id,))) cache.delete(make_template_fragment_key('submission_problem', (instance.id,))) cache.delete(make_template_fragment_key('problem_list_group', (instance.group_id,))) @receiver(post_save, sender=Contest) def contest_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('contest_html', (instance.id,))) @receiver(post_save, sender=Submission) def submission_update(sender, instance, **kwargs): update_submission(instance.id) @receiver(post_save, sender=Organization) def organization_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('organization_html', (instance.id,))) <commit_msg>Clear cache when user changes info.<commit_after>
from django.core.cache.utils import make_template_fragment_key from django.db.models.signals import post_save from django.dispatch import receiver from django.core.cache import cache from .models import Problem, Contest, Submission, Organization, Profile from .caching import update_submission @receiver(post_save, sender=Problem) def problem_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('problem_html', (instance.id,))) cache.delete(make_template_fragment_key('submission_problem', (instance.id,))) cache.delete(make_template_fragment_key('problem_list_group', (instance.group_id,))) @receiver(post_save, sender=Profile) def problem_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('user_on_rank', (instance.id,))) cache.delete(make_template_fragment_key('submission_user', (instance.id,))) @receiver(post_save, sender=Contest) def contest_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('contest_html', (instance.id,))) @receiver(post_save, sender=Submission) def submission_update(sender, instance, **kwargs): update_submission(instance.id) @receiver(post_save, sender=Organization) def organization_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('organization_html', (instance.id,)))
from django.core.cache.utils import make_template_fragment_key from django.db.models.signals import post_save from django.dispatch import receiver from django.core.cache import cache from .models import Problem, Contest, Submission, Organization from .caching import update_submission @receiver(post_save, sender=Problem) def problem_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('problem_html', (instance.id,))) cache.delete(make_template_fragment_key('submission_problem', (instance.id,))) cache.delete(make_template_fragment_key('problem_list_group', (instance.group_id,))) @receiver(post_save, sender=Contest) def contest_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('contest_html', (instance.id,))) @receiver(post_save, sender=Submission) def submission_update(sender, instance, **kwargs): update_submission(instance.id) @receiver(post_save, sender=Organization) def organization_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('organization_html', (instance.id,))) Clear cache when user changes info.from django.core.cache.utils import make_template_fragment_key from django.db.models.signals import post_save from django.dispatch import receiver from django.core.cache import cache from .models import Problem, Contest, Submission, Organization, Profile from .caching import update_submission @receiver(post_save, sender=Problem) def problem_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('problem_html', (instance.id,))) cache.delete(make_template_fragment_key('submission_problem', (instance.id,))) cache.delete(make_template_fragment_key('problem_list_group', (instance.group_id,))) @receiver(post_save, sender=Profile) def problem_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('user_on_rank', (instance.id,))) cache.delete(make_template_fragment_key('submission_user', (instance.id,))) @receiver(post_save, sender=Contest) def contest_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('contest_html', (instance.id,))) @receiver(post_save, sender=Submission) def submission_update(sender, instance, **kwargs): update_submission(instance.id) @receiver(post_save, sender=Organization) def organization_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('organization_html', (instance.id,)))
<commit_before>from django.core.cache.utils import make_template_fragment_key from django.db.models.signals import post_save from django.dispatch import receiver from django.core.cache import cache from .models import Problem, Contest, Submission, Organization from .caching import update_submission @receiver(post_save, sender=Problem) def problem_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('problem_html', (instance.id,))) cache.delete(make_template_fragment_key('submission_problem', (instance.id,))) cache.delete(make_template_fragment_key('problem_list_group', (instance.group_id,))) @receiver(post_save, sender=Contest) def contest_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('contest_html', (instance.id,))) @receiver(post_save, sender=Submission) def submission_update(sender, instance, **kwargs): update_submission(instance.id) @receiver(post_save, sender=Organization) def organization_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('organization_html', (instance.id,))) <commit_msg>Clear cache when user changes info.<commit_after>from django.core.cache.utils import make_template_fragment_key from django.db.models.signals import post_save from django.dispatch import receiver from django.core.cache import cache from .models import Problem, Contest, Submission, Organization, Profile from .caching import update_submission @receiver(post_save, sender=Problem) def problem_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('problem_html', (instance.id,))) cache.delete(make_template_fragment_key('submission_problem', (instance.id,))) cache.delete(make_template_fragment_key('problem_list_group', (instance.group_id,))) @receiver(post_save, sender=Profile) def problem_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('user_on_rank', (instance.id,))) cache.delete(make_template_fragment_key('submission_user', (instance.id,))) @receiver(post_save, sender=Contest) def contest_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('contest_html', (instance.id,))) @receiver(post_save, sender=Submission) def submission_update(sender, instance, **kwargs): update_submission(instance.id) @receiver(post_save, sender=Organization) def organization_update(sender, instance, **kwargs): cache.delete(make_template_fragment_key('organization_html', (instance.id,)))
23f734419ac3814e09ef3763fb666a3620ac1c01
scripts/osfstorage/correct_moved_node_settings.py
scripts/osfstorage/correct_moved_node_settings.py
import sys import logging from scripts import utils as script_utils from framework.transactions.context import TokuTransaction from website.app import init_app from website.addons.osfstorage import model logger = logging.getLogger(__name__) def do_migration(): for node_settings in model.OsfStorageNodeSettings.find(): for child in iter_children(node_settings.root_node): if child.node_settings != node_settings: logger.info('Update node_settings for {!r} in project {!r}'.format(child, node_settings.owner,)) child.node_settings = node_settings child.save() def iter_children(file_node): to_go = [file_node] while to_go: for child in to_go.pop(0).children: if child.is_folder: to_go.append(child) yield child def main(dry=True): init_app(set_backends=True, routes=False) # Sets the storage backends on all models with TokuTransaction(): do_migration() if dry: raise Exception('Abort Transaction - Dry Run') if __name__ == '__main__': dry = 'dry' in sys.argv if not dry: script_utils.add_file_logger(logger, __file__) main(dry=dry)
import sys import logging from scripts import utils as script_utils from framework.transactions.context import TokuTransaction from website.app import init_app from website.addons.osfstorage import model logger = logging.getLogger(__name__) def do_migration(): count = 0 errored = 0 for node_settings in model.OsfStorageNodeSettings.find(): for child in iter_children(node_settings.root_node): if child.node_settings != node_settings: logger.info('Update node_settings for {!r} in project {!r}'.format(child, node_settings.owner)) child.node_settings = node_settings try: child.save() except Exception as err: errored += 1 logger.error('Error occurred while updating {!r}'.format(child)) logger.exception(err) logger.error('Skipping...') else: count += 1 logger.info('Updated: {} file nodes'.format(count)) logger.info('Errored: {} file nodes'.format(errored)) def iter_children(file_node): to_go = [file_node] while to_go: for child in to_go.pop(0).children: if child.is_folder: to_go.append(child) yield child def main(dry=True): init_app(set_backends=True, routes=False) # Sets the storage backends on all models with TokuTransaction(): do_migration() if dry: raise Exception('Abort Transaction - Dry Run') if __name__ == '__main__': dry = 'dry' in sys.argv if not dry: script_utils.add_file_logger(logger, __file__) main(dry=dry)
Add count and allow errors to pass for now
Add count and allow errors to pass for now [skip ci]
Python
apache-2.0
pattisdr/osf.io,abought/osf.io,DanielSBrown/osf.io,samanehsan/osf.io,billyhunt/osf.io,brandonPurvis/osf.io,samchrisinger/osf.io,brandonPurvis/osf.io,mattclark/osf.io,emetsger/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,jmcarp/osf.io,acshi/osf.io,crcresearch/osf.io,sbt9uc/osf.io,mluke93/osf.io,haoyuchen1992/osf.io,acshi/osf.io,laurenrevere/osf.io,HarryRybacki/osf.io,felliott/osf.io,KAsante95/osf.io,dplorimer/osf,GageGaskins/osf.io,njantrania/osf.io,leb2dg/osf.io,RomanZWang/osf.io,cosenal/osf.io,RomanZWang/osf.io,zachjanicki/osf.io,HalcyonChimera/osf.io,mluo613/osf.io,leb2dg/osf.io,SSJohns/osf.io,brandonPurvis/osf.io,crcresearch/osf.io,caseyrollins/osf.io,samanehsan/osf.io,mluo613/osf.io,caneruguz/osf.io,erinspace/osf.io,billyhunt/osf.io,amyshi188/osf.io,sbt9uc/osf.io,danielneis/osf.io,haoyuchen1992/osf.io,cslzchen/osf.io,caneruguz/osf.io,sloria/osf.io,MerlinZhang/osf.io,samchrisinger/osf.io,CenterForOpenScience/osf.io,caseyrollins/osf.io,mluo613/osf.io,ZobairAlijan/osf.io,mfraezz/osf.io,laurenrevere/osf.io,SSJohns/osf.io,ticklemepierce/osf.io,adlius/osf.io,monikagrabowska/osf.io,kch8qx/osf.io,monikagrabowska/osf.io,njantrania/osf.io,acshi/osf.io,aaxelb/osf.io,KAsante95/osf.io,ZobairAlijan/osf.io,doublebits/osf.io,Ghalko/osf.io,amyshi188/osf.io,caseyrygt/osf.io,felliott/osf.io,Nesiehr/osf.io,MerlinZhang/osf.io,DanielSBrown/osf.io,jnayak1/osf.io,wearpants/osf.io,adlius/osf.io,cwisecarver/osf.io,doublebits/osf.io,TomHeatwole/osf.io,ckc6cz/osf.io,KAsante95/osf.io,RomanZWang/osf.io,caneruguz/osf.io,ckc6cz/osf.io,dplorimer/osf,Johnetordoff/osf.io,hmoco/osf.io,jnayak1/osf.io,caseyrollins/osf.io,petermalcolm/osf.io,brandonPurvis/osf.io,caseyrygt/osf.io,GageGaskins/osf.io,baylee-d/osf.io,Nesiehr/osf.io,ZobairAlijan/osf.io,cwisecarver/osf.io,caseyrygt/osf.io,emetsger/osf.io,cslzchen/osf.io,lyndsysimon/osf.io,reinaH/osf.io,abought/osf.io,billyhunt/osf.io,HarryRybacki/osf.io,emetsger/osf.io,GageGaskins/osf.io,monikagrabowska/osf.io,emetsger/osf.io,HalcyonChimera/osf.io,samchrisinger/osf.io,cldershem/osf.io,CenterForOpenScience/osf.io,saradbowman/osf.io,asanfilippo7/osf.io,cosenal/osf.io,leb2dg/osf.io,kch8qx/osf.io,danielneis/osf.io,icereval/osf.io,chennan47/osf.io,kch8qx/osf.io,MerlinZhang/osf.io,mattclark/osf.io,chrisseto/osf.io,Nesiehr/osf.io,zamattiac/osf.io,chrisseto/osf.io,ckc6cz/osf.io,jolene-esposito/osf.io,ticklemepierce/osf.io,saradbowman/osf.io,rdhyee/osf.io,MerlinZhang/osf.io,alexschiller/osf.io,samanehsan/osf.io,TomHeatwole/osf.io,arpitar/osf.io,petermalcolm/osf.io,zamattiac/osf.io,rdhyee/osf.io,caneruguz/osf.io,samchrisinger/osf.io,bdyetton/prettychart,acshi/osf.io,cslzchen/osf.io,kch8qx/osf.io,arpitar/osf.io,TomHeatwole/osf.io,DanielSBrown/osf.io,baylee-d/osf.io,zachjanicki/osf.io,felliott/osf.io,mattclark/osf.io,ckc6cz/osf.io,felliott/osf.io,RomanZWang/osf.io,bdyetton/prettychart,reinaH/osf.io,baylee-d/osf.io,alexschiller/osf.io,haoyuchen1992/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,amyshi188/osf.io,leb2dg/osf.io,billyhunt/osf.io,aaxelb/osf.io,erinspace/osf.io,brianjgeiger/osf.io,acshi/osf.io,jnayak1/osf.io,amyshi188/osf.io,pattisdr/osf.io,petermalcolm/osf.io,icereval/osf.io,HarryRybacki/osf.io,CenterForOpenScience/osf.io,jmcarp/osf.io,alexschiller/osf.io,kch8qx/osf.io,rdhyee/osf.io,hmoco/osf.io,chennan47/osf.io,KAsante95/osf.io,Johnetordoff/osf.io,adlius/osf.io,KAsante95/osf.io,SSJohns/osf.io,cslzchen/osf.io,hmoco/osf.io,Ghalko/osf.io,erinspace/osf.io,HalcyonChimera/osf.io,njantrania/osf.io,icereval/osf.io,laurenrevere/osf.io,HalcyonChimera/osf.io,ticklemepierce/osf.io,jolene-esposito/osf.io,abought/osf.io,lyndsysimon/osf.io,jmcarp/osf.io,asanfilippo7/osf.io,zachjanicki/osf.io,caseyrygt/osf.io,lyndsysimon/osf.io,zamattiac/osf.io,GageGaskins/osf.io,lyndsysimon/osf.io,kwierman/osf.io,petermalcolm/osf.io,doublebits/osf.io,SSJohns/osf.io,asanfilippo7/osf.io,doublebits/osf.io,TomBaxter/osf.io,doublebits/osf.io,TomBaxter/osf.io,rdhyee/osf.io,chrisseto/osf.io,monikagrabowska/osf.io,sloria/osf.io,dplorimer/osf,arpitar/osf.io,binoculars/osf.io,danielneis/osf.io,dplorimer/osf,mluke93/osf.io,hmoco/osf.io,mluo613/osf.io,ticklemepierce/osf.io,jolene-esposito/osf.io,HarryRybacki/osf.io,chrisseto/osf.io,haoyuchen1992/osf.io,bdyetton/prettychart,RomanZWang/osf.io,mluke93/osf.io,brianjgeiger/osf.io,binoculars/osf.io,wearpants/osf.io,reinaH/osf.io,mfraezz/osf.io,kwierman/osf.io,Ghalko/osf.io,binoculars/osf.io,wearpants/osf.io,kwierman/osf.io,samanehsan/osf.io,TomBaxter/osf.io,danielneis/osf.io,jmcarp/osf.io,asanfilippo7/osf.io,mluo613/osf.io,cosenal/osf.io,arpitar/osf.io,reinaH/osf.io,mfraezz/osf.io,abought/osf.io,mluke93/osf.io,cwisecarver/osf.io,wearpants/osf.io,njantrania/osf.io,sbt9uc/osf.io,sloria/osf.io,zachjanicki/osf.io,brandonPurvis/osf.io,Nesiehr/osf.io,cldershem/osf.io,pattisdr/osf.io,jolene-esposito/osf.io,sbt9uc/osf.io,alexschiller/osf.io,cwisecarver/osf.io,monikagrabowska/osf.io,cldershem/osf.io,zamattiac/osf.io,cldershem/osf.io,jnayak1/osf.io,cosenal/osf.io,Ghalko/osf.io,aaxelb/osf.io,TomHeatwole/osf.io,alexschiller/osf.io,CenterForOpenScience/osf.io,ZobairAlijan/osf.io,Johnetordoff/osf.io,bdyetton/prettychart,adlius/osf.io,DanielSBrown/osf.io,billyhunt/osf.io,kwierman/osf.io,aaxelb/osf.io,GageGaskins/osf.io,crcresearch/osf.io,chennan47/osf.io
import sys import logging from scripts import utils as script_utils from framework.transactions.context import TokuTransaction from website.app import init_app from website.addons.osfstorage import model logger = logging.getLogger(__name__) def do_migration(): for node_settings in model.OsfStorageNodeSettings.find(): for child in iter_children(node_settings.root_node): if child.node_settings != node_settings: logger.info('Update node_settings for {!r} in project {!r}'.format(child, node_settings.owner,)) child.node_settings = node_settings child.save() def iter_children(file_node): to_go = [file_node] while to_go: for child in to_go.pop(0).children: if child.is_folder: to_go.append(child) yield child def main(dry=True): init_app(set_backends=True, routes=False) # Sets the storage backends on all models with TokuTransaction(): do_migration() if dry: raise Exception('Abort Transaction - Dry Run') if __name__ == '__main__': dry = 'dry' in sys.argv if not dry: script_utils.add_file_logger(logger, __file__) main(dry=dry) Add count and allow errors to pass for now [skip ci]
import sys import logging from scripts import utils as script_utils from framework.transactions.context import TokuTransaction from website.app import init_app from website.addons.osfstorage import model logger = logging.getLogger(__name__) def do_migration(): count = 0 errored = 0 for node_settings in model.OsfStorageNodeSettings.find(): for child in iter_children(node_settings.root_node): if child.node_settings != node_settings: logger.info('Update node_settings for {!r} in project {!r}'.format(child, node_settings.owner)) child.node_settings = node_settings try: child.save() except Exception as err: errored += 1 logger.error('Error occurred while updating {!r}'.format(child)) logger.exception(err) logger.error('Skipping...') else: count += 1 logger.info('Updated: {} file nodes'.format(count)) logger.info('Errored: {} file nodes'.format(errored)) def iter_children(file_node): to_go = [file_node] while to_go: for child in to_go.pop(0).children: if child.is_folder: to_go.append(child) yield child def main(dry=True): init_app(set_backends=True, routes=False) # Sets the storage backends on all models with TokuTransaction(): do_migration() if dry: raise Exception('Abort Transaction - Dry Run') if __name__ == '__main__': dry = 'dry' in sys.argv if not dry: script_utils.add_file_logger(logger, __file__) main(dry=dry)
<commit_before>import sys import logging from scripts import utils as script_utils from framework.transactions.context import TokuTransaction from website.app import init_app from website.addons.osfstorage import model logger = logging.getLogger(__name__) def do_migration(): for node_settings in model.OsfStorageNodeSettings.find(): for child in iter_children(node_settings.root_node): if child.node_settings != node_settings: logger.info('Update node_settings for {!r} in project {!r}'.format(child, node_settings.owner,)) child.node_settings = node_settings child.save() def iter_children(file_node): to_go = [file_node] while to_go: for child in to_go.pop(0).children: if child.is_folder: to_go.append(child) yield child def main(dry=True): init_app(set_backends=True, routes=False) # Sets the storage backends on all models with TokuTransaction(): do_migration() if dry: raise Exception('Abort Transaction - Dry Run') if __name__ == '__main__': dry = 'dry' in sys.argv if not dry: script_utils.add_file_logger(logger, __file__) main(dry=dry) <commit_msg>Add count and allow errors to pass for now [skip ci]<commit_after>
import sys import logging from scripts import utils as script_utils from framework.transactions.context import TokuTransaction from website.app import init_app from website.addons.osfstorage import model logger = logging.getLogger(__name__) def do_migration(): count = 0 errored = 0 for node_settings in model.OsfStorageNodeSettings.find(): for child in iter_children(node_settings.root_node): if child.node_settings != node_settings: logger.info('Update node_settings for {!r} in project {!r}'.format(child, node_settings.owner)) child.node_settings = node_settings try: child.save() except Exception as err: errored += 1 logger.error('Error occurred while updating {!r}'.format(child)) logger.exception(err) logger.error('Skipping...') else: count += 1 logger.info('Updated: {} file nodes'.format(count)) logger.info('Errored: {} file nodes'.format(errored)) def iter_children(file_node): to_go = [file_node] while to_go: for child in to_go.pop(0).children: if child.is_folder: to_go.append(child) yield child def main(dry=True): init_app(set_backends=True, routes=False) # Sets the storage backends on all models with TokuTransaction(): do_migration() if dry: raise Exception('Abort Transaction - Dry Run') if __name__ == '__main__': dry = 'dry' in sys.argv if not dry: script_utils.add_file_logger(logger, __file__) main(dry=dry)
import sys import logging from scripts import utils as script_utils from framework.transactions.context import TokuTransaction from website.app import init_app from website.addons.osfstorage import model logger = logging.getLogger(__name__) def do_migration(): for node_settings in model.OsfStorageNodeSettings.find(): for child in iter_children(node_settings.root_node): if child.node_settings != node_settings: logger.info('Update node_settings for {!r} in project {!r}'.format(child, node_settings.owner,)) child.node_settings = node_settings child.save() def iter_children(file_node): to_go = [file_node] while to_go: for child in to_go.pop(0).children: if child.is_folder: to_go.append(child) yield child def main(dry=True): init_app(set_backends=True, routes=False) # Sets the storage backends on all models with TokuTransaction(): do_migration() if dry: raise Exception('Abort Transaction - Dry Run') if __name__ == '__main__': dry = 'dry' in sys.argv if not dry: script_utils.add_file_logger(logger, __file__) main(dry=dry) Add count and allow errors to pass for now [skip ci]import sys import logging from scripts import utils as script_utils from framework.transactions.context import TokuTransaction from website.app import init_app from website.addons.osfstorage import model logger = logging.getLogger(__name__) def do_migration(): count = 0 errored = 0 for node_settings in model.OsfStorageNodeSettings.find(): for child in iter_children(node_settings.root_node): if child.node_settings != node_settings: logger.info('Update node_settings for {!r} in project {!r}'.format(child, node_settings.owner)) child.node_settings = node_settings try: child.save() except Exception as err: errored += 1 logger.error('Error occurred while updating {!r}'.format(child)) logger.exception(err) logger.error('Skipping...') else: count += 1 logger.info('Updated: {} file nodes'.format(count)) logger.info('Errored: {} file nodes'.format(errored)) def iter_children(file_node): to_go = [file_node] while to_go: for child in to_go.pop(0).children: if child.is_folder: to_go.append(child) yield child def main(dry=True): init_app(set_backends=True, routes=False) # Sets the storage backends on all models with TokuTransaction(): do_migration() if dry: raise Exception('Abort Transaction - Dry Run') if __name__ == '__main__': dry = 'dry' in sys.argv if not dry: script_utils.add_file_logger(logger, __file__) main(dry=dry)
<commit_before>import sys import logging from scripts import utils as script_utils from framework.transactions.context import TokuTransaction from website.app import init_app from website.addons.osfstorage import model logger = logging.getLogger(__name__) def do_migration(): for node_settings in model.OsfStorageNodeSettings.find(): for child in iter_children(node_settings.root_node): if child.node_settings != node_settings: logger.info('Update node_settings for {!r} in project {!r}'.format(child, node_settings.owner,)) child.node_settings = node_settings child.save() def iter_children(file_node): to_go = [file_node] while to_go: for child in to_go.pop(0).children: if child.is_folder: to_go.append(child) yield child def main(dry=True): init_app(set_backends=True, routes=False) # Sets the storage backends on all models with TokuTransaction(): do_migration() if dry: raise Exception('Abort Transaction - Dry Run') if __name__ == '__main__': dry = 'dry' in sys.argv if not dry: script_utils.add_file_logger(logger, __file__) main(dry=dry) <commit_msg>Add count and allow errors to pass for now [skip ci]<commit_after>import sys import logging from scripts import utils as script_utils from framework.transactions.context import TokuTransaction from website.app import init_app from website.addons.osfstorage import model logger = logging.getLogger(__name__) def do_migration(): count = 0 errored = 0 for node_settings in model.OsfStorageNodeSettings.find(): for child in iter_children(node_settings.root_node): if child.node_settings != node_settings: logger.info('Update node_settings for {!r} in project {!r}'.format(child, node_settings.owner)) child.node_settings = node_settings try: child.save() except Exception as err: errored += 1 logger.error('Error occurred while updating {!r}'.format(child)) logger.exception(err) logger.error('Skipping...') else: count += 1 logger.info('Updated: {} file nodes'.format(count)) logger.info('Errored: {} file nodes'.format(errored)) def iter_children(file_node): to_go = [file_node] while to_go: for child in to_go.pop(0).children: if child.is_folder: to_go.append(child) yield child def main(dry=True): init_app(set_backends=True, routes=False) # Sets the storage backends on all models with TokuTransaction(): do_migration() if dry: raise Exception('Abort Transaction - Dry Run') if __name__ == '__main__': dry = 'dry' in sys.argv if not dry: script_utils.add_file_logger(logger, __file__) main(dry=dry)
fab10307cac59f758a5b36cf3fe5b80874f026b2
script/dependencies.py
script/dependencies.py
#!/usr/bin/env python import os dependencies = ( ('bins/el-rando', 'https://github.com/EvanHahn/el-rando.git'), ('bins/is_github_up', 'https://github.com/EvanHahn/is-GitHub-up.git'), ('bins/iscp', 'https://github.com/EvanHahn/iscp.git'), ('bins/journ', 'https://github.com/EvanHahn/journ.git'), ('bins/rename', 'https://github.com/EvanHahn/rename.git'), ) my_path = os.path.dirname(os.path.realpath(__file__)) root_path = os.path.join(my_path, '..') os.chdir(root_path) for (path, url) in dependencies: exists = os.path.isdir(path) subtree_command = 'pull' if exists else 'add' os.system('git subtree {0} --prefix {1} {2} master --squash'.format( subtree_command, path, url))
#!/usr/bin/env python import os dependencies = ( ('resources/vim/bundle/neobundle.vim', 'https://github.com/Shougo/neobundle.vim'), ('resources/zsh/zsh-syntax-highlighting', 'git://github.com/zsh-users/zsh-syntax-highlighting.git'), ('bins/el-rando', 'https://github.com/EvanHahn/el-rando.git'), ('bins/is_github_up', 'https://github.com/EvanHahn/is-GitHub-up.git'), ('bins/iscp', 'https://github.com/EvanHahn/iscp.git'), ('bins/journ', 'https://github.com/EvanHahn/journ.git'), ('bins/rename', 'https://github.com/EvanHahn/rename.git'), ) my_path = os.path.dirname(os.path.realpath(__file__)) root_path = os.path.join(my_path, '..') for (path, url) in dependencies: os.chdir(root_path) exists = os.path.isdir(path) if exists: os.chdir(path) os.system('git checkout master') os.system('git pull origin master') else: os.system('git clone {0} {1}'.format(url, path))
Switch to automated git clone and pull
Switch to automated git clone and pull
Python
unlicense
EvanHahn/dotfiles,EvanHahn/dotfiles,EvanHahn/dotfiles,EvanHahn/dotfiles
#!/usr/bin/env python import os dependencies = ( ('bins/el-rando', 'https://github.com/EvanHahn/el-rando.git'), ('bins/is_github_up', 'https://github.com/EvanHahn/is-GitHub-up.git'), ('bins/iscp', 'https://github.com/EvanHahn/iscp.git'), ('bins/journ', 'https://github.com/EvanHahn/journ.git'), ('bins/rename', 'https://github.com/EvanHahn/rename.git'), ) my_path = os.path.dirname(os.path.realpath(__file__)) root_path = os.path.join(my_path, '..') os.chdir(root_path) for (path, url) in dependencies: exists = os.path.isdir(path) subtree_command = 'pull' if exists else 'add' os.system('git subtree {0} --prefix {1} {2} master --squash'.format( subtree_command, path, url)) Switch to automated git clone and pull
#!/usr/bin/env python import os dependencies = ( ('resources/vim/bundle/neobundle.vim', 'https://github.com/Shougo/neobundle.vim'), ('resources/zsh/zsh-syntax-highlighting', 'git://github.com/zsh-users/zsh-syntax-highlighting.git'), ('bins/el-rando', 'https://github.com/EvanHahn/el-rando.git'), ('bins/is_github_up', 'https://github.com/EvanHahn/is-GitHub-up.git'), ('bins/iscp', 'https://github.com/EvanHahn/iscp.git'), ('bins/journ', 'https://github.com/EvanHahn/journ.git'), ('bins/rename', 'https://github.com/EvanHahn/rename.git'), ) my_path = os.path.dirname(os.path.realpath(__file__)) root_path = os.path.join(my_path, '..') for (path, url) in dependencies: os.chdir(root_path) exists = os.path.isdir(path) if exists: os.chdir(path) os.system('git checkout master') os.system('git pull origin master') else: os.system('git clone {0} {1}'.format(url, path))
<commit_before>#!/usr/bin/env python import os dependencies = ( ('bins/el-rando', 'https://github.com/EvanHahn/el-rando.git'), ('bins/is_github_up', 'https://github.com/EvanHahn/is-GitHub-up.git'), ('bins/iscp', 'https://github.com/EvanHahn/iscp.git'), ('bins/journ', 'https://github.com/EvanHahn/journ.git'), ('bins/rename', 'https://github.com/EvanHahn/rename.git'), ) my_path = os.path.dirname(os.path.realpath(__file__)) root_path = os.path.join(my_path, '..') os.chdir(root_path) for (path, url) in dependencies: exists = os.path.isdir(path) subtree_command = 'pull' if exists else 'add' os.system('git subtree {0} --prefix {1} {2} master --squash'.format( subtree_command, path, url)) <commit_msg>Switch to automated git clone and pull<commit_after>
#!/usr/bin/env python import os dependencies = ( ('resources/vim/bundle/neobundle.vim', 'https://github.com/Shougo/neobundle.vim'), ('resources/zsh/zsh-syntax-highlighting', 'git://github.com/zsh-users/zsh-syntax-highlighting.git'), ('bins/el-rando', 'https://github.com/EvanHahn/el-rando.git'), ('bins/is_github_up', 'https://github.com/EvanHahn/is-GitHub-up.git'), ('bins/iscp', 'https://github.com/EvanHahn/iscp.git'), ('bins/journ', 'https://github.com/EvanHahn/journ.git'), ('bins/rename', 'https://github.com/EvanHahn/rename.git'), ) my_path = os.path.dirname(os.path.realpath(__file__)) root_path = os.path.join(my_path, '..') for (path, url) in dependencies: os.chdir(root_path) exists = os.path.isdir(path) if exists: os.chdir(path) os.system('git checkout master') os.system('git pull origin master') else: os.system('git clone {0} {1}'.format(url, path))
#!/usr/bin/env python import os dependencies = ( ('bins/el-rando', 'https://github.com/EvanHahn/el-rando.git'), ('bins/is_github_up', 'https://github.com/EvanHahn/is-GitHub-up.git'), ('bins/iscp', 'https://github.com/EvanHahn/iscp.git'), ('bins/journ', 'https://github.com/EvanHahn/journ.git'), ('bins/rename', 'https://github.com/EvanHahn/rename.git'), ) my_path = os.path.dirname(os.path.realpath(__file__)) root_path = os.path.join(my_path, '..') os.chdir(root_path) for (path, url) in dependencies: exists = os.path.isdir(path) subtree_command = 'pull' if exists else 'add' os.system('git subtree {0} --prefix {1} {2} master --squash'.format( subtree_command, path, url)) Switch to automated git clone and pull#!/usr/bin/env python import os dependencies = ( ('resources/vim/bundle/neobundle.vim', 'https://github.com/Shougo/neobundle.vim'), ('resources/zsh/zsh-syntax-highlighting', 'git://github.com/zsh-users/zsh-syntax-highlighting.git'), ('bins/el-rando', 'https://github.com/EvanHahn/el-rando.git'), ('bins/is_github_up', 'https://github.com/EvanHahn/is-GitHub-up.git'), ('bins/iscp', 'https://github.com/EvanHahn/iscp.git'), ('bins/journ', 'https://github.com/EvanHahn/journ.git'), ('bins/rename', 'https://github.com/EvanHahn/rename.git'), ) my_path = os.path.dirname(os.path.realpath(__file__)) root_path = os.path.join(my_path, '..') for (path, url) in dependencies: os.chdir(root_path) exists = os.path.isdir(path) if exists: os.chdir(path) os.system('git checkout master') os.system('git pull origin master') else: os.system('git clone {0} {1}'.format(url, path))
<commit_before>#!/usr/bin/env python import os dependencies = ( ('bins/el-rando', 'https://github.com/EvanHahn/el-rando.git'), ('bins/is_github_up', 'https://github.com/EvanHahn/is-GitHub-up.git'), ('bins/iscp', 'https://github.com/EvanHahn/iscp.git'), ('bins/journ', 'https://github.com/EvanHahn/journ.git'), ('bins/rename', 'https://github.com/EvanHahn/rename.git'), ) my_path = os.path.dirname(os.path.realpath(__file__)) root_path = os.path.join(my_path, '..') os.chdir(root_path) for (path, url) in dependencies: exists = os.path.isdir(path) subtree_command = 'pull' if exists else 'add' os.system('git subtree {0} --prefix {1} {2} master --squash'.format( subtree_command, path, url)) <commit_msg>Switch to automated git clone and pull<commit_after>#!/usr/bin/env python import os dependencies = ( ('resources/vim/bundle/neobundle.vim', 'https://github.com/Shougo/neobundle.vim'), ('resources/zsh/zsh-syntax-highlighting', 'git://github.com/zsh-users/zsh-syntax-highlighting.git'), ('bins/el-rando', 'https://github.com/EvanHahn/el-rando.git'), ('bins/is_github_up', 'https://github.com/EvanHahn/is-GitHub-up.git'), ('bins/iscp', 'https://github.com/EvanHahn/iscp.git'), ('bins/journ', 'https://github.com/EvanHahn/journ.git'), ('bins/rename', 'https://github.com/EvanHahn/rename.git'), ) my_path = os.path.dirname(os.path.realpath(__file__)) root_path = os.path.join(my_path, '..') for (path, url) in dependencies: os.chdir(root_path) exists = os.path.isdir(path) if exists: os.chdir(path) os.system('git checkout master') os.system('git pull origin master') else: os.system('git clone {0} {1}'.format(url, path))
776150670026aae3fd53b75df6024bee32a677b5
examples/image_test.py
examples/image_test.py
import sys import os import pyglet.window from pyglet.gl import * from pyglet import clock from pyglet.ext.scene2d import Image2d from ctypes import * if len(sys.argv) != 2: print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0] sys.exit() window = pyglet.window.Window(width=400, height=400) image = Image2d.load(sys.argv[1]) s = max(image.width, image.height) c = clock.Clock(60) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60., 1., 1., 100.) glEnable(GL_COLOR_MATERIAL) glMatrixMode(GL_MODELVIEW) glClearColor(0, 0, 0, 0) glColor4f(1, 1, 1, 1) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_BLEND) while not window.has_exit: c.tick() window.dispatch_events() glClear(GL_COLOR_BUFFER_BIT) glLoadIdentity() glScalef(1./s, 1./s, 1.) glTranslatef(-image.width/2, -image.height/2, -1.) image.draw() window.flip()
import sys import os import ctypes import pyglet.window from pyglet.gl import * from pyglet import clock from pyglet import image if len(sys.argv) != 2: print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0] sys.exit() window = pyglet.window.Window(width=400, height=400) image = image.load(sys.argv[1]) imx = imy = 0 @window.event def on_mouse_drag(x, y, dx, dy, buttons, modifiers): global imx, imy imx += dx imy += dy clock.set_fps_limit(30) while not window.has_exit: clock.tick() window.dispatch_events() glClear(GL_COLOR_BUFFER_BIT) image.blit(imx, imy, 0) window.flip()
Use the core, make example more useful.
Use the core, make example more useful.
Python
bsd-3-clause
theblacklion/pyglet,mammadori/pyglet,mammadori/pyglet,oktayacikalin/pyglet,theblacklion/pyglet,oktayacikalin/pyglet,theblacklion/pyglet,theblacklion/pyglet,mammadori/pyglet,theblacklion/pyglet,oktayacikalin/pyglet,mammadori/pyglet,oktayacikalin/pyglet,oktayacikalin/pyglet
import sys import os import pyglet.window from pyglet.gl import * from pyglet import clock from pyglet.ext.scene2d import Image2d from ctypes import * if len(sys.argv) != 2: print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0] sys.exit() window = pyglet.window.Window(width=400, height=400) image = Image2d.load(sys.argv[1]) s = max(image.width, image.height) c = clock.Clock(60) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60., 1., 1., 100.) glEnable(GL_COLOR_MATERIAL) glMatrixMode(GL_MODELVIEW) glClearColor(0, 0, 0, 0) glColor4f(1, 1, 1, 1) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_BLEND) while not window.has_exit: c.tick() window.dispatch_events() glClear(GL_COLOR_BUFFER_BIT) glLoadIdentity() glScalef(1./s, 1./s, 1.) glTranslatef(-image.width/2, -image.height/2, -1.) image.draw() window.flip() Use the core, make example more useful.
import sys import os import ctypes import pyglet.window from pyglet.gl import * from pyglet import clock from pyglet import image if len(sys.argv) != 2: print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0] sys.exit() window = pyglet.window.Window(width=400, height=400) image = image.load(sys.argv[1]) imx = imy = 0 @window.event def on_mouse_drag(x, y, dx, dy, buttons, modifiers): global imx, imy imx += dx imy += dy clock.set_fps_limit(30) while not window.has_exit: clock.tick() window.dispatch_events() glClear(GL_COLOR_BUFFER_BIT) image.blit(imx, imy, 0) window.flip()
<commit_before>import sys import os import pyglet.window from pyglet.gl import * from pyglet import clock from pyglet.ext.scene2d import Image2d from ctypes import * if len(sys.argv) != 2: print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0] sys.exit() window = pyglet.window.Window(width=400, height=400) image = Image2d.load(sys.argv[1]) s = max(image.width, image.height) c = clock.Clock(60) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60., 1., 1., 100.) glEnable(GL_COLOR_MATERIAL) glMatrixMode(GL_MODELVIEW) glClearColor(0, 0, 0, 0) glColor4f(1, 1, 1, 1) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_BLEND) while not window.has_exit: c.tick() window.dispatch_events() glClear(GL_COLOR_BUFFER_BIT) glLoadIdentity() glScalef(1./s, 1./s, 1.) glTranslatef(-image.width/2, -image.height/2, -1.) image.draw() window.flip() <commit_msg>Use the core, make example more useful.<commit_after>
import sys import os import ctypes import pyglet.window from pyglet.gl import * from pyglet import clock from pyglet import image if len(sys.argv) != 2: print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0] sys.exit() window = pyglet.window.Window(width=400, height=400) image = image.load(sys.argv[1]) imx = imy = 0 @window.event def on_mouse_drag(x, y, dx, dy, buttons, modifiers): global imx, imy imx += dx imy += dy clock.set_fps_limit(30) while not window.has_exit: clock.tick() window.dispatch_events() glClear(GL_COLOR_BUFFER_BIT) image.blit(imx, imy, 0) window.flip()
import sys import os import pyglet.window from pyglet.gl import * from pyglet import clock from pyglet.ext.scene2d import Image2d from ctypes import * if len(sys.argv) != 2: print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0] sys.exit() window = pyglet.window.Window(width=400, height=400) image = Image2d.load(sys.argv[1]) s = max(image.width, image.height) c = clock.Clock(60) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60., 1., 1., 100.) glEnable(GL_COLOR_MATERIAL) glMatrixMode(GL_MODELVIEW) glClearColor(0, 0, 0, 0) glColor4f(1, 1, 1, 1) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_BLEND) while not window.has_exit: c.tick() window.dispatch_events() glClear(GL_COLOR_BUFFER_BIT) glLoadIdentity() glScalef(1./s, 1./s, 1.) glTranslatef(-image.width/2, -image.height/2, -1.) image.draw() window.flip() Use the core, make example more useful.import sys import os import ctypes import pyglet.window from pyglet.gl import * from pyglet import clock from pyglet import image if len(sys.argv) != 2: print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0] sys.exit() window = pyglet.window.Window(width=400, height=400) image = image.load(sys.argv[1]) imx = imy = 0 @window.event def on_mouse_drag(x, y, dx, dy, buttons, modifiers): global imx, imy imx += dx imy += dy clock.set_fps_limit(30) while not window.has_exit: clock.tick() window.dispatch_events() glClear(GL_COLOR_BUFFER_BIT) image.blit(imx, imy, 0) window.flip()
<commit_before>import sys import os import pyglet.window from pyglet.gl import * from pyglet import clock from pyglet.ext.scene2d import Image2d from ctypes import * if len(sys.argv) != 2: print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0] sys.exit() window = pyglet.window.Window(width=400, height=400) image = Image2d.load(sys.argv[1]) s = max(image.width, image.height) c = clock.Clock(60) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60., 1., 1., 100.) glEnable(GL_COLOR_MATERIAL) glMatrixMode(GL_MODELVIEW) glClearColor(0, 0, 0, 0) glColor4f(1, 1, 1, 1) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_BLEND) while not window.has_exit: c.tick() window.dispatch_events() glClear(GL_COLOR_BUFFER_BIT) glLoadIdentity() glScalef(1./s, 1./s, 1.) glTranslatef(-image.width/2, -image.height/2, -1.) image.draw() window.flip() <commit_msg>Use the core, make example more useful.<commit_after>import sys import os import ctypes import pyglet.window from pyglet.gl import * from pyglet import clock from pyglet import image if len(sys.argv) != 2: print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0] sys.exit() window = pyglet.window.Window(width=400, height=400) image = image.load(sys.argv[1]) imx = imy = 0 @window.event def on_mouse_drag(x, y, dx, dy, buttons, modifiers): global imx, imy imx += dx imy += dy clock.set_fps_limit(30) while not window.has_exit: clock.tick() window.dispatch_events() glClear(GL_COLOR_BUFFER_BIT) image.blit(imx, imy, 0) window.flip()
051aa6ca11bda22f4ea04775826f0f64152fef24
scripts/has_open_pr.py
scripts/has_open_pr.py
import argparse import os import sys from github3 import login class HasOpenPull(object): def __init__(self): self._init_github() def _init_github(self): username = os.environ.get('GITHUB_USERNAME') password = os.environ.get('GITHUB_PASSWORD') if not username or not password: print "Could not find Github username and password from the environment variables GITHUB_USERNAME and GITHUB_PASSWORD" sys.exit(1) self.gh = login(username, password) self.repo = self.gh.repository( 'SalesforceFoundation', 'CumulusCI', ) def __call__(self, branch): for pull in self.repo.iter_pulls(state='open', base='master'): if pull.head.ref == branch: return pull if __name__ == "__main__": parser = argparse.ArgumentParser(description='Check if a branch has an open pull request in Github') parser.add_argument('branch', type=str, help='The branch name to check') args = parser.parse_args() has_open_pull = HasOpenPull() pr = has_open_pull(args.branch) if pr: print "#{}".format(pr.number)
import argparse import os import sys from github3 import login class HasOpenPull(object): def __init__(self): self._init_github() def _init_github(self): username = os.environ.get('GITHUB_USERNAME') password = os.environ.get('GITHUB_PASSWORD') if not username or not password: print "Could not find Github username and password from the environment variables GITHUB_USERNAME and GITHUB_PASSWORD" sys.exit(1) self.gh = login(username, password) self.repo = self.gh.repository( 'SalesforceFoundation', 'CumulusCI', ) def __call__(self, branch): # Since the head parameter doesn't seem to work in the Github pulls API, # loop through the open PR's and compare the actual head ref. Otherwise, # this whole script could have been done with a simple curl command :/ for pull in self.repo.iter_pulls(state='open', base='master'): if pull.head.ref == branch: return pull if __name__ == "__main__": parser = argparse.ArgumentParser(description='Check if a branch has an open pull request in Github') parser.add_argument('branch', type=str, help='The branch name to check') args = parser.parse_args() has_open_pull = HasOpenPull() pr = has_open_pull(args.branch) if pr: print "#{}".format(pr.number)
Add comment about new script logic [skip CumulusCI-Test]
Add comment about new script logic [skip CumulusCI-Test]
Python
bsd-3-clause
e02d96ec16/CumulusCI,e02d96ec16/CumulusCI,SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI
import argparse import os import sys from github3 import login class HasOpenPull(object): def __init__(self): self._init_github() def _init_github(self): username = os.environ.get('GITHUB_USERNAME') password = os.environ.get('GITHUB_PASSWORD') if not username or not password: print "Could not find Github username and password from the environment variables GITHUB_USERNAME and GITHUB_PASSWORD" sys.exit(1) self.gh = login(username, password) self.repo = self.gh.repository( 'SalesforceFoundation', 'CumulusCI', ) def __call__(self, branch): for pull in self.repo.iter_pulls(state='open', base='master'): if pull.head.ref == branch: return pull if __name__ == "__main__": parser = argparse.ArgumentParser(description='Check if a branch has an open pull request in Github') parser.add_argument('branch', type=str, help='The branch name to check') args = parser.parse_args() has_open_pull = HasOpenPull() pr = has_open_pull(args.branch) if pr: print "#{}".format(pr.number) Add comment about new script logic [skip CumulusCI-Test]
import argparse import os import sys from github3 import login class HasOpenPull(object): def __init__(self): self._init_github() def _init_github(self): username = os.environ.get('GITHUB_USERNAME') password = os.environ.get('GITHUB_PASSWORD') if not username or not password: print "Could not find Github username and password from the environment variables GITHUB_USERNAME and GITHUB_PASSWORD" sys.exit(1) self.gh = login(username, password) self.repo = self.gh.repository( 'SalesforceFoundation', 'CumulusCI', ) def __call__(self, branch): # Since the head parameter doesn't seem to work in the Github pulls API, # loop through the open PR's and compare the actual head ref. Otherwise, # this whole script could have been done with a simple curl command :/ for pull in self.repo.iter_pulls(state='open', base='master'): if pull.head.ref == branch: return pull if __name__ == "__main__": parser = argparse.ArgumentParser(description='Check if a branch has an open pull request in Github') parser.add_argument('branch', type=str, help='The branch name to check') args = parser.parse_args() has_open_pull = HasOpenPull() pr = has_open_pull(args.branch) if pr: print "#{}".format(pr.number)
<commit_before>import argparse import os import sys from github3 import login class HasOpenPull(object): def __init__(self): self._init_github() def _init_github(self): username = os.environ.get('GITHUB_USERNAME') password = os.environ.get('GITHUB_PASSWORD') if not username or not password: print "Could not find Github username and password from the environment variables GITHUB_USERNAME and GITHUB_PASSWORD" sys.exit(1) self.gh = login(username, password) self.repo = self.gh.repository( 'SalesforceFoundation', 'CumulusCI', ) def __call__(self, branch): for pull in self.repo.iter_pulls(state='open', base='master'): if pull.head.ref == branch: return pull if __name__ == "__main__": parser = argparse.ArgumentParser(description='Check if a branch has an open pull request in Github') parser.add_argument('branch', type=str, help='The branch name to check') args = parser.parse_args() has_open_pull = HasOpenPull() pr = has_open_pull(args.branch) if pr: print "#{}".format(pr.number) <commit_msg>Add comment about new script logic [skip CumulusCI-Test]<commit_after>
import argparse import os import sys from github3 import login class HasOpenPull(object): def __init__(self): self._init_github() def _init_github(self): username = os.environ.get('GITHUB_USERNAME') password = os.environ.get('GITHUB_PASSWORD') if not username or not password: print "Could not find Github username and password from the environment variables GITHUB_USERNAME and GITHUB_PASSWORD" sys.exit(1) self.gh = login(username, password) self.repo = self.gh.repository( 'SalesforceFoundation', 'CumulusCI', ) def __call__(self, branch): # Since the head parameter doesn't seem to work in the Github pulls API, # loop through the open PR's and compare the actual head ref. Otherwise, # this whole script could have been done with a simple curl command :/ for pull in self.repo.iter_pulls(state='open', base='master'): if pull.head.ref == branch: return pull if __name__ == "__main__": parser = argparse.ArgumentParser(description='Check if a branch has an open pull request in Github') parser.add_argument('branch', type=str, help='The branch name to check') args = parser.parse_args() has_open_pull = HasOpenPull() pr = has_open_pull(args.branch) if pr: print "#{}".format(pr.number)
import argparse import os import sys from github3 import login class HasOpenPull(object): def __init__(self): self._init_github() def _init_github(self): username = os.environ.get('GITHUB_USERNAME') password = os.environ.get('GITHUB_PASSWORD') if not username or not password: print "Could not find Github username and password from the environment variables GITHUB_USERNAME and GITHUB_PASSWORD" sys.exit(1) self.gh = login(username, password) self.repo = self.gh.repository( 'SalesforceFoundation', 'CumulusCI', ) def __call__(self, branch): for pull in self.repo.iter_pulls(state='open', base='master'): if pull.head.ref == branch: return pull if __name__ == "__main__": parser = argparse.ArgumentParser(description='Check if a branch has an open pull request in Github') parser.add_argument('branch', type=str, help='The branch name to check') args = parser.parse_args() has_open_pull = HasOpenPull() pr = has_open_pull(args.branch) if pr: print "#{}".format(pr.number) Add comment about new script logic [skip CumulusCI-Test]import argparse import os import sys from github3 import login class HasOpenPull(object): def __init__(self): self._init_github() def _init_github(self): username = os.environ.get('GITHUB_USERNAME') password = os.environ.get('GITHUB_PASSWORD') if not username or not password: print "Could not find Github username and password from the environment variables GITHUB_USERNAME and GITHUB_PASSWORD" sys.exit(1) self.gh = login(username, password) self.repo = self.gh.repository( 'SalesforceFoundation', 'CumulusCI', ) def __call__(self, branch): # Since the head parameter doesn't seem to work in the Github pulls API, # loop through the open PR's and compare the actual head ref. Otherwise, # this whole script could have been done with a simple curl command :/ for pull in self.repo.iter_pulls(state='open', base='master'): if pull.head.ref == branch: return pull if __name__ == "__main__": parser = argparse.ArgumentParser(description='Check if a branch has an open pull request in Github') parser.add_argument('branch', type=str, help='The branch name to check') args = parser.parse_args() has_open_pull = HasOpenPull() pr = has_open_pull(args.branch) if pr: print "#{}".format(pr.number)
<commit_before>import argparse import os import sys from github3 import login class HasOpenPull(object): def __init__(self): self._init_github() def _init_github(self): username = os.environ.get('GITHUB_USERNAME') password = os.environ.get('GITHUB_PASSWORD') if not username or not password: print "Could not find Github username and password from the environment variables GITHUB_USERNAME and GITHUB_PASSWORD" sys.exit(1) self.gh = login(username, password) self.repo = self.gh.repository( 'SalesforceFoundation', 'CumulusCI', ) def __call__(self, branch): for pull in self.repo.iter_pulls(state='open', base='master'): if pull.head.ref == branch: return pull if __name__ == "__main__": parser = argparse.ArgumentParser(description='Check if a branch has an open pull request in Github') parser.add_argument('branch', type=str, help='The branch name to check') args = parser.parse_args() has_open_pull = HasOpenPull() pr = has_open_pull(args.branch) if pr: print "#{}".format(pr.number) <commit_msg>Add comment about new script logic [skip CumulusCI-Test]<commit_after>import argparse import os import sys from github3 import login class HasOpenPull(object): def __init__(self): self._init_github() def _init_github(self): username = os.environ.get('GITHUB_USERNAME') password = os.environ.get('GITHUB_PASSWORD') if not username or not password: print "Could not find Github username and password from the environment variables GITHUB_USERNAME and GITHUB_PASSWORD" sys.exit(1) self.gh = login(username, password) self.repo = self.gh.repository( 'SalesforceFoundation', 'CumulusCI', ) def __call__(self, branch): # Since the head parameter doesn't seem to work in the Github pulls API, # loop through the open PR's and compare the actual head ref. Otherwise, # this whole script could have been done with a simple curl command :/ for pull in self.repo.iter_pulls(state='open', base='master'): if pull.head.ref == branch: return pull if __name__ == "__main__": parser = argparse.ArgumentParser(description='Check if a branch has an open pull request in Github') parser.add_argument('branch', type=str, help='The branch name to check') args = parser.parse_args() has_open_pull = HasOpenPull() pr = has_open_pull(args.branch) if pr: print "#{}".format(pr.number)
7862dbc54ecbe274f36b5142defd0547537bd7cd
tests/test_01_create_index.py
tests/test_01_create_index.py
"""Create an image index. """ import os.path import shutil import filecmp import pytest import photo.index from conftest import tmpdir, gettestdata testimgs = [ "dsc_4623.jpg", "dsc_4664.jpg", "dsc_4831.jpg", "dsc_5126.jpg", "dsc_5167.jpg" ] testimgfiles = [ gettestdata(i) for i in testimgs ] refindex = gettestdata("index-create.yaml") @pytest.fixture(scope="module") def imgdir(tmpdir): for fname in testimgfiles: shutil.copy(fname, tmpdir) return tmpdir def test_create(imgdir): """Create a new index adding all images in the imgdir. """ idx = photo.index.Index(imgdir=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference" def test_read(imgdir): """Read the index file and write it out again. """ idx = photo.index.Index(idxfile=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference"
"""Create an image index. """ import os.path import shutil import filecmp import pytest import photo.index from conftest import tmpdir, gettestdata testimgs = [ "dsc_4623.jpg", "dsc_4664.jpg", "dsc_4831.jpg", "dsc_5126.jpg", "dsc_5167.jpg" ] testimgfiles = [ gettestdata(i) for i in testimgs ] refindex = gettestdata("index-create.yaml") @pytest.fixture(scope="module") def imgdir(tmpdir): for fname in testimgfiles: shutil.copy(fname, tmpdir) return tmpdir def test_create_curdir(imgdir, monkeypatch): """Create a new index in the current directory adding all images. """ monkeypatch.chdir(imgdir) idx = photo.index.Index(imgdir=".") idx.write() idxfile = ".index.yaml" assert filecmp.cmp(refindex, idxfile), "index file differs from reference" def test_create(imgdir): """Create a new index adding all images in the imgdir. """ idx = photo.index.Index(imgdir=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference" def test_read(imgdir): """Read the index file and write it out again. """ idx = photo.index.Index(idxfile=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference"
Add another test creating the index in the current working directory.
Add another test creating the index in the current working directory.
Python
apache-2.0
RKrahl/photo-tools
"""Create an image index. """ import os.path import shutil import filecmp import pytest import photo.index from conftest import tmpdir, gettestdata testimgs = [ "dsc_4623.jpg", "dsc_4664.jpg", "dsc_4831.jpg", "dsc_5126.jpg", "dsc_5167.jpg" ] testimgfiles = [ gettestdata(i) for i in testimgs ] refindex = gettestdata("index-create.yaml") @pytest.fixture(scope="module") def imgdir(tmpdir): for fname in testimgfiles: shutil.copy(fname, tmpdir) return tmpdir def test_create(imgdir): """Create a new index adding all images in the imgdir. """ idx = photo.index.Index(imgdir=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference" def test_read(imgdir): """Read the index file and write it out again. """ idx = photo.index.Index(idxfile=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference" Add another test creating the index in the current working directory.
"""Create an image index. """ import os.path import shutil import filecmp import pytest import photo.index from conftest import tmpdir, gettestdata testimgs = [ "dsc_4623.jpg", "dsc_4664.jpg", "dsc_4831.jpg", "dsc_5126.jpg", "dsc_5167.jpg" ] testimgfiles = [ gettestdata(i) for i in testimgs ] refindex = gettestdata("index-create.yaml") @pytest.fixture(scope="module") def imgdir(tmpdir): for fname in testimgfiles: shutil.copy(fname, tmpdir) return tmpdir def test_create_curdir(imgdir, monkeypatch): """Create a new index in the current directory adding all images. """ monkeypatch.chdir(imgdir) idx = photo.index.Index(imgdir=".") idx.write() idxfile = ".index.yaml" assert filecmp.cmp(refindex, idxfile), "index file differs from reference" def test_create(imgdir): """Create a new index adding all images in the imgdir. """ idx = photo.index.Index(imgdir=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference" def test_read(imgdir): """Read the index file and write it out again. """ idx = photo.index.Index(idxfile=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference"
<commit_before>"""Create an image index. """ import os.path import shutil import filecmp import pytest import photo.index from conftest import tmpdir, gettestdata testimgs = [ "dsc_4623.jpg", "dsc_4664.jpg", "dsc_4831.jpg", "dsc_5126.jpg", "dsc_5167.jpg" ] testimgfiles = [ gettestdata(i) for i in testimgs ] refindex = gettestdata("index-create.yaml") @pytest.fixture(scope="module") def imgdir(tmpdir): for fname in testimgfiles: shutil.copy(fname, tmpdir) return tmpdir def test_create(imgdir): """Create a new index adding all images in the imgdir. """ idx = photo.index.Index(imgdir=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference" def test_read(imgdir): """Read the index file and write it out again. """ idx = photo.index.Index(idxfile=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference" <commit_msg>Add another test creating the index in the current working directory.<commit_after>
"""Create an image index. """ import os.path import shutil import filecmp import pytest import photo.index from conftest import tmpdir, gettestdata testimgs = [ "dsc_4623.jpg", "dsc_4664.jpg", "dsc_4831.jpg", "dsc_5126.jpg", "dsc_5167.jpg" ] testimgfiles = [ gettestdata(i) for i in testimgs ] refindex = gettestdata("index-create.yaml") @pytest.fixture(scope="module") def imgdir(tmpdir): for fname in testimgfiles: shutil.copy(fname, tmpdir) return tmpdir def test_create_curdir(imgdir, monkeypatch): """Create a new index in the current directory adding all images. """ monkeypatch.chdir(imgdir) idx = photo.index.Index(imgdir=".") idx.write() idxfile = ".index.yaml" assert filecmp.cmp(refindex, idxfile), "index file differs from reference" def test_create(imgdir): """Create a new index adding all images in the imgdir. """ idx = photo.index.Index(imgdir=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference" def test_read(imgdir): """Read the index file and write it out again. """ idx = photo.index.Index(idxfile=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference"
"""Create an image index. """ import os.path import shutil import filecmp import pytest import photo.index from conftest import tmpdir, gettestdata testimgs = [ "dsc_4623.jpg", "dsc_4664.jpg", "dsc_4831.jpg", "dsc_5126.jpg", "dsc_5167.jpg" ] testimgfiles = [ gettestdata(i) for i in testimgs ] refindex = gettestdata("index-create.yaml") @pytest.fixture(scope="module") def imgdir(tmpdir): for fname in testimgfiles: shutil.copy(fname, tmpdir) return tmpdir def test_create(imgdir): """Create a new index adding all images in the imgdir. """ idx = photo.index.Index(imgdir=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference" def test_read(imgdir): """Read the index file and write it out again. """ idx = photo.index.Index(idxfile=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference" Add another test creating the index in the current working directory."""Create an image index. """ import os.path import shutil import filecmp import pytest import photo.index from conftest import tmpdir, gettestdata testimgs = [ "dsc_4623.jpg", "dsc_4664.jpg", "dsc_4831.jpg", "dsc_5126.jpg", "dsc_5167.jpg" ] testimgfiles = [ gettestdata(i) for i in testimgs ] refindex = gettestdata("index-create.yaml") @pytest.fixture(scope="module") def imgdir(tmpdir): for fname in testimgfiles: shutil.copy(fname, tmpdir) return tmpdir def test_create_curdir(imgdir, monkeypatch): """Create a new index in the current directory adding all images. """ monkeypatch.chdir(imgdir) idx = photo.index.Index(imgdir=".") idx.write() idxfile = ".index.yaml" assert filecmp.cmp(refindex, idxfile), "index file differs from reference" def test_create(imgdir): """Create a new index adding all images in the imgdir. """ idx = photo.index.Index(imgdir=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference" def test_read(imgdir): """Read the index file and write it out again. """ idx = photo.index.Index(idxfile=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference"
<commit_before>"""Create an image index. """ import os.path import shutil import filecmp import pytest import photo.index from conftest import tmpdir, gettestdata testimgs = [ "dsc_4623.jpg", "dsc_4664.jpg", "dsc_4831.jpg", "dsc_5126.jpg", "dsc_5167.jpg" ] testimgfiles = [ gettestdata(i) for i in testimgs ] refindex = gettestdata("index-create.yaml") @pytest.fixture(scope="module") def imgdir(tmpdir): for fname in testimgfiles: shutil.copy(fname, tmpdir) return tmpdir def test_create(imgdir): """Create a new index adding all images in the imgdir. """ idx = photo.index.Index(imgdir=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference" def test_read(imgdir): """Read the index file and write it out again. """ idx = photo.index.Index(idxfile=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference" <commit_msg>Add another test creating the index in the current working directory.<commit_after>"""Create an image index. """ import os.path import shutil import filecmp import pytest import photo.index from conftest import tmpdir, gettestdata testimgs = [ "dsc_4623.jpg", "dsc_4664.jpg", "dsc_4831.jpg", "dsc_5126.jpg", "dsc_5167.jpg" ] testimgfiles = [ gettestdata(i) for i in testimgs ] refindex = gettestdata("index-create.yaml") @pytest.fixture(scope="module") def imgdir(tmpdir): for fname in testimgfiles: shutil.copy(fname, tmpdir) return tmpdir def test_create_curdir(imgdir, monkeypatch): """Create a new index in the current directory adding all images. """ monkeypatch.chdir(imgdir) idx = photo.index.Index(imgdir=".") idx.write() idxfile = ".index.yaml" assert filecmp.cmp(refindex, idxfile), "index file differs from reference" def test_create(imgdir): """Create a new index adding all images in the imgdir. """ idx = photo.index.Index(imgdir=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference" def test_read(imgdir): """Read the index file and write it out again. """ idx = photo.index.Index(idxfile=imgdir) idx.write() idxfile = os.path.join(imgdir, ".index.yaml") assert filecmp.cmp(refindex, idxfile), "index file differs from reference"
cc841cc1020ca4df6f303fbb05e497a7c69c92f0
akvo/rsr/migrations/0087_auto_20161110_0920.py
akvo/rsr/migrations/0087_auto_20161110_0920.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def fix_employment_groups(apps, schema_editor): # We can't import the Employment or Group model directly as it may be a # newer version than this migration expects. We use the historical version. Group = apps.get_model("auth", "Group") Employment = apps.get_model("rsr", "Employment") for employment in Employment.objects.filter(group=None): employment.group = Group.objects.get(name='Users') employment.save() class Migration(migrations.Migration): dependencies = [ ('rsr', '0086_auto_20160921_0947'), ] operations = [ migrations.RunPython(fix_employment_groups), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def fix_employment_groups(apps, schema_editor): # We can't import the Employment or Group model directly as it may be a # newer version than this migration expects. We use the historical version. Group = apps.get_model("auth", "Group") Employment = apps.get_model("rsr", "Employment") for employment in Employment.objects.filter(group=None): try: employment.group = Group.objects.get(name='Users') employment.save() except Exception as e: print(e) class Migration(migrations.Migration): dependencies = [ ('rsr', '0086_auto_20160921_0947'), ] operations = [ migrations.RunPython(fix_employment_groups), ]
Fix broken migration with try-except blocks
Fix broken migration with try-except blocks Duplicate key errors were being caused if an employment similar to the one being created by the migration already existed.
Python
agpl-3.0
akvo/akvo-rsr,akvo/akvo-rsr,akvo/akvo-rsr,akvo/akvo-rsr
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def fix_employment_groups(apps, schema_editor): # We can't import the Employment or Group model directly as it may be a # newer version than this migration expects. We use the historical version. Group = apps.get_model("auth", "Group") Employment = apps.get_model("rsr", "Employment") for employment in Employment.objects.filter(group=None): employment.group = Group.objects.get(name='Users') employment.save() class Migration(migrations.Migration): dependencies = [ ('rsr', '0086_auto_20160921_0947'), ] operations = [ migrations.RunPython(fix_employment_groups), ] Fix broken migration with try-except blocks Duplicate key errors were being caused if an employment similar to the one being created by the migration already existed.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def fix_employment_groups(apps, schema_editor): # We can't import the Employment or Group model directly as it may be a # newer version than this migration expects. We use the historical version. Group = apps.get_model("auth", "Group") Employment = apps.get_model("rsr", "Employment") for employment in Employment.objects.filter(group=None): try: employment.group = Group.objects.get(name='Users') employment.save() except Exception as e: print(e) class Migration(migrations.Migration): dependencies = [ ('rsr', '0086_auto_20160921_0947'), ] operations = [ migrations.RunPython(fix_employment_groups), ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def fix_employment_groups(apps, schema_editor): # We can't import the Employment or Group model directly as it may be a # newer version than this migration expects. We use the historical version. Group = apps.get_model("auth", "Group") Employment = apps.get_model("rsr", "Employment") for employment in Employment.objects.filter(group=None): employment.group = Group.objects.get(name='Users') employment.save() class Migration(migrations.Migration): dependencies = [ ('rsr', '0086_auto_20160921_0947'), ] operations = [ migrations.RunPython(fix_employment_groups), ] <commit_msg>Fix broken migration with try-except blocks Duplicate key errors were being caused if an employment similar to the one being created by the migration already existed.<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def fix_employment_groups(apps, schema_editor): # We can't import the Employment or Group model directly as it may be a # newer version than this migration expects. We use the historical version. Group = apps.get_model("auth", "Group") Employment = apps.get_model("rsr", "Employment") for employment in Employment.objects.filter(group=None): try: employment.group = Group.objects.get(name='Users') employment.save() except Exception as e: print(e) class Migration(migrations.Migration): dependencies = [ ('rsr', '0086_auto_20160921_0947'), ] operations = [ migrations.RunPython(fix_employment_groups), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def fix_employment_groups(apps, schema_editor): # We can't import the Employment or Group model directly as it may be a # newer version than this migration expects. We use the historical version. Group = apps.get_model("auth", "Group") Employment = apps.get_model("rsr", "Employment") for employment in Employment.objects.filter(group=None): employment.group = Group.objects.get(name='Users') employment.save() class Migration(migrations.Migration): dependencies = [ ('rsr', '0086_auto_20160921_0947'), ] operations = [ migrations.RunPython(fix_employment_groups), ] Fix broken migration with try-except blocks Duplicate key errors were being caused if an employment similar to the one being created by the migration already existed.# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def fix_employment_groups(apps, schema_editor): # We can't import the Employment or Group model directly as it may be a # newer version than this migration expects. We use the historical version. Group = apps.get_model("auth", "Group") Employment = apps.get_model("rsr", "Employment") for employment in Employment.objects.filter(group=None): try: employment.group = Group.objects.get(name='Users') employment.save() except Exception as e: print(e) class Migration(migrations.Migration): dependencies = [ ('rsr', '0086_auto_20160921_0947'), ] operations = [ migrations.RunPython(fix_employment_groups), ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def fix_employment_groups(apps, schema_editor): # We can't import the Employment or Group model directly as it may be a # newer version than this migration expects. We use the historical version. Group = apps.get_model("auth", "Group") Employment = apps.get_model("rsr", "Employment") for employment in Employment.objects.filter(group=None): employment.group = Group.objects.get(name='Users') employment.save() class Migration(migrations.Migration): dependencies = [ ('rsr', '0086_auto_20160921_0947'), ] operations = [ migrations.RunPython(fix_employment_groups), ] <commit_msg>Fix broken migration with try-except blocks Duplicate key errors were being caused if an employment similar to the one being created by the migration already existed.<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def fix_employment_groups(apps, schema_editor): # We can't import the Employment or Group model directly as it may be a # newer version than this migration expects. We use the historical version. Group = apps.get_model("auth", "Group") Employment = apps.get_model("rsr", "Employment") for employment in Employment.objects.filter(group=None): try: employment.group = Group.objects.get(name='Users') employment.save() except Exception as e: print(e) class Migration(migrations.Migration): dependencies = [ ('rsr', '0086_auto_20160921_0947'), ] operations = [ migrations.RunPython(fix_employment_groups), ]
9715c55bdc5827ee399f02559c30bd053368dc8a
billjobs/tests/tests_user_admin_api.py
billjobs/tests/tests_user_admin_api.py
from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ fixtures=['account_test.yaml'] def setUp(self): self.client = APIClient() self.factory = APIRequestFactory() self.admin = User.objects.get(pk=1) def test_admin_list_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_admin_retrieve_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdminDetail.as_view() response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK)
from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ fixtures=['account_test.yaml'] def setUp(self): self.client = APIClient() self.factory = APIRequestFactory() self.admin = User.objects.get(pk=1) def test_admin_list_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_admin_retrieve_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdminDetail.as_view() response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_anonymous_do_not_list_user(self): request = self.factory.get('/billjobs/users/') view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
Test anonymous user do not access user list endpoint
Test anonymous user do not access user list endpoint
Python
mit
ioO/billjobs
from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ fixtures=['account_test.yaml'] def setUp(self): self.client = APIClient() self.factory = APIRequestFactory() self.admin = User.objects.get(pk=1) def test_admin_list_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_admin_retrieve_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdminDetail.as_view() response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK) Test anonymous user do not access user list endpoint
from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ fixtures=['account_test.yaml'] def setUp(self): self.client = APIClient() self.factory = APIRequestFactory() self.admin = User.objects.get(pk=1) def test_admin_list_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_admin_retrieve_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdminDetail.as_view() response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_anonymous_do_not_list_user(self): request = self.factory.get('/billjobs/users/') view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
<commit_before>from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ fixtures=['account_test.yaml'] def setUp(self): self.client = APIClient() self.factory = APIRequestFactory() self.admin = User.objects.get(pk=1) def test_admin_list_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_admin_retrieve_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdminDetail.as_view() response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK) <commit_msg>Test anonymous user do not access user list endpoint<commit_after>
from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ fixtures=['account_test.yaml'] def setUp(self): self.client = APIClient() self.factory = APIRequestFactory() self.admin = User.objects.get(pk=1) def test_admin_list_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_admin_retrieve_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdminDetail.as_view() response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_anonymous_do_not_list_user(self): request = self.factory.get('/billjobs/users/') view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ fixtures=['account_test.yaml'] def setUp(self): self.client = APIClient() self.factory = APIRequestFactory() self.admin = User.objects.get(pk=1) def test_admin_list_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_admin_retrieve_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdminDetail.as_view() response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK) Test anonymous user do not access user list endpointfrom django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ fixtures=['account_test.yaml'] def setUp(self): self.client = APIClient() self.factory = APIRequestFactory() self.admin = User.objects.get(pk=1) def test_admin_list_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_admin_retrieve_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdminDetail.as_view() response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_anonymous_do_not_list_user(self): request = self.factory.get('/billjobs/users/') view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
<commit_before>from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ fixtures=['account_test.yaml'] def setUp(self): self.client = APIClient() self.factory = APIRequestFactory() self.admin = User.objects.get(pk=1) def test_admin_list_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_admin_retrieve_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdminDetail.as_view() response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK) <commit_msg>Test anonymous user do not access user list endpoint<commit_after>from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ fixtures=['account_test.yaml'] def setUp(self): self.client = APIClient() self.factory = APIRequestFactory() self.admin = User.objects.get(pk=1) def test_admin_list_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_admin_retrieve_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdminDetail.as_view() response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_anonymous_do_not_list_user(self): request = self.factory.get('/billjobs/users/') view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
25ba377b7254ed770360bb1ee5a6ef6cb631f564
openedx/stanford/djangoapps/register_cme/admin.py
openedx/stanford/djangoapps/register_cme/admin.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import ExtraInfo class ExtraInfoAdmin(admin.ModelAdmin): """ Admin interface for ExtraInfo model. """ readonly_fields = ( 'user', ) class Meta(object): model = ExtraInfo admin.site.register(ExtraInfo, ExtraInfoAdmin)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import ExtraInfo class ExtraInfoAdmin(admin.ModelAdmin): """ Admin interface for ExtraInfo model. """ list_display = ( 'user', 'get_email', 'last_name', 'first_name', ) readonly_fields = ( 'user', ) search_fields = ( 'user__username', 'user__email', 'last_name', 'first_name', ) def get_email(self, obj): return obj.user.email get_email.short_description = 'Email address' class Meta(object): model = ExtraInfo admin.site.register(ExtraInfo, ExtraInfoAdmin)
Make ExtraInfo list user-friendly in Django Admin
Make ExtraInfo list user-friendly in Django Admin `Register_cme/extrainfo` in Django Admin was previously displaying users as `ExtraInfo` objects which admins had to click on individually to see each user's information. Each user is now displayed with fields: username, email, last and first name. Username is clickable to view more information. Added search bar enables search for users matching query for username, email, last and first name.
Python
agpl-3.0
Stanford-Online/edx-platform,caesar2164/edx-platform,caesar2164/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform,caesar2164/edx-platform,Stanford-Online/edx-platform,caesar2164/edx-platform
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import ExtraInfo class ExtraInfoAdmin(admin.ModelAdmin): """ Admin interface for ExtraInfo model. """ readonly_fields = ( 'user', ) class Meta(object): model = ExtraInfo admin.site.register(ExtraInfo, ExtraInfoAdmin) Make ExtraInfo list user-friendly in Django Admin `Register_cme/extrainfo` in Django Admin was previously displaying users as `ExtraInfo` objects which admins had to click on individually to see each user's information. Each user is now displayed with fields: username, email, last and first name. Username is clickable to view more information. Added search bar enables search for users matching query for username, email, last and first name.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import ExtraInfo class ExtraInfoAdmin(admin.ModelAdmin): """ Admin interface for ExtraInfo model. """ list_display = ( 'user', 'get_email', 'last_name', 'first_name', ) readonly_fields = ( 'user', ) search_fields = ( 'user__username', 'user__email', 'last_name', 'first_name', ) def get_email(self, obj): return obj.user.email get_email.short_description = 'Email address' class Meta(object): model = ExtraInfo admin.site.register(ExtraInfo, ExtraInfoAdmin)
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import ExtraInfo class ExtraInfoAdmin(admin.ModelAdmin): """ Admin interface for ExtraInfo model. """ readonly_fields = ( 'user', ) class Meta(object): model = ExtraInfo admin.site.register(ExtraInfo, ExtraInfoAdmin) <commit_msg>Make ExtraInfo list user-friendly in Django Admin `Register_cme/extrainfo` in Django Admin was previously displaying users as `ExtraInfo` objects which admins had to click on individually to see each user's information. Each user is now displayed with fields: username, email, last and first name. Username is clickable to view more information. Added search bar enables search for users matching query for username, email, last and first name.<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import ExtraInfo class ExtraInfoAdmin(admin.ModelAdmin): """ Admin interface for ExtraInfo model. """ list_display = ( 'user', 'get_email', 'last_name', 'first_name', ) readonly_fields = ( 'user', ) search_fields = ( 'user__username', 'user__email', 'last_name', 'first_name', ) def get_email(self, obj): return obj.user.email get_email.short_description = 'Email address' class Meta(object): model = ExtraInfo admin.site.register(ExtraInfo, ExtraInfoAdmin)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import ExtraInfo class ExtraInfoAdmin(admin.ModelAdmin): """ Admin interface for ExtraInfo model. """ readonly_fields = ( 'user', ) class Meta(object): model = ExtraInfo admin.site.register(ExtraInfo, ExtraInfoAdmin) Make ExtraInfo list user-friendly in Django Admin `Register_cme/extrainfo` in Django Admin was previously displaying users as `ExtraInfo` objects which admins had to click on individually to see each user's information. Each user is now displayed with fields: username, email, last and first name. Username is clickable to view more information. Added search bar enables search for users matching query for username, email, last and first name.# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import ExtraInfo class ExtraInfoAdmin(admin.ModelAdmin): """ Admin interface for ExtraInfo model. """ list_display = ( 'user', 'get_email', 'last_name', 'first_name', ) readonly_fields = ( 'user', ) search_fields = ( 'user__username', 'user__email', 'last_name', 'first_name', ) def get_email(self, obj): return obj.user.email get_email.short_description = 'Email address' class Meta(object): model = ExtraInfo admin.site.register(ExtraInfo, ExtraInfoAdmin)
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import ExtraInfo class ExtraInfoAdmin(admin.ModelAdmin): """ Admin interface for ExtraInfo model. """ readonly_fields = ( 'user', ) class Meta(object): model = ExtraInfo admin.site.register(ExtraInfo, ExtraInfoAdmin) <commit_msg>Make ExtraInfo list user-friendly in Django Admin `Register_cme/extrainfo` in Django Admin was previously displaying users as `ExtraInfo` objects which admins had to click on individually to see each user's information. Each user is now displayed with fields: username, email, last and first name. Username is clickable to view more information. Added search bar enables search for users matching query for username, email, last and first name.<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import ExtraInfo class ExtraInfoAdmin(admin.ModelAdmin): """ Admin interface for ExtraInfo model. """ list_display = ( 'user', 'get_email', 'last_name', 'first_name', ) readonly_fields = ( 'user', ) search_fields = ( 'user__username', 'user__email', 'last_name', 'first_name', ) def get_email(self, obj): return obj.user.email get_email.short_description = 'Email address' class Meta(object): model = ExtraInfo admin.site.register(ExtraInfo, ExtraInfoAdmin)
627a0dddbfe4982c4079b8ba49a55d7de53eeb11
runtests.py
runtests.py
#!/usr/bin/env python import os import sys from django.conf import settings import django DEFAULT_SETTINGS = { 'INSTALLED_APPS': ( 'django.contrib.gis', 'spillway', 'tests', ), 'DATABASES': { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': ':memory:' } }, } def runtests(): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) # Compatibility with Django 1.7's stricter initialization if hasattr(django, 'setup'): django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) try: from django.test.runner import DiscoverRunner runner_class = DiscoverRunner except ImportError: from django.test.simple import DjangoTestSuiteRunner runner_class = DjangoTestSuiteRunner failures = runner_class( verbosity=1, interactive=True, failfast=False).run_tests(['tests']) sys.exit(failures) if __name__ == '__main__': runtests()
#!/usr/bin/env python import os import sys import shutil import tempfile from django.conf import settings import django TMPDIR = tempfile.mkdtemp(prefix='spillway_') DEFAULT_SETTINGS = { 'INSTALLED_APPS': ( 'django.contrib.gis', 'spillway', 'tests', ), 'DATABASES': { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': ':memory:' } }, 'MEDIA_ROOT': TMPDIR } def teardown(): try: shutil.rmtree(TMPDIR) except OSError: print('Failed to remove {}'.format(TMPDIR)) def runtests(): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) # Compatibility with Django 1.7's stricter initialization if hasattr(django, 'setup'): django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) try: from django.test.runner import DiscoverRunner runner_class = DiscoverRunner except ImportError: from django.test.simple import DjangoTestSuiteRunner runner_class = DjangoTestSuiteRunner failures = runner_class( verbosity=1, interactive=True, failfast=False).run_tests(['tests']) teardown() sys.exit(failures) if __name__ == '__main__': runtests()
Use media root temp dir for tests
Use media root temp dir for tests
Python
bsd-3-clause
barseghyanartur/django-spillway,kuzmich/django-spillway,bkg/django-spillway
#!/usr/bin/env python import os import sys from django.conf import settings import django DEFAULT_SETTINGS = { 'INSTALLED_APPS': ( 'django.contrib.gis', 'spillway', 'tests', ), 'DATABASES': { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': ':memory:' } }, } def runtests(): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) # Compatibility with Django 1.7's stricter initialization if hasattr(django, 'setup'): django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) try: from django.test.runner import DiscoverRunner runner_class = DiscoverRunner except ImportError: from django.test.simple import DjangoTestSuiteRunner runner_class = DjangoTestSuiteRunner failures = runner_class( verbosity=1, interactive=True, failfast=False).run_tests(['tests']) sys.exit(failures) if __name__ == '__main__': runtests() Use media root temp dir for tests
#!/usr/bin/env python import os import sys import shutil import tempfile from django.conf import settings import django TMPDIR = tempfile.mkdtemp(prefix='spillway_') DEFAULT_SETTINGS = { 'INSTALLED_APPS': ( 'django.contrib.gis', 'spillway', 'tests', ), 'DATABASES': { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': ':memory:' } }, 'MEDIA_ROOT': TMPDIR } def teardown(): try: shutil.rmtree(TMPDIR) except OSError: print('Failed to remove {}'.format(TMPDIR)) def runtests(): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) # Compatibility with Django 1.7's stricter initialization if hasattr(django, 'setup'): django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) try: from django.test.runner import DiscoverRunner runner_class = DiscoverRunner except ImportError: from django.test.simple import DjangoTestSuiteRunner runner_class = DjangoTestSuiteRunner failures = runner_class( verbosity=1, interactive=True, failfast=False).run_tests(['tests']) teardown() sys.exit(failures) if __name__ == '__main__': runtests()
<commit_before>#!/usr/bin/env python import os import sys from django.conf import settings import django DEFAULT_SETTINGS = { 'INSTALLED_APPS': ( 'django.contrib.gis', 'spillway', 'tests', ), 'DATABASES': { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': ':memory:' } }, } def runtests(): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) # Compatibility with Django 1.7's stricter initialization if hasattr(django, 'setup'): django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) try: from django.test.runner import DiscoverRunner runner_class = DiscoverRunner except ImportError: from django.test.simple import DjangoTestSuiteRunner runner_class = DjangoTestSuiteRunner failures = runner_class( verbosity=1, interactive=True, failfast=False).run_tests(['tests']) sys.exit(failures) if __name__ == '__main__': runtests() <commit_msg>Use media root temp dir for tests<commit_after>
#!/usr/bin/env python import os import sys import shutil import tempfile from django.conf import settings import django TMPDIR = tempfile.mkdtemp(prefix='spillway_') DEFAULT_SETTINGS = { 'INSTALLED_APPS': ( 'django.contrib.gis', 'spillway', 'tests', ), 'DATABASES': { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': ':memory:' } }, 'MEDIA_ROOT': TMPDIR } def teardown(): try: shutil.rmtree(TMPDIR) except OSError: print('Failed to remove {}'.format(TMPDIR)) def runtests(): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) # Compatibility with Django 1.7's stricter initialization if hasattr(django, 'setup'): django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) try: from django.test.runner import DiscoverRunner runner_class = DiscoverRunner except ImportError: from django.test.simple import DjangoTestSuiteRunner runner_class = DjangoTestSuiteRunner failures = runner_class( verbosity=1, interactive=True, failfast=False).run_tests(['tests']) teardown() sys.exit(failures) if __name__ == '__main__': runtests()
#!/usr/bin/env python import os import sys from django.conf import settings import django DEFAULT_SETTINGS = { 'INSTALLED_APPS': ( 'django.contrib.gis', 'spillway', 'tests', ), 'DATABASES': { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': ':memory:' } }, } def runtests(): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) # Compatibility with Django 1.7's stricter initialization if hasattr(django, 'setup'): django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) try: from django.test.runner import DiscoverRunner runner_class = DiscoverRunner except ImportError: from django.test.simple import DjangoTestSuiteRunner runner_class = DjangoTestSuiteRunner failures = runner_class( verbosity=1, interactive=True, failfast=False).run_tests(['tests']) sys.exit(failures) if __name__ == '__main__': runtests() Use media root temp dir for tests#!/usr/bin/env python import os import sys import shutil import tempfile from django.conf import settings import django TMPDIR = tempfile.mkdtemp(prefix='spillway_') DEFAULT_SETTINGS = { 'INSTALLED_APPS': ( 'django.contrib.gis', 'spillway', 'tests', ), 'DATABASES': { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': ':memory:' } }, 'MEDIA_ROOT': TMPDIR } def teardown(): try: shutil.rmtree(TMPDIR) except OSError: print('Failed to remove {}'.format(TMPDIR)) def runtests(): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) # Compatibility with Django 1.7's stricter initialization if hasattr(django, 'setup'): django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) try: from django.test.runner import DiscoverRunner runner_class = DiscoverRunner except ImportError: from django.test.simple import DjangoTestSuiteRunner runner_class = DjangoTestSuiteRunner failures = runner_class( verbosity=1, interactive=True, failfast=False).run_tests(['tests']) teardown() sys.exit(failures) if __name__ == '__main__': runtests()
<commit_before>#!/usr/bin/env python import os import sys from django.conf import settings import django DEFAULT_SETTINGS = { 'INSTALLED_APPS': ( 'django.contrib.gis', 'spillway', 'tests', ), 'DATABASES': { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': ':memory:' } }, } def runtests(): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) # Compatibility with Django 1.7's stricter initialization if hasattr(django, 'setup'): django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) try: from django.test.runner import DiscoverRunner runner_class = DiscoverRunner except ImportError: from django.test.simple import DjangoTestSuiteRunner runner_class = DjangoTestSuiteRunner failures = runner_class( verbosity=1, interactive=True, failfast=False).run_tests(['tests']) sys.exit(failures) if __name__ == '__main__': runtests() <commit_msg>Use media root temp dir for tests<commit_after>#!/usr/bin/env python import os import sys import shutil import tempfile from django.conf import settings import django TMPDIR = tempfile.mkdtemp(prefix='spillway_') DEFAULT_SETTINGS = { 'INSTALLED_APPS': ( 'django.contrib.gis', 'spillway', 'tests', ), 'DATABASES': { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': ':memory:' } }, 'MEDIA_ROOT': TMPDIR } def teardown(): try: shutil.rmtree(TMPDIR) except OSError: print('Failed to remove {}'.format(TMPDIR)) def runtests(): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) # Compatibility with Django 1.7's stricter initialization if hasattr(django, 'setup'): django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) try: from django.test.runner import DiscoverRunner runner_class = DiscoverRunner except ImportError: from django.test.simple import DjangoTestSuiteRunner runner_class = DjangoTestSuiteRunner failures = runner_class( verbosity=1, interactive=True, failfast=False).run_tests(['tests']) teardown() sys.exit(failures) if __name__ == '__main__': runtests()
171d088c070742cfac3127f479eb2ad89a8b6b9c
test/win/gyptest-link-pdb.py
test/win/gyptest-link-pdb.py
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the 'Profile' attribute in VCLinker is extracted properly. """ import TestGyp import os import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'linker-flags' test.run_gyp('program-database.gyp', chdir=CHDIR) test.build('program-database.gyp', test.ALL, chdir=CHDIR) def FindFile(pdb): full_path = test.built_file_path(pdb, chdir=CHDIR) return os.path.isfile(full_path) # Verify the specified PDB is created when ProgramDatabaseFile # is provided. if not FindFile('name_set.pdb'): test.fail_test() else: test.pass_test()
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the 'Profile' attribute in VCLinker is extracted properly. """ import TestGyp import os import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'linker-flags' test.run_gyp('program-database.gyp', chdir=CHDIR) test.build('program-database.gyp', test.ALL, chdir=CHDIR) def FindFile(pdb): full_path = test.built_file_path(pdb, chdir=CHDIR) return os.path.isfile(full_path) # Verify the specified PDB is created when ProgramDatabaseFile # is provided. if not FindFile('name_set.pdb'): test.fail_test() else: test.pass_test()
Insert empty line at to fix patch.
Insert empty line at to fix patch. gyptest-link-pdb.py was checked in without a blank line. This appears to cause a patch issue with the try bots. This CL is only a whitespace change to attempt to fix that problem. SEE: patching file test/win/gyptest-link-pdb.py Hunk #1 FAILED at 26. 1 out of 1 hunk FAILED -- saving rejects to file test/win/gyptest-link-pdb.py.rej =================================================================== --- test/win/gyptest-link-pdb.py (revision 1530) +++ test/win/gyptest-link-pdb.py (working copy) @@ -26,7 +26,9 @@ # Verify the specified PDB is created when ProgramDatabaseFile # is provided. - if not FindFile('name_set.pdb'): + if not FindFile('name_outdir.pdb'): test.fail_test() - else: - test.pass_test() \ No newline at end of file + if not FindFile('name_proddir.pdb'): + test.fail_test() + + test.pass_test() Index: test/win/linker-flags/program-database.gyp TBR=bradnelson@chromium.org Review URL: https://codereview.chromium.org/11368061 git-svn-id: e7e1075985beda50ea81ac4472467b4f6e91fc78@1531 78cadc50-ecff-11dd-a971-7dbc132099af
Python
bsd-3-clause
omasanori/gyp,svn2github/gyp,sanyaade-teachings/gyp,android-ia/platform_external_chromium_org_tools_gyp,bnq4ever/gypgoogle,MIPS/external-chromium_org-tools-gyp,lukeweber/gyp-override,chromium/gyp,sloanyang/gyp,svn2github/kgyp,ttyangf/pdfium_gyp,cysp/gyp,dougbeal/gyp,mapbox/gyp,cchamberlain/gyp,erikge/watch_gyp,clar/gyp,pandaxcl/gyp,sloanyang/gyp,adblockplus/gyp,mkrautz/gyp-libmumble,AOSPU/external_chromium_org_tools_gyp,android-ia/platform_external_chromium_org_tools_gyp,brson/gyp,duanhjlt/gyp,android-ia/platform_external_chromium_org_tools_gyp,erikge/watch_gyp,IllusionRom-deprecated/android_platform_external_chromium_org_tools_gyp,MIPS/external-chromium_org-tools-gyp,sanyaade-teachings/gyp,cysp/gyp,sport-monkey/GYP,AWhetter/gyp,sdklite/gyp,luvit/gyp,dougbeal/gyp,pyokagan/gyp,ttyangf/gyp,geekboxzone/lollipop_external_chromium_org_tools_gyp,clar/gyp,bdarnell/gyp,channing/gyp,bnoordhuis/gyp,channing/gyp,turbulenz/gyp,chromium/gyp,ttyangf/pdfium_gyp,yinquan529/platform-external-chromium_org-tools-gyp,ttyangf/gyp,yjhjstz/gyp,msc-/gyp,msc-/gyp,svn2github/kgyp,omasanori/gyp,bpsinc-native/src_tools_gyp,IllusionRom-deprecated/android_platform_external_chromium_org_tools_gyp,sloanyang/gyp,Chilledheart/gyp,ryfx/gyp,Danath/gyp,enkripsi/gyp,clar/gyp,svn2github/kgyp,amoikevin/gyp,svn2github/kgyp,springmeyer/gyp,Danath/gyp,channing/gyp,Jack-Q/GYP-copy,lukeweber/gyp-override,bpsinc-native/src_tools_gyp,sanyaade-teachings/gyp,bnoordhuis/gyp,yangrongwei/gyp,cchamberlain/gyp,Danath/gyp,brson/gyp,bulldy80/gyp_unofficial,AWhetter/gyp,tarc/gyp,LazyCodingCat/gyp,yinquan529/platform-external-chromium_org-tools-gyp,mistydemeo/gyp,mgamer/gyp,adblockplus/gyp,android-ia/platform_external_chromium_org_tools_gyp,bdarnell/gyp,yjhjstz/gyp,brson/gyp,trafi/gyp,dougbeal/gyp,svn2github/gyp,sloanyang/gyp,yangrongwei/gyp,AWhetter/gyp,svn2github/gyp,bnoordhuis/gyp,turbulenz/gyp,adblockplus/gyp,alexcrichton/gyp,yjhjstz/gyp,AOSPU/external_chromium_org_tools_gyp,bulldy80/gyp_unofficial,springmeyer/gyp,saghul/gyn,enkripsi/gyp,bnq4ever/gypgoogle,Phuehvk/gyp,cysp/gyp,bdarnell/gyp,dougbeal/gyp,duanhjlt/gyp,duanhjlt/gyp,Chilledheart/gyp,cysp/gyp,Danath/gyp,erikge/watch_gyp,kevinchen3315/gyp-git,Phuehvk/gyp,mistydemeo/gyp,springmeyer/gyp,Jack-Q/GYP-copy,carlTLR/gyp,mapbox/gyp,carlTLR/gyp,azunite/gyp,yjhjstz/gyp,bpsinc-native/src_tools_gyp,mkrautz/gyp-libmumble,mumble-voip/libmumble-gyp,mistydemeo/gyp,springmeyer/gyp,adblockplus/gyp,openpeer/webrtc-gyp,sport-monkey/GYP,sport-monkey/GYP,brson/gyp,yinquan529/platform-external-chromium_org-tools-gyp,LazyCodingCat/gyp,mgamer/gyp,pandaxcl/gyp,Phuehvk/gyp,duanhjlt/gyp,ryfx/gyp,kevinchen3315/gyp-git,trafi/gyp,Jack-Q/GYP-copy,pyokagan/gyp,saghul/gyn,duanhjlt/gyp,pandaxcl/gyp,bnoordhuis/gyp,mgamer/gyp,azunite/gyp,xin3liang/platform_external_chromium_org_tools_gyp,erikge/watch_gyp,AWhetter/gyp,pandaxcl/gyp,sdklite/gyp,bnq4ever/gypgoogle,cchamberlain/gyp,yinquan529/platform-external-chromium_org-tools-gyp,omasanori/gyp,sdklite/gyp,turbulenz/gyp,LazyCodingCat/gyp,channing/gyp,alexcrichton/gyp,geekboxzone/lollipop_external_chromium_org_tools_gyp,azunite/gyp,ttyangf/gyp,cysp/gyp,pyokagan/gyp,svn2github/gyp,bulldy80/gyp_unofficial,msc-/gyp,ryfx/gyp,ttyangf/pdfium_gyp,saghul/gyn,omasanori/gyp,amoikevin/gyp,azunite/gyp_20150930,mumble-voip/libmumble-gyp,sdklite/gyp,tarc/gyp,luvit/gyp,ryfx/gyp,chromium/gyp,Chilledheart/gyp,svn2github/gyp,amoikevin/gyp,alexcrichton/gyp,azunite/gyp_20150930,mapbox/gyp,AOSPU/external_chromium_org_tools_gyp,erikge/watch_gyp,sdklite/gyp,okwasi/gyp,bpsinc-native/src_tools_gyp,pandaxcl/gyp,bnq4ever/gypgoogle,tarc/gyp,openpeer/webrtc-gyp,chromium/gyp,azunite/gyp,kevinchen3315/gyp-git,saghul/gyn,Omegaphora/external_chromium_org_tools_gyp,yangrongwei/gyp,enkripsi/gyp,alexcrichton/gyp,azunite/gyp_20150930,msc-/gyp,okwasi/gyp,IllusionRom-deprecated/android_platform_external_chromium_org_tools_gyp,okumura/gyp,Danath/gyp,clar/gyp,ttyangf/pdfium_gyp,MIPS/external-chromium_org-tools-gyp,okumura/gyp,cchamberlain/gyp,bnoordhuis/gyp,IllusionRom-deprecated/android_platform_external_chromium_org_tools_gyp,kevinchen3315/gyp-git,turbulenz/gyp,sanyaade-teachings/gyp,mapbox/gyp,mumble-voip/libmumble-gyp,Jack-Q/GYP-copy,pyokagan/gyp,springmeyer/gyp,xin3liang/platform_external_chromium_org_tools_gyp,amoikevin/gyp,Jack-Q/GYP-copy,okwasi/gyp,luvit/gyp,ttyangf/gyp,ryfx/gyp,openpeer/webrtc-gyp,carlTLR/gyp,tarc/gyp,bdarnell/gyp,bnq4ever/gypgoogle,okwasi/gyp,bulldy80/gyp_unofficial,cchamberlain/gyp,yangrongwei/gyp,luvit/gyp,Chilledheart/gyp,svn2github/kgyp,Phuehvk/gyp,AWhetter/gyp,LazyCodingCat/gyp,xin3liang/platform_external_chromium_org_tools_gyp,ttyangf/gyp,geekboxzone/lollipop_external_chromium_org_tools_gyp,geekboxzone/lollipop_external_chromium_org_tools_gyp,lukeweber/gyp-override,mapbox/gyp,clar/gyp,mistydemeo/gyp,msc-/gyp,sport-monkey/GYP,Omegaphora/external_chromium_org_tools_gyp,dougbeal/gyp,openpeer/webrtc-gyp,sport-monkey/GYP,LazyCodingCat/gyp,mumble-voip/libmumble-gyp,openpeer/webrtc-gyp,carlTLR/gyp,Phuehvk/gyp,saghul/gyn,enkripsi/gyp,mkrautz/gyp-libmumble,trafi/gyp,Omegaphora/external_chromium_org_tools_gyp,azunite/gyp,Omegaphora/external_chromium_org_tools_gyp,lukeweber/gyp-override,pyokagan/gyp,adblockplus/gyp,mgamer/gyp,turbulenz/gyp,azunite/gyp_20150930,AOSPU/external_chromium_org_tools_gyp,sanyaade-teachings/gyp,azunite/gyp_20150930,tarc/gyp,yjhjstz/gyp,amoikevin/gyp,okumura/gyp,MIPS/external-chromium_org-tools-gyp,okumura/gyp,bulldy80/gyp_unofficial,trafi/gyp,mgamer/gyp,mkrautz/gyp-libmumble,xin3liang/platform_external_chromium_org_tools_gyp,ttyangf/pdfium_gyp,trafi/gyp,enkripsi/gyp,Chilledheart/gyp,chromium/gyp,carlTLR/gyp
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the 'Profile' attribute in VCLinker is extracted properly. """ import TestGyp import os import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'linker-flags' test.run_gyp('program-database.gyp', chdir=CHDIR) test.build('program-database.gyp', test.ALL, chdir=CHDIR) def FindFile(pdb): full_path = test.built_file_path(pdb, chdir=CHDIR) return os.path.isfile(full_path) # Verify the specified PDB is created when ProgramDatabaseFile # is provided. if not FindFile('name_set.pdb'): test.fail_test() else: test.pass_test()Insert empty line at to fix patch. gyptest-link-pdb.py was checked in without a blank line. This appears to cause a patch issue with the try bots. This CL is only a whitespace change to attempt to fix that problem. SEE: patching file test/win/gyptest-link-pdb.py Hunk #1 FAILED at 26. 1 out of 1 hunk FAILED -- saving rejects to file test/win/gyptest-link-pdb.py.rej =================================================================== --- test/win/gyptest-link-pdb.py (revision 1530) +++ test/win/gyptest-link-pdb.py (working copy) @@ -26,7 +26,9 @@ # Verify the specified PDB is created when ProgramDatabaseFile # is provided. - if not FindFile('name_set.pdb'): + if not FindFile('name_outdir.pdb'): test.fail_test() - else: - test.pass_test() \ No newline at end of file + if not FindFile('name_proddir.pdb'): + test.fail_test() + + test.pass_test() Index: test/win/linker-flags/program-database.gyp TBR=bradnelson@chromium.org Review URL: https://codereview.chromium.org/11368061 git-svn-id: e7e1075985beda50ea81ac4472467b4f6e91fc78@1531 78cadc50-ecff-11dd-a971-7dbc132099af
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the 'Profile' attribute in VCLinker is extracted properly. """ import TestGyp import os import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'linker-flags' test.run_gyp('program-database.gyp', chdir=CHDIR) test.build('program-database.gyp', test.ALL, chdir=CHDIR) def FindFile(pdb): full_path = test.built_file_path(pdb, chdir=CHDIR) return os.path.isfile(full_path) # Verify the specified PDB is created when ProgramDatabaseFile # is provided. if not FindFile('name_set.pdb'): test.fail_test() else: test.pass_test()
<commit_before>#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the 'Profile' attribute in VCLinker is extracted properly. """ import TestGyp import os import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'linker-flags' test.run_gyp('program-database.gyp', chdir=CHDIR) test.build('program-database.gyp', test.ALL, chdir=CHDIR) def FindFile(pdb): full_path = test.built_file_path(pdb, chdir=CHDIR) return os.path.isfile(full_path) # Verify the specified PDB is created when ProgramDatabaseFile # is provided. if not FindFile('name_set.pdb'): test.fail_test() else: test.pass_test()<commit_msg>Insert empty line at to fix patch. gyptest-link-pdb.py was checked in without a blank line. This appears to cause a patch issue with the try bots. This CL is only a whitespace change to attempt to fix that problem. SEE: patching file test/win/gyptest-link-pdb.py Hunk #1 FAILED at 26. 1 out of 1 hunk FAILED -- saving rejects to file test/win/gyptest-link-pdb.py.rej =================================================================== --- test/win/gyptest-link-pdb.py (revision 1530) +++ test/win/gyptest-link-pdb.py (working copy) @@ -26,7 +26,9 @@ # Verify the specified PDB is created when ProgramDatabaseFile # is provided. - if not FindFile('name_set.pdb'): + if not FindFile('name_outdir.pdb'): test.fail_test() - else: - test.pass_test() \ No newline at end of file + if not FindFile('name_proddir.pdb'): + test.fail_test() + + test.pass_test() Index: test/win/linker-flags/program-database.gyp TBR=bradnelson@chromium.org Review URL: https://codereview.chromium.org/11368061 git-svn-id: e7e1075985beda50ea81ac4472467b4f6e91fc78@1531 78cadc50-ecff-11dd-a971-7dbc132099af<commit_after>
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the 'Profile' attribute in VCLinker is extracted properly. """ import TestGyp import os import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'linker-flags' test.run_gyp('program-database.gyp', chdir=CHDIR) test.build('program-database.gyp', test.ALL, chdir=CHDIR) def FindFile(pdb): full_path = test.built_file_path(pdb, chdir=CHDIR) return os.path.isfile(full_path) # Verify the specified PDB is created when ProgramDatabaseFile # is provided. if not FindFile('name_set.pdb'): test.fail_test() else: test.pass_test()
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the 'Profile' attribute in VCLinker is extracted properly. """ import TestGyp import os import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'linker-flags' test.run_gyp('program-database.gyp', chdir=CHDIR) test.build('program-database.gyp', test.ALL, chdir=CHDIR) def FindFile(pdb): full_path = test.built_file_path(pdb, chdir=CHDIR) return os.path.isfile(full_path) # Verify the specified PDB is created when ProgramDatabaseFile # is provided. if not FindFile('name_set.pdb'): test.fail_test() else: test.pass_test()Insert empty line at to fix patch. gyptest-link-pdb.py was checked in without a blank line. This appears to cause a patch issue with the try bots. This CL is only a whitespace change to attempt to fix that problem. SEE: patching file test/win/gyptest-link-pdb.py Hunk #1 FAILED at 26. 1 out of 1 hunk FAILED -- saving rejects to file test/win/gyptest-link-pdb.py.rej =================================================================== --- test/win/gyptest-link-pdb.py (revision 1530) +++ test/win/gyptest-link-pdb.py (working copy) @@ -26,7 +26,9 @@ # Verify the specified PDB is created when ProgramDatabaseFile # is provided. - if not FindFile('name_set.pdb'): + if not FindFile('name_outdir.pdb'): test.fail_test() - else: - test.pass_test() \ No newline at end of file + if not FindFile('name_proddir.pdb'): + test.fail_test() + + test.pass_test() Index: test/win/linker-flags/program-database.gyp TBR=bradnelson@chromium.org Review URL: https://codereview.chromium.org/11368061 git-svn-id: e7e1075985beda50ea81ac4472467b4f6e91fc78@1531 78cadc50-ecff-11dd-a971-7dbc132099af#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the 'Profile' attribute in VCLinker is extracted properly. """ import TestGyp import os import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'linker-flags' test.run_gyp('program-database.gyp', chdir=CHDIR) test.build('program-database.gyp', test.ALL, chdir=CHDIR) def FindFile(pdb): full_path = test.built_file_path(pdb, chdir=CHDIR) return os.path.isfile(full_path) # Verify the specified PDB is created when ProgramDatabaseFile # is provided. if not FindFile('name_set.pdb'): test.fail_test() else: test.pass_test()
<commit_before>#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the 'Profile' attribute in VCLinker is extracted properly. """ import TestGyp import os import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'linker-flags' test.run_gyp('program-database.gyp', chdir=CHDIR) test.build('program-database.gyp', test.ALL, chdir=CHDIR) def FindFile(pdb): full_path = test.built_file_path(pdb, chdir=CHDIR) return os.path.isfile(full_path) # Verify the specified PDB is created when ProgramDatabaseFile # is provided. if not FindFile('name_set.pdb'): test.fail_test() else: test.pass_test()<commit_msg>Insert empty line at to fix patch. gyptest-link-pdb.py was checked in without a blank line. This appears to cause a patch issue with the try bots. This CL is only a whitespace change to attempt to fix that problem. SEE: patching file test/win/gyptest-link-pdb.py Hunk #1 FAILED at 26. 1 out of 1 hunk FAILED -- saving rejects to file test/win/gyptest-link-pdb.py.rej =================================================================== --- test/win/gyptest-link-pdb.py (revision 1530) +++ test/win/gyptest-link-pdb.py (working copy) @@ -26,7 +26,9 @@ # Verify the specified PDB is created when ProgramDatabaseFile # is provided. - if not FindFile('name_set.pdb'): + if not FindFile('name_outdir.pdb'): test.fail_test() - else: - test.pass_test() \ No newline at end of file + if not FindFile('name_proddir.pdb'): + test.fail_test() + + test.pass_test() Index: test/win/linker-flags/program-database.gyp TBR=bradnelson@chromium.org Review URL: https://codereview.chromium.org/11368061 git-svn-id: e7e1075985beda50ea81ac4472467b4f6e91fc78@1531 78cadc50-ecff-11dd-a971-7dbc132099af<commit_after>#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the 'Profile' attribute in VCLinker is extracted properly. """ import TestGyp import os import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'linker-flags' test.run_gyp('program-database.gyp', chdir=CHDIR) test.build('program-database.gyp', test.ALL, chdir=CHDIR) def FindFile(pdb): full_path = test.built_file_path(pdb, chdir=CHDIR) return os.path.isfile(full_path) # Verify the specified PDB is created when ProgramDatabaseFile # is provided. if not FindFile('name_set.pdb'): test.fail_test() else: test.pass_test()
98c0ccec77cc6f1657c21acb3cdc07b483a9a178
proselint/checks/writegood/lexical_illusions.py
proselint/checks/writegood/lexical_illusions.py
"""WGD200: Lexical illusions. --- layout: post error_code: WGD200 source: write-good source_url: https://github.com/btford/write-good title: Lexical illusion present date: 2014-06-10 12:31:19 categories: writing --- A lexical illusion happens when a word word is unintentiall repeated twice, and and this happens most often between line breaks. """ from proselint.tools import existence_check, memoize @memoize def check(text): """Check the text.""" err = "WGD105" msg = u"There's a lexical illusion here: a word is repeated." commercialese = [ "the\sthe", "is\sis" ] return existence_check(text, commercialese, err, msg)
"""WGD200: Lexical illusions. --- layout: post error_code: WGD200 source: write-good source_url: https://github.com/btford/write-good title: Lexical illusion present date: 2014-06-10 12:31:19 categories: writing --- A lexical illusion happens when a word word is unintentiall repeated twice, and and this happens most often between line breaks. """ from proselint.tools import existence_check, memoize @memoize def check(text): """Check the text.""" err = "WGD105" msg = u"There's a lexical illusion here: a word is repeated." commercialese = [ "the\sthe", ] return existence_check(text, commercialese, err, msg)
Remove "is is" from lexical illusions
Remove "is is" from lexical illusions
Python
bsd-3-clause
jstewmon/proselint,jstewmon/proselint,amperser/proselint,jstewmon/proselint,amperser/proselint,amperser/proselint,amperser/proselint,amperser/proselint
"""WGD200: Lexical illusions. --- layout: post error_code: WGD200 source: write-good source_url: https://github.com/btford/write-good title: Lexical illusion present date: 2014-06-10 12:31:19 categories: writing --- A lexical illusion happens when a word word is unintentiall repeated twice, and and this happens most often between line breaks. """ from proselint.tools import existence_check, memoize @memoize def check(text): """Check the text.""" err = "WGD105" msg = u"There's a lexical illusion here: a word is repeated." commercialese = [ "the\sthe", "is\sis" ] return existence_check(text, commercialese, err, msg) Remove "is is" from lexical illusions
"""WGD200: Lexical illusions. --- layout: post error_code: WGD200 source: write-good source_url: https://github.com/btford/write-good title: Lexical illusion present date: 2014-06-10 12:31:19 categories: writing --- A lexical illusion happens when a word word is unintentiall repeated twice, and and this happens most often between line breaks. """ from proselint.tools import existence_check, memoize @memoize def check(text): """Check the text.""" err = "WGD105" msg = u"There's a lexical illusion here: a word is repeated." commercialese = [ "the\sthe", ] return existence_check(text, commercialese, err, msg)
<commit_before>"""WGD200: Lexical illusions. --- layout: post error_code: WGD200 source: write-good source_url: https://github.com/btford/write-good title: Lexical illusion present date: 2014-06-10 12:31:19 categories: writing --- A lexical illusion happens when a word word is unintentiall repeated twice, and and this happens most often between line breaks. """ from proselint.tools import existence_check, memoize @memoize def check(text): """Check the text.""" err = "WGD105" msg = u"There's a lexical illusion here: a word is repeated." commercialese = [ "the\sthe", "is\sis" ] return existence_check(text, commercialese, err, msg) <commit_msg>Remove "is is" from lexical illusions<commit_after>
"""WGD200: Lexical illusions. --- layout: post error_code: WGD200 source: write-good source_url: https://github.com/btford/write-good title: Lexical illusion present date: 2014-06-10 12:31:19 categories: writing --- A lexical illusion happens when a word word is unintentiall repeated twice, and and this happens most often between line breaks. """ from proselint.tools import existence_check, memoize @memoize def check(text): """Check the text.""" err = "WGD105" msg = u"There's a lexical illusion here: a word is repeated." commercialese = [ "the\sthe", ] return existence_check(text, commercialese, err, msg)
"""WGD200: Lexical illusions. --- layout: post error_code: WGD200 source: write-good source_url: https://github.com/btford/write-good title: Lexical illusion present date: 2014-06-10 12:31:19 categories: writing --- A lexical illusion happens when a word word is unintentiall repeated twice, and and this happens most often between line breaks. """ from proselint.tools import existence_check, memoize @memoize def check(text): """Check the text.""" err = "WGD105" msg = u"There's a lexical illusion here: a word is repeated." commercialese = [ "the\sthe", "is\sis" ] return existence_check(text, commercialese, err, msg) Remove "is is" from lexical illusions"""WGD200: Lexical illusions. --- layout: post error_code: WGD200 source: write-good source_url: https://github.com/btford/write-good title: Lexical illusion present date: 2014-06-10 12:31:19 categories: writing --- A lexical illusion happens when a word word is unintentiall repeated twice, and and this happens most often between line breaks. """ from proselint.tools import existence_check, memoize @memoize def check(text): """Check the text.""" err = "WGD105" msg = u"There's a lexical illusion here: a word is repeated." commercialese = [ "the\sthe", ] return existence_check(text, commercialese, err, msg)
<commit_before>"""WGD200: Lexical illusions. --- layout: post error_code: WGD200 source: write-good source_url: https://github.com/btford/write-good title: Lexical illusion present date: 2014-06-10 12:31:19 categories: writing --- A lexical illusion happens when a word word is unintentiall repeated twice, and and this happens most often between line breaks. """ from proselint.tools import existence_check, memoize @memoize def check(text): """Check the text.""" err = "WGD105" msg = u"There's a lexical illusion here: a word is repeated." commercialese = [ "the\sthe", "is\sis" ] return existence_check(text, commercialese, err, msg) <commit_msg>Remove "is is" from lexical illusions<commit_after>"""WGD200: Lexical illusions. --- layout: post error_code: WGD200 source: write-good source_url: https://github.com/btford/write-good title: Lexical illusion present date: 2014-06-10 12:31:19 categories: writing --- A lexical illusion happens when a word word is unintentiall repeated twice, and and this happens most often between line breaks. """ from proselint.tools import existence_check, memoize @memoize def check(text): """Check the text.""" err = "WGD105" msg = u"There's a lexical illusion here: a word is repeated." commercialese = [ "the\sthe", ] return existence_check(text, commercialese, err, msg)
9cdf31681eff6509e9191a244bf9398e32996fdf
byceps/services/news/models/channel.py
byceps/services/news/models/channel.py
""" byceps.services.news.models.channel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ....database import db from ....typing import BrandID from ....util.instances import ReprBuilder from ..transfer.models import ChannelID class Channel(db.Model): """A channel to which news items can be published.""" __tablename__ = 'news_channels' id = db.Column(db.Unicode(40), primary_key=True) brand_id = db.Column(db.Unicode(20), db.ForeignKey('brands.id'), index=True, nullable=False) url_prefix = db.Column(db.Text, nullable=False) def __init__(self, channel_id: ChannelID, brand_id: BrandID, url_prefix: str) -> None: self.id = channel_id self.brand_id = brand_id self.url_prefix = url_prefix def __repr__(self) -> str: return ReprBuilder(self) \ .add_with_lookup('id') \ .add('brand', self.brand_id) \ .build()
""" byceps.services.news.models.channel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ....database import db from ....typing import BrandID from ....util.instances import ReprBuilder from ..transfer.models import ChannelID class Channel(db.Model): """A channel to which news items can be published.""" __tablename__ = 'news_channels' id = db.Column(db.Unicode(40), primary_key=True) brand_id = db.Column(db.Unicode(20), db.ForeignKey('brands.id'), index=True, nullable=False) url_prefix = db.Column(db.UnicodeText, nullable=False) def __init__(self, channel_id: ChannelID, brand_id: BrandID, url_prefix: str) -> None: self.id = channel_id self.brand_id = brand_id self.url_prefix = url_prefix def __repr__(self) -> str: return ReprBuilder(self) \ .add_with_lookup('id') \ .add('brand', self.brand_id) \ .build()
Use `UnicodeText` instead of `Text` to ensure a unicode-capable column type is used in the backend
Use `UnicodeText` instead of `Text` to ensure a unicode-capable column type is used in the backend
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps
""" byceps.services.news.models.channel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ....database import db from ....typing import BrandID from ....util.instances import ReprBuilder from ..transfer.models import ChannelID class Channel(db.Model): """A channel to which news items can be published.""" __tablename__ = 'news_channels' id = db.Column(db.Unicode(40), primary_key=True) brand_id = db.Column(db.Unicode(20), db.ForeignKey('brands.id'), index=True, nullable=False) url_prefix = db.Column(db.Text, nullable=False) def __init__(self, channel_id: ChannelID, brand_id: BrandID, url_prefix: str) -> None: self.id = channel_id self.brand_id = brand_id self.url_prefix = url_prefix def __repr__(self) -> str: return ReprBuilder(self) \ .add_with_lookup('id') \ .add('brand', self.brand_id) \ .build() Use `UnicodeText` instead of `Text` to ensure a unicode-capable column type is used in the backend
""" byceps.services.news.models.channel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ....database import db from ....typing import BrandID from ....util.instances import ReprBuilder from ..transfer.models import ChannelID class Channel(db.Model): """A channel to which news items can be published.""" __tablename__ = 'news_channels' id = db.Column(db.Unicode(40), primary_key=True) brand_id = db.Column(db.Unicode(20), db.ForeignKey('brands.id'), index=True, nullable=False) url_prefix = db.Column(db.UnicodeText, nullable=False) def __init__(self, channel_id: ChannelID, brand_id: BrandID, url_prefix: str) -> None: self.id = channel_id self.brand_id = brand_id self.url_prefix = url_prefix def __repr__(self) -> str: return ReprBuilder(self) \ .add_with_lookup('id') \ .add('brand', self.brand_id) \ .build()
<commit_before>""" byceps.services.news.models.channel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ....database import db from ....typing import BrandID from ....util.instances import ReprBuilder from ..transfer.models import ChannelID class Channel(db.Model): """A channel to which news items can be published.""" __tablename__ = 'news_channels' id = db.Column(db.Unicode(40), primary_key=True) brand_id = db.Column(db.Unicode(20), db.ForeignKey('brands.id'), index=True, nullable=False) url_prefix = db.Column(db.Text, nullable=False) def __init__(self, channel_id: ChannelID, brand_id: BrandID, url_prefix: str) -> None: self.id = channel_id self.brand_id = brand_id self.url_prefix = url_prefix def __repr__(self) -> str: return ReprBuilder(self) \ .add_with_lookup('id') \ .add('brand', self.brand_id) \ .build() <commit_msg>Use `UnicodeText` instead of `Text` to ensure a unicode-capable column type is used in the backend<commit_after>
""" byceps.services.news.models.channel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ....database import db from ....typing import BrandID from ....util.instances import ReprBuilder from ..transfer.models import ChannelID class Channel(db.Model): """A channel to which news items can be published.""" __tablename__ = 'news_channels' id = db.Column(db.Unicode(40), primary_key=True) brand_id = db.Column(db.Unicode(20), db.ForeignKey('brands.id'), index=True, nullable=False) url_prefix = db.Column(db.UnicodeText, nullable=False) def __init__(self, channel_id: ChannelID, brand_id: BrandID, url_prefix: str) -> None: self.id = channel_id self.brand_id = brand_id self.url_prefix = url_prefix def __repr__(self) -> str: return ReprBuilder(self) \ .add_with_lookup('id') \ .add('brand', self.brand_id) \ .build()
""" byceps.services.news.models.channel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ....database import db from ....typing import BrandID from ....util.instances import ReprBuilder from ..transfer.models import ChannelID class Channel(db.Model): """A channel to which news items can be published.""" __tablename__ = 'news_channels' id = db.Column(db.Unicode(40), primary_key=True) brand_id = db.Column(db.Unicode(20), db.ForeignKey('brands.id'), index=True, nullable=False) url_prefix = db.Column(db.Text, nullable=False) def __init__(self, channel_id: ChannelID, brand_id: BrandID, url_prefix: str) -> None: self.id = channel_id self.brand_id = brand_id self.url_prefix = url_prefix def __repr__(self) -> str: return ReprBuilder(self) \ .add_with_lookup('id') \ .add('brand', self.brand_id) \ .build() Use `UnicodeText` instead of `Text` to ensure a unicode-capable column type is used in the backend""" byceps.services.news.models.channel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ....database import db from ....typing import BrandID from ....util.instances import ReprBuilder from ..transfer.models import ChannelID class Channel(db.Model): """A channel to which news items can be published.""" __tablename__ = 'news_channels' id = db.Column(db.Unicode(40), primary_key=True) brand_id = db.Column(db.Unicode(20), db.ForeignKey('brands.id'), index=True, nullable=False) url_prefix = db.Column(db.UnicodeText, nullable=False) def __init__(self, channel_id: ChannelID, brand_id: BrandID, url_prefix: str) -> None: self.id = channel_id self.brand_id = brand_id self.url_prefix = url_prefix def __repr__(self) -> str: return ReprBuilder(self) \ .add_with_lookup('id') \ .add('brand', self.brand_id) \ .build()
<commit_before>""" byceps.services.news.models.channel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ....database import db from ....typing import BrandID from ....util.instances import ReprBuilder from ..transfer.models import ChannelID class Channel(db.Model): """A channel to which news items can be published.""" __tablename__ = 'news_channels' id = db.Column(db.Unicode(40), primary_key=True) brand_id = db.Column(db.Unicode(20), db.ForeignKey('brands.id'), index=True, nullable=False) url_prefix = db.Column(db.Text, nullable=False) def __init__(self, channel_id: ChannelID, brand_id: BrandID, url_prefix: str) -> None: self.id = channel_id self.brand_id = brand_id self.url_prefix = url_prefix def __repr__(self) -> str: return ReprBuilder(self) \ .add_with_lookup('id') \ .add('brand', self.brand_id) \ .build() <commit_msg>Use `UnicodeText` instead of `Text` to ensure a unicode-capable column type is used in the backend<commit_after>""" byceps.services.news.models.channel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ....database import db from ....typing import BrandID from ....util.instances import ReprBuilder from ..transfer.models import ChannelID class Channel(db.Model): """A channel to which news items can be published.""" __tablename__ = 'news_channels' id = db.Column(db.Unicode(40), primary_key=True) brand_id = db.Column(db.Unicode(20), db.ForeignKey('brands.id'), index=True, nullable=False) url_prefix = db.Column(db.UnicodeText, nullable=False) def __init__(self, channel_id: ChannelID, brand_id: BrandID, url_prefix: str) -> None: self.id = channel_id self.brand_id = brand_id self.url_prefix = url_prefix def __repr__(self) -> str: return ReprBuilder(self) \ .add_with_lookup('id') \ .add('brand', self.brand_id) \ .build()
4710db78a5904ed381755cdf55a48ef4b3541619
python/python2/simplerandom/iterators/__init__.py
python/python2/simplerandom/iterators/__init__.py
""" Simple Pseudo-random number generators. This module provides iterators that generate unsigned 32-bit PRNs. """ __all__ = [ "RandomCongIterator", "RandomSHR3Iterator", "RandomMWCIterator", "RandomMWC64Iterator", "RandomKISSIterator", "RandomKISS2Iterator", "RandomLFIB4Iterator", "RandomSWBIterator", "RandomFibIterator", ] try: from simplerandom.iterators._iterators_cython import * _using_extension = True except ImportError: from simplerandom.iterators._iterators_py import * _using_extension = False
""" Simple Pseudo-random number generators. This module provides iterators that generate unsigned 32-bit PRNs. """ __all__ = [ "RandomCongIterator", "RandomSHR3Iterator", "RandomMWCIterator", "RandomMWC64Iterator", "RandomKISSIterator", "RandomKISS2Iterator", "RandomLFIB4Iterator", "RandomSWBIterator", "RandomFibIterator", "RandomLFSR113Iterator", ] try: from simplerandom.iterators._iterators_cython import * _using_extension = True except ImportError: from simplerandom.iterators._iterators_py import * _using_extension = False
Add LFSR113 to init file.
Add LFSR113 to init file.
Python
mit
cmcqueen/simplerandom,cmcqueen/simplerandom,cmcqueen/simplerandom,cmcqueen/simplerandom,cmcqueen/simplerandom
""" Simple Pseudo-random number generators. This module provides iterators that generate unsigned 32-bit PRNs. """ __all__ = [ "RandomCongIterator", "RandomSHR3Iterator", "RandomMWCIterator", "RandomMWC64Iterator", "RandomKISSIterator", "RandomKISS2Iterator", "RandomLFIB4Iterator", "RandomSWBIterator", "RandomFibIterator", ] try: from simplerandom.iterators._iterators_cython import * _using_extension = True except ImportError: from simplerandom.iterators._iterators_py import * _using_extension = False Add LFSR113 to init file.
""" Simple Pseudo-random number generators. This module provides iterators that generate unsigned 32-bit PRNs. """ __all__ = [ "RandomCongIterator", "RandomSHR3Iterator", "RandomMWCIterator", "RandomMWC64Iterator", "RandomKISSIterator", "RandomKISS2Iterator", "RandomLFIB4Iterator", "RandomSWBIterator", "RandomFibIterator", "RandomLFSR113Iterator", ] try: from simplerandom.iterators._iterators_cython import * _using_extension = True except ImportError: from simplerandom.iterators._iterators_py import * _using_extension = False
<commit_before>""" Simple Pseudo-random number generators. This module provides iterators that generate unsigned 32-bit PRNs. """ __all__ = [ "RandomCongIterator", "RandomSHR3Iterator", "RandomMWCIterator", "RandomMWC64Iterator", "RandomKISSIterator", "RandomKISS2Iterator", "RandomLFIB4Iterator", "RandomSWBIterator", "RandomFibIterator", ] try: from simplerandom.iterators._iterators_cython import * _using_extension = True except ImportError: from simplerandom.iterators._iterators_py import * _using_extension = False <commit_msg>Add LFSR113 to init file.<commit_after>
""" Simple Pseudo-random number generators. This module provides iterators that generate unsigned 32-bit PRNs. """ __all__ = [ "RandomCongIterator", "RandomSHR3Iterator", "RandomMWCIterator", "RandomMWC64Iterator", "RandomKISSIterator", "RandomKISS2Iterator", "RandomLFIB4Iterator", "RandomSWBIterator", "RandomFibIterator", "RandomLFSR113Iterator", ] try: from simplerandom.iterators._iterators_cython import * _using_extension = True except ImportError: from simplerandom.iterators._iterators_py import * _using_extension = False
""" Simple Pseudo-random number generators. This module provides iterators that generate unsigned 32-bit PRNs. """ __all__ = [ "RandomCongIterator", "RandomSHR3Iterator", "RandomMWCIterator", "RandomMWC64Iterator", "RandomKISSIterator", "RandomKISS2Iterator", "RandomLFIB4Iterator", "RandomSWBIterator", "RandomFibIterator", ] try: from simplerandom.iterators._iterators_cython import * _using_extension = True except ImportError: from simplerandom.iterators._iterators_py import * _using_extension = False Add LFSR113 to init file.""" Simple Pseudo-random number generators. This module provides iterators that generate unsigned 32-bit PRNs. """ __all__ = [ "RandomCongIterator", "RandomSHR3Iterator", "RandomMWCIterator", "RandomMWC64Iterator", "RandomKISSIterator", "RandomKISS2Iterator", "RandomLFIB4Iterator", "RandomSWBIterator", "RandomFibIterator", "RandomLFSR113Iterator", ] try: from simplerandom.iterators._iterators_cython import * _using_extension = True except ImportError: from simplerandom.iterators._iterators_py import * _using_extension = False
<commit_before>""" Simple Pseudo-random number generators. This module provides iterators that generate unsigned 32-bit PRNs. """ __all__ = [ "RandomCongIterator", "RandomSHR3Iterator", "RandomMWCIterator", "RandomMWC64Iterator", "RandomKISSIterator", "RandomKISS2Iterator", "RandomLFIB4Iterator", "RandomSWBIterator", "RandomFibIterator", ] try: from simplerandom.iterators._iterators_cython import * _using_extension = True except ImportError: from simplerandom.iterators._iterators_py import * _using_extension = False <commit_msg>Add LFSR113 to init file.<commit_after>""" Simple Pseudo-random number generators. This module provides iterators that generate unsigned 32-bit PRNs. """ __all__ = [ "RandomCongIterator", "RandomSHR3Iterator", "RandomMWCIterator", "RandomMWC64Iterator", "RandomKISSIterator", "RandomKISS2Iterator", "RandomLFIB4Iterator", "RandomSWBIterator", "RandomFibIterator", "RandomLFSR113Iterator", ] try: from simplerandom.iterators._iterators_cython import * _using_extension = True except ImportError: from simplerandom.iterators._iterators_py import * _using_extension = False
84a2f2f019216ec96121159365ef4ca66f5d4e25
corehq/util/couch.py
corehq/util/couch.py
from couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() if (unwrapped.get('domain', domain) != domain or domain not in unwrapped.get('domains', [domain]) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404()
from couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() if ((unwrapped.get('domain', None) != domain and domain not in unwrapped.get('domains', [])) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404()
Handle doc without domain or domains
Handle doc without domain or domains
Python
bsd-3-clause
qedsoftware/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() if (unwrapped.get('domain', domain) != domain or domain not in unwrapped.get('domains', [domain]) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404() Handle doc without domain or domains
from couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() if ((unwrapped.get('domain', None) != domain and domain not in unwrapped.get('domains', [])) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404()
<commit_before>from couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() if (unwrapped.get('domain', domain) != domain or domain not in unwrapped.get('domains', [domain]) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404() <commit_msg>Handle doc without domain or domains<commit_after>
from couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() if ((unwrapped.get('domain', None) != domain and domain not in unwrapped.get('domains', [])) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404()
from couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() if (unwrapped.get('domain', domain) != domain or domain not in unwrapped.get('domains', [domain]) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404() Handle doc without domain or domainsfrom couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() if ((unwrapped.get('domain', None) != domain and domain not in unwrapped.get('domains', [])) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404()
<commit_before>from couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() if (unwrapped.get('domain', domain) != domain or domain not in unwrapped.get('domains', [domain]) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404() <commit_msg>Handle doc without domain or domains<commit_after>from couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() if ((unwrapped.get('domain', None) != domain and domain not in unwrapped.get('domains', [])) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404()
5188561f7de7f6762e1820a6b447f144f963b1d0
common/spaces.py
common/spaces.py
"""Digital Ocean Spaces interaction""" import boto3 from django.conf import settings class SpacesBucket(): """Interact with Spaces buckets""" def __init__(self): session = boto3.session.Session() self._client = session.client('s3', region_name='nyc3', endpoint_url='https://nyc3.digitaloceanspaces.com', aws_access_key_id=settings.SPACES_ACCESS_KEY_ID, aws_secret_access_key=settings.SPACES_ACCESS_KEY_SECRET) def create(self, name="new-space-name"): """Create a new Space""" self._client.create_bucket(Bucket=name) def list(self): """List all buckets on your account""" response = self._client.list_buckets() spaces = [space['Name'] for space in response['Buckets']] print("Spaces List: %s" % spaces)
"""Digital Ocean Spaces interaction""" import boto3 from django.conf import settings class SpacesBucket(): """Interact with Spaces buckets""" def __init__(self, space_name="lutris"): session = boto3.session.Session() self._client = session.client('s3', region_name='nyc3', endpoint_url='https://nyc3.digitaloceanspaces.com', aws_access_key_id=settings.SPACES_ACCESS_KEY_ID, aws_secret_access_key=settings.SPACES_ACCESS_KEY_SECRET) self.space_name = space_name def create(self, name="new-space-name"): """Create a new Space""" self._client.create_bucket(Bucket=name) def list_spaces(self): """List all buckets on your account""" response = self._client.list_buckets() return [space['Name'] for space in response['Buckets']] def upload(self, local_path, dest_path, public=False): """Upload a file to Spaces""" self._client.upload_file(local_path, self.space_name, dest_path) if public: self._client.put_object_acl( ACL="public-read", Bucket=self.space_name, Key=dest_path )
Add upload to Spaces API client
Add upload to Spaces API client
Python
agpl-3.0
lutris/website,lutris/website,lutris/website,lutris/website
"""Digital Ocean Spaces interaction""" import boto3 from django.conf import settings class SpacesBucket(): """Interact with Spaces buckets""" def __init__(self): session = boto3.session.Session() self._client = session.client('s3', region_name='nyc3', endpoint_url='https://nyc3.digitaloceanspaces.com', aws_access_key_id=settings.SPACES_ACCESS_KEY_ID, aws_secret_access_key=settings.SPACES_ACCESS_KEY_SECRET) def create(self, name="new-space-name"): """Create a new Space""" self._client.create_bucket(Bucket=name) def list(self): """List all buckets on your account""" response = self._client.list_buckets() spaces = [space['Name'] for space in response['Buckets']] print("Spaces List: %s" % spaces) Add upload to Spaces API client
"""Digital Ocean Spaces interaction""" import boto3 from django.conf import settings class SpacesBucket(): """Interact with Spaces buckets""" def __init__(self, space_name="lutris"): session = boto3.session.Session() self._client = session.client('s3', region_name='nyc3', endpoint_url='https://nyc3.digitaloceanspaces.com', aws_access_key_id=settings.SPACES_ACCESS_KEY_ID, aws_secret_access_key=settings.SPACES_ACCESS_KEY_SECRET) self.space_name = space_name def create(self, name="new-space-name"): """Create a new Space""" self._client.create_bucket(Bucket=name) def list_spaces(self): """List all buckets on your account""" response = self._client.list_buckets() return [space['Name'] for space in response['Buckets']] def upload(self, local_path, dest_path, public=False): """Upload a file to Spaces""" self._client.upload_file(local_path, self.space_name, dest_path) if public: self._client.put_object_acl( ACL="public-read", Bucket=self.space_name, Key=dest_path )
<commit_before>"""Digital Ocean Spaces interaction""" import boto3 from django.conf import settings class SpacesBucket(): """Interact with Spaces buckets""" def __init__(self): session = boto3.session.Session() self._client = session.client('s3', region_name='nyc3', endpoint_url='https://nyc3.digitaloceanspaces.com', aws_access_key_id=settings.SPACES_ACCESS_KEY_ID, aws_secret_access_key=settings.SPACES_ACCESS_KEY_SECRET) def create(self, name="new-space-name"): """Create a new Space""" self._client.create_bucket(Bucket=name) def list(self): """List all buckets on your account""" response = self._client.list_buckets() spaces = [space['Name'] for space in response['Buckets']] print("Spaces List: %s" % spaces) <commit_msg>Add upload to Spaces API client<commit_after>
"""Digital Ocean Spaces interaction""" import boto3 from django.conf import settings class SpacesBucket(): """Interact with Spaces buckets""" def __init__(self, space_name="lutris"): session = boto3.session.Session() self._client = session.client('s3', region_name='nyc3', endpoint_url='https://nyc3.digitaloceanspaces.com', aws_access_key_id=settings.SPACES_ACCESS_KEY_ID, aws_secret_access_key=settings.SPACES_ACCESS_KEY_SECRET) self.space_name = space_name def create(self, name="new-space-name"): """Create a new Space""" self._client.create_bucket(Bucket=name) def list_spaces(self): """List all buckets on your account""" response = self._client.list_buckets() return [space['Name'] for space in response['Buckets']] def upload(self, local_path, dest_path, public=False): """Upload a file to Spaces""" self._client.upload_file(local_path, self.space_name, dest_path) if public: self._client.put_object_acl( ACL="public-read", Bucket=self.space_name, Key=dest_path )
"""Digital Ocean Spaces interaction""" import boto3 from django.conf import settings class SpacesBucket(): """Interact with Spaces buckets""" def __init__(self): session = boto3.session.Session() self._client = session.client('s3', region_name='nyc3', endpoint_url='https://nyc3.digitaloceanspaces.com', aws_access_key_id=settings.SPACES_ACCESS_KEY_ID, aws_secret_access_key=settings.SPACES_ACCESS_KEY_SECRET) def create(self, name="new-space-name"): """Create a new Space""" self._client.create_bucket(Bucket=name) def list(self): """List all buckets on your account""" response = self._client.list_buckets() spaces = [space['Name'] for space in response['Buckets']] print("Spaces List: %s" % spaces) Add upload to Spaces API client"""Digital Ocean Spaces interaction""" import boto3 from django.conf import settings class SpacesBucket(): """Interact with Spaces buckets""" def __init__(self, space_name="lutris"): session = boto3.session.Session() self._client = session.client('s3', region_name='nyc3', endpoint_url='https://nyc3.digitaloceanspaces.com', aws_access_key_id=settings.SPACES_ACCESS_KEY_ID, aws_secret_access_key=settings.SPACES_ACCESS_KEY_SECRET) self.space_name = space_name def create(self, name="new-space-name"): """Create a new Space""" self._client.create_bucket(Bucket=name) def list_spaces(self): """List all buckets on your account""" response = self._client.list_buckets() return [space['Name'] for space in response['Buckets']] def upload(self, local_path, dest_path, public=False): """Upload a file to Spaces""" self._client.upload_file(local_path, self.space_name, dest_path) if public: self._client.put_object_acl( ACL="public-read", Bucket=self.space_name, Key=dest_path )
<commit_before>"""Digital Ocean Spaces interaction""" import boto3 from django.conf import settings class SpacesBucket(): """Interact with Spaces buckets""" def __init__(self): session = boto3.session.Session() self._client = session.client('s3', region_name='nyc3', endpoint_url='https://nyc3.digitaloceanspaces.com', aws_access_key_id=settings.SPACES_ACCESS_KEY_ID, aws_secret_access_key=settings.SPACES_ACCESS_KEY_SECRET) def create(self, name="new-space-name"): """Create a new Space""" self._client.create_bucket(Bucket=name) def list(self): """List all buckets on your account""" response = self._client.list_buckets() spaces = [space['Name'] for space in response['Buckets']] print("Spaces List: %s" % spaces) <commit_msg>Add upload to Spaces API client<commit_after>"""Digital Ocean Spaces interaction""" import boto3 from django.conf import settings class SpacesBucket(): """Interact with Spaces buckets""" def __init__(self, space_name="lutris"): session = boto3.session.Session() self._client = session.client('s3', region_name='nyc3', endpoint_url='https://nyc3.digitaloceanspaces.com', aws_access_key_id=settings.SPACES_ACCESS_KEY_ID, aws_secret_access_key=settings.SPACES_ACCESS_KEY_SECRET) self.space_name = space_name def create(self, name="new-space-name"): """Create a new Space""" self._client.create_bucket(Bucket=name) def list_spaces(self): """List all buckets on your account""" response = self._client.list_buckets() return [space['Name'] for space in response['Buckets']] def upload(self, local_path, dest_path, public=False): """Upload a file to Spaces""" self._client.upload_file(local_path, self.space_name, dest_path) if public: self._client.put_object_acl( ACL="public-read", Bucket=self.space_name, Key=dest_path )
ccf24a73870f62b25becd1e244616c758ffe2748
jacquard/service/commands.py
jacquard/service/commands.py
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=8888, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, )
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=1212, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, )
Use 1212 as the default port
Use 1212 as the default port
Python
mit
prophile/jacquard,prophile/jacquard
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=8888, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, ) Use 1212 as the default port
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=1212, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, )
<commit_before>import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=8888, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, ) <commit_msg>Use 1212 as the default port<commit_after>
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=1212, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, )
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=8888, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, ) Use 1212 as the default portimport werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=1212, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, )
<commit_before>import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=8888, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, ) <commit_msg>Use 1212 as the default port<commit_after>import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=1212, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, )
48ae2127fcd2e6b1ba1b0d2649d936991a30881b
juliet.py
juliet.py
#!/usr/bin/python3 import argparse, sys from src import Configurator, Builder, Loader def main(): """ Parse command line arguments and execute passed subcommands. """ # Parse subcommand parser = argparse.ArgumentParser(description='Pythonic static sites generator') subparsers = parser.add_subparsers(dest="sp", help="sub-command to be executed") parser_build = subparsers.add_parser('build', help="Build static site from local directory") args = parser.parse_args() # Execute passed sub-command or return error if(args.sp == "build"): build(args) def build(args): """ Build website to configured location. """ # Parse configuration and define Environment config = {} config["site"] = Configurator.getConfig() config["posts"] = Loader.getFromFolder("posts/", args) config["pages"] = Loader.getFromFolder("pages/", args) jinjaEnv = Configurator.configureJinja(config["site"]) print(config) # Build statics Builder.buildStatics(config) # Build posts and pages Builder.buildPosts(config, jinjaEnv) # Build page and pages #Builder.buildPages(config, jinjaEnv) if __name__ == "__main__": main()
#!/usr/bin/python3 import argparse, sys from src import Configurator, Builder, Loader def main(): """ Parse command line arguments and execute passed subcommands. """ # Parse subcommand parser = argparse.ArgumentParser(description='Pythonic static sites generator') subparsers = parser.add_subparsers(dest="sp", help="sub-command to be executed") parser_build = subparsers.add_parser('build', help="Build static site from local directory") args = parser.parse_args() # Execute passed sub-command or return error if(args.sp == "build"): build(args) def build(args): """ Build website to configured location. """ # Parse configuration config = {} config["site"] = Configurator.getConfig() # Load articles, pages and static elements from the files config["posts"] = Loader.getFromFolder("posts/", args) config["pages"] = Loader.getFromFolder("pages/", args) config["statics"] = Loader.getFromFolder("themes/" + config["site"]["theme"] + "/statics/", args) # Configure Jinja2 environment jinjaEnv = Configurator.configureJinja(config["site"]) print(config) # Build statics Builder.buildStatics(config) # Build posts and pages Builder.buildPosts(config, jinjaEnv) Builder.buildPages(config, jinjaEnv) if __name__ == "__main__": main()
Load statics like posts and pages. Documentation.
Load statics like posts and pages. Documentation.
Python
mit
hlef/juliet,hlef/juliet,hlef/juliet
#!/usr/bin/python3 import argparse, sys from src import Configurator, Builder, Loader def main(): """ Parse command line arguments and execute passed subcommands. """ # Parse subcommand parser = argparse.ArgumentParser(description='Pythonic static sites generator') subparsers = parser.add_subparsers(dest="sp", help="sub-command to be executed") parser_build = subparsers.add_parser('build', help="Build static site from local directory") args = parser.parse_args() # Execute passed sub-command or return error if(args.sp == "build"): build(args) def build(args): """ Build website to configured location. """ # Parse configuration and define Environment config = {} config["site"] = Configurator.getConfig() config["posts"] = Loader.getFromFolder("posts/", args) config["pages"] = Loader.getFromFolder("pages/", args) jinjaEnv = Configurator.configureJinja(config["site"]) print(config) # Build statics Builder.buildStatics(config) # Build posts and pages Builder.buildPosts(config, jinjaEnv) # Build page and pages #Builder.buildPages(config, jinjaEnv) if __name__ == "__main__": main() Load statics like posts and pages. Documentation.
#!/usr/bin/python3 import argparse, sys from src import Configurator, Builder, Loader def main(): """ Parse command line arguments and execute passed subcommands. """ # Parse subcommand parser = argparse.ArgumentParser(description='Pythonic static sites generator') subparsers = parser.add_subparsers(dest="sp", help="sub-command to be executed") parser_build = subparsers.add_parser('build', help="Build static site from local directory") args = parser.parse_args() # Execute passed sub-command or return error if(args.sp == "build"): build(args) def build(args): """ Build website to configured location. """ # Parse configuration config = {} config["site"] = Configurator.getConfig() # Load articles, pages and static elements from the files config["posts"] = Loader.getFromFolder("posts/", args) config["pages"] = Loader.getFromFolder("pages/", args) config["statics"] = Loader.getFromFolder("themes/" + config["site"]["theme"] + "/statics/", args) # Configure Jinja2 environment jinjaEnv = Configurator.configureJinja(config["site"]) print(config) # Build statics Builder.buildStatics(config) # Build posts and pages Builder.buildPosts(config, jinjaEnv) Builder.buildPages(config, jinjaEnv) if __name__ == "__main__": main()
<commit_before>#!/usr/bin/python3 import argparse, sys from src import Configurator, Builder, Loader def main(): """ Parse command line arguments and execute passed subcommands. """ # Parse subcommand parser = argparse.ArgumentParser(description='Pythonic static sites generator') subparsers = parser.add_subparsers(dest="sp", help="sub-command to be executed") parser_build = subparsers.add_parser('build', help="Build static site from local directory") args = parser.parse_args() # Execute passed sub-command or return error if(args.sp == "build"): build(args) def build(args): """ Build website to configured location. """ # Parse configuration and define Environment config = {} config["site"] = Configurator.getConfig() config["posts"] = Loader.getFromFolder("posts/", args) config["pages"] = Loader.getFromFolder("pages/", args) jinjaEnv = Configurator.configureJinja(config["site"]) print(config) # Build statics Builder.buildStatics(config) # Build posts and pages Builder.buildPosts(config, jinjaEnv) # Build page and pages #Builder.buildPages(config, jinjaEnv) if __name__ == "__main__": main() <commit_msg>Load statics like posts and pages. Documentation.<commit_after>
#!/usr/bin/python3 import argparse, sys from src import Configurator, Builder, Loader def main(): """ Parse command line arguments and execute passed subcommands. """ # Parse subcommand parser = argparse.ArgumentParser(description='Pythonic static sites generator') subparsers = parser.add_subparsers(dest="sp", help="sub-command to be executed") parser_build = subparsers.add_parser('build', help="Build static site from local directory") args = parser.parse_args() # Execute passed sub-command or return error if(args.sp == "build"): build(args) def build(args): """ Build website to configured location. """ # Parse configuration config = {} config["site"] = Configurator.getConfig() # Load articles, pages and static elements from the files config["posts"] = Loader.getFromFolder("posts/", args) config["pages"] = Loader.getFromFolder("pages/", args) config["statics"] = Loader.getFromFolder("themes/" + config["site"]["theme"] + "/statics/", args) # Configure Jinja2 environment jinjaEnv = Configurator.configureJinja(config["site"]) print(config) # Build statics Builder.buildStatics(config) # Build posts and pages Builder.buildPosts(config, jinjaEnv) Builder.buildPages(config, jinjaEnv) if __name__ == "__main__": main()
#!/usr/bin/python3 import argparse, sys from src import Configurator, Builder, Loader def main(): """ Parse command line arguments and execute passed subcommands. """ # Parse subcommand parser = argparse.ArgumentParser(description='Pythonic static sites generator') subparsers = parser.add_subparsers(dest="sp", help="sub-command to be executed") parser_build = subparsers.add_parser('build', help="Build static site from local directory") args = parser.parse_args() # Execute passed sub-command or return error if(args.sp == "build"): build(args) def build(args): """ Build website to configured location. """ # Parse configuration and define Environment config = {} config["site"] = Configurator.getConfig() config["posts"] = Loader.getFromFolder("posts/", args) config["pages"] = Loader.getFromFolder("pages/", args) jinjaEnv = Configurator.configureJinja(config["site"]) print(config) # Build statics Builder.buildStatics(config) # Build posts and pages Builder.buildPosts(config, jinjaEnv) # Build page and pages #Builder.buildPages(config, jinjaEnv) if __name__ == "__main__": main() Load statics like posts and pages. Documentation.#!/usr/bin/python3 import argparse, sys from src import Configurator, Builder, Loader def main(): """ Parse command line arguments and execute passed subcommands. """ # Parse subcommand parser = argparse.ArgumentParser(description='Pythonic static sites generator') subparsers = parser.add_subparsers(dest="sp", help="sub-command to be executed") parser_build = subparsers.add_parser('build', help="Build static site from local directory") args = parser.parse_args() # Execute passed sub-command or return error if(args.sp == "build"): build(args) def build(args): """ Build website to configured location. """ # Parse configuration config = {} config["site"] = Configurator.getConfig() # Load articles, pages and static elements from the files config["posts"] = Loader.getFromFolder("posts/", args) config["pages"] = Loader.getFromFolder("pages/", args) config["statics"] = Loader.getFromFolder("themes/" + config["site"]["theme"] + "/statics/", args) # Configure Jinja2 environment jinjaEnv = Configurator.configureJinja(config["site"]) print(config) # Build statics Builder.buildStatics(config) # Build posts and pages Builder.buildPosts(config, jinjaEnv) Builder.buildPages(config, jinjaEnv) if __name__ == "__main__": main()
<commit_before>#!/usr/bin/python3 import argparse, sys from src import Configurator, Builder, Loader def main(): """ Parse command line arguments and execute passed subcommands. """ # Parse subcommand parser = argparse.ArgumentParser(description='Pythonic static sites generator') subparsers = parser.add_subparsers(dest="sp", help="sub-command to be executed") parser_build = subparsers.add_parser('build', help="Build static site from local directory") args = parser.parse_args() # Execute passed sub-command or return error if(args.sp == "build"): build(args) def build(args): """ Build website to configured location. """ # Parse configuration and define Environment config = {} config["site"] = Configurator.getConfig() config["posts"] = Loader.getFromFolder("posts/", args) config["pages"] = Loader.getFromFolder("pages/", args) jinjaEnv = Configurator.configureJinja(config["site"]) print(config) # Build statics Builder.buildStatics(config) # Build posts and pages Builder.buildPosts(config, jinjaEnv) # Build page and pages #Builder.buildPages(config, jinjaEnv) if __name__ == "__main__": main() <commit_msg>Load statics like posts and pages. Documentation.<commit_after>#!/usr/bin/python3 import argparse, sys from src import Configurator, Builder, Loader def main(): """ Parse command line arguments and execute passed subcommands. """ # Parse subcommand parser = argparse.ArgumentParser(description='Pythonic static sites generator') subparsers = parser.add_subparsers(dest="sp", help="sub-command to be executed") parser_build = subparsers.add_parser('build', help="Build static site from local directory") args = parser.parse_args() # Execute passed sub-command or return error if(args.sp == "build"): build(args) def build(args): """ Build website to configured location. """ # Parse configuration config = {} config["site"] = Configurator.getConfig() # Load articles, pages and static elements from the files config["posts"] = Loader.getFromFolder("posts/", args) config["pages"] = Loader.getFromFolder("pages/", args) config["statics"] = Loader.getFromFolder("themes/" + config["site"]["theme"] + "/statics/", args) # Configure Jinja2 environment jinjaEnv = Configurator.configureJinja(config["site"]) print(config) # Build statics Builder.buildStatics(config) # Build posts and pages Builder.buildPosts(config, jinjaEnv) Builder.buildPages(config, jinjaEnv) if __name__ == "__main__": main()
ff80cfab47b03de5d86d82907de0f28caa7829e9
test_project/dashboards.py
test_project/dashboards.py
from controlcenter import Dashboard, widgets class EmptyDashboard(Dashboard): pass class MyWidget0(widgets.Widget): pass class MyWidget1(widgets.Widget): pass class NonEmptyDashboard(Dashboard): widgets = [ MyWidget0, widgets.Group([MyWidget1]) ]
from controlcenter import Dashboard, widgets class EmptyDashboard(Dashboard): pass class MyWidget0(widgets.Widget): template_name = 'chart.html' class MyWidget1(widgets.Widget): template_name = 'chart.html' class NonEmptyDashboard(Dashboard): widgets = [ MyWidget0, widgets.Group([MyWidget1]) ]
Define template_name for test widgets
Tests: Define template_name for test widgets This avoids an "AssertionError: MyWidget0.template_name is not defined." on Django 2.1, which no longer silences {% include %} exceptions. Django deprecation notes: https://docs.djangoproject.com/en/2.1/internals/deprecation/#deprecation-removed-in-2-1
Python
bsd-3-clause
byashimov/django-controlcenter,byashimov/django-controlcenter,byashimov/django-controlcenter
from controlcenter import Dashboard, widgets class EmptyDashboard(Dashboard): pass class MyWidget0(widgets.Widget): pass class MyWidget1(widgets.Widget): pass class NonEmptyDashboard(Dashboard): widgets = [ MyWidget0, widgets.Group([MyWidget1]) ] Tests: Define template_name for test widgets This avoids an "AssertionError: MyWidget0.template_name is not defined." on Django 2.1, which no longer silences {% include %} exceptions. Django deprecation notes: https://docs.djangoproject.com/en/2.1/internals/deprecation/#deprecation-removed-in-2-1
from controlcenter import Dashboard, widgets class EmptyDashboard(Dashboard): pass class MyWidget0(widgets.Widget): template_name = 'chart.html' class MyWidget1(widgets.Widget): template_name = 'chart.html' class NonEmptyDashboard(Dashboard): widgets = [ MyWidget0, widgets.Group([MyWidget1]) ]
<commit_before>from controlcenter import Dashboard, widgets class EmptyDashboard(Dashboard): pass class MyWidget0(widgets.Widget): pass class MyWidget1(widgets.Widget): pass class NonEmptyDashboard(Dashboard): widgets = [ MyWidget0, widgets.Group([MyWidget1]) ] <commit_msg>Tests: Define template_name for test widgets This avoids an "AssertionError: MyWidget0.template_name is not defined." on Django 2.1, which no longer silences {% include %} exceptions. Django deprecation notes: https://docs.djangoproject.com/en/2.1/internals/deprecation/#deprecation-removed-in-2-1<commit_after>
from controlcenter import Dashboard, widgets class EmptyDashboard(Dashboard): pass class MyWidget0(widgets.Widget): template_name = 'chart.html' class MyWidget1(widgets.Widget): template_name = 'chart.html' class NonEmptyDashboard(Dashboard): widgets = [ MyWidget0, widgets.Group([MyWidget1]) ]
from controlcenter import Dashboard, widgets class EmptyDashboard(Dashboard): pass class MyWidget0(widgets.Widget): pass class MyWidget1(widgets.Widget): pass class NonEmptyDashboard(Dashboard): widgets = [ MyWidget0, widgets.Group([MyWidget1]) ] Tests: Define template_name for test widgets This avoids an "AssertionError: MyWidget0.template_name is not defined." on Django 2.1, which no longer silences {% include %} exceptions. Django deprecation notes: https://docs.djangoproject.com/en/2.1/internals/deprecation/#deprecation-removed-in-2-1from controlcenter import Dashboard, widgets class EmptyDashboard(Dashboard): pass class MyWidget0(widgets.Widget): template_name = 'chart.html' class MyWidget1(widgets.Widget): template_name = 'chart.html' class NonEmptyDashboard(Dashboard): widgets = [ MyWidget0, widgets.Group([MyWidget1]) ]
<commit_before>from controlcenter import Dashboard, widgets class EmptyDashboard(Dashboard): pass class MyWidget0(widgets.Widget): pass class MyWidget1(widgets.Widget): pass class NonEmptyDashboard(Dashboard): widgets = [ MyWidget0, widgets.Group([MyWidget1]) ] <commit_msg>Tests: Define template_name for test widgets This avoids an "AssertionError: MyWidget0.template_name is not defined." on Django 2.1, which no longer silences {% include %} exceptions. Django deprecation notes: https://docs.djangoproject.com/en/2.1/internals/deprecation/#deprecation-removed-in-2-1<commit_after>from controlcenter import Dashboard, widgets class EmptyDashboard(Dashboard): pass class MyWidget0(widgets.Widget): template_name = 'chart.html' class MyWidget1(widgets.Widget): template_name = 'chart.html' class NonEmptyDashboard(Dashboard): widgets = [ MyWidget0, widgets.Group([MyWidget1]) ]
9d9704f631156e01d55d1d1217a41ab3704bdc03
tests/unit/test_context.py
tests/unit/test_context.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # 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. import testtools from openstack.common import context class ContextTest(testtools.TestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # 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. from openstack.common import context from tests import utils class ContextTest(utils.BaseTestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx)
Replace direct use of testtools BaseTestCase.
Replace direct use of testtools BaseTestCase. Using the BaseTestCase across the tests in the tree lets us put in log fixtures and consistently handle mox and stubout. Part of blueprint grizzly-testtools. Change-Id: Iba7eb2c63b0c514009b2c28e5930b27726a147b0
Python
apache-2.0
dims/oslo.context,JioCloud/oslo.context,citrix-openstack-build/oslo.context,varunarya10/oslo.context,openstack/oslo.context,yanheven/oslo.middleware
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # 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. import testtools from openstack.common import context class ContextTest(testtools.TestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx) Replace direct use of testtools BaseTestCase. Using the BaseTestCase across the tests in the tree lets us put in log fixtures and consistently handle mox and stubout. Part of blueprint grizzly-testtools. Change-Id: Iba7eb2c63b0c514009b2c28e5930b27726a147b0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # 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. from openstack.common import context from tests import utils class ContextTest(utils.BaseTestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx)
<commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # 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. import testtools from openstack.common import context class ContextTest(testtools.TestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx) <commit_msg>Replace direct use of testtools BaseTestCase. Using the BaseTestCase across the tests in the tree lets us put in log fixtures and consistently handle mox and stubout. Part of blueprint grizzly-testtools. Change-Id: Iba7eb2c63b0c514009b2c28e5930b27726a147b0<commit_after>
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # 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. from openstack.common import context from tests import utils class ContextTest(utils.BaseTestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # 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. import testtools from openstack.common import context class ContextTest(testtools.TestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx) Replace direct use of testtools BaseTestCase. Using the BaseTestCase across the tests in the tree lets us put in log fixtures and consistently handle mox and stubout. Part of blueprint grizzly-testtools. Change-Id: Iba7eb2c63b0c514009b2c28e5930b27726a147b0# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # 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. from openstack.common import context from tests import utils class ContextTest(utils.BaseTestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx)
<commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # 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. import testtools from openstack.common import context class ContextTest(testtools.TestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx) <commit_msg>Replace direct use of testtools BaseTestCase. Using the BaseTestCase across the tests in the tree lets us put in log fixtures and consistently handle mox and stubout. Part of blueprint grizzly-testtools. Change-Id: Iba7eb2c63b0c514009b2c28e5930b27726a147b0<commit_after># vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # 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. from openstack.common import context from tests import utils class ContextTest(utils.BaseTestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx)
f23cfabee531a6aaa050b647b9ae54ad047335ea
ixdjango/logging_.py
ixdjango/logging_.py
""" Logging Handler """ import logging import logging.handlers import os import re import socket class IXAFormatter(logging.Formatter): """ A formatter for IXA logging environment. """ HOSTNAME = re.sub( r':\d+$', '', os.environ.get('SITE_DOMAIN', socket.gethostname())) FORMAT = '%(asctime)s {hostname} %(name)s[%(process)d]: %(message)s'.\ format(hostname=HOSTNAME) DATE_FORMAT = '%b %d %H:%M:%S' def __init__(self): super(IXAFormatter, self).__init__(fmt=self.FORMAT, datefmt=self.DATE_FORMAT) def format(self, record): # strip newlines message = super(IXAFormatter, self).format(record) message = message.replace('\n', ' ') message += '\n' return message class SysLogHandler(logging.handlers.SysLogHandler): """ A SysLogHandler not appending NUL character to messages """ append_nul = False
""" Logging Handler """ import logging import logging.handlers import os import re import socket import time class IXAFormatter(logging.Formatter): """ A formatter for IXA logging environment. """ HOSTNAME = re.sub( r':\d+$', '', os.environ.get('SITE_DOMAIN', socket.gethostname())) FORMAT = '%(asctime)s {hostname} %(name)s[%(process)d]: %(message)s'.\ format(hostname=HOSTNAME) DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ' converter = time.gmtime def __init__(self): super(IXAFormatter, self).__init__(fmt=self.FORMAT, datefmt=self.DATE_FORMAT) def format(self, record): # strip newlines message = super(IXAFormatter, self).format(record) message = message.replace('\n', ' ') message += '\n' return message class SysLogHandler(logging.handlers.SysLogHandler): """ A SysLogHandler not appending NUL character to messages """ append_nul = False
Change time format to properly formatted UTC
Change time format to properly formatted UTC [#46004]
Python
mit
infoxchange/ixdjango
""" Logging Handler """ import logging import logging.handlers import os import re import socket class IXAFormatter(logging.Formatter): """ A formatter for IXA logging environment. """ HOSTNAME = re.sub( r':\d+$', '', os.environ.get('SITE_DOMAIN', socket.gethostname())) FORMAT = '%(asctime)s {hostname} %(name)s[%(process)d]: %(message)s'.\ format(hostname=HOSTNAME) DATE_FORMAT = '%b %d %H:%M:%S' def __init__(self): super(IXAFormatter, self).__init__(fmt=self.FORMAT, datefmt=self.DATE_FORMAT) def format(self, record): # strip newlines message = super(IXAFormatter, self).format(record) message = message.replace('\n', ' ') message += '\n' return message class SysLogHandler(logging.handlers.SysLogHandler): """ A SysLogHandler not appending NUL character to messages """ append_nul = False Change time format to properly formatted UTC [#46004]
""" Logging Handler """ import logging import logging.handlers import os import re import socket import time class IXAFormatter(logging.Formatter): """ A formatter for IXA logging environment. """ HOSTNAME = re.sub( r':\d+$', '', os.environ.get('SITE_DOMAIN', socket.gethostname())) FORMAT = '%(asctime)s {hostname} %(name)s[%(process)d]: %(message)s'.\ format(hostname=HOSTNAME) DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ' converter = time.gmtime def __init__(self): super(IXAFormatter, self).__init__(fmt=self.FORMAT, datefmt=self.DATE_FORMAT) def format(self, record): # strip newlines message = super(IXAFormatter, self).format(record) message = message.replace('\n', ' ') message += '\n' return message class SysLogHandler(logging.handlers.SysLogHandler): """ A SysLogHandler not appending NUL character to messages """ append_nul = False
<commit_before>""" Logging Handler """ import logging import logging.handlers import os import re import socket class IXAFormatter(logging.Formatter): """ A formatter for IXA logging environment. """ HOSTNAME = re.sub( r':\d+$', '', os.environ.get('SITE_DOMAIN', socket.gethostname())) FORMAT = '%(asctime)s {hostname} %(name)s[%(process)d]: %(message)s'.\ format(hostname=HOSTNAME) DATE_FORMAT = '%b %d %H:%M:%S' def __init__(self): super(IXAFormatter, self).__init__(fmt=self.FORMAT, datefmt=self.DATE_FORMAT) def format(self, record): # strip newlines message = super(IXAFormatter, self).format(record) message = message.replace('\n', ' ') message += '\n' return message class SysLogHandler(logging.handlers.SysLogHandler): """ A SysLogHandler not appending NUL character to messages """ append_nul = False <commit_msg>Change time format to properly formatted UTC [#46004]<commit_after>
""" Logging Handler """ import logging import logging.handlers import os import re import socket import time class IXAFormatter(logging.Formatter): """ A formatter for IXA logging environment. """ HOSTNAME = re.sub( r':\d+$', '', os.environ.get('SITE_DOMAIN', socket.gethostname())) FORMAT = '%(asctime)s {hostname} %(name)s[%(process)d]: %(message)s'.\ format(hostname=HOSTNAME) DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ' converter = time.gmtime def __init__(self): super(IXAFormatter, self).__init__(fmt=self.FORMAT, datefmt=self.DATE_FORMAT) def format(self, record): # strip newlines message = super(IXAFormatter, self).format(record) message = message.replace('\n', ' ') message += '\n' return message class SysLogHandler(logging.handlers.SysLogHandler): """ A SysLogHandler not appending NUL character to messages """ append_nul = False
""" Logging Handler """ import logging import logging.handlers import os import re import socket class IXAFormatter(logging.Formatter): """ A formatter for IXA logging environment. """ HOSTNAME = re.sub( r':\d+$', '', os.environ.get('SITE_DOMAIN', socket.gethostname())) FORMAT = '%(asctime)s {hostname} %(name)s[%(process)d]: %(message)s'.\ format(hostname=HOSTNAME) DATE_FORMAT = '%b %d %H:%M:%S' def __init__(self): super(IXAFormatter, self).__init__(fmt=self.FORMAT, datefmt=self.DATE_FORMAT) def format(self, record): # strip newlines message = super(IXAFormatter, self).format(record) message = message.replace('\n', ' ') message += '\n' return message class SysLogHandler(logging.handlers.SysLogHandler): """ A SysLogHandler not appending NUL character to messages """ append_nul = False Change time format to properly formatted UTC [#46004]""" Logging Handler """ import logging import logging.handlers import os import re import socket import time class IXAFormatter(logging.Formatter): """ A formatter for IXA logging environment. """ HOSTNAME = re.sub( r':\d+$', '', os.environ.get('SITE_DOMAIN', socket.gethostname())) FORMAT = '%(asctime)s {hostname} %(name)s[%(process)d]: %(message)s'.\ format(hostname=HOSTNAME) DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ' converter = time.gmtime def __init__(self): super(IXAFormatter, self).__init__(fmt=self.FORMAT, datefmt=self.DATE_FORMAT) def format(self, record): # strip newlines message = super(IXAFormatter, self).format(record) message = message.replace('\n', ' ') message += '\n' return message class SysLogHandler(logging.handlers.SysLogHandler): """ A SysLogHandler not appending NUL character to messages """ append_nul = False
<commit_before>""" Logging Handler """ import logging import logging.handlers import os import re import socket class IXAFormatter(logging.Formatter): """ A formatter for IXA logging environment. """ HOSTNAME = re.sub( r':\d+$', '', os.environ.get('SITE_DOMAIN', socket.gethostname())) FORMAT = '%(asctime)s {hostname} %(name)s[%(process)d]: %(message)s'.\ format(hostname=HOSTNAME) DATE_FORMAT = '%b %d %H:%M:%S' def __init__(self): super(IXAFormatter, self).__init__(fmt=self.FORMAT, datefmt=self.DATE_FORMAT) def format(self, record): # strip newlines message = super(IXAFormatter, self).format(record) message = message.replace('\n', ' ') message += '\n' return message class SysLogHandler(logging.handlers.SysLogHandler): """ A SysLogHandler not appending NUL character to messages """ append_nul = False <commit_msg>Change time format to properly formatted UTC [#46004]<commit_after>""" Logging Handler """ import logging import logging.handlers import os import re import socket import time class IXAFormatter(logging.Formatter): """ A formatter for IXA logging environment. """ HOSTNAME = re.sub( r':\d+$', '', os.environ.get('SITE_DOMAIN', socket.gethostname())) FORMAT = '%(asctime)s {hostname} %(name)s[%(process)d]: %(message)s'.\ format(hostname=HOSTNAME) DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ' converter = time.gmtime def __init__(self): super(IXAFormatter, self).__init__(fmt=self.FORMAT, datefmt=self.DATE_FORMAT) def format(self, record): # strip newlines message = super(IXAFormatter, self).format(record) message = message.replace('\n', ' ') message += '\n' return message class SysLogHandler(logging.handlers.SysLogHandler): """ A SysLogHandler not appending NUL character to messages """ append_nul = False
334c16a70e7e60520f98c0fc989f03437a585a81
krisk/connections.py
krisk/connections.py
from collections import OrderedDict from IPython.display import Javascript import json from krisk.util import join_current_dir ECHARTS_URL = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/3.2.0/' ECHARTS_FILE = 'echarts.min' d_paths = OrderedDict({}) THEMES = ['dark','vintage','roma','shine','infographic','macarons'] THEMES_URL='//echarts.baidu.com/asset/theme/' PATH_LOCAL = join_current_dir('static') # PATH_LOCAL = 'pandas-echarts/krisk/static' #TODO FIX LOCAL PATH! NEED TO DO nbextension install # def init_notebook(): # """Inject Javascript to notebook, default using local js. # """ # return Javascript(""" # require.config({ # baseUrl : '%s', # paths: { # echarts: 'echarts.min' # } # }); # """ % PATH_LOCAL) def init_notebook(): """Inject Javascript to notebook, default using local js. """ return Javascript(""" require.config({ baseUrl : "//rawgit.com/napjon/krisk/master/krisk/static", paths: { echarts: "//cdnjs.cloudflare.com/ajax/libs/echarts/3.2.1/echarts.min" } }); """) def get_paths(): return ['echarts'] + THEMES
from collections import OrderedDict from IPython.display import Javascript import json from krisk.util import join_current_dir ECHARTS_URL = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/3.2.0/' ECHARTS_FILE = 'echarts.min' d_paths = OrderedDict({}) THEMES = ['dark','vintage','roma','shine','infographic','macarons'] THEMES_URL='//echarts.baidu.com/asset/theme/' PATH_LOCAL = join_current_dir('static') # PATH_LOCAL = 'pandas-echarts/krisk/static' #TODO FIX LOCAL PATH! NEED TO DO nbextension install # def init_notebook(): # """Inject Javascript to notebook, default using local js. # """ # return Javascript(""" # require.config({ # baseUrl : '%s', # paths: { # echarts: 'echarts.min' # } # }); # """ % PATH_LOCAL) def init_notebook(): """Inject Javascript to notebook, default using local js. """ return Javascript(""" require.config({ baseUrl : "//rawgit.com/napjon/krisk/master/krisk/static", paths: { echarts: "//cdnjs.cloudflare.com/ajax/libs/echarts/3.2.1/echarts.min" }, waitSeconds: 15 }); """) def get_paths(): return ['echarts'] + THEMES
Update connection to script to waitSeconds to load js
Update connection to script to waitSeconds to load js
Python
bsd-3-clause
napjon/krisk,napjon/krisk,napjon/krisk
from collections import OrderedDict from IPython.display import Javascript import json from krisk.util import join_current_dir ECHARTS_URL = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/3.2.0/' ECHARTS_FILE = 'echarts.min' d_paths = OrderedDict({}) THEMES = ['dark','vintage','roma','shine','infographic','macarons'] THEMES_URL='//echarts.baidu.com/asset/theme/' PATH_LOCAL = join_current_dir('static') # PATH_LOCAL = 'pandas-echarts/krisk/static' #TODO FIX LOCAL PATH! NEED TO DO nbextension install # def init_notebook(): # """Inject Javascript to notebook, default using local js. # """ # return Javascript(""" # require.config({ # baseUrl : '%s', # paths: { # echarts: 'echarts.min' # } # }); # """ % PATH_LOCAL) def init_notebook(): """Inject Javascript to notebook, default using local js. """ return Javascript(""" require.config({ baseUrl : "//rawgit.com/napjon/krisk/master/krisk/static", paths: { echarts: "//cdnjs.cloudflare.com/ajax/libs/echarts/3.2.1/echarts.min" } }); """) def get_paths(): return ['echarts'] + THEMES Update connection to script to waitSeconds to load js
from collections import OrderedDict from IPython.display import Javascript import json from krisk.util import join_current_dir ECHARTS_URL = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/3.2.0/' ECHARTS_FILE = 'echarts.min' d_paths = OrderedDict({}) THEMES = ['dark','vintage','roma','shine','infographic','macarons'] THEMES_URL='//echarts.baidu.com/asset/theme/' PATH_LOCAL = join_current_dir('static') # PATH_LOCAL = 'pandas-echarts/krisk/static' #TODO FIX LOCAL PATH! NEED TO DO nbextension install # def init_notebook(): # """Inject Javascript to notebook, default using local js. # """ # return Javascript(""" # require.config({ # baseUrl : '%s', # paths: { # echarts: 'echarts.min' # } # }); # """ % PATH_LOCAL) def init_notebook(): """Inject Javascript to notebook, default using local js. """ return Javascript(""" require.config({ baseUrl : "//rawgit.com/napjon/krisk/master/krisk/static", paths: { echarts: "//cdnjs.cloudflare.com/ajax/libs/echarts/3.2.1/echarts.min" }, waitSeconds: 15 }); """) def get_paths(): return ['echarts'] + THEMES
<commit_before> from collections import OrderedDict from IPython.display import Javascript import json from krisk.util import join_current_dir ECHARTS_URL = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/3.2.0/' ECHARTS_FILE = 'echarts.min' d_paths = OrderedDict({}) THEMES = ['dark','vintage','roma','shine','infographic','macarons'] THEMES_URL='//echarts.baidu.com/asset/theme/' PATH_LOCAL = join_current_dir('static') # PATH_LOCAL = 'pandas-echarts/krisk/static' #TODO FIX LOCAL PATH! NEED TO DO nbextension install # def init_notebook(): # """Inject Javascript to notebook, default using local js. # """ # return Javascript(""" # require.config({ # baseUrl : '%s', # paths: { # echarts: 'echarts.min' # } # }); # """ % PATH_LOCAL) def init_notebook(): """Inject Javascript to notebook, default using local js. """ return Javascript(""" require.config({ baseUrl : "//rawgit.com/napjon/krisk/master/krisk/static", paths: { echarts: "//cdnjs.cloudflare.com/ajax/libs/echarts/3.2.1/echarts.min" } }); """) def get_paths(): return ['echarts'] + THEMES <commit_msg>Update connection to script to waitSeconds to load js<commit_after>
from collections import OrderedDict from IPython.display import Javascript import json from krisk.util import join_current_dir ECHARTS_URL = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/3.2.0/' ECHARTS_FILE = 'echarts.min' d_paths = OrderedDict({}) THEMES = ['dark','vintage','roma','shine','infographic','macarons'] THEMES_URL='//echarts.baidu.com/asset/theme/' PATH_LOCAL = join_current_dir('static') # PATH_LOCAL = 'pandas-echarts/krisk/static' #TODO FIX LOCAL PATH! NEED TO DO nbextension install # def init_notebook(): # """Inject Javascript to notebook, default using local js. # """ # return Javascript(""" # require.config({ # baseUrl : '%s', # paths: { # echarts: 'echarts.min' # } # }); # """ % PATH_LOCAL) def init_notebook(): """Inject Javascript to notebook, default using local js. """ return Javascript(""" require.config({ baseUrl : "//rawgit.com/napjon/krisk/master/krisk/static", paths: { echarts: "//cdnjs.cloudflare.com/ajax/libs/echarts/3.2.1/echarts.min" }, waitSeconds: 15 }); """) def get_paths(): return ['echarts'] + THEMES
from collections import OrderedDict from IPython.display import Javascript import json from krisk.util import join_current_dir ECHARTS_URL = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/3.2.0/' ECHARTS_FILE = 'echarts.min' d_paths = OrderedDict({}) THEMES = ['dark','vintage','roma','shine','infographic','macarons'] THEMES_URL='//echarts.baidu.com/asset/theme/' PATH_LOCAL = join_current_dir('static') # PATH_LOCAL = 'pandas-echarts/krisk/static' #TODO FIX LOCAL PATH! NEED TO DO nbextension install # def init_notebook(): # """Inject Javascript to notebook, default using local js. # """ # return Javascript(""" # require.config({ # baseUrl : '%s', # paths: { # echarts: 'echarts.min' # } # }); # """ % PATH_LOCAL) def init_notebook(): """Inject Javascript to notebook, default using local js. """ return Javascript(""" require.config({ baseUrl : "//rawgit.com/napjon/krisk/master/krisk/static", paths: { echarts: "//cdnjs.cloudflare.com/ajax/libs/echarts/3.2.1/echarts.min" } }); """) def get_paths(): return ['echarts'] + THEMES Update connection to script to waitSeconds to load js from collections import OrderedDict from IPython.display import Javascript import json from krisk.util import join_current_dir ECHARTS_URL = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/3.2.0/' ECHARTS_FILE = 'echarts.min' d_paths = OrderedDict({}) THEMES = ['dark','vintage','roma','shine','infographic','macarons'] THEMES_URL='//echarts.baidu.com/asset/theme/' PATH_LOCAL = join_current_dir('static') # PATH_LOCAL = 'pandas-echarts/krisk/static' #TODO FIX LOCAL PATH! NEED TO DO nbextension install # def init_notebook(): # """Inject Javascript to notebook, default using local js. # """ # return Javascript(""" # require.config({ # baseUrl : '%s', # paths: { # echarts: 'echarts.min' # } # }); # """ % PATH_LOCAL) def init_notebook(): """Inject Javascript to notebook, default using local js. """ return Javascript(""" require.config({ baseUrl : "//rawgit.com/napjon/krisk/master/krisk/static", paths: { echarts: "//cdnjs.cloudflare.com/ajax/libs/echarts/3.2.1/echarts.min" }, waitSeconds: 15 }); """) def get_paths(): return ['echarts'] + THEMES
<commit_before> from collections import OrderedDict from IPython.display import Javascript import json from krisk.util import join_current_dir ECHARTS_URL = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/3.2.0/' ECHARTS_FILE = 'echarts.min' d_paths = OrderedDict({}) THEMES = ['dark','vintage','roma','shine','infographic','macarons'] THEMES_URL='//echarts.baidu.com/asset/theme/' PATH_LOCAL = join_current_dir('static') # PATH_LOCAL = 'pandas-echarts/krisk/static' #TODO FIX LOCAL PATH! NEED TO DO nbextension install # def init_notebook(): # """Inject Javascript to notebook, default using local js. # """ # return Javascript(""" # require.config({ # baseUrl : '%s', # paths: { # echarts: 'echarts.min' # } # }); # """ % PATH_LOCAL) def init_notebook(): """Inject Javascript to notebook, default using local js. """ return Javascript(""" require.config({ baseUrl : "//rawgit.com/napjon/krisk/master/krisk/static", paths: { echarts: "//cdnjs.cloudflare.com/ajax/libs/echarts/3.2.1/echarts.min" } }); """) def get_paths(): return ['echarts'] + THEMES <commit_msg>Update connection to script to waitSeconds to load js<commit_after> from collections import OrderedDict from IPython.display import Javascript import json from krisk.util import join_current_dir ECHARTS_URL = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/3.2.0/' ECHARTS_FILE = 'echarts.min' d_paths = OrderedDict({}) THEMES = ['dark','vintage','roma','shine','infographic','macarons'] THEMES_URL='//echarts.baidu.com/asset/theme/' PATH_LOCAL = join_current_dir('static') # PATH_LOCAL = 'pandas-echarts/krisk/static' #TODO FIX LOCAL PATH! NEED TO DO nbextension install # def init_notebook(): # """Inject Javascript to notebook, default using local js. # """ # return Javascript(""" # require.config({ # baseUrl : '%s', # paths: { # echarts: 'echarts.min' # } # }); # """ % PATH_LOCAL) def init_notebook(): """Inject Javascript to notebook, default using local js. """ return Javascript(""" require.config({ baseUrl : "//rawgit.com/napjon/krisk/master/krisk/static", paths: { echarts: "//cdnjs.cloudflare.com/ajax/libs/echarts/3.2.1/echarts.min" }, waitSeconds: 15 }); """) def get_paths(): return ['echarts'] + THEMES
640ce1a3b4f9cca4ebcc10f3d62b1d4d995dd0c5
src/foremast/pipeline/create_pipeline_manual.py
src/foremast/pipeline/create_pipeline_manual.py
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # 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. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_dict = lookup.json(filename=json_file) json_dict['name'] = json_file self.post_pipeline(json_dict) return True
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # 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. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .clean_pipelines import delete_pipeline from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: delete_pipeline(app=self.app_name, pipeline_name=json_file) json_dict = lookup.json(filename=json_file) json_dict['name'] = json_file self.post_pipeline(json_dict) return True
Delete manual Pipeline before creating
fix: Delete manual Pipeline before creating See also: #72
Python
apache-2.0
gogoair/foremast,gogoair/foremast
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # 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. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_dict = lookup.json(filename=json_file) json_dict['name'] = json_file self.post_pipeline(json_dict) return True fix: Delete manual Pipeline before creating See also: #72
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # 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. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .clean_pipelines import delete_pipeline from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: delete_pipeline(app=self.app_name, pipeline_name=json_file) json_dict = lookup.json(filename=json_file) json_dict['name'] = json_file self.post_pipeline(json_dict) return True
<commit_before># Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # 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. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_dict = lookup.json(filename=json_file) json_dict['name'] = json_file self.post_pipeline(json_dict) return True <commit_msg>fix: Delete manual Pipeline before creating See also: #72<commit_after>
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # 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. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .clean_pipelines import delete_pipeline from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: delete_pipeline(app=self.app_name, pipeline_name=json_file) json_dict = lookup.json(filename=json_file) json_dict['name'] = json_file self.post_pipeline(json_dict) return True
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # 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. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_dict = lookup.json(filename=json_file) json_dict['name'] = json_file self.post_pipeline(json_dict) return True fix: Delete manual Pipeline before creating See also: #72# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # 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. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .clean_pipelines import delete_pipeline from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: delete_pipeline(app=self.app_name, pipeline_name=json_file) json_dict = lookup.json(filename=json_file) json_dict['name'] = json_file self.post_pipeline(json_dict) return True
<commit_before># Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # 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. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_dict = lookup.json(filename=json_file) json_dict['name'] = json_file self.post_pipeline(json_dict) return True <commit_msg>fix: Delete manual Pipeline before creating See also: #72<commit_after># Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # 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. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .clean_pipelines import delete_pipeline from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: delete_pipeline(app=self.app_name, pipeline_name=json_file) json_dict = lookup.json(filename=json_file) json_dict['name'] = json_file self.post_pipeline(json_dict) return True
8fb2eb1c51daa5614b1b4ab15428350d2b28c093
accounts/models.py
accounts/models.py
# coding: utf-8 from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from registration.signals import user_activated from django.dispatch import receiver class UserAccount(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='account') class Meta: verbose_name = _('user account') verbose_name_plural = _('user accounts') @receiver(user_activated) def registration_completed(sender, user, request, **kwargs): account, created = UserAccount.objects.get_or_create(user=user) print account, created
# coding: utf-8 from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from registration.signals import user_activated from django.dispatch import receiver class UserAccount(models.Model): """ A user account. Used to store any information related to users. """ user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='account') class Meta: verbose_name = _('user account') verbose_name_plural = _('user accounts') @receiver(user_activated) def registration_completed(sender, user, request, **kwargs): account, created = UserAccount.objects.get_or_create(user=user) print account, created
Add docstring to UserAccount model
Add docstring to UserAccount model
Python
agpl-3.0
pitpalme/volunteer_planner,pitpalme/volunteer_planner,flindenberg/volunteer_planner,klinger/volunteer_planner,flindenberg/volunteer_planner,alper/volunteer_planner,volunteer-planner/volunteer_planner,coders4help/volunteer_planner,coders4help/volunteer_planner,klinger/volunteer_planner,volunteer-planner/volunteer_planner,christophmeissner/volunteer_planner,christophmeissner/volunteer_planner,klinger/volunteer_planner,flindenberg/volunteer_planner,alper/volunteer_planner,christophmeissner/volunteer_planner,christophmeissner/volunteer_planner,alper/volunteer_planner,volunteer-planner/volunteer_planner,pitpalme/volunteer_planner,coders4help/volunteer_planner,pitpalme/volunteer_planner,volunteer-planner/volunteer_planner,klinger/volunteer_planner,coders4help/volunteer_planner
# coding: utf-8 from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from registration.signals import user_activated from django.dispatch import receiver class UserAccount(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='account') class Meta: verbose_name = _('user account') verbose_name_plural = _('user accounts') @receiver(user_activated) def registration_completed(sender, user, request, **kwargs): account, created = UserAccount.objects.get_or_create(user=user) print account, created Add docstring to UserAccount model
# coding: utf-8 from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from registration.signals import user_activated from django.dispatch import receiver class UserAccount(models.Model): """ A user account. Used to store any information related to users. """ user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='account') class Meta: verbose_name = _('user account') verbose_name_plural = _('user accounts') @receiver(user_activated) def registration_completed(sender, user, request, **kwargs): account, created = UserAccount.objects.get_or_create(user=user) print account, created
<commit_before># coding: utf-8 from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from registration.signals import user_activated from django.dispatch import receiver class UserAccount(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='account') class Meta: verbose_name = _('user account') verbose_name_plural = _('user accounts') @receiver(user_activated) def registration_completed(sender, user, request, **kwargs): account, created = UserAccount.objects.get_or_create(user=user) print account, created <commit_msg>Add docstring to UserAccount model<commit_after>
# coding: utf-8 from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from registration.signals import user_activated from django.dispatch import receiver class UserAccount(models.Model): """ A user account. Used to store any information related to users. """ user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='account') class Meta: verbose_name = _('user account') verbose_name_plural = _('user accounts') @receiver(user_activated) def registration_completed(sender, user, request, **kwargs): account, created = UserAccount.objects.get_or_create(user=user) print account, created
# coding: utf-8 from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from registration.signals import user_activated from django.dispatch import receiver class UserAccount(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='account') class Meta: verbose_name = _('user account') verbose_name_plural = _('user accounts') @receiver(user_activated) def registration_completed(sender, user, request, **kwargs): account, created = UserAccount.objects.get_or_create(user=user) print account, created Add docstring to UserAccount model# coding: utf-8 from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from registration.signals import user_activated from django.dispatch import receiver class UserAccount(models.Model): """ A user account. Used to store any information related to users. """ user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='account') class Meta: verbose_name = _('user account') verbose_name_plural = _('user accounts') @receiver(user_activated) def registration_completed(sender, user, request, **kwargs): account, created = UserAccount.objects.get_or_create(user=user) print account, created
<commit_before># coding: utf-8 from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from registration.signals import user_activated from django.dispatch import receiver class UserAccount(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='account') class Meta: verbose_name = _('user account') verbose_name_plural = _('user accounts') @receiver(user_activated) def registration_completed(sender, user, request, **kwargs): account, created = UserAccount.objects.get_or_create(user=user) print account, created <commit_msg>Add docstring to UserAccount model<commit_after># coding: utf-8 from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from registration.signals import user_activated from django.dispatch import receiver class UserAccount(models.Model): """ A user account. Used to store any information related to users. """ user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='account') class Meta: verbose_name = _('user account') verbose_name_plural = _('user accounts') @receiver(user_activated) def registration_completed(sender, user, request, **kwargs): account, created = UserAccount.objects.get_or_create(user=user) print account, created
ad622ab0a4a70187ffb023687a64497657d79442
members/views.py
members/views.py
# -*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.http import HttpResponse from hackfmi.utils import json_view from .models import User def homepage(request): return render(request, "index.html", {}) @json_view def search(request, name): members = User.objects.filter(first_name__icontains=name) or \ User.objects.filter(last_name__icontains=name) or \ User.objects.filter(username__icontains=name) json_data = [dict( id=member.id, faculty_number=member.faculty_number, full_name=' '.join([member.first_name, member.last_name])) for member in members] return json_data def login(request): from .forms import LoginForm from django.contrib import auth if not request.user.is_authenticated(): if request.POST: form = LoginForm(request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request, user) return redirect('members.views.homepage') else: pass # Return a 'disabled account' error message else: from django.forms.util import ErrorList errors = form._errors.setdefault("myfield", ErrorList()) errors.append(u"My error here") else: form = LoginForm() return render(request, 'members/login_form.html', locals()) else: return redirect('members.views.homepage')
# -*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import views from hackfmi.utils import json_view from .models import User def homepage(request): return render(request, "index.html", {}) @json_view def search(request, name): members = User.objects.filter(first_name__icontains=name) or \ User.objects.filter(last_name__icontains=name) or \ User.objects.filter(username__icontains=name) json_data = [dict( id=member.id, faculty_number=member.faculty_number, full_name=' '.join([member.first_name, member.last_name])) for member in members] return json_data def login(request): if request.user.is_authenticated(): return redirect('members.views.homepage') else: return views.login(request, template_name='members/login_form.html')
Use default auth django app
Use default auth django app
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
# -*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.http import HttpResponse from hackfmi.utils import json_view from .models import User def homepage(request): return render(request, "index.html", {}) @json_view def search(request, name): members = User.objects.filter(first_name__icontains=name) or \ User.objects.filter(last_name__icontains=name) or \ User.objects.filter(username__icontains=name) json_data = [dict( id=member.id, faculty_number=member.faculty_number, full_name=' '.join([member.first_name, member.last_name])) for member in members] return json_data def login(request): from .forms import LoginForm from django.contrib import auth if not request.user.is_authenticated(): if request.POST: form = LoginForm(request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request, user) return redirect('members.views.homepage') else: pass # Return a 'disabled account' error message else: from django.forms.util import ErrorList errors = form._errors.setdefault("myfield", ErrorList()) errors.append(u"My error here") else: form = LoginForm() return render(request, 'members/login_form.html', locals()) else: return redirect('members.views.homepage') Use default auth django app
# -*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import views from hackfmi.utils import json_view from .models import User def homepage(request): return render(request, "index.html", {}) @json_view def search(request, name): members = User.objects.filter(first_name__icontains=name) or \ User.objects.filter(last_name__icontains=name) or \ User.objects.filter(username__icontains=name) json_data = [dict( id=member.id, faculty_number=member.faculty_number, full_name=' '.join([member.first_name, member.last_name])) for member in members] return json_data def login(request): if request.user.is_authenticated(): return redirect('members.views.homepage') else: return views.login(request, template_name='members/login_form.html')
<commit_before># -*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.http import HttpResponse from hackfmi.utils import json_view from .models import User def homepage(request): return render(request, "index.html", {}) @json_view def search(request, name): members = User.objects.filter(first_name__icontains=name) or \ User.objects.filter(last_name__icontains=name) or \ User.objects.filter(username__icontains=name) json_data = [dict( id=member.id, faculty_number=member.faculty_number, full_name=' '.join([member.first_name, member.last_name])) for member in members] return json_data def login(request): from .forms import LoginForm from django.contrib import auth if not request.user.is_authenticated(): if request.POST: form = LoginForm(request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request, user) return redirect('members.views.homepage') else: pass # Return a 'disabled account' error message else: from django.forms.util import ErrorList errors = form._errors.setdefault("myfield", ErrorList()) errors.append(u"My error here") else: form = LoginForm() return render(request, 'members/login_form.html', locals()) else: return redirect('members.views.homepage') <commit_msg>Use default auth django app<commit_after>
# -*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import views from hackfmi.utils import json_view from .models import User def homepage(request): return render(request, "index.html", {}) @json_view def search(request, name): members = User.objects.filter(first_name__icontains=name) or \ User.objects.filter(last_name__icontains=name) or \ User.objects.filter(username__icontains=name) json_data = [dict( id=member.id, faculty_number=member.faculty_number, full_name=' '.join([member.first_name, member.last_name])) for member in members] return json_data def login(request): if request.user.is_authenticated(): return redirect('members.views.homepage') else: return views.login(request, template_name='members/login_form.html')
# -*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.http import HttpResponse from hackfmi.utils import json_view from .models import User def homepage(request): return render(request, "index.html", {}) @json_view def search(request, name): members = User.objects.filter(first_name__icontains=name) or \ User.objects.filter(last_name__icontains=name) or \ User.objects.filter(username__icontains=name) json_data = [dict( id=member.id, faculty_number=member.faculty_number, full_name=' '.join([member.first_name, member.last_name])) for member in members] return json_data def login(request): from .forms import LoginForm from django.contrib import auth if not request.user.is_authenticated(): if request.POST: form = LoginForm(request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request, user) return redirect('members.views.homepage') else: pass # Return a 'disabled account' error message else: from django.forms.util import ErrorList errors = form._errors.setdefault("myfield", ErrorList()) errors.append(u"My error here") else: form = LoginForm() return render(request, 'members/login_form.html', locals()) else: return redirect('members.views.homepage') Use default auth django app# -*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import views from hackfmi.utils import json_view from .models import User def homepage(request): return render(request, "index.html", {}) @json_view def search(request, name): members = User.objects.filter(first_name__icontains=name) or \ User.objects.filter(last_name__icontains=name) or \ User.objects.filter(username__icontains=name) json_data = [dict( id=member.id, faculty_number=member.faculty_number, full_name=' '.join([member.first_name, member.last_name])) for member in members] return json_data def login(request): if request.user.is_authenticated(): return redirect('members.views.homepage') else: return views.login(request, template_name='members/login_form.html')
<commit_before># -*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.http import HttpResponse from hackfmi.utils import json_view from .models import User def homepage(request): return render(request, "index.html", {}) @json_view def search(request, name): members = User.objects.filter(first_name__icontains=name) or \ User.objects.filter(last_name__icontains=name) or \ User.objects.filter(username__icontains=name) json_data = [dict( id=member.id, faculty_number=member.faculty_number, full_name=' '.join([member.first_name, member.last_name])) for member in members] return json_data def login(request): from .forms import LoginForm from django.contrib import auth if not request.user.is_authenticated(): if request.POST: form = LoginForm(request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request, user) return redirect('members.views.homepage') else: pass # Return a 'disabled account' error message else: from django.forms.util import ErrorList errors = form._errors.setdefault("myfield", ErrorList()) errors.append(u"My error here") else: form = LoginForm() return render(request, 'members/login_form.html', locals()) else: return redirect('members.views.homepage') <commit_msg>Use default auth django app<commit_after># -*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import views from hackfmi.utils import json_view from .models import User def homepage(request): return render(request, "index.html", {}) @json_view def search(request, name): members = User.objects.filter(first_name__icontains=name) or \ User.objects.filter(last_name__icontains=name) or \ User.objects.filter(username__icontains=name) json_data = [dict( id=member.id, faculty_number=member.faculty_number, full_name=' '.join([member.first_name, member.last_name])) for member in members] return json_data def login(request): if request.user.is_authenticated(): return redirect('members.views.homepage') else: return views.login(request, template_name='members/login_form.html')
03d9c825bb7e86550b3d6fa9afd39c126cb9034d
basis_set_exchange/__init__.py
basis_set_exchange/__init__.py
''' Basis Set Exchange Contains utilities for reading, writing, and converting basis set information ''' # Just import the basic user API from .api import (get_basis, lookup_basis_by_role, get_metadata, get_reference_data, get_all_basis_names, get_references, get_basis_family, get_basis_names_by_family, get_families, get_family_notes, get_basis_notes, get_schema, get_formats, get_reference_formats, get_roles) # Handle versioneer from ._version import get_versions versions = get_versions() __version__ = versions['version'] __git_revision__ = versions['full-revisionid'] del get_versions, versions
''' Basis Set Exchange Contains utilities for reading, writing, and converting basis set information ''' # Just import the basic user API from .api import (get_basis, lookup_basis_by_role, get_metadata, get_reference_data, get_all_basis_names, get_references, get_basis_family, get_basis_names_by_family, get_families, get_family_notes, get_basis_notes, get_schema, get_formats, get_reference_formats, get_roles) # Handle versioneer from ._version import get_versions versions = get_versions() __version__ = versions['version'] __git_revision__ = versions['full-revisionid'] del get_versions, versions def version(): '''Obtain the version of the basis set exchange library''' return __version__
Add simple function to get the version of the bse
Add simple function to get the version of the bse
Python
bsd-3-clause
MOLSSI-BSE/basis_set_exchange
''' Basis Set Exchange Contains utilities for reading, writing, and converting basis set information ''' # Just import the basic user API from .api import (get_basis, lookup_basis_by_role, get_metadata, get_reference_data, get_all_basis_names, get_references, get_basis_family, get_basis_names_by_family, get_families, get_family_notes, get_basis_notes, get_schema, get_formats, get_reference_formats, get_roles) # Handle versioneer from ._version import get_versions versions = get_versions() __version__ = versions['version'] __git_revision__ = versions['full-revisionid'] del get_versions, versions Add simple function to get the version of the bse
''' Basis Set Exchange Contains utilities for reading, writing, and converting basis set information ''' # Just import the basic user API from .api import (get_basis, lookup_basis_by_role, get_metadata, get_reference_data, get_all_basis_names, get_references, get_basis_family, get_basis_names_by_family, get_families, get_family_notes, get_basis_notes, get_schema, get_formats, get_reference_formats, get_roles) # Handle versioneer from ._version import get_versions versions = get_versions() __version__ = versions['version'] __git_revision__ = versions['full-revisionid'] del get_versions, versions def version(): '''Obtain the version of the basis set exchange library''' return __version__
<commit_before>''' Basis Set Exchange Contains utilities for reading, writing, and converting basis set information ''' # Just import the basic user API from .api import (get_basis, lookup_basis_by_role, get_metadata, get_reference_data, get_all_basis_names, get_references, get_basis_family, get_basis_names_by_family, get_families, get_family_notes, get_basis_notes, get_schema, get_formats, get_reference_formats, get_roles) # Handle versioneer from ._version import get_versions versions = get_versions() __version__ = versions['version'] __git_revision__ = versions['full-revisionid'] del get_versions, versions <commit_msg>Add simple function to get the version of the bse<commit_after>
''' Basis Set Exchange Contains utilities for reading, writing, and converting basis set information ''' # Just import the basic user API from .api import (get_basis, lookup_basis_by_role, get_metadata, get_reference_data, get_all_basis_names, get_references, get_basis_family, get_basis_names_by_family, get_families, get_family_notes, get_basis_notes, get_schema, get_formats, get_reference_formats, get_roles) # Handle versioneer from ._version import get_versions versions = get_versions() __version__ = versions['version'] __git_revision__ = versions['full-revisionid'] del get_versions, versions def version(): '''Obtain the version of the basis set exchange library''' return __version__
''' Basis Set Exchange Contains utilities for reading, writing, and converting basis set information ''' # Just import the basic user API from .api import (get_basis, lookup_basis_by_role, get_metadata, get_reference_data, get_all_basis_names, get_references, get_basis_family, get_basis_names_by_family, get_families, get_family_notes, get_basis_notes, get_schema, get_formats, get_reference_formats, get_roles) # Handle versioneer from ._version import get_versions versions = get_versions() __version__ = versions['version'] __git_revision__ = versions['full-revisionid'] del get_versions, versions Add simple function to get the version of the bse''' Basis Set Exchange Contains utilities for reading, writing, and converting basis set information ''' # Just import the basic user API from .api import (get_basis, lookup_basis_by_role, get_metadata, get_reference_data, get_all_basis_names, get_references, get_basis_family, get_basis_names_by_family, get_families, get_family_notes, get_basis_notes, get_schema, get_formats, get_reference_formats, get_roles) # Handle versioneer from ._version import get_versions versions = get_versions() __version__ = versions['version'] __git_revision__ = versions['full-revisionid'] del get_versions, versions def version(): '''Obtain the version of the basis set exchange library''' return __version__
<commit_before>''' Basis Set Exchange Contains utilities for reading, writing, and converting basis set information ''' # Just import the basic user API from .api import (get_basis, lookup_basis_by_role, get_metadata, get_reference_data, get_all_basis_names, get_references, get_basis_family, get_basis_names_by_family, get_families, get_family_notes, get_basis_notes, get_schema, get_formats, get_reference_formats, get_roles) # Handle versioneer from ._version import get_versions versions = get_versions() __version__ = versions['version'] __git_revision__ = versions['full-revisionid'] del get_versions, versions <commit_msg>Add simple function to get the version of the bse<commit_after>''' Basis Set Exchange Contains utilities for reading, writing, and converting basis set information ''' # Just import the basic user API from .api import (get_basis, lookup_basis_by_role, get_metadata, get_reference_data, get_all_basis_names, get_references, get_basis_family, get_basis_names_by_family, get_families, get_family_notes, get_basis_notes, get_schema, get_formats, get_reference_formats, get_roles) # Handle versioneer from ._version import get_versions versions = get_versions() __version__ = versions['version'] __git_revision__ = versions['full-revisionid'] del get_versions, versions def version(): '''Obtain the version of the basis set exchange library''' return __version__
bcb24ef03a65d80c09ef47f19a64fd854a70c082
tests/chainer_tests/training_tests/extensions_tests/test_print_report.py
tests/chainer_tests/training_tests/extensions_tests/test_print_report.py
import sys import unittest from mock import MagicMock from chainer import testing from chainer.training import extensions class TestPrintReport(unittest.TestCase): def _setup(self, delete_flush=False): self.logreport = MagicMock(spec=extensions.LogReport( ['epoch'], trigger=(1, 'iteration'), log_name=None)) self.stream = MagicMock() if delete_flush: del self.stream.flush self.report = extensions.PrintReport( ['epoch'], log_report=self.logreport, out=self.stream) self.trainer = testing.get_trainer_with_mock_updater( stop_trigger=(1, 'iteration')) self.trainer.extend(self.logreport) self.trainer.extend(self.report) self.logreport.log = [{'epoch': 0}] def test_stream_with_flush_is_flushed(self): self._setup(delete_flush=False) self.assertTrue(hasattr(self.stream, 'flush')) self.stream.flush.assert_not_called() self.report(self.trainer) self.stream.flush.assert_called_with() def test_stream_without_flush_raises_no_exception(self): self._setup(delete_flush=True) self.assertFalse(hasattr(self.stream, 'flush')) self.report(self.trainer) testing.run_module(__name__, __file__)
import sys import unittest from mock import MagicMock from chainer import testing from chainer.training import extensions class TestPrintReport(unittest.TestCase): def _setup(self, stream=None, delete_flush=False): self.logreport = MagicMock(spec=extensions.LogReport( ['epoch'], trigger=(1, 'iteration'), log_name=None)) if stream is None: self.stream = MagicMock() if delete_flush: del self.stream.flush else: self.stream = stream self.report = extensions.PrintReport( ['epoch'], log_report=self.logreport, out=self.stream) self.trainer = testing.get_trainer_with_mock_updater( stop_trigger=(1, 'iteration')) self.trainer.extend(self.logreport) self.trainer.extend(self.report) self.logreport.log = [{'epoch': 0}] def test_stream_with_flush_is_flushed(self): self._setup(delete_flush=False) self.assertTrue(hasattr(self.stream, 'flush')) self.stream.flush.assert_not_called() self.report(self.trainer) self.stream.flush.assert_called_with() def test_stream_without_flush_raises_no_exception(self): self._setup(delete_flush=True) self.assertFalse(hasattr(self.stream, 'flush')) self.report(self.trainer) def test_real_stream_raises_no_exception(self): self._setup(stream=sys.stderr) self.report(self.trainer) testing.run_module(__name__, __file__)
Test PrintReport with a real stream
Test PrintReport with a real stream
Python
mit
ktnyt/chainer,pfnet/chainer,rezoo/chainer,hvy/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,okuta/chainer,hvy/chainer,niboshi/chainer,keisuke-umezawa/chainer,wkentaro/chainer,okuta/chainer,jnishi/chainer,niboshi/chainer,hvy/chainer,jnishi/chainer,hvy/chainer,chainer/chainer,chainer/chainer,keisuke-umezawa/chainer,okuta/chainer,ktnyt/chainer,niboshi/chainer,wkentaro/chainer,chainer/chainer,ktnyt/chainer,niboshi/chainer,wkentaro/chainer,ktnyt/chainer,chainer/chainer,okuta/chainer,jnishi/chainer,jnishi/chainer,tkerola/chainer,wkentaro/chainer
import sys import unittest from mock import MagicMock from chainer import testing from chainer.training import extensions class TestPrintReport(unittest.TestCase): def _setup(self, delete_flush=False): self.logreport = MagicMock(spec=extensions.LogReport( ['epoch'], trigger=(1, 'iteration'), log_name=None)) self.stream = MagicMock() if delete_flush: del self.stream.flush self.report = extensions.PrintReport( ['epoch'], log_report=self.logreport, out=self.stream) self.trainer = testing.get_trainer_with_mock_updater( stop_trigger=(1, 'iteration')) self.trainer.extend(self.logreport) self.trainer.extend(self.report) self.logreport.log = [{'epoch': 0}] def test_stream_with_flush_is_flushed(self): self._setup(delete_flush=False) self.assertTrue(hasattr(self.stream, 'flush')) self.stream.flush.assert_not_called() self.report(self.trainer) self.stream.flush.assert_called_with() def test_stream_without_flush_raises_no_exception(self): self._setup(delete_flush=True) self.assertFalse(hasattr(self.stream, 'flush')) self.report(self.trainer) testing.run_module(__name__, __file__) Test PrintReport with a real stream
import sys import unittest from mock import MagicMock from chainer import testing from chainer.training import extensions class TestPrintReport(unittest.TestCase): def _setup(self, stream=None, delete_flush=False): self.logreport = MagicMock(spec=extensions.LogReport( ['epoch'], trigger=(1, 'iteration'), log_name=None)) if stream is None: self.stream = MagicMock() if delete_flush: del self.stream.flush else: self.stream = stream self.report = extensions.PrintReport( ['epoch'], log_report=self.logreport, out=self.stream) self.trainer = testing.get_trainer_with_mock_updater( stop_trigger=(1, 'iteration')) self.trainer.extend(self.logreport) self.trainer.extend(self.report) self.logreport.log = [{'epoch': 0}] def test_stream_with_flush_is_flushed(self): self._setup(delete_flush=False) self.assertTrue(hasattr(self.stream, 'flush')) self.stream.flush.assert_not_called() self.report(self.trainer) self.stream.flush.assert_called_with() def test_stream_without_flush_raises_no_exception(self): self._setup(delete_flush=True) self.assertFalse(hasattr(self.stream, 'flush')) self.report(self.trainer) def test_real_stream_raises_no_exception(self): self._setup(stream=sys.stderr) self.report(self.trainer) testing.run_module(__name__, __file__)
<commit_before>import sys import unittest from mock import MagicMock from chainer import testing from chainer.training import extensions class TestPrintReport(unittest.TestCase): def _setup(self, delete_flush=False): self.logreport = MagicMock(spec=extensions.LogReport( ['epoch'], trigger=(1, 'iteration'), log_name=None)) self.stream = MagicMock() if delete_flush: del self.stream.flush self.report = extensions.PrintReport( ['epoch'], log_report=self.logreport, out=self.stream) self.trainer = testing.get_trainer_with_mock_updater( stop_trigger=(1, 'iteration')) self.trainer.extend(self.logreport) self.trainer.extend(self.report) self.logreport.log = [{'epoch': 0}] def test_stream_with_flush_is_flushed(self): self._setup(delete_flush=False) self.assertTrue(hasattr(self.stream, 'flush')) self.stream.flush.assert_not_called() self.report(self.trainer) self.stream.flush.assert_called_with() def test_stream_without_flush_raises_no_exception(self): self._setup(delete_flush=True) self.assertFalse(hasattr(self.stream, 'flush')) self.report(self.trainer) testing.run_module(__name__, __file__) <commit_msg>Test PrintReport with a real stream<commit_after>
import sys import unittest from mock import MagicMock from chainer import testing from chainer.training import extensions class TestPrintReport(unittest.TestCase): def _setup(self, stream=None, delete_flush=False): self.logreport = MagicMock(spec=extensions.LogReport( ['epoch'], trigger=(1, 'iteration'), log_name=None)) if stream is None: self.stream = MagicMock() if delete_flush: del self.stream.flush else: self.stream = stream self.report = extensions.PrintReport( ['epoch'], log_report=self.logreport, out=self.stream) self.trainer = testing.get_trainer_with_mock_updater( stop_trigger=(1, 'iteration')) self.trainer.extend(self.logreport) self.trainer.extend(self.report) self.logreport.log = [{'epoch': 0}] def test_stream_with_flush_is_flushed(self): self._setup(delete_flush=False) self.assertTrue(hasattr(self.stream, 'flush')) self.stream.flush.assert_not_called() self.report(self.trainer) self.stream.flush.assert_called_with() def test_stream_without_flush_raises_no_exception(self): self._setup(delete_flush=True) self.assertFalse(hasattr(self.stream, 'flush')) self.report(self.trainer) def test_real_stream_raises_no_exception(self): self._setup(stream=sys.stderr) self.report(self.trainer) testing.run_module(__name__, __file__)
import sys import unittest from mock import MagicMock from chainer import testing from chainer.training import extensions class TestPrintReport(unittest.TestCase): def _setup(self, delete_flush=False): self.logreport = MagicMock(spec=extensions.LogReport( ['epoch'], trigger=(1, 'iteration'), log_name=None)) self.stream = MagicMock() if delete_flush: del self.stream.flush self.report = extensions.PrintReport( ['epoch'], log_report=self.logreport, out=self.stream) self.trainer = testing.get_trainer_with_mock_updater( stop_trigger=(1, 'iteration')) self.trainer.extend(self.logreport) self.trainer.extend(self.report) self.logreport.log = [{'epoch': 0}] def test_stream_with_flush_is_flushed(self): self._setup(delete_flush=False) self.assertTrue(hasattr(self.stream, 'flush')) self.stream.flush.assert_not_called() self.report(self.trainer) self.stream.flush.assert_called_with() def test_stream_without_flush_raises_no_exception(self): self._setup(delete_flush=True) self.assertFalse(hasattr(self.stream, 'flush')) self.report(self.trainer) testing.run_module(__name__, __file__) Test PrintReport with a real streamimport sys import unittest from mock import MagicMock from chainer import testing from chainer.training import extensions class TestPrintReport(unittest.TestCase): def _setup(self, stream=None, delete_flush=False): self.logreport = MagicMock(spec=extensions.LogReport( ['epoch'], trigger=(1, 'iteration'), log_name=None)) if stream is None: self.stream = MagicMock() if delete_flush: del self.stream.flush else: self.stream = stream self.report = extensions.PrintReport( ['epoch'], log_report=self.logreport, out=self.stream) self.trainer = testing.get_trainer_with_mock_updater( stop_trigger=(1, 'iteration')) self.trainer.extend(self.logreport) self.trainer.extend(self.report) self.logreport.log = [{'epoch': 0}] def test_stream_with_flush_is_flushed(self): self._setup(delete_flush=False) self.assertTrue(hasattr(self.stream, 'flush')) self.stream.flush.assert_not_called() self.report(self.trainer) self.stream.flush.assert_called_with() def test_stream_without_flush_raises_no_exception(self): self._setup(delete_flush=True) self.assertFalse(hasattr(self.stream, 'flush')) self.report(self.trainer) def test_real_stream_raises_no_exception(self): self._setup(stream=sys.stderr) self.report(self.trainer) testing.run_module(__name__, __file__)
<commit_before>import sys import unittest from mock import MagicMock from chainer import testing from chainer.training import extensions class TestPrintReport(unittest.TestCase): def _setup(self, delete_flush=False): self.logreport = MagicMock(spec=extensions.LogReport( ['epoch'], trigger=(1, 'iteration'), log_name=None)) self.stream = MagicMock() if delete_flush: del self.stream.flush self.report = extensions.PrintReport( ['epoch'], log_report=self.logreport, out=self.stream) self.trainer = testing.get_trainer_with_mock_updater( stop_trigger=(1, 'iteration')) self.trainer.extend(self.logreport) self.trainer.extend(self.report) self.logreport.log = [{'epoch': 0}] def test_stream_with_flush_is_flushed(self): self._setup(delete_flush=False) self.assertTrue(hasattr(self.stream, 'flush')) self.stream.flush.assert_not_called() self.report(self.trainer) self.stream.flush.assert_called_with() def test_stream_without_flush_raises_no_exception(self): self._setup(delete_flush=True) self.assertFalse(hasattr(self.stream, 'flush')) self.report(self.trainer) testing.run_module(__name__, __file__) <commit_msg>Test PrintReport with a real stream<commit_after>import sys import unittest from mock import MagicMock from chainer import testing from chainer.training import extensions class TestPrintReport(unittest.TestCase): def _setup(self, stream=None, delete_flush=False): self.logreport = MagicMock(spec=extensions.LogReport( ['epoch'], trigger=(1, 'iteration'), log_name=None)) if stream is None: self.stream = MagicMock() if delete_flush: del self.stream.flush else: self.stream = stream self.report = extensions.PrintReport( ['epoch'], log_report=self.logreport, out=self.stream) self.trainer = testing.get_trainer_with_mock_updater( stop_trigger=(1, 'iteration')) self.trainer.extend(self.logreport) self.trainer.extend(self.report) self.logreport.log = [{'epoch': 0}] def test_stream_with_flush_is_flushed(self): self._setup(delete_flush=False) self.assertTrue(hasattr(self.stream, 'flush')) self.stream.flush.assert_not_called() self.report(self.trainer) self.stream.flush.assert_called_with() def test_stream_without_flush_raises_no_exception(self): self._setup(delete_flush=True) self.assertFalse(hasattr(self.stream, 'flush')) self.report(self.trainer) def test_real_stream_raises_no_exception(self): self._setup(stream=sys.stderr) self.report(self.trainer) testing.run_module(__name__, __file__)
798e547eba14721009854796e4306dc7d739bc03
manage.py
manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", os.environ['DJANGO_SETTINGS_MODULE']) from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
UPDATE - change env variable
UPDATE - change env variable
Python
mit
mingkim/QuesCheetah,mingkim/QuesCheetah,mingkim/QuesCheetah,mingkim/QuesCheetah
#!/usr/bin/env python import os import sys if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) UPDATE - change env variable
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", os.environ['DJANGO_SETTINGS_MODULE']) from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
<commit_before>#!/usr/bin/env python import os import sys if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) <commit_msg>UPDATE - change env variable<commit_after>
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", os.environ['DJANGO_SETTINGS_MODULE']) from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) UPDATE - change env variable#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", os.environ['DJANGO_SETTINGS_MODULE']) from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
<commit_before>#!/usr/bin/env python import os import sys if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) <commit_msg>UPDATE - change env variable<commit_after>#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", os.environ['DJANGO_SETTINGS_MODULE']) from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
36708e49f29ccbac33827ea8331760e27aa7320f
manage.py
manage.py
#!/usr/bin/python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Use env python instance, not a static location, fixes virtualenv oddities
Use env python instance, not a static location, fixes virtualenv oddities
Python
bsd-3-clause
nikdoof/test-auth
#!/usr/bin/python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings) Use env python instance, not a static location, fixes virtualenv oddities
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
<commit_before>#!/usr/bin/python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings) <commit_msg>Use env python instance, not a static location, fixes virtualenv oddities<commit_after>
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
#!/usr/bin/python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings) Use env python instance, not a static location, fixes virtualenv oddities#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
<commit_before>#!/usr/bin/python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings) <commit_msg>Use env python instance, not a static location, fixes virtualenv oddities<commit_after>#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
95eb73ce7645ae6275fbb958ec803ce521b16198
helusers/urls.py
helusers/urls.py
"""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." )
"""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." ) urlpatterns.extend( [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] )
Check configuration before specifying urlpatterns
Check configuration before specifying urlpatterns If the configuration is incorrect, it doesn't make sense to specify the URL patterns in that case.
Python
bsd-2-clause
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
"""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." ) Check configuration before specifying urlpatterns If the configuration is incorrect, it doesn't make sense to specify the URL patterns in that case.
"""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." ) urlpatterns.extend( [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] )
<commit_before>"""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." ) <commit_msg>Check configuration before specifying urlpatterns If the configuration is incorrect, it doesn't make sense to specify the URL patterns in that case.<commit_after>
"""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." ) urlpatterns.extend( [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] )
"""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." ) Check configuration before specifying urlpatterns If the configuration is incorrect, it doesn't make sense to specify the URL patterns in that case."""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." ) urlpatterns.extend( [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] )
<commit_before>"""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." ) <commit_msg>Check configuration before specifying urlpatterns If the configuration is incorrect, it doesn't make sense to specify the URL patterns in that case.<commit_after>"""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." ) urlpatterns.extend( [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] )
0778a0a47967f0283a22908bcf89c0d98ce1647f
tests/test_redefine_colors.py
tests/test_redefine_colors.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Test redefinition of colors.""" import colorise import pytest @pytest.mark.skip_on_windows def test_redefine_colors_error(): with pytest.raises(colorise.error.NotSupportedError): colorise.redefine_colors({})
#!/usr/bin/env python # -*- coding: utf-8 -*- """Test redefinition of colors.""" import colorise import pytest @pytest.mark.skip_on_windows def test_redefine_colors_error(): assert not colorise.can_redefine_colors() with pytest.raises(colorise.error.NotSupportedError): colorise.redefine_colors({})
Test color redefinition on nix
Test color redefinition on nix
Python
bsd-3-clause
MisanthropicBit/colorise
#!/usr/bin/env python # -*- coding: utf-8 -*- """Test redefinition of colors.""" import colorise import pytest @pytest.mark.skip_on_windows def test_redefine_colors_error(): with pytest.raises(colorise.error.NotSupportedError): colorise.redefine_colors({}) Test color redefinition on nix
#!/usr/bin/env python # -*- coding: utf-8 -*- """Test redefinition of colors.""" import colorise import pytest @pytest.mark.skip_on_windows def test_redefine_colors_error(): assert not colorise.can_redefine_colors() with pytest.raises(colorise.error.NotSupportedError): colorise.redefine_colors({})
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- """Test redefinition of colors.""" import colorise import pytest @pytest.mark.skip_on_windows def test_redefine_colors_error(): with pytest.raises(colorise.error.NotSupportedError): colorise.redefine_colors({}) <commit_msg>Test color redefinition on nix<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- """Test redefinition of colors.""" import colorise import pytest @pytest.mark.skip_on_windows def test_redefine_colors_error(): assert not colorise.can_redefine_colors() with pytest.raises(colorise.error.NotSupportedError): colorise.redefine_colors({})
#!/usr/bin/env python # -*- coding: utf-8 -*- """Test redefinition of colors.""" import colorise import pytest @pytest.mark.skip_on_windows def test_redefine_colors_error(): with pytest.raises(colorise.error.NotSupportedError): colorise.redefine_colors({}) Test color redefinition on nix#!/usr/bin/env python # -*- coding: utf-8 -*- """Test redefinition of colors.""" import colorise import pytest @pytest.mark.skip_on_windows def test_redefine_colors_error(): assert not colorise.can_redefine_colors() with pytest.raises(colorise.error.NotSupportedError): colorise.redefine_colors({})
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- """Test redefinition of colors.""" import colorise import pytest @pytest.mark.skip_on_windows def test_redefine_colors_error(): with pytest.raises(colorise.error.NotSupportedError): colorise.redefine_colors({}) <commit_msg>Test color redefinition on nix<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- """Test redefinition of colors.""" import colorise import pytest @pytest.mark.skip_on_windows def test_redefine_colors_error(): assert not colorise.can_redefine_colors() with pytest.raises(colorise.error.NotSupportedError): colorise.redefine_colors({})
963ad8662b44d223bd5003c848dccc65802016e3
src/tests/utils.py
src/tests/utils.py
# -*- coding: utf-8 -*- """ Created on Sat Aug 24 14:44:07 2013 @author: steve """ import numpy as np import scipy as sp import mdptoolbox.example STATES = 10 ACTIONS = 3 SMALLNUM = 10e-12 # np.arrays P_small = np.array([[[0.5, 0.5],[0.8, 0.2]],[[0, 1],[0.1, 0.9]]]) R_small = np.array([[5, 10], [-1, 2]]) P_sparse = np.empty(2, dtype=object) P_sparse[0] = sp.sparse.csr_matrix([[0.5, 0.5],[0.8, 0.2]]) P_sparse[1] = sp.sparse.csr_matrix([[0, 1],[0.1, 0.9]]) P_forest, R_forest = mdptoolbox.example.forest() P_forest_sparse, R_forest_sparse = mdptoolbox.example.forest(S=STATES, is_sparse=True) np.random.seed(0) P_rand, R_rand = mdptoolbox.example.rand(STATES, ACTIONS) np.random.seed(0) P_rand_sparse, R_rand_sparse = mdptoolbox.example.rand(STATES, ACTIONS, is_sparse=True)
# -*- coding: utf-8 -*- """ Created on Sat Aug 24 14:44:07 2013 @author: steve """ import numpy as np import scipy as sp import mdptoolbox.example STATES = 10 ACTIONS = 3 SMALLNUM = 10e-12 # np.arrays P_small, R_small = mdptoolbox.example.small() P_sparse = np.empty(2, dtype=object) P_sparse[0] = sp.sparse.csr_matrix(P_small[0]) P_sparse[1] = sp.sparse.csr_matrix(P_small[1]) P_forest, R_forest = mdptoolbox.example.forest() P_forest_sparse, R_forest_sparse = mdptoolbox.example.forest(S=STATES, is_sparse=True) np.random.seed(0) P_rand, R_rand = mdptoolbox.example.rand(STATES, ACTIONS) np.random.seed(0) P_rand_sparse, R_rand_sparse = mdptoolbox.example.rand(STATES, ACTIONS, is_sparse=True)
Use mdptoolbox.example.small in the tests
[tests] Use mdptoolbox.example.small in the tests
Python
bsd-3-clause
yasserglez/pymdptoolbox,silgon/pymdptoolbox,sawcordwell/pymdptoolbox,yasserglez/pymdptoolbox,sawcordwell/pymdptoolbox,silgon/pymdptoolbox,McCabeJM/pymdptoolbox,McCabeJM/pymdptoolbox
# -*- coding: utf-8 -*- """ Created on Sat Aug 24 14:44:07 2013 @author: steve """ import numpy as np import scipy as sp import mdptoolbox.example STATES = 10 ACTIONS = 3 SMALLNUM = 10e-12 # np.arrays P_small = np.array([[[0.5, 0.5],[0.8, 0.2]],[[0, 1],[0.1, 0.9]]]) R_small = np.array([[5, 10], [-1, 2]]) P_sparse = np.empty(2, dtype=object) P_sparse[0] = sp.sparse.csr_matrix([[0.5, 0.5],[0.8, 0.2]]) P_sparse[1] = sp.sparse.csr_matrix([[0, 1],[0.1, 0.9]]) P_forest, R_forest = mdptoolbox.example.forest() P_forest_sparse, R_forest_sparse = mdptoolbox.example.forest(S=STATES, is_sparse=True) np.random.seed(0) P_rand, R_rand = mdptoolbox.example.rand(STATES, ACTIONS) np.random.seed(0) P_rand_sparse, R_rand_sparse = mdptoolbox.example.rand(STATES, ACTIONS, is_sparse=True) [tests] Use mdptoolbox.example.small in the tests
# -*- coding: utf-8 -*- """ Created on Sat Aug 24 14:44:07 2013 @author: steve """ import numpy as np import scipy as sp import mdptoolbox.example STATES = 10 ACTIONS = 3 SMALLNUM = 10e-12 # np.arrays P_small, R_small = mdptoolbox.example.small() P_sparse = np.empty(2, dtype=object) P_sparse[0] = sp.sparse.csr_matrix(P_small[0]) P_sparse[1] = sp.sparse.csr_matrix(P_small[1]) P_forest, R_forest = mdptoolbox.example.forest() P_forest_sparse, R_forest_sparse = mdptoolbox.example.forest(S=STATES, is_sparse=True) np.random.seed(0) P_rand, R_rand = mdptoolbox.example.rand(STATES, ACTIONS) np.random.seed(0) P_rand_sparse, R_rand_sparse = mdptoolbox.example.rand(STATES, ACTIONS, is_sparse=True)
<commit_before># -*- coding: utf-8 -*- """ Created on Sat Aug 24 14:44:07 2013 @author: steve """ import numpy as np import scipy as sp import mdptoolbox.example STATES = 10 ACTIONS = 3 SMALLNUM = 10e-12 # np.arrays P_small = np.array([[[0.5, 0.5],[0.8, 0.2]],[[0, 1],[0.1, 0.9]]]) R_small = np.array([[5, 10], [-1, 2]]) P_sparse = np.empty(2, dtype=object) P_sparse[0] = sp.sparse.csr_matrix([[0.5, 0.5],[0.8, 0.2]]) P_sparse[1] = sp.sparse.csr_matrix([[0, 1],[0.1, 0.9]]) P_forest, R_forest = mdptoolbox.example.forest() P_forest_sparse, R_forest_sparse = mdptoolbox.example.forest(S=STATES, is_sparse=True) np.random.seed(0) P_rand, R_rand = mdptoolbox.example.rand(STATES, ACTIONS) np.random.seed(0) P_rand_sparse, R_rand_sparse = mdptoolbox.example.rand(STATES, ACTIONS, is_sparse=True) <commit_msg>[tests] Use mdptoolbox.example.small in the tests<commit_after>
# -*- coding: utf-8 -*- """ Created on Sat Aug 24 14:44:07 2013 @author: steve """ import numpy as np import scipy as sp import mdptoolbox.example STATES = 10 ACTIONS = 3 SMALLNUM = 10e-12 # np.arrays P_small, R_small = mdptoolbox.example.small() P_sparse = np.empty(2, dtype=object) P_sparse[0] = sp.sparse.csr_matrix(P_small[0]) P_sparse[1] = sp.sparse.csr_matrix(P_small[1]) P_forest, R_forest = mdptoolbox.example.forest() P_forest_sparse, R_forest_sparse = mdptoolbox.example.forest(S=STATES, is_sparse=True) np.random.seed(0) P_rand, R_rand = mdptoolbox.example.rand(STATES, ACTIONS) np.random.seed(0) P_rand_sparse, R_rand_sparse = mdptoolbox.example.rand(STATES, ACTIONS, is_sparse=True)
# -*- coding: utf-8 -*- """ Created on Sat Aug 24 14:44:07 2013 @author: steve """ import numpy as np import scipy as sp import mdptoolbox.example STATES = 10 ACTIONS = 3 SMALLNUM = 10e-12 # np.arrays P_small = np.array([[[0.5, 0.5],[0.8, 0.2]],[[0, 1],[0.1, 0.9]]]) R_small = np.array([[5, 10], [-1, 2]]) P_sparse = np.empty(2, dtype=object) P_sparse[0] = sp.sparse.csr_matrix([[0.5, 0.5],[0.8, 0.2]]) P_sparse[1] = sp.sparse.csr_matrix([[0, 1],[0.1, 0.9]]) P_forest, R_forest = mdptoolbox.example.forest() P_forest_sparse, R_forest_sparse = mdptoolbox.example.forest(S=STATES, is_sparse=True) np.random.seed(0) P_rand, R_rand = mdptoolbox.example.rand(STATES, ACTIONS) np.random.seed(0) P_rand_sparse, R_rand_sparse = mdptoolbox.example.rand(STATES, ACTIONS, is_sparse=True) [tests] Use mdptoolbox.example.small in the tests# -*- coding: utf-8 -*- """ Created on Sat Aug 24 14:44:07 2013 @author: steve """ import numpy as np import scipy as sp import mdptoolbox.example STATES = 10 ACTIONS = 3 SMALLNUM = 10e-12 # np.arrays P_small, R_small = mdptoolbox.example.small() P_sparse = np.empty(2, dtype=object) P_sparse[0] = sp.sparse.csr_matrix(P_small[0]) P_sparse[1] = sp.sparse.csr_matrix(P_small[1]) P_forest, R_forest = mdptoolbox.example.forest() P_forest_sparse, R_forest_sparse = mdptoolbox.example.forest(S=STATES, is_sparse=True) np.random.seed(0) P_rand, R_rand = mdptoolbox.example.rand(STATES, ACTIONS) np.random.seed(0) P_rand_sparse, R_rand_sparse = mdptoolbox.example.rand(STATES, ACTIONS, is_sparse=True)
<commit_before># -*- coding: utf-8 -*- """ Created on Sat Aug 24 14:44:07 2013 @author: steve """ import numpy as np import scipy as sp import mdptoolbox.example STATES = 10 ACTIONS = 3 SMALLNUM = 10e-12 # np.arrays P_small = np.array([[[0.5, 0.5],[0.8, 0.2]],[[0, 1],[0.1, 0.9]]]) R_small = np.array([[5, 10], [-1, 2]]) P_sparse = np.empty(2, dtype=object) P_sparse[0] = sp.sparse.csr_matrix([[0.5, 0.5],[0.8, 0.2]]) P_sparse[1] = sp.sparse.csr_matrix([[0, 1],[0.1, 0.9]]) P_forest, R_forest = mdptoolbox.example.forest() P_forest_sparse, R_forest_sparse = mdptoolbox.example.forest(S=STATES, is_sparse=True) np.random.seed(0) P_rand, R_rand = mdptoolbox.example.rand(STATES, ACTIONS) np.random.seed(0) P_rand_sparse, R_rand_sparse = mdptoolbox.example.rand(STATES, ACTIONS, is_sparse=True) <commit_msg>[tests] Use mdptoolbox.example.small in the tests<commit_after># -*- coding: utf-8 -*- """ Created on Sat Aug 24 14:44:07 2013 @author: steve """ import numpy as np import scipy as sp import mdptoolbox.example STATES = 10 ACTIONS = 3 SMALLNUM = 10e-12 # np.arrays P_small, R_small = mdptoolbox.example.small() P_sparse = np.empty(2, dtype=object) P_sparse[0] = sp.sparse.csr_matrix(P_small[0]) P_sparse[1] = sp.sparse.csr_matrix(P_small[1]) P_forest, R_forest = mdptoolbox.example.forest() P_forest_sparse, R_forest_sparse = mdptoolbox.example.forest(S=STATES, is_sparse=True) np.random.seed(0) P_rand, R_rand = mdptoolbox.example.rand(STATES, ACTIONS) np.random.seed(0) P_rand_sparse, R_rand_sparse = mdptoolbox.example.rand(STATES, ACTIONS, is_sparse=True)
810c4061a4ba34eef862a5c8e0d6fafbdb9ec566
allauth/socialaccount/providers/stripe/provider.py
allauth/socialaccount/providers/stripe/provider.py
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class StripeAccount(ProviderAccount): pass class StripeProvider(OAuth2Provider): id = 'stripe' name = 'Stripe' account_class = StripeAccount def extract_uid(self, data): return data['id'] def extract_common_fields(self, data): return dict(name=data.get('display_name'), email=data.get('email')) def get_default_scope(self): return ['read_only'] provider_classes = [StripeProvider]
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class StripeAccount(ProviderAccount): def to_str(self): default = super(StripeAccount, self).to_str() return self.account.extra_data.get('business_name', default) class StripeProvider(OAuth2Provider): id = 'stripe' name = 'Stripe' account_class = StripeAccount def extract_uid(self, data): return data['id'] def extract_common_fields(self, data): return dict(name=data.get('display_name'), email=data.get('email')) def get_default_scope(self): return ['read_only'] provider_classes = [StripeProvider]
Add proper stringification via StripeAccount.to_str
feat(stripe): Add proper stringification via StripeAccount.to_str Better stringification for Stripe accounts, using the 'business_name' key in extra_data. Addresses #1871.
Python
mit
pztrick/django-allauth,rsalmaso/django-allauth,pztrick/django-allauth,lukeburden/django-allauth,bittner/django-allauth,pennersr/django-allauth,pennersr/django-allauth,bittner/django-allauth,AltSchool/django-allauth,lukeburden/django-allauth,lukeburden/django-allauth,rsalmaso/django-allauth,bittner/django-allauth,rsalmaso/django-allauth,pennersr/django-allauth,AltSchool/django-allauth,pztrick/django-allauth,AltSchool/django-allauth
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class StripeAccount(ProviderAccount): pass class StripeProvider(OAuth2Provider): id = 'stripe' name = 'Stripe' account_class = StripeAccount def extract_uid(self, data): return data['id'] def extract_common_fields(self, data): return dict(name=data.get('display_name'), email=data.get('email')) def get_default_scope(self): return ['read_only'] provider_classes = [StripeProvider] feat(stripe): Add proper stringification via StripeAccount.to_str Better stringification for Stripe accounts, using the 'business_name' key in extra_data. Addresses #1871.
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class StripeAccount(ProviderAccount): def to_str(self): default = super(StripeAccount, self).to_str() return self.account.extra_data.get('business_name', default) class StripeProvider(OAuth2Provider): id = 'stripe' name = 'Stripe' account_class = StripeAccount def extract_uid(self, data): return data['id'] def extract_common_fields(self, data): return dict(name=data.get('display_name'), email=data.get('email')) def get_default_scope(self): return ['read_only'] provider_classes = [StripeProvider]
<commit_before>from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class StripeAccount(ProviderAccount): pass class StripeProvider(OAuth2Provider): id = 'stripe' name = 'Stripe' account_class = StripeAccount def extract_uid(self, data): return data['id'] def extract_common_fields(self, data): return dict(name=data.get('display_name'), email=data.get('email')) def get_default_scope(self): return ['read_only'] provider_classes = [StripeProvider] <commit_msg>feat(stripe): Add proper stringification via StripeAccount.to_str Better stringification for Stripe accounts, using the 'business_name' key in extra_data. Addresses #1871.<commit_after>
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class StripeAccount(ProviderAccount): def to_str(self): default = super(StripeAccount, self).to_str() return self.account.extra_data.get('business_name', default) class StripeProvider(OAuth2Provider): id = 'stripe' name = 'Stripe' account_class = StripeAccount def extract_uid(self, data): return data['id'] def extract_common_fields(self, data): return dict(name=data.get('display_name'), email=data.get('email')) def get_default_scope(self): return ['read_only'] provider_classes = [StripeProvider]
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class StripeAccount(ProviderAccount): pass class StripeProvider(OAuth2Provider): id = 'stripe' name = 'Stripe' account_class = StripeAccount def extract_uid(self, data): return data['id'] def extract_common_fields(self, data): return dict(name=data.get('display_name'), email=data.get('email')) def get_default_scope(self): return ['read_only'] provider_classes = [StripeProvider] feat(stripe): Add proper stringification via StripeAccount.to_str Better stringification for Stripe accounts, using the 'business_name' key in extra_data. Addresses #1871.from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class StripeAccount(ProviderAccount): def to_str(self): default = super(StripeAccount, self).to_str() return self.account.extra_data.get('business_name', default) class StripeProvider(OAuth2Provider): id = 'stripe' name = 'Stripe' account_class = StripeAccount def extract_uid(self, data): return data['id'] def extract_common_fields(self, data): return dict(name=data.get('display_name'), email=data.get('email')) def get_default_scope(self): return ['read_only'] provider_classes = [StripeProvider]
<commit_before>from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class StripeAccount(ProviderAccount): pass class StripeProvider(OAuth2Provider): id = 'stripe' name = 'Stripe' account_class = StripeAccount def extract_uid(self, data): return data['id'] def extract_common_fields(self, data): return dict(name=data.get('display_name'), email=data.get('email')) def get_default_scope(self): return ['read_only'] provider_classes = [StripeProvider] <commit_msg>feat(stripe): Add proper stringification via StripeAccount.to_str Better stringification for Stripe accounts, using the 'business_name' key in extra_data. Addresses #1871.<commit_after>from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class StripeAccount(ProviderAccount): def to_str(self): default = super(StripeAccount, self).to_str() return self.account.extra_data.get('business_name', default) class StripeProvider(OAuth2Provider): id = 'stripe' name = 'Stripe' account_class = StripeAccount def extract_uid(self, data): return data['id'] def extract_common_fields(self, data): return dict(name=data.get('display_name'), email=data.get('email')) def get_default_scope(self): return ['read_only'] provider_classes = [StripeProvider]
6fb5110d4fb1c3de7d065267f9d8f7302c303ec1
allauth/socialaccount/providers/twitch/provider.py
allauth/socialaccount/providers/twitch/provider.py
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class TwitchAccount(ProviderAccount): def get_profile_url(self): return 'http://twitch.tv/' + self.account.extra_data.get('name') def get_avatar_url(self): return self.account.extra_data.get('logo') def to_str(self): dflt = super(TwitchAccount, self).to_str() return self.account.extra_data.get('name', dflt) class TwitchProvider(OAuth2Provider): id = 'twitch' name = 'Twitch' account_class = TwitchAccount def extract_uid(self, data): return str(data['_id']) def extract_common_fields(self, data): return dict(username=data.get('name'), name=data.get('display_name'), email=data.get('email')) provider_classes = [TwitchProvider]
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class TwitchAccount(ProviderAccount): def get_profile_url(self): return 'http://twitch.tv/' + self.account.extra_data.get('name') def get_avatar_url(self): return self.account.extra_data.get('logo') def to_str(self): dflt = super(TwitchAccount, self).to_str() return self.account.extra_data.get('name', dflt) class TwitchProvider(OAuth2Provider): id = 'twitch' name = 'Twitch' account_class = TwitchAccount def extract_uid(self, data): return str(data['_id']) def extract_common_fields(self, data): return { "username": data.get("name"), "name": data.get("display_name"), "email": data.get("email"), } def get_default_scope(self): return ["user_read"] provider_classes = [TwitchProvider]
Add user_read as default scope
twitch: Add user_read as default scope
Python
mit
bittner/django-allauth,pennersr/django-allauth,pztrick/django-allauth,rsalmaso/django-allauth,rsalmaso/django-allauth,bittner/django-allauth,pztrick/django-allauth,lukeburden/django-allauth,AltSchool/django-allauth,pennersr/django-allauth,AltSchool/django-allauth,pennersr/django-allauth,AltSchool/django-allauth,rsalmaso/django-allauth,lukeburden/django-allauth,bittner/django-allauth,pztrick/django-allauth,lukeburden/django-allauth
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class TwitchAccount(ProviderAccount): def get_profile_url(self): return 'http://twitch.tv/' + self.account.extra_data.get('name') def get_avatar_url(self): return self.account.extra_data.get('logo') def to_str(self): dflt = super(TwitchAccount, self).to_str() return self.account.extra_data.get('name', dflt) class TwitchProvider(OAuth2Provider): id = 'twitch' name = 'Twitch' account_class = TwitchAccount def extract_uid(self, data): return str(data['_id']) def extract_common_fields(self, data): return dict(username=data.get('name'), name=data.get('display_name'), email=data.get('email')) provider_classes = [TwitchProvider] twitch: Add user_read as default scope
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class TwitchAccount(ProviderAccount): def get_profile_url(self): return 'http://twitch.tv/' + self.account.extra_data.get('name') def get_avatar_url(self): return self.account.extra_data.get('logo') def to_str(self): dflt = super(TwitchAccount, self).to_str() return self.account.extra_data.get('name', dflt) class TwitchProvider(OAuth2Provider): id = 'twitch' name = 'Twitch' account_class = TwitchAccount def extract_uid(self, data): return str(data['_id']) def extract_common_fields(self, data): return { "username": data.get("name"), "name": data.get("display_name"), "email": data.get("email"), } def get_default_scope(self): return ["user_read"] provider_classes = [TwitchProvider]
<commit_before>from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class TwitchAccount(ProviderAccount): def get_profile_url(self): return 'http://twitch.tv/' + self.account.extra_data.get('name') def get_avatar_url(self): return self.account.extra_data.get('logo') def to_str(self): dflt = super(TwitchAccount, self).to_str() return self.account.extra_data.get('name', dflt) class TwitchProvider(OAuth2Provider): id = 'twitch' name = 'Twitch' account_class = TwitchAccount def extract_uid(self, data): return str(data['_id']) def extract_common_fields(self, data): return dict(username=data.get('name'), name=data.get('display_name'), email=data.get('email')) provider_classes = [TwitchProvider] <commit_msg>twitch: Add user_read as default scope<commit_after>
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class TwitchAccount(ProviderAccount): def get_profile_url(self): return 'http://twitch.tv/' + self.account.extra_data.get('name') def get_avatar_url(self): return self.account.extra_data.get('logo') def to_str(self): dflt = super(TwitchAccount, self).to_str() return self.account.extra_data.get('name', dflt) class TwitchProvider(OAuth2Provider): id = 'twitch' name = 'Twitch' account_class = TwitchAccount def extract_uid(self, data): return str(data['_id']) def extract_common_fields(self, data): return { "username": data.get("name"), "name": data.get("display_name"), "email": data.get("email"), } def get_default_scope(self): return ["user_read"] provider_classes = [TwitchProvider]
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class TwitchAccount(ProviderAccount): def get_profile_url(self): return 'http://twitch.tv/' + self.account.extra_data.get('name') def get_avatar_url(self): return self.account.extra_data.get('logo') def to_str(self): dflt = super(TwitchAccount, self).to_str() return self.account.extra_data.get('name', dflt) class TwitchProvider(OAuth2Provider): id = 'twitch' name = 'Twitch' account_class = TwitchAccount def extract_uid(self, data): return str(data['_id']) def extract_common_fields(self, data): return dict(username=data.get('name'), name=data.get('display_name'), email=data.get('email')) provider_classes = [TwitchProvider] twitch: Add user_read as default scopefrom allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class TwitchAccount(ProviderAccount): def get_profile_url(self): return 'http://twitch.tv/' + self.account.extra_data.get('name') def get_avatar_url(self): return self.account.extra_data.get('logo') def to_str(self): dflt = super(TwitchAccount, self).to_str() return self.account.extra_data.get('name', dflt) class TwitchProvider(OAuth2Provider): id = 'twitch' name = 'Twitch' account_class = TwitchAccount def extract_uid(self, data): return str(data['_id']) def extract_common_fields(self, data): return { "username": data.get("name"), "name": data.get("display_name"), "email": data.get("email"), } def get_default_scope(self): return ["user_read"] provider_classes = [TwitchProvider]
<commit_before>from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class TwitchAccount(ProviderAccount): def get_profile_url(self): return 'http://twitch.tv/' + self.account.extra_data.get('name') def get_avatar_url(self): return self.account.extra_data.get('logo') def to_str(self): dflt = super(TwitchAccount, self).to_str() return self.account.extra_data.get('name', dflt) class TwitchProvider(OAuth2Provider): id = 'twitch' name = 'Twitch' account_class = TwitchAccount def extract_uid(self, data): return str(data['_id']) def extract_common_fields(self, data): return dict(username=data.get('name'), name=data.get('display_name'), email=data.get('email')) provider_classes = [TwitchProvider] <commit_msg>twitch: Add user_read as default scope<commit_after>from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class TwitchAccount(ProviderAccount): def get_profile_url(self): return 'http://twitch.tv/' + self.account.extra_data.get('name') def get_avatar_url(self): return self.account.extra_data.get('logo') def to_str(self): dflt = super(TwitchAccount, self).to_str() return self.account.extra_data.get('name', dflt) class TwitchProvider(OAuth2Provider): id = 'twitch' name = 'Twitch' account_class = TwitchAccount def extract_uid(self, data): return str(data['_id']) def extract_common_fields(self, data): return { "username": data.get("name"), "name": data.get("display_name"), "email": data.get("email"), } def get_default_scope(self): return ["user_read"] provider_classes = [TwitchProvider]
00497693001193789c26823fe96044259380b493
inthe_am/taskmanager/models/bugwarriorconfigrunlog.py
inthe_am/taskmanager/models/bugwarriorconfigrunlog.py
from django.db import models from .bugwarriorconfig import BugwarriorConfig class BugwarriorConfigRunLog(models.Model): config = models.ForeignKey( BugwarriorConfig, related_name='run_logs', ) success = models.BooleanField(default=False) output = models.TextField() stack_trace = models.TextField() started = models.DateTimeField() finished = models.DateTimeField(null=True) def add_output(self, new): lines = [line for line in self.output.split('\n') if line] lines.append(new) self.output = '\n'.join(lines) def __unicode__(self): if self.success: category = 'Successful' else: category = 'Failed' return u"{category} bugwarrior-pull run of {config}".format( category=category, config=self.config ) class Meta: app_label = 'taskmanager'
from django.db import models from .bugwarriorconfig import BugwarriorConfig class BugwarriorConfigRunLog(models.Model): config = models.ForeignKey( BugwarriorConfig, related_name='run_logs', ) success = models.BooleanField(default=False) output = models.TextField() stack_trace = models.TextField() started = models.DateTimeField() finished = models.DateTimeField(null=True) def add_output(self, new): lines = [line for line in self.output.split('\n') if line] lines.append(new) self.output = '\n'.join(lines) self.save() def __unicode__(self): if self.success: category = 'Successful' else: category = 'Failed' return u"{category} bugwarrior-pull run of {config}".format( category=category, config=self.config ) class Meta: app_label = 'taskmanager'
Save runlog as output is added.
Save runlog as output is added.
Python
agpl-3.0
coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am
from django.db import models from .bugwarriorconfig import BugwarriorConfig class BugwarriorConfigRunLog(models.Model): config = models.ForeignKey( BugwarriorConfig, related_name='run_logs', ) success = models.BooleanField(default=False) output = models.TextField() stack_trace = models.TextField() started = models.DateTimeField() finished = models.DateTimeField(null=True) def add_output(self, new): lines = [line for line in self.output.split('\n') if line] lines.append(new) self.output = '\n'.join(lines) def __unicode__(self): if self.success: category = 'Successful' else: category = 'Failed' return u"{category} bugwarrior-pull run of {config}".format( category=category, config=self.config ) class Meta: app_label = 'taskmanager' Save runlog as output is added.
from django.db import models from .bugwarriorconfig import BugwarriorConfig class BugwarriorConfigRunLog(models.Model): config = models.ForeignKey( BugwarriorConfig, related_name='run_logs', ) success = models.BooleanField(default=False) output = models.TextField() stack_trace = models.TextField() started = models.DateTimeField() finished = models.DateTimeField(null=True) def add_output(self, new): lines = [line for line in self.output.split('\n') if line] lines.append(new) self.output = '\n'.join(lines) self.save() def __unicode__(self): if self.success: category = 'Successful' else: category = 'Failed' return u"{category} bugwarrior-pull run of {config}".format( category=category, config=self.config ) class Meta: app_label = 'taskmanager'
<commit_before>from django.db import models from .bugwarriorconfig import BugwarriorConfig class BugwarriorConfigRunLog(models.Model): config = models.ForeignKey( BugwarriorConfig, related_name='run_logs', ) success = models.BooleanField(default=False) output = models.TextField() stack_trace = models.TextField() started = models.DateTimeField() finished = models.DateTimeField(null=True) def add_output(self, new): lines = [line for line in self.output.split('\n') if line] lines.append(new) self.output = '\n'.join(lines) def __unicode__(self): if self.success: category = 'Successful' else: category = 'Failed' return u"{category} bugwarrior-pull run of {config}".format( category=category, config=self.config ) class Meta: app_label = 'taskmanager' <commit_msg>Save runlog as output is added.<commit_after>
from django.db import models from .bugwarriorconfig import BugwarriorConfig class BugwarriorConfigRunLog(models.Model): config = models.ForeignKey( BugwarriorConfig, related_name='run_logs', ) success = models.BooleanField(default=False) output = models.TextField() stack_trace = models.TextField() started = models.DateTimeField() finished = models.DateTimeField(null=True) def add_output(self, new): lines = [line for line in self.output.split('\n') if line] lines.append(new) self.output = '\n'.join(lines) self.save() def __unicode__(self): if self.success: category = 'Successful' else: category = 'Failed' return u"{category} bugwarrior-pull run of {config}".format( category=category, config=self.config ) class Meta: app_label = 'taskmanager'
from django.db import models from .bugwarriorconfig import BugwarriorConfig class BugwarriorConfigRunLog(models.Model): config = models.ForeignKey( BugwarriorConfig, related_name='run_logs', ) success = models.BooleanField(default=False) output = models.TextField() stack_trace = models.TextField() started = models.DateTimeField() finished = models.DateTimeField(null=True) def add_output(self, new): lines = [line for line in self.output.split('\n') if line] lines.append(new) self.output = '\n'.join(lines) def __unicode__(self): if self.success: category = 'Successful' else: category = 'Failed' return u"{category} bugwarrior-pull run of {config}".format( category=category, config=self.config ) class Meta: app_label = 'taskmanager' Save runlog as output is added.from django.db import models from .bugwarriorconfig import BugwarriorConfig class BugwarriorConfigRunLog(models.Model): config = models.ForeignKey( BugwarriorConfig, related_name='run_logs', ) success = models.BooleanField(default=False) output = models.TextField() stack_trace = models.TextField() started = models.DateTimeField() finished = models.DateTimeField(null=True) def add_output(self, new): lines = [line for line in self.output.split('\n') if line] lines.append(new) self.output = '\n'.join(lines) self.save() def __unicode__(self): if self.success: category = 'Successful' else: category = 'Failed' return u"{category} bugwarrior-pull run of {config}".format( category=category, config=self.config ) class Meta: app_label = 'taskmanager'
<commit_before>from django.db import models from .bugwarriorconfig import BugwarriorConfig class BugwarriorConfigRunLog(models.Model): config = models.ForeignKey( BugwarriorConfig, related_name='run_logs', ) success = models.BooleanField(default=False) output = models.TextField() stack_trace = models.TextField() started = models.DateTimeField() finished = models.DateTimeField(null=True) def add_output(self, new): lines = [line for line in self.output.split('\n') if line] lines.append(new) self.output = '\n'.join(lines) def __unicode__(self): if self.success: category = 'Successful' else: category = 'Failed' return u"{category} bugwarrior-pull run of {config}".format( category=category, config=self.config ) class Meta: app_label = 'taskmanager' <commit_msg>Save runlog as output is added.<commit_after>from django.db import models from .bugwarriorconfig import BugwarriorConfig class BugwarriorConfigRunLog(models.Model): config = models.ForeignKey( BugwarriorConfig, related_name='run_logs', ) success = models.BooleanField(default=False) output = models.TextField() stack_trace = models.TextField() started = models.DateTimeField() finished = models.DateTimeField(null=True) def add_output(self, new): lines = [line for line in self.output.split('\n') if line] lines.append(new) self.output = '\n'.join(lines) self.save() def __unicode__(self): if self.success: category = 'Successful' else: category = 'Failed' return u"{category} bugwarrior-pull run of {config}".format( category=category, config=self.config ) class Meta: app_label = 'taskmanager'
9ac9efbea5ad9e51d564ec563fe25349726ec1f7
inpassing/view_util.py
inpassing/view_util.py
# Copyright (c) 2016 Luke San Antonio Bialecki # All rights reserved. from . import exceptions as ex from . import models from .models import db, User, Org def user_is_participant(user_id, org_id): q = db.session.query(models.org_participants).filter_by( participant=user_id, org=org_id ) (ret,) = db.session.query(q.exists()).first() return ret def user_is_mod(user_id, org_id): q = db.session.query(models.org_mods).filter_by(mod=user_id, org=org_id) (ret,) = db.session.query(q.exists()).first() return ret def get_field(request, field): val = request.get_json().get(field, None) if val is None: raise ex.MissingFieldError(field) return val def get_org_by_id(org_id): org = Org.query.filter_by(id=org_id).first() if org is None: raise ex.OrgNotFound(org_id) return org def get_user_by_id(user_id): user = User.query.filter_by(id=user_id).first() if user is None: raise ex.UserNotFound(user_id) return user
# Copyright (c) 2016 Luke San Antonio Bialecki # All rights reserved. from . import exceptions as ex from . import models from .models import db, User, Org, Daystate def user_is_participant(user_id, org_id): q = db.session.query(models.org_participants).filter_by( participant=user_id, org=org_id ) (ret,) = db.session.query(q.exists()).first() return ret def user_is_mod(user_id, org_id): q = db.session.query(models.org_mods).filter_by(mod=user_id, org=org_id) (ret,) = db.session.query(q.exists()).first() return ret def get_field(request, field): val = request.get_json().get(field, None) if val is None: raise ex.MissingFieldError(field) return val def get_org_by_id(org_id): org = Org.query.filter_by(id=org_id).first() if org is None: raise ex.OrgNotFound(org_id) return org def get_user_by_id(user_id): user = User.query.filter_by(id=user_id).first() if user is None: raise ex.UserNotFound(user_id) return user def daystate_exists(daystate_id, org_id): query = Daystate.query.filter_by(id=daystate_id, org_id=org_id) (ret,) = db.session.query(query.exists()).first() return ret
Add function to figure out if a given daystate ID is valid for an org
Add function to figure out if a given daystate ID is valid for an org
Python
mit
lukesanantonio/inpassing-backend,lukesanantonio/inpassing-backend
# Copyright (c) 2016 Luke San Antonio Bialecki # All rights reserved. from . import exceptions as ex from . import models from .models import db, User, Org def user_is_participant(user_id, org_id): q = db.session.query(models.org_participants).filter_by( participant=user_id, org=org_id ) (ret,) = db.session.query(q.exists()).first() return ret def user_is_mod(user_id, org_id): q = db.session.query(models.org_mods).filter_by(mod=user_id, org=org_id) (ret,) = db.session.query(q.exists()).first() return ret def get_field(request, field): val = request.get_json().get(field, None) if val is None: raise ex.MissingFieldError(field) return val def get_org_by_id(org_id): org = Org.query.filter_by(id=org_id).first() if org is None: raise ex.OrgNotFound(org_id) return org def get_user_by_id(user_id): user = User.query.filter_by(id=user_id).first() if user is None: raise ex.UserNotFound(user_id) return user Add function to figure out if a given daystate ID is valid for an org
# Copyright (c) 2016 Luke San Antonio Bialecki # All rights reserved. from . import exceptions as ex from . import models from .models import db, User, Org, Daystate def user_is_participant(user_id, org_id): q = db.session.query(models.org_participants).filter_by( participant=user_id, org=org_id ) (ret,) = db.session.query(q.exists()).first() return ret def user_is_mod(user_id, org_id): q = db.session.query(models.org_mods).filter_by(mod=user_id, org=org_id) (ret,) = db.session.query(q.exists()).first() return ret def get_field(request, field): val = request.get_json().get(field, None) if val is None: raise ex.MissingFieldError(field) return val def get_org_by_id(org_id): org = Org.query.filter_by(id=org_id).first() if org is None: raise ex.OrgNotFound(org_id) return org def get_user_by_id(user_id): user = User.query.filter_by(id=user_id).first() if user is None: raise ex.UserNotFound(user_id) return user def daystate_exists(daystate_id, org_id): query = Daystate.query.filter_by(id=daystate_id, org_id=org_id) (ret,) = db.session.query(query.exists()).first() return ret
<commit_before># Copyright (c) 2016 Luke San Antonio Bialecki # All rights reserved. from . import exceptions as ex from . import models from .models import db, User, Org def user_is_participant(user_id, org_id): q = db.session.query(models.org_participants).filter_by( participant=user_id, org=org_id ) (ret,) = db.session.query(q.exists()).first() return ret def user_is_mod(user_id, org_id): q = db.session.query(models.org_mods).filter_by(mod=user_id, org=org_id) (ret,) = db.session.query(q.exists()).first() return ret def get_field(request, field): val = request.get_json().get(field, None) if val is None: raise ex.MissingFieldError(field) return val def get_org_by_id(org_id): org = Org.query.filter_by(id=org_id).first() if org is None: raise ex.OrgNotFound(org_id) return org def get_user_by_id(user_id): user = User.query.filter_by(id=user_id).first() if user is None: raise ex.UserNotFound(user_id) return user <commit_msg>Add function to figure out if a given daystate ID is valid for an org<commit_after>
# Copyright (c) 2016 Luke San Antonio Bialecki # All rights reserved. from . import exceptions as ex from . import models from .models import db, User, Org, Daystate def user_is_participant(user_id, org_id): q = db.session.query(models.org_participants).filter_by( participant=user_id, org=org_id ) (ret,) = db.session.query(q.exists()).first() return ret def user_is_mod(user_id, org_id): q = db.session.query(models.org_mods).filter_by(mod=user_id, org=org_id) (ret,) = db.session.query(q.exists()).first() return ret def get_field(request, field): val = request.get_json().get(field, None) if val is None: raise ex.MissingFieldError(field) return val def get_org_by_id(org_id): org = Org.query.filter_by(id=org_id).first() if org is None: raise ex.OrgNotFound(org_id) return org def get_user_by_id(user_id): user = User.query.filter_by(id=user_id).first() if user is None: raise ex.UserNotFound(user_id) return user def daystate_exists(daystate_id, org_id): query = Daystate.query.filter_by(id=daystate_id, org_id=org_id) (ret,) = db.session.query(query.exists()).first() return ret
# Copyright (c) 2016 Luke San Antonio Bialecki # All rights reserved. from . import exceptions as ex from . import models from .models import db, User, Org def user_is_participant(user_id, org_id): q = db.session.query(models.org_participants).filter_by( participant=user_id, org=org_id ) (ret,) = db.session.query(q.exists()).first() return ret def user_is_mod(user_id, org_id): q = db.session.query(models.org_mods).filter_by(mod=user_id, org=org_id) (ret,) = db.session.query(q.exists()).first() return ret def get_field(request, field): val = request.get_json().get(field, None) if val is None: raise ex.MissingFieldError(field) return val def get_org_by_id(org_id): org = Org.query.filter_by(id=org_id).first() if org is None: raise ex.OrgNotFound(org_id) return org def get_user_by_id(user_id): user = User.query.filter_by(id=user_id).first() if user is None: raise ex.UserNotFound(user_id) return user Add function to figure out if a given daystate ID is valid for an org# Copyright (c) 2016 Luke San Antonio Bialecki # All rights reserved. from . import exceptions as ex from . import models from .models import db, User, Org, Daystate def user_is_participant(user_id, org_id): q = db.session.query(models.org_participants).filter_by( participant=user_id, org=org_id ) (ret,) = db.session.query(q.exists()).first() return ret def user_is_mod(user_id, org_id): q = db.session.query(models.org_mods).filter_by(mod=user_id, org=org_id) (ret,) = db.session.query(q.exists()).first() return ret def get_field(request, field): val = request.get_json().get(field, None) if val is None: raise ex.MissingFieldError(field) return val def get_org_by_id(org_id): org = Org.query.filter_by(id=org_id).first() if org is None: raise ex.OrgNotFound(org_id) return org def get_user_by_id(user_id): user = User.query.filter_by(id=user_id).first() if user is None: raise ex.UserNotFound(user_id) return user def daystate_exists(daystate_id, org_id): query = Daystate.query.filter_by(id=daystate_id, org_id=org_id) (ret,) = db.session.query(query.exists()).first() return ret
<commit_before># Copyright (c) 2016 Luke San Antonio Bialecki # All rights reserved. from . import exceptions as ex from . import models from .models import db, User, Org def user_is_participant(user_id, org_id): q = db.session.query(models.org_participants).filter_by( participant=user_id, org=org_id ) (ret,) = db.session.query(q.exists()).first() return ret def user_is_mod(user_id, org_id): q = db.session.query(models.org_mods).filter_by(mod=user_id, org=org_id) (ret,) = db.session.query(q.exists()).first() return ret def get_field(request, field): val = request.get_json().get(field, None) if val is None: raise ex.MissingFieldError(field) return val def get_org_by_id(org_id): org = Org.query.filter_by(id=org_id).first() if org is None: raise ex.OrgNotFound(org_id) return org def get_user_by_id(user_id): user = User.query.filter_by(id=user_id).first() if user is None: raise ex.UserNotFound(user_id) return user <commit_msg>Add function to figure out if a given daystate ID is valid for an org<commit_after># Copyright (c) 2016 Luke San Antonio Bialecki # All rights reserved. from . import exceptions as ex from . import models from .models import db, User, Org, Daystate def user_is_participant(user_id, org_id): q = db.session.query(models.org_participants).filter_by( participant=user_id, org=org_id ) (ret,) = db.session.query(q.exists()).first() return ret def user_is_mod(user_id, org_id): q = db.session.query(models.org_mods).filter_by(mod=user_id, org=org_id) (ret,) = db.session.query(q.exists()).first() return ret def get_field(request, field): val = request.get_json().get(field, None) if val is None: raise ex.MissingFieldError(field) return val def get_org_by_id(org_id): org = Org.query.filter_by(id=org_id).first() if org is None: raise ex.OrgNotFound(org_id) return org def get_user_by_id(user_id): user = User.query.filter_by(id=user_id).first() if user is None: raise ex.UserNotFound(user_id) return user def daystate_exists(daystate_id, org_id): query = Daystate.query.filter_by(id=daystate_id, org_id=org_id) (ret,) = db.session.query(query.exists()).first() return ret
fa404452f77b3756e2a54df75c6503cae697e118
mentor/forms.py
mentor/forms.py
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from mentor.models import UserProfile class RegistrationForm(UserCreationForm): email = forms.EmailField(required=False) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() user_profile = UserProfile(user=user) user_profile.save() return user
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from mentor.models import UserProfile class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("email", "password1", "password2") def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.username = self.cleaned_data["email"] user.email = self.cleaned_data["email"] if commit: user.save() user_profile = UserProfile(user=user) user_profile.save() return user
Copy email address to username
Copy email address to username
Python
mit
amaunder21/c4tkmentors,amaunder21/c4tkmentors
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from mentor.models import UserProfile class RegistrationForm(UserCreationForm): email = forms.EmailField(required=False) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() user_profile = UserProfile(user=user) user_profile.save() return user Copy email address to username
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from mentor.models import UserProfile class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("email", "password1", "password2") def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.username = self.cleaned_data["email"] user.email = self.cleaned_data["email"] if commit: user.save() user_profile = UserProfile(user=user) user_profile.save() return user
<commit_before>from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from mentor.models import UserProfile class RegistrationForm(UserCreationForm): email = forms.EmailField(required=False) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() user_profile = UserProfile(user=user) user_profile.save() return user <commit_msg>Copy email address to username<commit_after>
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from mentor.models import UserProfile class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("email", "password1", "password2") def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.username = self.cleaned_data["email"] user.email = self.cleaned_data["email"] if commit: user.save() user_profile = UserProfile(user=user) user_profile.save() return user
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from mentor.models import UserProfile class RegistrationForm(UserCreationForm): email = forms.EmailField(required=False) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() user_profile = UserProfile(user=user) user_profile.save() return user Copy email address to usernamefrom django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from mentor.models import UserProfile class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("email", "password1", "password2") def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.username = self.cleaned_data["email"] user.email = self.cleaned_data["email"] if commit: user.save() user_profile = UserProfile(user=user) user_profile.save() return user
<commit_before>from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from mentor.models import UserProfile class RegistrationForm(UserCreationForm): email = forms.EmailField(required=False) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() user_profile = UserProfile(user=user) user_profile.save() return user <commit_msg>Copy email address to username<commit_after>from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from mentor.models import UserProfile class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("email", "password1", "password2") def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.username = self.cleaned_data["email"] user.email = self.cleaned_data["email"] if commit: user.save() user_profile = UserProfile(user=user) user_profile.save() return user
808cd0f8ac27a9f113efddba50a37837f364723e
idios/models.py
idios/models.py
from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class ProfileBase(models.Model): user = models.ForeignKey(User, unique=True, verbose_name=_("user")) group_content_type = models.ForeignKey(ContentType, null=True, blank=True) group_object_id = models.PositiveIntegerField(null=True, blank=True) group = generic.GenericForeignKey("group_content_type", "group_object_id") class Meta: verbose_name = _("profile") verbose_name_plural = _("profiles") abstract = True def __unicode__(self): return self.user.username def get_absolute_url(self, group=None): # @@@ make group-aware return reverse("profile_detail", kwargs={"username": self.user.username})
from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User class ProfileBase(models.Model): user = models.ForeignKey(User, unique=True, verbose_name=_("user")) class Meta: verbose_name = _("profile") verbose_name_plural = _("profiles") abstract = True def __unicode__(self): return self.user.username def get_absolute_url(self, group=None): # @@@ make group-aware return reverse("profile_detail", kwargs={"username": self.user.username})
Revert "added GFK for group"
Revert "added GFK for group" This reverts commit 957e11ef62823a29472eeec4dade65ae01bbea70.
Python
bsd-3-clause
eldarion/idios,eldarion/idios,paltman/idios,rbrady/idios,rbrady/idios,paltman/idios
from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class ProfileBase(models.Model): user = models.ForeignKey(User, unique=True, verbose_name=_("user")) group_content_type = models.ForeignKey(ContentType, null=True, blank=True) group_object_id = models.PositiveIntegerField(null=True, blank=True) group = generic.GenericForeignKey("group_content_type", "group_object_id") class Meta: verbose_name = _("profile") verbose_name_plural = _("profiles") abstract = True def __unicode__(self): return self.user.username def get_absolute_url(self, group=None): # @@@ make group-aware return reverse("profile_detail", kwargs={"username": self.user.username}) Revert "added GFK for group" This reverts commit 957e11ef62823a29472eeec4dade65ae01bbea70.
from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User class ProfileBase(models.Model): user = models.ForeignKey(User, unique=True, verbose_name=_("user")) class Meta: verbose_name = _("profile") verbose_name_plural = _("profiles") abstract = True def __unicode__(self): return self.user.username def get_absolute_url(self, group=None): # @@@ make group-aware return reverse("profile_detail", kwargs={"username": self.user.username})
<commit_before>from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class ProfileBase(models.Model): user = models.ForeignKey(User, unique=True, verbose_name=_("user")) group_content_type = models.ForeignKey(ContentType, null=True, blank=True) group_object_id = models.PositiveIntegerField(null=True, blank=True) group = generic.GenericForeignKey("group_content_type", "group_object_id") class Meta: verbose_name = _("profile") verbose_name_plural = _("profiles") abstract = True def __unicode__(self): return self.user.username def get_absolute_url(self, group=None): # @@@ make group-aware return reverse("profile_detail", kwargs={"username": self.user.username}) <commit_msg>Revert "added GFK for group" This reverts commit 957e11ef62823a29472eeec4dade65ae01bbea70.<commit_after>
from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User class ProfileBase(models.Model): user = models.ForeignKey(User, unique=True, verbose_name=_("user")) class Meta: verbose_name = _("profile") verbose_name_plural = _("profiles") abstract = True def __unicode__(self): return self.user.username def get_absolute_url(self, group=None): # @@@ make group-aware return reverse("profile_detail", kwargs={"username": self.user.username})
from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class ProfileBase(models.Model): user = models.ForeignKey(User, unique=True, verbose_name=_("user")) group_content_type = models.ForeignKey(ContentType, null=True, blank=True) group_object_id = models.PositiveIntegerField(null=True, blank=True) group = generic.GenericForeignKey("group_content_type", "group_object_id") class Meta: verbose_name = _("profile") verbose_name_plural = _("profiles") abstract = True def __unicode__(self): return self.user.username def get_absolute_url(self, group=None): # @@@ make group-aware return reverse("profile_detail", kwargs={"username": self.user.username}) Revert "added GFK for group" This reverts commit 957e11ef62823a29472eeec4dade65ae01bbea70.from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User class ProfileBase(models.Model): user = models.ForeignKey(User, unique=True, verbose_name=_("user")) class Meta: verbose_name = _("profile") verbose_name_plural = _("profiles") abstract = True def __unicode__(self): return self.user.username def get_absolute_url(self, group=None): # @@@ make group-aware return reverse("profile_detail", kwargs={"username": self.user.username})
<commit_before>from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class ProfileBase(models.Model): user = models.ForeignKey(User, unique=True, verbose_name=_("user")) group_content_type = models.ForeignKey(ContentType, null=True, blank=True) group_object_id = models.PositiveIntegerField(null=True, blank=True) group = generic.GenericForeignKey("group_content_type", "group_object_id") class Meta: verbose_name = _("profile") verbose_name_plural = _("profiles") abstract = True def __unicode__(self): return self.user.username def get_absolute_url(self, group=None): # @@@ make group-aware return reverse("profile_detail", kwargs={"username": self.user.username}) <commit_msg>Revert "added GFK for group" This reverts commit 957e11ef62823a29472eeec4dade65ae01bbea70.<commit_after>from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User class ProfileBase(models.Model): user = models.ForeignKey(User, unique=True, verbose_name=_("user")) class Meta: verbose_name = _("profile") verbose_name_plural = _("profiles") abstract = True def __unicode__(self): return self.user.username def get_absolute_url(self, group=None): # @@@ make group-aware return reverse("profile_detail", kwargs={"username": self.user.username})
0300bb45fb52dfaa801bb83b10f3e8316642026d
clintools/deployed_settings.py
clintools/deployed_settings.py
from settings import * DEBUG = TEMPLATE_DEBUG = False ALLOWED_HOSTS = ['pttrack.snhc.wustl.edu'] with open(os.path.join(BASE_DIR, 'secrets/secret_key.txt')) as f: SECRET_KEY = f.read().strip() # TODO: change for deployment? # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
from settings import * DEBUG = TEMPLATE_DEBUG = False ALLOWED_HOSTS = ['pttrack.snhc.wustl.edu'] with open(os.path.join(BASE_DIR, 'secrets/secret_key.txt')) as f: SECRET_KEY = f.read().strip() SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True X_FRAME_OPTIONS = 'DENY' # TODO: change for deployment? # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
Update deployed settings with results from deploy check.
Update deployed settings with results from deploy check.
Python
mit
SaturdayNeighborhoodHealthClinic/clintools,SaturdayNeighborhoodHealthClinic/clintools,SaturdayNeighborhoodHealthClinic/clintools
from settings import * DEBUG = TEMPLATE_DEBUG = False ALLOWED_HOSTS = ['pttrack.snhc.wustl.edu'] with open(os.path.join(BASE_DIR, 'secrets/secret_key.txt')) as f: SECRET_KEY = f.read().strip() # TODO: change for deployment? # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }Update deployed settings with results from deploy check.
from settings import * DEBUG = TEMPLATE_DEBUG = False ALLOWED_HOSTS = ['pttrack.snhc.wustl.edu'] with open(os.path.join(BASE_DIR, 'secrets/secret_key.txt')) as f: SECRET_KEY = f.read().strip() SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True X_FRAME_OPTIONS = 'DENY' # TODO: change for deployment? # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
<commit_before>from settings import * DEBUG = TEMPLATE_DEBUG = False ALLOWED_HOSTS = ['pttrack.snhc.wustl.edu'] with open(os.path.join(BASE_DIR, 'secrets/secret_key.txt')) as f: SECRET_KEY = f.read().strip() # TODO: change for deployment? # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }<commit_msg>Update deployed settings with results from deploy check.<commit_after>
from settings import * DEBUG = TEMPLATE_DEBUG = False ALLOWED_HOSTS = ['pttrack.snhc.wustl.edu'] with open(os.path.join(BASE_DIR, 'secrets/secret_key.txt')) as f: SECRET_KEY = f.read().strip() SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True X_FRAME_OPTIONS = 'DENY' # TODO: change for deployment? # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
from settings import * DEBUG = TEMPLATE_DEBUG = False ALLOWED_HOSTS = ['pttrack.snhc.wustl.edu'] with open(os.path.join(BASE_DIR, 'secrets/secret_key.txt')) as f: SECRET_KEY = f.read().strip() # TODO: change for deployment? # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }Update deployed settings with results from deploy check.from settings import * DEBUG = TEMPLATE_DEBUG = False ALLOWED_HOSTS = ['pttrack.snhc.wustl.edu'] with open(os.path.join(BASE_DIR, 'secrets/secret_key.txt')) as f: SECRET_KEY = f.read().strip() SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True X_FRAME_OPTIONS = 'DENY' # TODO: change for deployment? # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
<commit_before>from settings import * DEBUG = TEMPLATE_DEBUG = False ALLOWED_HOSTS = ['pttrack.snhc.wustl.edu'] with open(os.path.join(BASE_DIR, 'secrets/secret_key.txt')) as f: SECRET_KEY = f.read().strip() # TODO: change for deployment? # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }<commit_msg>Update deployed settings with results from deploy check.<commit_after>from settings import * DEBUG = TEMPLATE_DEBUG = False ALLOWED_HOSTS = ['pttrack.snhc.wustl.edu'] with open(os.path.join(BASE_DIR, 'secrets/secret_key.txt')) as f: SECRET_KEY = f.read().strip() SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True X_FRAME_OPTIONS = 'DENY' # TODO: change for deployment? # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
5c7f881cd2122be826c2c7351c1c221479ebec39
lib/challenge.py
lib/challenge.py
# python # vim: set fileencoding=UTF-8 : class Challenge: sample = 'sample' def __init__(self): self.lines = [] self.model = [] self.result = [] self.output = '' def main(self): self.read() self.build() self.calc() self.format() #-------------------------------------------------- # Default workflow #-------------------------------------------------- def read(self): self.lines = self.sample.splitlines() def build(self): pass def calc(self): pass def format(self): self.output = str(self.result) #-------------------------------------------------- # Accessing lines #-------------------------------------------------- def line(self, number): return self.lines[number] def lines(self): return self.lines def lineToIntegers(self, line_nr): return [int(i) for i in self.line(line_nr).split(',')] def lineToFloats(self, line_nr): return [float(i) for i in self.line(line_nr).split(',')] #-------------------------------------------------- # Packing #-------------------------------------------------- def packIntegers(self): self.output = ', '.join(str(x) for x in self.result)
# python # vim: set fileencoding=UTF-8 : import re import types class Challenge: sample = 'sample' splitter = '\s+|\s?,\s?' def __init__(self): self.lines = [] self.model = types.SimpleNamespace() self.result = types.SimpleNamespace() self.output = '' def main(self): self.read() self.build() self.calc() self.format() #-------------------------------------------------- # Default workflow #-------------------------------------------------- def read(self): lines = self.sample.strip().splitlines() self.lines = [line.strip() for line in lines] def build(self): pass def calc(self): pass def format(self): self.output = str(self.result) #-------------------------------------------------- # Accessing lines #-------------------------------------------------- def line(self, number): return self.lines[number] def lines(self): return self.lines def lineToIntegers(self, line_nr): return [int(i) for i in re.compile(self.splitter) .split(self.line(line_nr))] def lineToFloats(self, line_nr): return [float(i) for i in re.compile(self.splitter) .split(self.line(line_nr))] #-------------------------------------------------- # Packing #-------------------------------------------------- def packIntegers(self): self.output = ', '.join(str(x) for x in self.result)
Add SimpleNamespace objects for model and result of challange parent class.
Add SimpleNamespace objects for model and result of challange parent class.
Python
mit
elmar-hinz/Python.Challenges
# python # vim: set fileencoding=UTF-8 : class Challenge: sample = 'sample' def __init__(self): self.lines = [] self.model = [] self.result = [] self.output = '' def main(self): self.read() self.build() self.calc() self.format() #-------------------------------------------------- # Default workflow #-------------------------------------------------- def read(self): self.lines = self.sample.splitlines() def build(self): pass def calc(self): pass def format(self): self.output = str(self.result) #-------------------------------------------------- # Accessing lines #-------------------------------------------------- def line(self, number): return self.lines[number] def lines(self): return self.lines def lineToIntegers(self, line_nr): return [int(i) for i in self.line(line_nr).split(',')] def lineToFloats(self, line_nr): return [float(i) for i in self.line(line_nr).split(',')] #-------------------------------------------------- # Packing #-------------------------------------------------- def packIntegers(self): self.output = ', '.join(str(x) for x in self.result) Add SimpleNamespace objects for model and result of challange parent class.
# python # vim: set fileencoding=UTF-8 : import re import types class Challenge: sample = 'sample' splitter = '\s+|\s?,\s?' def __init__(self): self.lines = [] self.model = types.SimpleNamespace() self.result = types.SimpleNamespace() self.output = '' def main(self): self.read() self.build() self.calc() self.format() #-------------------------------------------------- # Default workflow #-------------------------------------------------- def read(self): lines = self.sample.strip().splitlines() self.lines = [line.strip() for line in lines] def build(self): pass def calc(self): pass def format(self): self.output = str(self.result) #-------------------------------------------------- # Accessing lines #-------------------------------------------------- def line(self, number): return self.lines[number] def lines(self): return self.lines def lineToIntegers(self, line_nr): return [int(i) for i in re.compile(self.splitter) .split(self.line(line_nr))] def lineToFloats(self, line_nr): return [float(i) for i in re.compile(self.splitter) .split(self.line(line_nr))] #-------------------------------------------------- # Packing #-------------------------------------------------- def packIntegers(self): self.output = ', '.join(str(x) for x in self.result)
<commit_before># python # vim: set fileencoding=UTF-8 : class Challenge: sample = 'sample' def __init__(self): self.lines = [] self.model = [] self.result = [] self.output = '' def main(self): self.read() self.build() self.calc() self.format() #-------------------------------------------------- # Default workflow #-------------------------------------------------- def read(self): self.lines = self.sample.splitlines() def build(self): pass def calc(self): pass def format(self): self.output = str(self.result) #-------------------------------------------------- # Accessing lines #-------------------------------------------------- def line(self, number): return self.lines[number] def lines(self): return self.lines def lineToIntegers(self, line_nr): return [int(i) for i in self.line(line_nr).split(',')] def lineToFloats(self, line_nr): return [float(i) for i in self.line(line_nr).split(',')] #-------------------------------------------------- # Packing #-------------------------------------------------- def packIntegers(self): self.output = ', '.join(str(x) for x in self.result) <commit_msg>Add SimpleNamespace objects for model and result of challange parent class.<commit_after>
# python # vim: set fileencoding=UTF-8 : import re import types class Challenge: sample = 'sample' splitter = '\s+|\s?,\s?' def __init__(self): self.lines = [] self.model = types.SimpleNamespace() self.result = types.SimpleNamespace() self.output = '' def main(self): self.read() self.build() self.calc() self.format() #-------------------------------------------------- # Default workflow #-------------------------------------------------- def read(self): lines = self.sample.strip().splitlines() self.lines = [line.strip() for line in lines] def build(self): pass def calc(self): pass def format(self): self.output = str(self.result) #-------------------------------------------------- # Accessing lines #-------------------------------------------------- def line(self, number): return self.lines[number] def lines(self): return self.lines def lineToIntegers(self, line_nr): return [int(i) for i in re.compile(self.splitter) .split(self.line(line_nr))] def lineToFloats(self, line_nr): return [float(i) for i in re.compile(self.splitter) .split(self.line(line_nr))] #-------------------------------------------------- # Packing #-------------------------------------------------- def packIntegers(self): self.output = ', '.join(str(x) for x in self.result)
# python # vim: set fileencoding=UTF-8 : class Challenge: sample = 'sample' def __init__(self): self.lines = [] self.model = [] self.result = [] self.output = '' def main(self): self.read() self.build() self.calc() self.format() #-------------------------------------------------- # Default workflow #-------------------------------------------------- def read(self): self.lines = self.sample.splitlines() def build(self): pass def calc(self): pass def format(self): self.output = str(self.result) #-------------------------------------------------- # Accessing lines #-------------------------------------------------- def line(self, number): return self.lines[number] def lines(self): return self.lines def lineToIntegers(self, line_nr): return [int(i) for i in self.line(line_nr).split(',')] def lineToFloats(self, line_nr): return [float(i) for i in self.line(line_nr).split(',')] #-------------------------------------------------- # Packing #-------------------------------------------------- def packIntegers(self): self.output = ', '.join(str(x) for x in self.result) Add SimpleNamespace objects for model and result of challange parent class.# python # vim: set fileencoding=UTF-8 : import re import types class Challenge: sample = 'sample' splitter = '\s+|\s?,\s?' def __init__(self): self.lines = [] self.model = types.SimpleNamespace() self.result = types.SimpleNamespace() self.output = '' def main(self): self.read() self.build() self.calc() self.format() #-------------------------------------------------- # Default workflow #-------------------------------------------------- def read(self): lines = self.sample.strip().splitlines() self.lines = [line.strip() for line in lines] def build(self): pass def calc(self): pass def format(self): self.output = str(self.result) #-------------------------------------------------- # Accessing lines #-------------------------------------------------- def line(self, number): return self.lines[number] def lines(self): return self.lines def lineToIntegers(self, line_nr): return [int(i) for i in re.compile(self.splitter) .split(self.line(line_nr))] def lineToFloats(self, line_nr): return [float(i) for i in re.compile(self.splitter) .split(self.line(line_nr))] #-------------------------------------------------- # Packing #-------------------------------------------------- def packIntegers(self): self.output = ', '.join(str(x) for x in self.result)
<commit_before># python # vim: set fileencoding=UTF-8 : class Challenge: sample = 'sample' def __init__(self): self.lines = [] self.model = [] self.result = [] self.output = '' def main(self): self.read() self.build() self.calc() self.format() #-------------------------------------------------- # Default workflow #-------------------------------------------------- def read(self): self.lines = self.sample.splitlines() def build(self): pass def calc(self): pass def format(self): self.output = str(self.result) #-------------------------------------------------- # Accessing lines #-------------------------------------------------- def line(self, number): return self.lines[number] def lines(self): return self.lines def lineToIntegers(self, line_nr): return [int(i) for i in self.line(line_nr).split(',')] def lineToFloats(self, line_nr): return [float(i) for i in self.line(line_nr).split(',')] #-------------------------------------------------- # Packing #-------------------------------------------------- def packIntegers(self): self.output = ', '.join(str(x) for x in self.result) <commit_msg>Add SimpleNamespace objects for model and result of challange parent class.<commit_after># python # vim: set fileencoding=UTF-8 : import re import types class Challenge: sample = 'sample' splitter = '\s+|\s?,\s?' def __init__(self): self.lines = [] self.model = types.SimpleNamespace() self.result = types.SimpleNamespace() self.output = '' def main(self): self.read() self.build() self.calc() self.format() #-------------------------------------------------- # Default workflow #-------------------------------------------------- def read(self): lines = self.sample.strip().splitlines() self.lines = [line.strip() for line in lines] def build(self): pass def calc(self): pass def format(self): self.output = str(self.result) #-------------------------------------------------- # Accessing lines #-------------------------------------------------- def line(self, number): return self.lines[number] def lines(self): return self.lines def lineToIntegers(self, line_nr): return [int(i) for i in re.compile(self.splitter) .split(self.line(line_nr))] def lineToFloats(self, line_nr): return [float(i) for i in re.compile(self.splitter) .split(self.line(line_nr))] #-------------------------------------------------- # Packing #-------------------------------------------------- def packIntegers(self): self.output = ', '.join(str(x) for x in self.result)
d62cbb79992c7a178c97a36c86b05bc590d2cc61
tcconfig/_split_line_list.py
tcconfig/_split_line_list.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import re def __null_line_strip(line): return line def __line_strip(line): return line.strip() def split_line_list( line_list, re_line_separator=re.compile("^$"), is_include_match_line=False, is_strip=True): block_list = [] block = [] strip_func = __line_strip if is_strip else __null_line_strip for line in line_list: line = strip_func(line) if re_line_separator.search(line): if block: block_list.append(block) block = [] if is_include_match_line: block.append(line) continue block.append(line) if block: block_list.append(block) return block_list
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import re def __null_line_strip(line): return line def __line_strip(line): return line.strip() def split_line_list( line_list, re_block_separator=re.compile("^$"), is_include_match_line=False, is_strip=True): block_list = [] block = [] strip_func = __line_strip if is_strip else __null_line_strip for line in line_list: line = strip_func(line) if re_block_separator.search(line): if block: block_list.append(block) block = [] if is_include_match_line: block.append(line) continue block.append(line) if block: block_list.append(block) return block_list
Rename an argument to be more precisely represent the use purpose
Rename an argument to be more precisely represent the use purpose
Python
mit
thombashi/tcconfig,thombashi/tcconfig
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import re def __null_line_strip(line): return line def __line_strip(line): return line.strip() def split_line_list( line_list, re_line_separator=re.compile("^$"), is_include_match_line=False, is_strip=True): block_list = [] block = [] strip_func = __line_strip if is_strip else __null_line_strip for line in line_list: line = strip_func(line) if re_line_separator.search(line): if block: block_list.append(block) block = [] if is_include_match_line: block.append(line) continue block.append(line) if block: block_list.append(block) return block_list Rename an argument to be more precisely represent the use purpose
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import re def __null_line_strip(line): return line def __line_strip(line): return line.strip() def split_line_list( line_list, re_block_separator=re.compile("^$"), is_include_match_line=False, is_strip=True): block_list = [] block = [] strip_func = __line_strip if is_strip else __null_line_strip for line in line_list: line = strip_func(line) if re_block_separator.search(line): if block: block_list.append(block) block = [] if is_include_match_line: block.append(line) continue block.append(line) if block: block_list.append(block) return block_list
<commit_before># encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import re def __null_line_strip(line): return line def __line_strip(line): return line.strip() def split_line_list( line_list, re_line_separator=re.compile("^$"), is_include_match_line=False, is_strip=True): block_list = [] block = [] strip_func = __line_strip if is_strip else __null_line_strip for line in line_list: line = strip_func(line) if re_line_separator.search(line): if block: block_list.append(block) block = [] if is_include_match_line: block.append(line) continue block.append(line) if block: block_list.append(block) return block_list <commit_msg>Rename an argument to be more precisely represent the use purpose<commit_after>
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import re def __null_line_strip(line): return line def __line_strip(line): return line.strip() def split_line_list( line_list, re_block_separator=re.compile("^$"), is_include_match_line=False, is_strip=True): block_list = [] block = [] strip_func = __line_strip if is_strip else __null_line_strip for line in line_list: line = strip_func(line) if re_block_separator.search(line): if block: block_list.append(block) block = [] if is_include_match_line: block.append(line) continue block.append(line) if block: block_list.append(block) return block_list
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import re def __null_line_strip(line): return line def __line_strip(line): return line.strip() def split_line_list( line_list, re_line_separator=re.compile("^$"), is_include_match_line=False, is_strip=True): block_list = [] block = [] strip_func = __line_strip if is_strip else __null_line_strip for line in line_list: line = strip_func(line) if re_line_separator.search(line): if block: block_list.append(block) block = [] if is_include_match_line: block.append(line) continue block.append(line) if block: block_list.append(block) return block_list Rename an argument to be more precisely represent the use purpose# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import re def __null_line_strip(line): return line def __line_strip(line): return line.strip() def split_line_list( line_list, re_block_separator=re.compile("^$"), is_include_match_line=False, is_strip=True): block_list = [] block = [] strip_func = __line_strip if is_strip else __null_line_strip for line in line_list: line = strip_func(line) if re_block_separator.search(line): if block: block_list.append(block) block = [] if is_include_match_line: block.append(line) continue block.append(line) if block: block_list.append(block) return block_list
<commit_before># encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import re def __null_line_strip(line): return line def __line_strip(line): return line.strip() def split_line_list( line_list, re_line_separator=re.compile("^$"), is_include_match_line=False, is_strip=True): block_list = [] block = [] strip_func = __line_strip if is_strip else __null_line_strip for line in line_list: line = strip_func(line) if re_line_separator.search(line): if block: block_list.append(block) block = [] if is_include_match_line: block.append(line) continue block.append(line) if block: block_list.append(block) return block_list <commit_msg>Rename an argument to be more precisely represent the use purpose<commit_after># encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import re def __null_line_strip(line): return line def __line_strip(line): return line.strip() def split_line_list( line_list, re_block_separator=re.compile("^$"), is_include_match_line=False, is_strip=True): block_list = [] block = [] strip_func = __line_strip if is_strip else __null_line_strip for line in line_list: line = strip_func(line) if re_block_separator.search(line): if block: block_list.append(block) block = [] if is_include_match_line: block.append(line) continue block.append(line) if block: block_list.append(block) return block_list
f053615c51a7b937e4dedc561757f675e95380a7
poradnia/cases/migrations/0002_auto_20150102_1532.py
poradnia/cases/migrations/0002_auto_20150102_1532.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cases', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('tags', '0001_initial'), ] operations = [ migrations.AddField( model_name='case', name='client', field=models.ForeignKey(to=settings.AUTH_USER_MODEL), preserve_default=True, ), migrations.AddField( model_name='case', name='tags', field=models.ManyToManyField(to='tags.Tag', null=True, blank=True), preserve_default=True, ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cases', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.AddField( model_name='case', name='client', field=models.ForeignKey(to=settings.AUTH_USER_MODEL), preserve_default=True, ), ]
Fix cases migrations after drop tags
Fix cases migrations after drop tags
Python
mit
rwakulszowa/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cases', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('tags', '0001_initial'), ] operations = [ migrations.AddField( model_name='case', name='client', field=models.ForeignKey(to=settings.AUTH_USER_MODEL), preserve_default=True, ), migrations.AddField( model_name='case', name='tags', field=models.ManyToManyField(to='tags.Tag', null=True, blank=True), preserve_default=True, ), ] Fix cases migrations after drop tags
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cases', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.AddField( model_name='case', name='client', field=models.ForeignKey(to=settings.AUTH_USER_MODEL), preserve_default=True, ), ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cases', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('tags', '0001_initial'), ] operations = [ migrations.AddField( model_name='case', name='client', field=models.ForeignKey(to=settings.AUTH_USER_MODEL), preserve_default=True, ), migrations.AddField( model_name='case', name='tags', field=models.ManyToManyField(to='tags.Tag', null=True, blank=True), preserve_default=True, ), ] <commit_msg>Fix cases migrations after drop tags<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cases', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.AddField( model_name='case', name='client', field=models.ForeignKey(to=settings.AUTH_USER_MODEL), preserve_default=True, ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cases', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('tags', '0001_initial'), ] operations = [ migrations.AddField( model_name='case', name='client', field=models.ForeignKey(to=settings.AUTH_USER_MODEL), preserve_default=True, ), migrations.AddField( model_name='case', name='tags', field=models.ManyToManyField(to='tags.Tag', null=True, blank=True), preserve_default=True, ), ] Fix cases migrations after drop tags# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cases', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.AddField( model_name='case', name='client', field=models.ForeignKey(to=settings.AUTH_USER_MODEL), preserve_default=True, ), ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cases', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('tags', '0001_initial'), ] operations = [ migrations.AddField( model_name='case', name='client', field=models.ForeignKey(to=settings.AUTH_USER_MODEL), preserve_default=True, ), migrations.AddField( model_name='case', name='tags', field=models.ManyToManyField(to='tags.Tag', null=True, blank=True), preserve_default=True, ), ] <commit_msg>Fix cases migrations after drop tags<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cases', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.AddField( model_name='case', name='client', field=models.ForeignKey(to=settings.AUTH_USER_MODEL), preserve_default=True, ), ]
43e4e154df6274ea80b5d495a682c2d17cdb178d
cla_backend/apps/knowledgebase/tests/test_events.py
cla_backend/apps/knowledgebase/tests/test_events.py
from django.test import TestCase from cla_eventlog.tests.base import EventTestCaseMixin class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase): EVENT_KEY = 'alternative_help' def test_assign_alternative_help(self): self._test_process_with_expicit_code( ['COSPF', 'IRKB'] )
from django.test import TestCase from cla_eventlog.tests.base import EventTestCaseMixin class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase): EVENT_KEY = 'alternative_help' def test_assign_alternative_help(self): self._test_process_with_expicit_code( ['COSPF', 'IRKB', 'SPFN', 'SPFM'] )
Add new outcome codes to tests
Add new outcome codes to tests
Python
mit
ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend
from django.test import TestCase from cla_eventlog.tests.base import EventTestCaseMixin class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase): EVENT_KEY = 'alternative_help' def test_assign_alternative_help(self): self._test_process_with_expicit_code( ['COSPF', 'IRKB'] ) Add new outcome codes to tests
from django.test import TestCase from cla_eventlog.tests.base import EventTestCaseMixin class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase): EVENT_KEY = 'alternative_help' def test_assign_alternative_help(self): self._test_process_with_expicit_code( ['COSPF', 'IRKB', 'SPFN', 'SPFM'] )
<commit_before>from django.test import TestCase from cla_eventlog.tests.base import EventTestCaseMixin class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase): EVENT_KEY = 'alternative_help' def test_assign_alternative_help(self): self._test_process_with_expicit_code( ['COSPF', 'IRKB'] ) <commit_msg>Add new outcome codes to tests<commit_after>
from django.test import TestCase from cla_eventlog.tests.base import EventTestCaseMixin class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase): EVENT_KEY = 'alternative_help' def test_assign_alternative_help(self): self._test_process_with_expicit_code( ['COSPF', 'IRKB', 'SPFN', 'SPFM'] )
from django.test import TestCase from cla_eventlog.tests.base import EventTestCaseMixin class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase): EVENT_KEY = 'alternative_help' def test_assign_alternative_help(self): self._test_process_with_expicit_code( ['COSPF', 'IRKB'] ) Add new outcome codes to testsfrom django.test import TestCase from cla_eventlog.tests.base import EventTestCaseMixin class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase): EVENT_KEY = 'alternative_help' def test_assign_alternative_help(self): self._test_process_with_expicit_code( ['COSPF', 'IRKB', 'SPFN', 'SPFM'] )
<commit_before>from django.test import TestCase from cla_eventlog.tests.base import EventTestCaseMixin class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase): EVENT_KEY = 'alternative_help' def test_assign_alternative_help(self): self._test_process_with_expicit_code( ['COSPF', 'IRKB'] ) <commit_msg>Add new outcome codes to tests<commit_after>from django.test import TestCase from cla_eventlog.tests.base import EventTestCaseMixin class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase): EVENT_KEY = 'alternative_help' def test_assign_alternative_help(self): self._test_process_with_expicit_code( ['COSPF', 'IRKB', 'SPFN', 'SPFM'] )
bf0b00d8103dd87b4a99aeccd7501f055e747e7a
ctlibre/urls.py
ctlibre/urls.py
from django.conf import settings from django.conf.urls import patterns, include, url, static from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'ctlibre.views.home', name='home'), url(r'^article/(?P<slug>[^/]+)', 'news.views.article_detail', name='article-detail'), url(r'^admin/', include(admin.site.urls)), ) # Serve static media during development urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += patterns('', url(r'^', include('cms.urls')), )
from django.conf import settings from django.conf.urls import patterns, include, url, static from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'ctlibre.views.home', name='home'), url(r'^article/(?P<slug>[^/]+)/$', 'news.views.article_detail', name='article-detail'), url(r'^admin/', include(admin.site.urls)), ) # Serve static media during development urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += patterns('', url(r'^', include('cms.urls')), )
Add ending slash to regex for article-detail view
Add ending slash to regex for article-detail view
Python
agpl-3.0
dellsystem/ctlibre.com
from django.conf import settings from django.conf.urls import patterns, include, url, static from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'ctlibre.views.home', name='home'), url(r'^article/(?P<slug>[^/]+)', 'news.views.article_detail', name='article-detail'), url(r'^admin/', include(admin.site.urls)), ) # Serve static media during development urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += patterns('', url(r'^', include('cms.urls')), ) Add ending slash to regex for article-detail view
from django.conf import settings from django.conf.urls import patterns, include, url, static from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'ctlibre.views.home', name='home'), url(r'^article/(?P<slug>[^/]+)/$', 'news.views.article_detail', name='article-detail'), url(r'^admin/', include(admin.site.urls)), ) # Serve static media during development urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += patterns('', url(r'^', include('cms.urls')), )
<commit_before>from django.conf import settings from django.conf.urls import patterns, include, url, static from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'ctlibre.views.home', name='home'), url(r'^article/(?P<slug>[^/]+)', 'news.views.article_detail', name='article-detail'), url(r'^admin/', include(admin.site.urls)), ) # Serve static media during development urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += patterns('', url(r'^', include('cms.urls')), ) <commit_msg>Add ending slash to regex for article-detail view<commit_after>
from django.conf import settings from django.conf.urls import patterns, include, url, static from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'ctlibre.views.home', name='home'), url(r'^article/(?P<slug>[^/]+)/$', 'news.views.article_detail', name='article-detail'), url(r'^admin/', include(admin.site.urls)), ) # Serve static media during development urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += patterns('', url(r'^', include('cms.urls')), )
from django.conf import settings from django.conf.urls import patterns, include, url, static from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'ctlibre.views.home', name='home'), url(r'^article/(?P<slug>[^/]+)', 'news.views.article_detail', name='article-detail'), url(r'^admin/', include(admin.site.urls)), ) # Serve static media during development urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += patterns('', url(r'^', include('cms.urls')), ) Add ending slash to regex for article-detail viewfrom django.conf import settings from django.conf.urls import patterns, include, url, static from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'ctlibre.views.home', name='home'), url(r'^article/(?P<slug>[^/]+)/$', 'news.views.article_detail', name='article-detail'), url(r'^admin/', include(admin.site.urls)), ) # Serve static media during development urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += patterns('', url(r'^', include('cms.urls')), )
<commit_before>from django.conf import settings from django.conf.urls import patterns, include, url, static from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'ctlibre.views.home', name='home'), url(r'^article/(?P<slug>[^/]+)', 'news.views.article_detail', name='article-detail'), url(r'^admin/', include(admin.site.urls)), ) # Serve static media during development urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += patterns('', url(r'^', include('cms.urls')), ) <commit_msg>Add ending slash to regex for article-detail view<commit_after>from django.conf import settings from django.conf.urls import patterns, include, url, static from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'ctlibre.views.home', name='home'), url(r'^article/(?P<slug>[^/]+)/$', 'news.views.article_detail', name='article-detail'), url(r'^admin/', include(admin.site.urls)), ) # Serve static media during development urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += patterns('', url(r'^', include('cms.urls')), )
1de4a0edd0f3c43b53e3a91c10d23155889791c6
tca/chat/tests.py
tca/chat/tests.py
from django.test import TestCase # Create your tests here.
from django.test import TestCase from django.core.urlresolvers import reverse from urllib import urlencode import json class ViewTestCaseMixin(object): """A mixin providing some convenience methods for testing views. Expects that a ``view_name`` property exists on the class which mixes it in. """ def get_view_url(self, *args, **kwargs): return reverse(self.view_name, args=args, kwargs=kwargs) def build_url(self, base_url, query_dict=None): url_template = "{base_url}?{query_string}" if query_dict is None: return base_url return url_template.format( base_url=base_url, query_string=urlencode(query_dict) ) def get(self, parameters=None, *args, **kwargs): """ Sends a GET request to the view-under-test and returns the response :param parameters: The query string parameters of the GET request """ base_url = self.get_view_url(*args, **kwargs) return self.client.get(self.build_url(base_url, parameters)) def post(self, body=None, content_type='application/json', *args, **kwargs): """ Sends a POST request to the view-under-test and returns the response :param body: The content to be included in the body of the request """ base_url = self.get_view_url(*args, **kwargs) if body is None: body = '' return self.client.post( self.build_url(base_url), body, content_type=content_type) def post_json(self, json_payload, *args, **kwargs): """ Sends a POST request to the view-under-test and returns the response. The body of the POST request is formed by serializing the ``json_payload`` object to JSON. """ payload = json.dumps(json_payload) return self.post( body=payload, content_type='application/json', *args, **kwargs)
Add a helper mixin for view test cases
Add a helper mixin for view test cases The mixin defines some helper methods which are useful when testing views (REST endpoints).
Python
bsd-3-clause
mlalic/TumCampusAppBackend,mlalic/TumCampusAppBackend
from django.test import TestCase # Create your tests here. Add a helper mixin for view test cases The mixin defines some helper methods which are useful when testing views (REST endpoints).
from django.test import TestCase from django.core.urlresolvers import reverse from urllib import urlencode import json class ViewTestCaseMixin(object): """A mixin providing some convenience methods for testing views. Expects that a ``view_name`` property exists on the class which mixes it in. """ def get_view_url(self, *args, **kwargs): return reverse(self.view_name, args=args, kwargs=kwargs) def build_url(self, base_url, query_dict=None): url_template = "{base_url}?{query_string}" if query_dict is None: return base_url return url_template.format( base_url=base_url, query_string=urlencode(query_dict) ) def get(self, parameters=None, *args, **kwargs): """ Sends a GET request to the view-under-test and returns the response :param parameters: The query string parameters of the GET request """ base_url = self.get_view_url(*args, **kwargs) return self.client.get(self.build_url(base_url, parameters)) def post(self, body=None, content_type='application/json', *args, **kwargs): """ Sends a POST request to the view-under-test and returns the response :param body: The content to be included in the body of the request """ base_url = self.get_view_url(*args, **kwargs) if body is None: body = '' return self.client.post( self.build_url(base_url), body, content_type=content_type) def post_json(self, json_payload, *args, **kwargs): """ Sends a POST request to the view-under-test and returns the response. The body of the POST request is formed by serializing the ``json_payload`` object to JSON. """ payload = json.dumps(json_payload) return self.post( body=payload, content_type='application/json', *args, **kwargs)
<commit_before>from django.test import TestCase # Create your tests here. <commit_msg>Add a helper mixin for view test cases The mixin defines some helper methods which are useful when testing views (REST endpoints).<commit_after>
from django.test import TestCase from django.core.urlresolvers import reverse from urllib import urlencode import json class ViewTestCaseMixin(object): """A mixin providing some convenience methods for testing views. Expects that a ``view_name`` property exists on the class which mixes it in. """ def get_view_url(self, *args, **kwargs): return reverse(self.view_name, args=args, kwargs=kwargs) def build_url(self, base_url, query_dict=None): url_template = "{base_url}?{query_string}" if query_dict is None: return base_url return url_template.format( base_url=base_url, query_string=urlencode(query_dict) ) def get(self, parameters=None, *args, **kwargs): """ Sends a GET request to the view-under-test and returns the response :param parameters: The query string parameters of the GET request """ base_url = self.get_view_url(*args, **kwargs) return self.client.get(self.build_url(base_url, parameters)) def post(self, body=None, content_type='application/json', *args, **kwargs): """ Sends a POST request to the view-under-test and returns the response :param body: The content to be included in the body of the request """ base_url = self.get_view_url(*args, **kwargs) if body is None: body = '' return self.client.post( self.build_url(base_url), body, content_type=content_type) def post_json(self, json_payload, *args, **kwargs): """ Sends a POST request to the view-under-test and returns the response. The body of the POST request is formed by serializing the ``json_payload`` object to JSON. """ payload = json.dumps(json_payload) return self.post( body=payload, content_type='application/json', *args, **kwargs)
from django.test import TestCase # Create your tests here. Add a helper mixin for view test cases The mixin defines some helper methods which are useful when testing views (REST endpoints).from django.test import TestCase from django.core.urlresolvers import reverse from urllib import urlencode import json class ViewTestCaseMixin(object): """A mixin providing some convenience methods for testing views. Expects that a ``view_name`` property exists on the class which mixes it in. """ def get_view_url(self, *args, **kwargs): return reverse(self.view_name, args=args, kwargs=kwargs) def build_url(self, base_url, query_dict=None): url_template = "{base_url}?{query_string}" if query_dict is None: return base_url return url_template.format( base_url=base_url, query_string=urlencode(query_dict) ) def get(self, parameters=None, *args, **kwargs): """ Sends a GET request to the view-under-test and returns the response :param parameters: The query string parameters of the GET request """ base_url = self.get_view_url(*args, **kwargs) return self.client.get(self.build_url(base_url, parameters)) def post(self, body=None, content_type='application/json', *args, **kwargs): """ Sends a POST request to the view-under-test and returns the response :param body: The content to be included in the body of the request """ base_url = self.get_view_url(*args, **kwargs) if body is None: body = '' return self.client.post( self.build_url(base_url), body, content_type=content_type) def post_json(self, json_payload, *args, **kwargs): """ Sends a POST request to the view-under-test and returns the response. The body of the POST request is formed by serializing the ``json_payload`` object to JSON. """ payload = json.dumps(json_payload) return self.post( body=payload, content_type='application/json', *args, **kwargs)
<commit_before>from django.test import TestCase # Create your tests here. <commit_msg>Add a helper mixin for view test cases The mixin defines some helper methods which are useful when testing views (REST endpoints).<commit_after>from django.test import TestCase from django.core.urlresolvers import reverse from urllib import urlencode import json class ViewTestCaseMixin(object): """A mixin providing some convenience methods for testing views. Expects that a ``view_name`` property exists on the class which mixes it in. """ def get_view_url(self, *args, **kwargs): return reverse(self.view_name, args=args, kwargs=kwargs) def build_url(self, base_url, query_dict=None): url_template = "{base_url}?{query_string}" if query_dict is None: return base_url return url_template.format( base_url=base_url, query_string=urlencode(query_dict) ) def get(self, parameters=None, *args, **kwargs): """ Sends a GET request to the view-under-test and returns the response :param parameters: The query string parameters of the GET request """ base_url = self.get_view_url(*args, **kwargs) return self.client.get(self.build_url(base_url, parameters)) def post(self, body=None, content_type='application/json', *args, **kwargs): """ Sends a POST request to the view-under-test and returns the response :param body: The content to be included in the body of the request """ base_url = self.get_view_url(*args, **kwargs) if body is None: body = '' return self.client.post( self.build_url(base_url), body, content_type=content_type) def post_json(self, json_payload, *args, **kwargs): """ Sends a POST request to the view-under-test and returns the response. The body of the POST request is formed by serializing the ``json_payload`` object to JSON. """ payload = json.dumps(json_payload) return self.post( body=payload, content_type='application/json', *args, **kwargs)
a688c8287c7f4c52d856f5bef363a73526a7b1d8
orders/views.py
orders/views.py
from django.db.models import Sum from django.db.models.query import QuerySet from django.shortcuts import render, get_object_or_404 from django.utils import timezone from orders.models import Order def order_details(request, order_pk): order = get_object_or_404(Order.objects.prefetch_related('books'), pk=order_pk) return render(request, 'orders/details.html', {'order': order, 'book_list': [book.book_type for book in order.books.all()]}) def not_executed(request): orders = get_orders().filter(valid_until__gt=timezone.now(), sold_count=0) return render(request, 'orders/not_executed.html', {'orders': orders}) def outdated(request): orders = get_orders().filter(valid_until__lte=timezone.now(), sold_count=0) return render(request, 'orders/outdated.html', {'orders': orders}) def executed(request): orders = get_orders().exclude(sold_count=0) return render(request, 'orders/executed.html', {'orders': orders}) def get_orders() -> QuerySet: """ The function returns QuerySet of Order model with all necessary values for displaying also selected/prefetched. :return: the QuerySet of Order model """ return Order.objects.select_related('user').prefetch_related('books').annotate(sold_count=Sum('books__sold'))
from django.db.models import Sum from django.db.models.query import QuerySet from django.shortcuts import render, get_object_or_404 from django.utils import timezone from orders.models import Order def order_details(request, order_pk): order = get_object_or_404(Order.objects.prefetch_related('books', 'books__book_type').select_related('user'), pk=order_pk) return render(request, 'orders/details.html', {'order': order, 'book_list': [book.book_type for book in order.books.all()]}) def not_executed(request): orders = get_orders().filter(valid_until__gt=timezone.now(), sold_count=0) return render(request, 'orders/not_executed.html', {'orders': orders}) def outdated(request): orders = get_orders().filter(valid_until__lte=timezone.now(), sold_count=0) return render(request, 'orders/outdated.html', {'orders': orders}) def executed(request): orders = get_orders().exclude(sold_count=0) return render(request, 'orders/executed.html', {'orders': orders}) def get_orders() -> QuerySet: """ The function returns QuerySet of Order model with all necessary values for displaying also selected/prefetched. :return: the QuerySet of Order model """ return Order.objects.select_related('user').prefetch_related('books').annotate(sold_count=Sum('books__sold'))
Optimize number of SQL queries in Order details view
Optimize number of SQL queries in Order details view
Python
agpl-3.0
m4tx/egielda,m4tx/egielda,m4tx/egielda
from django.db.models import Sum from django.db.models.query import QuerySet from django.shortcuts import render, get_object_or_404 from django.utils import timezone from orders.models import Order def order_details(request, order_pk): order = get_object_or_404(Order.objects.prefetch_related('books'), pk=order_pk) return render(request, 'orders/details.html', {'order': order, 'book_list': [book.book_type for book in order.books.all()]}) def not_executed(request): orders = get_orders().filter(valid_until__gt=timezone.now(), sold_count=0) return render(request, 'orders/not_executed.html', {'orders': orders}) def outdated(request): orders = get_orders().filter(valid_until__lte=timezone.now(), sold_count=0) return render(request, 'orders/outdated.html', {'orders': orders}) def executed(request): orders = get_orders().exclude(sold_count=0) return render(request, 'orders/executed.html', {'orders': orders}) def get_orders() -> QuerySet: """ The function returns QuerySet of Order model with all necessary values for displaying also selected/prefetched. :return: the QuerySet of Order model """ return Order.objects.select_related('user').prefetch_related('books').annotate(sold_count=Sum('books__sold'))Optimize number of SQL queries in Order details view
from django.db.models import Sum from django.db.models.query import QuerySet from django.shortcuts import render, get_object_or_404 from django.utils import timezone from orders.models import Order def order_details(request, order_pk): order = get_object_or_404(Order.objects.prefetch_related('books', 'books__book_type').select_related('user'), pk=order_pk) return render(request, 'orders/details.html', {'order': order, 'book_list': [book.book_type for book in order.books.all()]}) def not_executed(request): orders = get_orders().filter(valid_until__gt=timezone.now(), sold_count=0) return render(request, 'orders/not_executed.html', {'orders': orders}) def outdated(request): orders = get_orders().filter(valid_until__lte=timezone.now(), sold_count=0) return render(request, 'orders/outdated.html', {'orders': orders}) def executed(request): orders = get_orders().exclude(sold_count=0) return render(request, 'orders/executed.html', {'orders': orders}) def get_orders() -> QuerySet: """ The function returns QuerySet of Order model with all necessary values for displaying also selected/prefetched. :return: the QuerySet of Order model """ return Order.objects.select_related('user').prefetch_related('books').annotate(sold_count=Sum('books__sold'))
<commit_before>from django.db.models import Sum from django.db.models.query import QuerySet from django.shortcuts import render, get_object_or_404 from django.utils import timezone from orders.models import Order def order_details(request, order_pk): order = get_object_or_404(Order.objects.prefetch_related('books'), pk=order_pk) return render(request, 'orders/details.html', {'order': order, 'book_list': [book.book_type for book in order.books.all()]}) def not_executed(request): orders = get_orders().filter(valid_until__gt=timezone.now(), sold_count=0) return render(request, 'orders/not_executed.html', {'orders': orders}) def outdated(request): orders = get_orders().filter(valid_until__lte=timezone.now(), sold_count=0) return render(request, 'orders/outdated.html', {'orders': orders}) def executed(request): orders = get_orders().exclude(sold_count=0) return render(request, 'orders/executed.html', {'orders': orders}) def get_orders() -> QuerySet: """ The function returns QuerySet of Order model with all necessary values for displaying also selected/prefetched. :return: the QuerySet of Order model """ return Order.objects.select_related('user').prefetch_related('books').annotate(sold_count=Sum('books__sold'))<commit_msg>Optimize number of SQL queries in Order details view<commit_after>
from django.db.models import Sum from django.db.models.query import QuerySet from django.shortcuts import render, get_object_or_404 from django.utils import timezone from orders.models import Order def order_details(request, order_pk): order = get_object_or_404(Order.objects.prefetch_related('books', 'books__book_type').select_related('user'), pk=order_pk) return render(request, 'orders/details.html', {'order': order, 'book_list': [book.book_type for book in order.books.all()]}) def not_executed(request): orders = get_orders().filter(valid_until__gt=timezone.now(), sold_count=0) return render(request, 'orders/not_executed.html', {'orders': orders}) def outdated(request): orders = get_orders().filter(valid_until__lte=timezone.now(), sold_count=0) return render(request, 'orders/outdated.html', {'orders': orders}) def executed(request): orders = get_orders().exclude(sold_count=0) return render(request, 'orders/executed.html', {'orders': orders}) def get_orders() -> QuerySet: """ The function returns QuerySet of Order model with all necessary values for displaying also selected/prefetched. :return: the QuerySet of Order model """ return Order.objects.select_related('user').prefetch_related('books').annotate(sold_count=Sum('books__sold'))
from django.db.models import Sum from django.db.models.query import QuerySet from django.shortcuts import render, get_object_or_404 from django.utils import timezone from orders.models import Order def order_details(request, order_pk): order = get_object_or_404(Order.objects.prefetch_related('books'), pk=order_pk) return render(request, 'orders/details.html', {'order': order, 'book_list': [book.book_type for book in order.books.all()]}) def not_executed(request): orders = get_orders().filter(valid_until__gt=timezone.now(), sold_count=0) return render(request, 'orders/not_executed.html', {'orders': orders}) def outdated(request): orders = get_orders().filter(valid_until__lte=timezone.now(), sold_count=0) return render(request, 'orders/outdated.html', {'orders': orders}) def executed(request): orders = get_orders().exclude(sold_count=0) return render(request, 'orders/executed.html', {'orders': orders}) def get_orders() -> QuerySet: """ The function returns QuerySet of Order model with all necessary values for displaying also selected/prefetched. :return: the QuerySet of Order model """ return Order.objects.select_related('user').prefetch_related('books').annotate(sold_count=Sum('books__sold'))Optimize number of SQL queries in Order details viewfrom django.db.models import Sum from django.db.models.query import QuerySet from django.shortcuts import render, get_object_or_404 from django.utils import timezone from orders.models import Order def order_details(request, order_pk): order = get_object_or_404(Order.objects.prefetch_related('books', 'books__book_type').select_related('user'), pk=order_pk) return render(request, 'orders/details.html', {'order': order, 'book_list': [book.book_type for book in order.books.all()]}) def not_executed(request): orders = get_orders().filter(valid_until__gt=timezone.now(), sold_count=0) return render(request, 'orders/not_executed.html', {'orders': orders}) def outdated(request): orders = get_orders().filter(valid_until__lte=timezone.now(), sold_count=0) return render(request, 'orders/outdated.html', {'orders': orders}) def executed(request): orders = get_orders().exclude(sold_count=0) return render(request, 'orders/executed.html', {'orders': orders}) def get_orders() -> QuerySet: """ The function returns QuerySet of Order model with all necessary values for displaying also selected/prefetched. :return: the QuerySet of Order model """ return Order.objects.select_related('user').prefetch_related('books').annotate(sold_count=Sum('books__sold'))
<commit_before>from django.db.models import Sum from django.db.models.query import QuerySet from django.shortcuts import render, get_object_or_404 from django.utils import timezone from orders.models import Order def order_details(request, order_pk): order = get_object_or_404(Order.objects.prefetch_related('books'), pk=order_pk) return render(request, 'orders/details.html', {'order': order, 'book_list': [book.book_type for book in order.books.all()]}) def not_executed(request): orders = get_orders().filter(valid_until__gt=timezone.now(), sold_count=0) return render(request, 'orders/not_executed.html', {'orders': orders}) def outdated(request): orders = get_orders().filter(valid_until__lte=timezone.now(), sold_count=0) return render(request, 'orders/outdated.html', {'orders': orders}) def executed(request): orders = get_orders().exclude(sold_count=0) return render(request, 'orders/executed.html', {'orders': orders}) def get_orders() -> QuerySet: """ The function returns QuerySet of Order model with all necessary values for displaying also selected/prefetched. :return: the QuerySet of Order model """ return Order.objects.select_related('user').prefetch_related('books').annotate(sold_count=Sum('books__sold'))<commit_msg>Optimize number of SQL queries in Order details view<commit_after>from django.db.models import Sum from django.db.models.query import QuerySet from django.shortcuts import render, get_object_or_404 from django.utils import timezone from orders.models import Order def order_details(request, order_pk): order = get_object_or_404(Order.objects.prefetch_related('books', 'books__book_type').select_related('user'), pk=order_pk) return render(request, 'orders/details.html', {'order': order, 'book_list': [book.book_type for book in order.books.all()]}) def not_executed(request): orders = get_orders().filter(valid_until__gt=timezone.now(), sold_count=0) return render(request, 'orders/not_executed.html', {'orders': orders}) def outdated(request): orders = get_orders().filter(valid_until__lte=timezone.now(), sold_count=0) return render(request, 'orders/outdated.html', {'orders': orders}) def executed(request): orders = get_orders().exclude(sold_count=0) return render(request, 'orders/executed.html', {'orders': orders}) def get_orders() -> QuerySet: """ The function returns QuerySet of Order model with all necessary values for displaying also selected/prefetched. :return: the QuerySet of Order model """ return Order.objects.select_related('user').prefetch_related('books').annotate(sold_count=Sum('books__sold'))
c15bbff2fbe9f4063ca0776262526e5270eefc1e
config/__init__.py
config/__init__.py
""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser import os """ Default options """ #TODO: format this to match the dicts generated by configparser from files. #TODO: more default options... _CONFIG_DEFAULTS = { # default database path is ../db/test.db relative to this file "db_path": os.path.join( os.path.dirname(os.path.dirname(__file__)), "db/test.db") } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = os.path.dirname(__file__) filename = os.path.join(cfg_path, "config.ini") cp = configparser.ConfigParser(_CONFIG_DEFAULTS) #TODO: use logging instead of print... print("Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) print(str(cfg))
""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser import os """ Default options """ #TODO: more default options... _CONFIG_DEFAULTS = { "paths": { # default database path is ../db/test.db relative to this file "db_path": os.path.join( os.path.dirname(os.path.dirname(__file__)), "db/test.db"), }, } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = os.path.dirname(__file__) filename = os.path.join(cfg_path, "config.ini") cp = configparser.ConfigParser() #_CONFIG_DEFAULTS) # read default values from dict cp.read_dict(_CONFIG_DEFAULTS) #TODO: use logging instead of print... print("Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) print(str(cfg))
Add proper default values to config (although hardcoded).
Add proper default values to config (although hardcoded).
Python
mit
mgunyho/kiltiskahvi
""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser import os """ Default options """ #TODO: format this to match the dicts generated by configparser from files. #TODO: more default options... _CONFIG_DEFAULTS = { # default database path is ../db/test.db relative to this file "db_path": os.path.join( os.path.dirname(os.path.dirname(__file__)), "db/test.db") } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = os.path.dirname(__file__) filename = os.path.join(cfg_path, "config.ini") cp = configparser.ConfigParser(_CONFIG_DEFAULTS) #TODO: use logging instead of print... print("Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) print(str(cfg)) Add proper default values to config (although hardcoded).
""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser import os """ Default options """ #TODO: more default options... _CONFIG_DEFAULTS = { "paths": { # default database path is ../db/test.db relative to this file "db_path": os.path.join( os.path.dirname(os.path.dirname(__file__)), "db/test.db"), }, } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = os.path.dirname(__file__) filename = os.path.join(cfg_path, "config.ini") cp = configparser.ConfigParser() #_CONFIG_DEFAULTS) # read default values from dict cp.read_dict(_CONFIG_DEFAULTS) #TODO: use logging instead of print... print("Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) print(str(cfg))
<commit_before>""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser import os """ Default options """ #TODO: format this to match the dicts generated by configparser from files. #TODO: more default options... _CONFIG_DEFAULTS = { # default database path is ../db/test.db relative to this file "db_path": os.path.join( os.path.dirname(os.path.dirname(__file__)), "db/test.db") } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = os.path.dirname(__file__) filename = os.path.join(cfg_path, "config.ini") cp = configparser.ConfigParser(_CONFIG_DEFAULTS) #TODO: use logging instead of print... print("Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) print(str(cfg)) <commit_msg>Add proper default values to config (although hardcoded).<commit_after>
""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser import os """ Default options """ #TODO: more default options... _CONFIG_DEFAULTS = { "paths": { # default database path is ../db/test.db relative to this file "db_path": os.path.join( os.path.dirname(os.path.dirname(__file__)), "db/test.db"), }, } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = os.path.dirname(__file__) filename = os.path.join(cfg_path, "config.ini") cp = configparser.ConfigParser() #_CONFIG_DEFAULTS) # read default values from dict cp.read_dict(_CONFIG_DEFAULTS) #TODO: use logging instead of print... print("Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) print(str(cfg))
""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser import os """ Default options """ #TODO: format this to match the dicts generated by configparser from files. #TODO: more default options... _CONFIG_DEFAULTS = { # default database path is ../db/test.db relative to this file "db_path": os.path.join( os.path.dirname(os.path.dirname(__file__)), "db/test.db") } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = os.path.dirname(__file__) filename = os.path.join(cfg_path, "config.ini") cp = configparser.ConfigParser(_CONFIG_DEFAULTS) #TODO: use logging instead of print... print("Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) print(str(cfg)) Add proper default values to config (although hardcoded).""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser import os """ Default options """ #TODO: more default options... _CONFIG_DEFAULTS = { "paths": { # default database path is ../db/test.db relative to this file "db_path": os.path.join( os.path.dirname(os.path.dirname(__file__)), "db/test.db"), }, } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = os.path.dirname(__file__) filename = os.path.join(cfg_path, "config.ini") cp = configparser.ConfigParser() #_CONFIG_DEFAULTS) # read default values from dict cp.read_dict(_CONFIG_DEFAULTS) #TODO: use logging instead of print... print("Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) print(str(cfg))
<commit_before>""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser import os """ Default options """ #TODO: format this to match the dicts generated by configparser from files. #TODO: more default options... _CONFIG_DEFAULTS = { # default database path is ../db/test.db relative to this file "db_path": os.path.join( os.path.dirname(os.path.dirname(__file__)), "db/test.db") } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = os.path.dirname(__file__) filename = os.path.join(cfg_path, "config.ini") cp = configparser.ConfigParser(_CONFIG_DEFAULTS) #TODO: use logging instead of print... print("Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) print(str(cfg)) <commit_msg>Add proper default values to config (although hardcoded).<commit_after>""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser import os """ Default options """ #TODO: more default options... _CONFIG_DEFAULTS = { "paths": { # default database path is ../db/test.db relative to this file "db_path": os.path.join( os.path.dirname(os.path.dirname(__file__)), "db/test.db"), }, } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = os.path.dirname(__file__) filename = os.path.join(cfg_path, "config.ini") cp = configparser.ConfigParser() #_CONFIG_DEFAULTS) # read default values from dict cp.read_dict(_CONFIG_DEFAULTS) #TODO: use logging instead of print... print("Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) print(str(cfg))
b90433326e2d99b34acceb8552b038501a7d238d
examples/regression_offset_autograd.py
examples/regression_offset_autograd.py
import autograd.numpy as np from pymanopt import Problem from pymanopt.solvers import TrustRegions from pymanopt.manifolds import Euclidean, Product if __name__ == "__main__": # Generate random data X = np.random.randn(3, 100) Y = X[0:1, :] - 2*X[1:2, :] + np.random.randn(1, 100) + 5 # Cost function is the sqaured test error def cost((w, b)): return np.sum((Y-np.dot(w.T, X)-b)**2) # first-order, second-order solver = TrustRegions() # R^3 x R^1 manifold = Product([Euclidean(3, 1), Euclidean(1, 1)]) # Solve the problem with pymanopt problem = Problem(man=manifold, cost=cost, verbosity=0) wopt = solver.solve(problem) print('Weights found by pymanopt (top) / ' 'closed form solution (bottom)') print(wopt[0].T) print(wopt[1]) X1 = np.concatenate((X, np.ones((1, 100))), axis=0) wclosed = np.linalg.inv(X1.dot(X1.T)).dot(X1).dot(Y.T) print(wclosed[0:3].T) print(wclosed[3])
import autograd.numpy as np from pymanopt import Problem from pymanopt.solvers import TrustRegions from pymanopt.manifolds import Euclidean, Product if __name__ == "__main__": # Generate random data X = np.random.randn(3, 100) Y = X[0:1, :] - 2*X[1:2, :] + np.random.randn(1, 100) + 5 # Cost function is the sqaured test error # Note, weights is a tuple/list containing both weight vector w and bias b. # This is necessary for autograd to calculate the gradient w.r.t. both # arguments in one go. def cost(weights): w = weights[0] b = weights[1] return np.sum((Y-np.dot(w.T, X)-b)**2) # first-order, second-order solver = TrustRegions() # R^3 x R^1 manifold = Product([Euclidean(3, 1), Euclidean(1, 1)]) # Solve the problem with pymanopt problem = Problem(man=manifold, cost=cost, verbosity=0) wopt = solver.solve(problem) print('Weights found by pymanopt (top) / ' 'closed form solution (bottom)') print(wopt[0].T) print(wopt[1]) X1 = np.concatenate((X, np.ones((1, 100))), axis=0) wclosed = np.linalg.inv(X1.dot(X1.T)).dot(X1).dot(Y.T) print(wclosed[0:3].T) print(wclosed[3])
Fix regression autograd example for python3
Fix regression autograd example for python3
Python
bsd-3-clause
nkoep/pymanopt,nkoep/pymanopt,nkoep/pymanopt,tingelst/pymanopt,pymanopt/pymanopt,pymanopt/pymanopt,j-towns/pymanopt
import autograd.numpy as np from pymanopt import Problem from pymanopt.solvers import TrustRegions from pymanopt.manifolds import Euclidean, Product if __name__ == "__main__": # Generate random data X = np.random.randn(3, 100) Y = X[0:1, :] - 2*X[1:2, :] + np.random.randn(1, 100) + 5 # Cost function is the sqaured test error def cost((w, b)): return np.sum((Y-np.dot(w.T, X)-b)**2) # first-order, second-order solver = TrustRegions() # R^3 x R^1 manifold = Product([Euclidean(3, 1), Euclidean(1, 1)]) # Solve the problem with pymanopt problem = Problem(man=manifold, cost=cost, verbosity=0) wopt = solver.solve(problem) print('Weights found by pymanopt (top) / ' 'closed form solution (bottom)') print(wopt[0].T) print(wopt[1]) X1 = np.concatenate((X, np.ones((1, 100))), axis=0) wclosed = np.linalg.inv(X1.dot(X1.T)).dot(X1).dot(Y.T) print(wclosed[0:3].T) print(wclosed[3]) Fix regression autograd example for python3
import autograd.numpy as np from pymanopt import Problem from pymanopt.solvers import TrustRegions from pymanopt.manifolds import Euclidean, Product if __name__ == "__main__": # Generate random data X = np.random.randn(3, 100) Y = X[0:1, :] - 2*X[1:2, :] + np.random.randn(1, 100) + 5 # Cost function is the sqaured test error # Note, weights is a tuple/list containing both weight vector w and bias b. # This is necessary for autograd to calculate the gradient w.r.t. both # arguments in one go. def cost(weights): w = weights[0] b = weights[1] return np.sum((Y-np.dot(w.T, X)-b)**2) # first-order, second-order solver = TrustRegions() # R^3 x R^1 manifold = Product([Euclidean(3, 1), Euclidean(1, 1)]) # Solve the problem with pymanopt problem = Problem(man=manifold, cost=cost, verbosity=0) wopt = solver.solve(problem) print('Weights found by pymanopt (top) / ' 'closed form solution (bottom)') print(wopt[0].T) print(wopt[1]) X1 = np.concatenate((X, np.ones((1, 100))), axis=0) wclosed = np.linalg.inv(X1.dot(X1.T)).dot(X1).dot(Y.T) print(wclosed[0:3].T) print(wclosed[3])
<commit_before>import autograd.numpy as np from pymanopt import Problem from pymanopt.solvers import TrustRegions from pymanopt.manifolds import Euclidean, Product if __name__ == "__main__": # Generate random data X = np.random.randn(3, 100) Y = X[0:1, :] - 2*X[1:2, :] + np.random.randn(1, 100) + 5 # Cost function is the sqaured test error def cost((w, b)): return np.sum((Y-np.dot(w.T, X)-b)**2) # first-order, second-order solver = TrustRegions() # R^3 x R^1 manifold = Product([Euclidean(3, 1), Euclidean(1, 1)]) # Solve the problem with pymanopt problem = Problem(man=manifold, cost=cost, verbosity=0) wopt = solver.solve(problem) print('Weights found by pymanopt (top) / ' 'closed form solution (bottom)') print(wopt[0].T) print(wopt[1]) X1 = np.concatenate((X, np.ones((1, 100))), axis=0) wclosed = np.linalg.inv(X1.dot(X1.T)).dot(X1).dot(Y.T) print(wclosed[0:3].T) print(wclosed[3]) <commit_msg>Fix regression autograd example for python3<commit_after>
import autograd.numpy as np from pymanopt import Problem from pymanopt.solvers import TrustRegions from pymanopt.manifolds import Euclidean, Product if __name__ == "__main__": # Generate random data X = np.random.randn(3, 100) Y = X[0:1, :] - 2*X[1:2, :] + np.random.randn(1, 100) + 5 # Cost function is the sqaured test error # Note, weights is a tuple/list containing both weight vector w and bias b. # This is necessary for autograd to calculate the gradient w.r.t. both # arguments in one go. def cost(weights): w = weights[0] b = weights[1] return np.sum((Y-np.dot(w.T, X)-b)**2) # first-order, second-order solver = TrustRegions() # R^3 x R^1 manifold = Product([Euclidean(3, 1), Euclidean(1, 1)]) # Solve the problem with pymanopt problem = Problem(man=manifold, cost=cost, verbosity=0) wopt = solver.solve(problem) print('Weights found by pymanopt (top) / ' 'closed form solution (bottom)') print(wopt[0].T) print(wopt[1]) X1 = np.concatenate((X, np.ones((1, 100))), axis=0) wclosed = np.linalg.inv(X1.dot(X1.T)).dot(X1).dot(Y.T) print(wclosed[0:3].T) print(wclosed[3])
import autograd.numpy as np from pymanopt import Problem from pymanopt.solvers import TrustRegions from pymanopt.manifolds import Euclidean, Product if __name__ == "__main__": # Generate random data X = np.random.randn(3, 100) Y = X[0:1, :] - 2*X[1:2, :] + np.random.randn(1, 100) + 5 # Cost function is the sqaured test error def cost((w, b)): return np.sum((Y-np.dot(w.T, X)-b)**2) # first-order, second-order solver = TrustRegions() # R^3 x R^1 manifold = Product([Euclidean(3, 1), Euclidean(1, 1)]) # Solve the problem with pymanopt problem = Problem(man=manifold, cost=cost, verbosity=0) wopt = solver.solve(problem) print('Weights found by pymanopt (top) / ' 'closed form solution (bottom)') print(wopt[0].T) print(wopt[1]) X1 = np.concatenate((X, np.ones((1, 100))), axis=0) wclosed = np.linalg.inv(X1.dot(X1.T)).dot(X1).dot(Y.T) print(wclosed[0:3].T) print(wclosed[3]) Fix regression autograd example for python3import autograd.numpy as np from pymanopt import Problem from pymanopt.solvers import TrustRegions from pymanopt.manifolds import Euclidean, Product if __name__ == "__main__": # Generate random data X = np.random.randn(3, 100) Y = X[0:1, :] - 2*X[1:2, :] + np.random.randn(1, 100) + 5 # Cost function is the sqaured test error # Note, weights is a tuple/list containing both weight vector w and bias b. # This is necessary for autograd to calculate the gradient w.r.t. both # arguments in one go. def cost(weights): w = weights[0] b = weights[1] return np.sum((Y-np.dot(w.T, X)-b)**2) # first-order, second-order solver = TrustRegions() # R^3 x R^1 manifold = Product([Euclidean(3, 1), Euclidean(1, 1)]) # Solve the problem with pymanopt problem = Problem(man=manifold, cost=cost, verbosity=0) wopt = solver.solve(problem) print('Weights found by pymanopt (top) / ' 'closed form solution (bottom)') print(wopt[0].T) print(wopt[1]) X1 = np.concatenate((X, np.ones((1, 100))), axis=0) wclosed = np.linalg.inv(X1.dot(X1.T)).dot(X1).dot(Y.T) print(wclosed[0:3].T) print(wclosed[3])
<commit_before>import autograd.numpy as np from pymanopt import Problem from pymanopt.solvers import TrustRegions from pymanopt.manifolds import Euclidean, Product if __name__ == "__main__": # Generate random data X = np.random.randn(3, 100) Y = X[0:1, :] - 2*X[1:2, :] + np.random.randn(1, 100) + 5 # Cost function is the sqaured test error def cost((w, b)): return np.sum((Y-np.dot(w.T, X)-b)**2) # first-order, second-order solver = TrustRegions() # R^3 x R^1 manifold = Product([Euclidean(3, 1), Euclidean(1, 1)]) # Solve the problem with pymanopt problem = Problem(man=manifold, cost=cost, verbosity=0) wopt = solver.solve(problem) print('Weights found by pymanopt (top) / ' 'closed form solution (bottom)') print(wopt[0].T) print(wopt[1]) X1 = np.concatenate((X, np.ones((1, 100))), axis=0) wclosed = np.linalg.inv(X1.dot(X1.T)).dot(X1).dot(Y.T) print(wclosed[0:3].T) print(wclosed[3]) <commit_msg>Fix regression autograd example for python3<commit_after>import autograd.numpy as np from pymanopt import Problem from pymanopt.solvers import TrustRegions from pymanopt.manifolds import Euclidean, Product if __name__ == "__main__": # Generate random data X = np.random.randn(3, 100) Y = X[0:1, :] - 2*X[1:2, :] + np.random.randn(1, 100) + 5 # Cost function is the sqaured test error # Note, weights is a tuple/list containing both weight vector w and bias b. # This is necessary for autograd to calculate the gradient w.r.t. both # arguments in one go. def cost(weights): w = weights[0] b = weights[1] return np.sum((Y-np.dot(w.T, X)-b)**2) # first-order, second-order solver = TrustRegions() # R^3 x R^1 manifold = Product([Euclidean(3, 1), Euclidean(1, 1)]) # Solve the problem with pymanopt problem = Problem(man=manifold, cost=cost, verbosity=0) wopt = solver.solve(problem) print('Weights found by pymanopt (top) / ' 'closed form solution (bottom)') print(wopt[0].T) print(wopt[1]) X1 = np.concatenate((X, np.ones((1, 100))), axis=0) wclosed = np.linalg.inv(X1.dot(X1.T)).dot(X1).dot(Y.T) print(wclosed[0:3].T) print(wclosed[3])
92631d96a9acac10e8af98bbaa5ec2afee1ae12f
openrcv/main.py
openrcv/main.py
#!/usr/bin/env python """ This module houses the "highest-level" programmatic API. """ import sys from openrcv import models from openrcv.models import BallotList from openrcv.parsing import BLTParser from openrcv.utils import FILE_ENCODING def do_parse(ballots_path, encoding=None): if encoding is None: encoding = FILE_ENCODING ballots = models.random_ballot_list(range(6), 5) #print(repr(ballots.ballots)) parser = BLTParser() info = parser.parse_path(ballots_path) print(repr(info))
#!/usr/bin/env python """ This module houses the "highest-level" programmatic API. """ import sys from openrcv import models from openrcv.models import BallotList from openrcv.parsing import BLTParser from openrcv.utils import FILE_ENCODING def make_json_tests(): contests = [] for count in range(3, 6): contest = models.random_contest(count) contests.append(contest) contests_obj = [c.__jsobj__() for c in contests] tests_jobj = { "_version": "0.1.0-alpha", "contests": contests_obj } json = models.to_json(tests_jobj) print(json) def do_parse(ballots_path, encoding=None): if encoding is None: encoding = FILE_ENCODING parser = BLTParser() info = parser.parse_path(ballots_path) print(repr(info))
Add code for generating test files.
Add code for generating test files.
Python
mit
cjerdonek/open-rcv,cjerdonek/open-rcv
#!/usr/bin/env python """ This module houses the "highest-level" programmatic API. """ import sys from openrcv import models from openrcv.models import BallotList from openrcv.parsing import BLTParser from openrcv.utils import FILE_ENCODING def do_parse(ballots_path, encoding=None): if encoding is None: encoding = FILE_ENCODING ballots = models.random_ballot_list(range(6), 5) #print(repr(ballots.ballots)) parser = BLTParser() info = parser.parse_path(ballots_path) print(repr(info)) Add code for generating test files.
#!/usr/bin/env python """ This module houses the "highest-level" programmatic API. """ import sys from openrcv import models from openrcv.models import BallotList from openrcv.parsing import BLTParser from openrcv.utils import FILE_ENCODING def make_json_tests(): contests = [] for count in range(3, 6): contest = models.random_contest(count) contests.append(contest) contests_obj = [c.__jsobj__() for c in contests] tests_jobj = { "_version": "0.1.0-alpha", "contests": contests_obj } json = models.to_json(tests_jobj) print(json) def do_parse(ballots_path, encoding=None): if encoding is None: encoding = FILE_ENCODING parser = BLTParser() info = parser.parse_path(ballots_path) print(repr(info))
<commit_before>#!/usr/bin/env python """ This module houses the "highest-level" programmatic API. """ import sys from openrcv import models from openrcv.models import BallotList from openrcv.parsing import BLTParser from openrcv.utils import FILE_ENCODING def do_parse(ballots_path, encoding=None): if encoding is None: encoding = FILE_ENCODING ballots = models.random_ballot_list(range(6), 5) #print(repr(ballots.ballots)) parser = BLTParser() info = parser.parse_path(ballots_path) print(repr(info)) <commit_msg>Add code for generating test files.<commit_after>
#!/usr/bin/env python """ This module houses the "highest-level" programmatic API. """ import sys from openrcv import models from openrcv.models import BallotList from openrcv.parsing import BLTParser from openrcv.utils import FILE_ENCODING def make_json_tests(): contests = [] for count in range(3, 6): contest = models.random_contest(count) contests.append(contest) contests_obj = [c.__jsobj__() for c in contests] tests_jobj = { "_version": "0.1.0-alpha", "contests": contests_obj } json = models.to_json(tests_jobj) print(json) def do_parse(ballots_path, encoding=None): if encoding is None: encoding = FILE_ENCODING parser = BLTParser() info = parser.parse_path(ballots_path) print(repr(info))
#!/usr/bin/env python """ This module houses the "highest-level" programmatic API. """ import sys from openrcv import models from openrcv.models import BallotList from openrcv.parsing import BLTParser from openrcv.utils import FILE_ENCODING def do_parse(ballots_path, encoding=None): if encoding is None: encoding = FILE_ENCODING ballots = models.random_ballot_list(range(6), 5) #print(repr(ballots.ballots)) parser = BLTParser() info = parser.parse_path(ballots_path) print(repr(info)) Add code for generating test files.#!/usr/bin/env python """ This module houses the "highest-level" programmatic API. """ import sys from openrcv import models from openrcv.models import BallotList from openrcv.parsing import BLTParser from openrcv.utils import FILE_ENCODING def make_json_tests(): contests = [] for count in range(3, 6): contest = models.random_contest(count) contests.append(contest) contests_obj = [c.__jsobj__() for c in contests] tests_jobj = { "_version": "0.1.0-alpha", "contests": contests_obj } json = models.to_json(tests_jobj) print(json) def do_parse(ballots_path, encoding=None): if encoding is None: encoding = FILE_ENCODING parser = BLTParser() info = parser.parse_path(ballots_path) print(repr(info))
<commit_before>#!/usr/bin/env python """ This module houses the "highest-level" programmatic API. """ import sys from openrcv import models from openrcv.models import BallotList from openrcv.parsing import BLTParser from openrcv.utils import FILE_ENCODING def do_parse(ballots_path, encoding=None): if encoding is None: encoding = FILE_ENCODING ballots = models.random_ballot_list(range(6), 5) #print(repr(ballots.ballots)) parser = BLTParser() info = parser.parse_path(ballots_path) print(repr(info)) <commit_msg>Add code for generating test files.<commit_after>#!/usr/bin/env python """ This module houses the "highest-level" programmatic API. """ import sys from openrcv import models from openrcv.models import BallotList from openrcv.parsing import BLTParser from openrcv.utils import FILE_ENCODING def make_json_tests(): contests = [] for count in range(3, 6): contest = models.random_contest(count) contests.append(contest) contests_obj = [c.__jsobj__() for c in contests] tests_jobj = { "_version": "0.1.0-alpha", "contests": contests_obj } json = models.to_json(tests_jobj) print(json) def do_parse(ballots_path, encoding=None): if encoding is None: encoding = FILE_ENCODING parser = BLTParser() info = parser.parse_path(ballots_path) print(repr(info))
5cd87adf93502a4de5b413c2f537af57ffe4c418
paley.py
paley.py
import turtle import math import sys class Paley: def __init__(self, p, radius = 290): self.p = p self.radius = radius """Return coordinates of ith vertex""" def getVertex(self, i): angle = i * 2 * math.pi / self.p return (self.radius * math.cos(angle), self.radius * math.sin(angle)) """Draw the Paley graph""" def draw(self): t = turtle.Turtle() t.speed(0) t.ht() visited = [False for i in xrange(self.p)] for i in xrange(self.p): t.pu() t.goto(self.getVertex(i)) for residue in xrange(1, (self.p - 1) / 2): j = (i + residue * residue) % self.p if not visited[j]: t.pd() t.goto(self.getVertex(j)) t.pu() t.goto(self.getVertex(i)) visited[i] = True turtle.done() def main(): if len(sys.argv) > 1: pal = Paley(int(sys.argv[1])) if len(sys.argv) > 2: pal.radius = int(sys.argv[2]) pal.draw() else: print "Please specify size of Paley graph" if __name__ == "__main__": main()
import turtle import math import sys class Paley: def __init__(self, p, radius = 290): self.p = p self.radius = radius """Return coordinates of ith vertex""" def getVertex(self, i): angle = i * 2 * math.pi / self.p return (self.radius * math.cos(angle), self.radius * math.sin(angle)) """Draw the Paley graph""" def draw(self): t = turtle.Turtle() t.speed(0) t.ht() visited = [[False for j in xrange(self.p)] for i in xrange(self.p)] for i in xrange(self.p): t.pu() t.goto(self.getVertex(i)) for residue in xrange(1, (self.p - 1) / 2): j = (i + residue * residue) % self.p if not visited[i][j]: t.pd() t.goto(self.getVertex(j)) t.pu() t.goto(self.getVertex(i)) visited[i][j] = visited[j][i] = True turtle.done() def main(): if len(sys.argv) > 1: pal = Paley(int(sys.argv[1])) if len(sys.argv) > 2: pal.radius = int(sys.argv[2]) pal.draw() else: print "Please specify size of Paley graph" if __name__ == "__main__": main()
Use 2D array instead of 1D to keep track of which edges have been drawn
Use 2D array instead of 1D to keep track of which edges have been drawn TODO: this probably isn't necessary
Python
mit
smpcole/paley-graph-drawer,smpcole/paley-graph-drawer
import turtle import math import sys class Paley: def __init__(self, p, radius = 290): self.p = p self.radius = radius """Return coordinates of ith vertex""" def getVertex(self, i): angle = i * 2 * math.pi / self.p return (self.radius * math.cos(angle), self.radius * math.sin(angle)) """Draw the Paley graph""" def draw(self): t = turtle.Turtle() t.speed(0) t.ht() visited = [False for i in xrange(self.p)] for i in xrange(self.p): t.pu() t.goto(self.getVertex(i)) for residue in xrange(1, (self.p - 1) / 2): j = (i + residue * residue) % self.p if not visited[j]: t.pd() t.goto(self.getVertex(j)) t.pu() t.goto(self.getVertex(i)) visited[i] = True turtle.done() def main(): if len(sys.argv) > 1: pal = Paley(int(sys.argv[1])) if len(sys.argv) > 2: pal.radius = int(sys.argv[2]) pal.draw() else: print "Please specify size of Paley graph" if __name__ == "__main__": main() Use 2D array instead of 1D to keep track of which edges have been drawn TODO: this probably isn't necessary
import turtle import math import sys class Paley: def __init__(self, p, radius = 290): self.p = p self.radius = radius """Return coordinates of ith vertex""" def getVertex(self, i): angle = i * 2 * math.pi / self.p return (self.radius * math.cos(angle), self.radius * math.sin(angle)) """Draw the Paley graph""" def draw(self): t = turtle.Turtle() t.speed(0) t.ht() visited = [[False for j in xrange(self.p)] for i in xrange(self.p)] for i in xrange(self.p): t.pu() t.goto(self.getVertex(i)) for residue in xrange(1, (self.p - 1) / 2): j = (i + residue * residue) % self.p if not visited[i][j]: t.pd() t.goto(self.getVertex(j)) t.pu() t.goto(self.getVertex(i)) visited[i][j] = visited[j][i] = True turtle.done() def main(): if len(sys.argv) > 1: pal = Paley(int(sys.argv[1])) if len(sys.argv) > 2: pal.radius = int(sys.argv[2]) pal.draw() else: print "Please specify size of Paley graph" if __name__ == "__main__": main()
<commit_before>import turtle import math import sys class Paley: def __init__(self, p, radius = 290): self.p = p self.radius = radius """Return coordinates of ith vertex""" def getVertex(self, i): angle = i * 2 * math.pi / self.p return (self.radius * math.cos(angle), self.radius * math.sin(angle)) """Draw the Paley graph""" def draw(self): t = turtle.Turtle() t.speed(0) t.ht() visited = [False for i in xrange(self.p)] for i in xrange(self.p): t.pu() t.goto(self.getVertex(i)) for residue in xrange(1, (self.p - 1) / 2): j = (i + residue * residue) % self.p if not visited[j]: t.pd() t.goto(self.getVertex(j)) t.pu() t.goto(self.getVertex(i)) visited[i] = True turtle.done() def main(): if len(sys.argv) > 1: pal = Paley(int(sys.argv[1])) if len(sys.argv) > 2: pal.radius = int(sys.argv[2]) pal.draw() else: print "Please specify size of Paley graph" if __name__ == "__main__": main() <commit_msg>Use 2D array instead of 1D to keep track of which edges have been drawn TODO: this probably isn't necessary<commit_after>
import turtle import math import sys class Paley: def __init__(self, p, radius = 290): self.p = p self.radius = radius """Return coordinates of ith vertex""" def getVertex(self, i): angle = i * 2 * math.pi / self.p return (self.radius * math.cos(angle), self.radius * math.sin(angle)) """Draw the Paley graph""" def draw(self): t = turtle.Turtle() t.speed(0) t.ht() visited = [[False for j in xrange(self.p)] for i in xrange(self.p)] for i in xrange(self.p): t.pu() t.goto(self.getVertex(i)) for residue in xrange(1, (self.p - 1) / 2): j = (i + residue * residue) % self.p if not visited[i][j]: t.pd() t.goto(self.getVertex(j)) t.pu() t.goto(self.getVertex(i)) visited[i][j] = visited[j][i] = True turtle.done() def main(): if len(sys.argv) > 1: pal = Paley(int(sys.argv[1])) if len(sys.argv) > 2: pal.radius = int(sys.argv[2]) pal.draw() else: print "Please specify size of Paley graph" if __name__ == "__main__": main()
import turtle import math import sys class Paley: def __init__(self, p, radius = 290): self.p = p self.radius = radius """Return coordinates of ith vertex""" def getVertex(self, i): angle = i * 2 * math.pi / self.p return (self.radius * math.cos(angle), self.radius * math.sin(angle)) """Draw the Paley graph""" def draw(self): t = turtle.Turtle() t.speed(0) t.ht() visited = [False for i in xrange(self.p)] for i in xrange(self.p): t.pu() t.goto(self.getVertex(i)) for residue in xrange(1, (self.p - 1) / 2): j = (i + residue * residue) % self.p if not visited[j]: t.pd() t.goto(self.getVertex(j)) t.pu() t.goto(self.getVertex(i)) visited[i] = True turtle.done() def main(): if len(sys.argv) > 1: pal = Paley(int(sys.argv[1])) if len(sys.argv) > 2: pal.radius = int(sys.argv[2]) pal.draw() else: print "Please specify size of Paley graph" if __name__ == "__main__": main() Use 2D array instead of 1D to keep track of which edges have been drawn TODO: this probably isn't necessaryimport turtle import math import sys class Paley: def __init__(self, p, radius = 290): self.p = p self.radius = radius """Return coordinates of ith vertex""" def getVertex(self, i): angle = i * 2 * math.pi / self.p return (self.radius * math.cos(angle), self.radius * math.sin(angle)) """Draw the Paley graph""" def draw(self): t = turtle.Turtle() t.speed(0) t.ht() visited = [[False for j in xrange(self.p)] for i in xrange(self.p)] for i in xrange(self.p): t.pu() t.goto(self.getVertex(i)) for residue in xrange(1, (self.p - 1) / 2): j = (i + residue * residue) % self.p if not visited[i][j]: t.pd() t.goto(self.getVertex(j)) t.pu() t.goto(self.getVertex(i)) visited[i][j] = visited[j][i] = True turtle.done() def main(): if len(sys.argv) > 1: pal = Paley(int(sys.argv[1])) if len(sys.argv) > 2: pal.radius = int(sys.argv[2]) pal.draw() else: print "Please specify size of Paley graph" if __name__ == "__main__": main()
<commit_before>import turtle import math import sys class Paley: def __init__(self, p, radius = 290): self.p = p self.radius = radius """Return coordinates of ith vertex""" def getVertex(self, i): angle = i * 2 * math.pi / self.p return (self.radius * math.cos(angle), self.radius * math.sin(angle)) """Draw the Paley graph""" def draw(self): t = turtle.Turtle() t.speed(0) t.ht() visited = [False for i in xrange(self.p)] for i in xrange(self.p): t.pu() t.goto(self.getVertex(i)) for residue in xrange(1, (self.p - 1) / 2): j = (i + residue * residue) % self.p if not visited[j]: t.pd() t.goto(self.getVertex(j)) t.pu() t.goto(self.getVertex(i)) visited[i] = True turtle.done() def main(): if len(sys.argv) > 1: pal = Paley(int(sys.argv[1])) if len(sys.argv) > 2: pal.radius = int(sys.argv[2]) pal.draw() else: print "Please specify size of Paley graph" if __name__ == "__main__": main() <commit_msg>Use 2D array instead of 1D to keep track of which edges have been drawn TODO: this probably isn't necessary<commit_after>import turtle import math import sys class Paley: def __init__(self, p, radius = 290): self.p = p self.radius = radius """Return coordinates of ith vertex""" def getVertex(self, i): angle = i * 2 * math.pi / self.p return (self.radius * math.cos(angle), self.radius * math.sin(angle)) """Draw the Paley graph""" def draw(self): t = turtle.Turtle() t.speed(0) t.ht() visited = [[False for j in xrange(self.p)] for i in xrange(self.p)] for i in xrange(self.p): t.pu() t.goto(self.getVertex(i)) for residue in xrange(1, (self.p - 1) / 2): j = (i + residue * residue) % self.p if not visited[i][j]: t.pd() t.goto(self.getVertex(j)) t.pu() t.goto(self.getVertex(i)) visited[i][j] = visited[j][i] = True turtle.done() def main(): if len(sys.argv) > 1: pal = Paley(int(sys.argv[1])) if len(sys.argv) > 2: pal.radius = int(sys.argv[2]) pal.draw() else: print "Please specify size of Paley graph" if __name__ == "__main__": main()
a378702e0f384237aa1bc1a6ef85c6e9ace398dc
tests/eldag_canon_test.py
tests/eldag_canon_test.py
"""Tests for the canonicalization facility for Eldags.""" from drudge import Perm, Group, canon_eldag def test_eldag_can_be_canonicalized(): """Tests the Eldag canonicalization facility. Note that this test more focuses on better coverage in the canonpy interface to libcanon, rather than on the correctness of canonicalization algorithm, which should be already tested within libcanon. In this test, we have two bivalent nodes in the Eldag, one without symmetry, one with symmetry. They are both connected to two terminal nodes with the same colour. In this graph, the connection to the non-symmetric node determines the resulted permutations. """ transp = Perm([1, 0], 1) symms = [None, Group([transp]), None, None] colours = [0, 1, 1, 1] # We force the non-symmetric node to come earlier. for if_same in [True, False]: # If the non-symmetric node is connected to the two terminal nodes in # order. The symmetric node always connect to them in order. edges = [2, 3, 2, 3] if if_same else [3, 2, 2, 3] ia = [0, 2, 4, 4, 4] node_order, perms = canon_eldag(edges, ia, symms, colours) # Assertions applicable to both cases. assert node_order[0] == 0 assert node_order[1] == 1 for i in [0, 2, 3]: assert perms[i] is None continue # The ordering of the two terminals. if if_same: assert node_order[2:] == [2, 3] else: assert node_order[2:] == [3, 2] # The permutation of the symmetric node. perm = perms[1] if if_same: assert perm[0] == 0 assert perm[1] == 1 assert perm.acc == 0 else: assert perm[0] == 1 assert perm[1] == 0 assert perm.acc == 1 continue return
Add test for eldag canonicalization
Add test for eldag canonicalization The test covers many cases for eldag canonicalization. Note that this test does not covers a lot of error reporting, since the eldag canonicalization is less likely to be called by users of drudge.
Python
mit
tschijnmo/drudge,tschijnmo/drudge,tschijnmo/drudge
Add test for eldag canonicalization The test covers many cases for eldag canonicalization. Note that this test does not covers a lot of error reporting, since the eldag canonicalization is less likely to be called by users of drudge.
"""Tests for the canonicalization facility for Eldags.""" from drudge import Perm, Group, canon_eldag def test_eldag_can_be_canonicalized(): """Tests the Eldag canonicalization facility. Note that this test more focuses on better coverage in the canonpy interface to libcanon, rather than on the correctness of canonicalization algorithm, which should be already tested within libcanon. In this test, we have two bivalent nodes in the Eldag, one without symmetry, one with symmetry. They are both connected to two terminal nodes with the same colour. In this graph, the connection to the non-symmetric node determines the resulted permutations. """ transp = Perm([1, 0], 1) symms = [None, Group([transp]), None, None] colours = [0, 1, 1, 1] # We force the non-symmetric node to come earlier. for if_same in [True, False]: # If the non-symmetric node is connected to the two terminal nodes in # order. The symmetric node always connect to them in order. edges = [2, 3, 2, 3] if if_same else [3, 2, 2, 3] ia = [0, 2, 4, 4, 4] node_order, perms = canon_eldag(edges, ia, symms, colours) # Assertions applicable to both cases. assert node_order[0] == 0 assert node_order[1] == 1 for i in [0, 2, 3]: assert perms[i] is None continue # The ordering of the two terminals. if if_same: assert node_order[2:] == [2, 3] else: assert node_order[2:] == [3, 2] # The permutation of the symmetric node. perm = perms[1] if if_same: assert perm[0] == 0 assert perm[1] == 1 assert perm.acc == 0 else: assert perm[0] == 1 assert perm[1] == 0 assert perm.acc == 1 continue return
<commit_before><commit_msg>Add test for eldag canonicalization The test covers many cases for eldag canonicalization. Note that this test does not covers a lot of error reporting, since the eldag canonicalization is less likely to be called by users of drudge.<commit_after>
"""Tests for the canonicalization facility for Eldags.""" from drudge import Perm, Group, canon_eldag def test_eldag_can_be_canonicalized(): """Tests the Eldag canonicalization facility. Note that this test more focuses on better coverage in the canonpy interface to libcanon, rather than on the correctness of canonicalization algorithm, which should be already tested within libcanon. In this test, we have two bivalent nodes in the Eldag, one without symmetry, one with symmetry. They are both connected to two terminal nodes with the same colour. In this graph, the connection to the non-symmetric node determines the resulted permutations. """ transp = Perm([1, 0], 1) symms = [None, Group([transp]), None, None] colours = [0, 1, 1, 1] # We force the non-symmetric node to come earlier. for if_same in [True, False]: # If the non-symmetric node is connected to the two terminal nodes in # order. The symmetric node always connect to them in order. edges = [2, 3, 2, 3] if if_same else [3, 2, 2, 3] ia = [0, 2, 4, 4, 4] node_order, perms = canon_eldag(edges, ia, symms, colours) # Assertions applicable to both cases. assert node_order[0] == 0 assert node_order[1] == 1 for i in [0, 2, 3]: assert perms[i] is None continue # The ordering of the two terminals. if if_same: assert node_order[2:] == [2, 3] else: assert node_order[2:] == [3, 2] # The permutation of the symmetric node. perm = perms[1] if if_same: assert perm[0] == 0 assert perm[1] == 1 assert perm.acc == 0 else: assert perm[0] == 1 assert perm[1] == 0 assert perm.acc == 1 continue return
Add test for eldag canonicalization The test covers many cases for eldag canonicalization. Note that this test does not covers a lot of error reporting, since the eldag canonicalization is less likely to be called by users of drudge."""Tests for the canonicalization facility for Eldags.""" from drudge import Perm, Group, canon_eldag def test_eldag_can_be_canonicalized(): """Tests the Eldag canonicalization facility. Note that this test more focuses on better coverage in the canonpy interface to libcanon, rather than on the correctness of canonicalization algorithm, which should be already tested within libcanon. In this test, we have two bivalent nodes in the Eldag, one without symmetry, one with symmetry. They are both connected to two terminal nodes with the same colour. In this graph, the connection to the non-symmetric node determines the resulted permutations. """ transp = Perm([1, 0], 1) symms = [None, Group([transp]), None, None] colours = [0, 1, 1, 1] # We force the non-symmetric node to come earlier. for if_same in [True, False]: # If the non-symmetric node is connected to the two terminal nodes in # order. The symmetric node always connect to them in order. edges = [2, 3, 2, 3] if if_same else [3, 2, 2, 3] ia = [0, 2, 4, 4, 4] node_order, perms = canon_eldag(edges, ia, symms, colours) # Assertions applicable to both cases. assert node_order[0] == 0 assert node_order[1] == 1 for i in [0, 2, 3]: assert perms[i] is None continue # The ordering of the two terminals. if if_same: assert node_order[2:] == [2, 3] else: assert node_order[2:] == [3, 2] # The permutation of the symmetric node. perm = perms[1] if if_same: assert perm[0] == 0 assert perm[1] == 1 assert perm.acc == 0 else: assert perm[0] == 1 assert perm[1] == 0 assert perm.acc == 1 continue return
<commit_before><commit_msg>Add test for eldag canonicalization The test covers many cases for eldag canonicalization. Note that this test does not covers a lot of error reporting, since the eldag canonicalization is less likely to be called by users of drudge.<commit_after>"""Tests for the canonicalization facility for Eldags.""" from drudge import Perm, Group, canon_eldag def test_eldag_can_be_canonicalized(): """Tests the Eldag canonicalization facility. Note that this test more focuses on better coverage in the canonpy interface to libcanon, rather than on the correctness of canonicalization algorithm, which should be already tested within libcanon. In this test, we have two bivalent nodes in the Eldag, one without symmetry, one with symmetry. They are both connected to two terminal nodes with the same colour. In this graph, the connection to the non-symmetric node determines the resulted permutations. """ transp = Perm([1, 0], 1) symms = [None, Group([transp]), None, None] colours = [0, 1, 1, 1] # We force the non-symmetric node to come earlier. for if_same in [True, False]: # If the non-symmetric node is connected to the two terminal nodes in # order. The symmetric node always connect to them in order. edges = [2, 3, 2, 3] if if_same else [3, 2, 2, 3] ia = [0, 2, 4, 4, 4] node_order, perms = canon_eldag(edges, ia, symms, colours) # Assertions applicable to both cases. assert node_order[0] == 0 assert node_order[1] == 1 for i in [0, 2, 3]: assert perms[i] is None continue # The ordering of the two terminals. if if_same: assert node_order[2:] == [2, 3] else: assert node_order[2:] == [3, 2] # The permutation of the symmetric node. perm = perms[1] if if_same: assert perm[0] == 0 assert perm[1] == 1 assert perm.acc == 0 else: assert perm[0] == 1 assert perm[1] == 0 assert perm.acc == 1 continue return
78ef59e29e2bed99d07261ff947f16be69e0e6b5
tests/fake_dbus_tools/swm.py
tests/fake_dbus_tools/swm.py
import gtk import dbus.service import sys from dbus.mainloop.glib import DBusGMainLoop class SLMService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('org.genivi.SoftwareLoadingManager', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, "/org/genivi/SoftwareLoadingManager") @dbus.service.method("org.genivi.SoftwareLoadingManager", async_callbacks=('send_reply', 'send_error')) def downloadComplete(self, update_image, signature, send_reply, send_error): print('SoftwareLoadingManager.SLMService.downloadComplete(%s, %s): Called.', update_image, signature) send_reply(True) fl = open("/tmp/dbustestswm.txt", 'w') fl.write("DownloadComplete") fl.close() if __name__ == "__main__": DBusGMainLoop(set_as_default=True) swlm_service = SLMService() while True: gtk.main_iteration()
import dbus.service import sys from dbus.mainloop.glib import DBusGMainLoop import gobject class SLMService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('org.genivi.SoftwareLoadingManager', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, "/org/genivi/SoftwareLoadingManager") @dbus.service.method("org.genivi.SoftwareLoadingManager", async_callbacks=('send_reply', 'send_error')) def downloadComplete(self, update_image, signature, send_reply, send_error): print('SoftwareLoadingManager.SLMService.downloadComplete(%s, %s): Called.', update_image, signature) send_reply(True) fl = open("/tmp/dbustestswm.txt", 'w') fl.write("DownloadComplete") fl.close() if __name__ == "__main__": DBusGMainLoop(set_as_default=True) mainloop = gobject.MainLoop() swlm_service = SLMService() while True: mainloop.run()
Replace gtk mainloop with glib mainloop
Replace gtk mainloop with glib mainloop This is because Travis CI runs headless and importing gtk fails
Python
mpl-2.0
advancedtelematic/aktualizr,advancedtelematic/aktualizr,advancedtelematic/sota_client_cpp,advancedtelematic/aktualizr,advancedtelematic/aktualizr,advancedtelematic/sota_client_cpp
import gtk import dbus.service import sys from dbus.mainloop.glib import DBusGMainLoop class SLMService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('org.genivi.SoftwareLoadingManager', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, "/org/genivi/SoftwareLoadingManager") @dbus.service.method("org.genivi.SoftwareLoadingManager", async_callbacks=('send_reply', 'send_error')) def downloadComplete(self, update_image, signature, send_reply, send_error): print('SoftwareLoadingManager.SLMService.downloadComplete(%s, %s): Called.', update_image, signature) send_reply(True) fl = open("/tmp/dbustestswm.txt", 'w') fl.write("DownloadComplete") fl.close() if __name__ == "__main__": DBusGMainLoop(set_as_default=True) swlm_service = SLMService() while True: gtk.main_iteration()Replace gtk mainloop with glib mainloop This is because Travis CI runs headless and importing gtk fails
import dbus.service import sys from dbus.mainloop.glib import DBusGMainLoop import gobject class SLMService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('org.genivi.SoftwareLoadingManager', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, "/org/genivi/SoftwareLoadingManager") @dbus.service.method("org.genivi.SoftwareLoadingManager", async_callbacks=('send_reply', 'send_error')) def downloadComplete(self, update_image, signature, send_reply, send_error): print('SoftwareLoadingManager.SLMService.downloadComplete(%s, %s): Called.', update_image, signature) send_reply(True) fl = open("/tmp/dbustestswm.txt", 'w') fl.write("DownloadComplete") fl.close() if __name__ == "__main__": DBusGMainLoop(set_as_default=True) mainloop = gobject.MainLoop() swlm_service = SLMService() while True: mainloop.run()
<commit_before> import gtk import dbus.service import sys from dbus.mainloop.glib import DBusGMainLoop class SLMService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('org.genivi.SoftwareLoadingManager', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, "/org/genivi/SoftwareLoadingManager") @dbus.service.method("org.genivi.SoftwareLoadingManager", async_callbacks=('send_reply', 'send_error')) def downloadComplete(self, update_image, signature, send_reply, send_error): print('SoftwareLoadingManager.SLMService.downloadComplete(%s, %s): Called.', update_image, signature) send_reply(True) fl = open("/tmp/dbustestswm.txt", 'w') fl.write("DownloadComplete") fl.close() if __name__ == "__main__": DBusGMainLoop(set_as_default=True) swlm_service = SLMService() while True: gtk.main_iteration()<commit_msg>Replace gtk mainloop with glib mainloop This is because Travis CI runs headless and importing gtk fails<commit_after>
import dbus.service import sys from dbus.mainloop.glib import DBusGMainLoop import gobject class SLMService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('org.genivi.SoftwareLoadingManager', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, "/org/genivi/SoftwareLoadingManager") @dbus.service.method("org.genivi.SoftwareLoadingManager", async_callbacks=('send_reply', 'send_error')) def downloadComplete(self, update_image, signature, send_reply, send_error): print('SoftwareLoadingManager.SLMService.downloadComplete(%s, %s): Called.', update_image, signature) send_reply(True) fl = open("/tmp/dbustestswm.txt", 'w') fl.write("DownloadComplete") fl.close() if __name__ == "__main__": DBusGMainLoop(set_as_default=True) mainloop = gobject.MainLoop() swlm_service = SLMService() while True: mainloop.run()
import gtk import dbus.service import sys from dbus.mainloop.glib import DBusGMainLoop class SLMService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('org.genivi.SoftwareLoadingManager', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, "/org/genivi/SoftwareLoadingManager") @dbus.service.method("org.genivi.SoftwareLoadingManager", async_callbacks=('send_reply', 'send_error')) def downloadComplete(self, update_image, signature, send_reply, send_error): print('SoftwareLoadingManager.SLMService.downloadComplete(%s, %s): Called.', update_image, signature) send_reply(True) fl = open("/tmp/dbustestswm.txt", 'w') fl.write("DownloadComplete") fl.close() if __name__ == "__main__": DBusGMainLoop(set_as_default=True) swlm_service = SLMService() while True: gtk.main_iteration()Replace gtk mainloop with glib mainloop This is because Travis CI runs headless and importing gtk fails import dbus.service import sys from dbus.mainloop.glib import DBusGMainLoop import gobject class SLMService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('org.genivi.SoftwareLoadingManager', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, "/org/genivi/SoftwareLoadingManager") @dbus.service.method("org.genivi.SoftwareLoadingManager", async_callbacks=('send_reply', 'send_error')) def downloadComplete(self, update_image, signature, send_reply, send_error): print('SoftwareLoadingManager.SLMService.downloadComplete(%s, %s): Called.', update_image, signature) send_reply(True) fl = open("/tmp/dbustestswm.txt", 'w') fl.write("DownloadComplete") fl.close() if __name__ == "__main__": DBusGMainLoop(set_as_default=True) mainloop = gobject.MainLoop() swlm_service = SLMService() while True: mainloop.run()
<commit_before> import gtk import dbus.service import sys from dbus.mainloop.glib import DBusGMainLoop class SLMService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('org.genivi.SoftwareLoadingManager', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, "/org/genivi/SoftwareLoadingManager") @dbus.service.method("org.genivi.SoftwareLoadingManager", async_callbacks=('send_reply', 'send_error')) def downloadComplete(self, update_image, signature, send_reply, send_error): print('SoftwareLoadingManager.SLMService.downloadComplete(%s, %s): Called.', update_image, signature) send_reply(True) fl = open("/tmp/dbustestswm.txt", 'w') fl.write("DownloadComplete") fl.close() if __name__ == "__main__": DBusGMainLoop(set_as_default=True) swlm_service = SLMService() while True: gtk.main_iteration()<commit_msg>Replace gtk mainloop with glib mainloop This is because Travis CI runs headless and importing gtk fails<commit_after> import dbus.service import sys from dbus.mainloop.glib import DBusGMainLoop import gobject class SLMService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('org.genivi.SoftwareLoadingManager', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, "/org/genivi/SoftwareLoadingManager") @dbus.service.method("org.genivi.SoftwareLoadingManager", async_callbacks=('send_reply', 'send_error')) def downloadComplete(self, update_image, signature, send_reply, send_error): print('SoftwareLoadingManager.SLMService.downloadComplete(%s, %s): Called.', update_image, signature) send_reply(True) fl = open("/tmp/dbustestswm.txt", 'w') fl.write("DownloadComplete") fl.close() if __name__ == "__main__": DBusGMainLoop(set_as_default=True) mainloop = gobject.MainLoop() swlm_service = SLMService() while True: mainloop.run()
13c1410de300a7f414b51cb001534f021441a00f
tests/test_authentication.py
tests/test_authentication.py
import unittest import tempfile from authentication import authentication class SignupTests(unittest.TestCase): """ Signup tests. """ def test_signup(self): """ Test that a valid signup request returns an OK status. """ test_app = authentication.app.test_client() def test_missing_username(self): pass class LoginTests(unittest.TestCase): """ Tests for logging in. """ if __name__ == '__main__': unittest.main()
import unittest import tempfile from authentication import authentication class SignupTests(unittest.TestCase): """ Signup tests. """ def test_signup(self): """ Test that a valid signup request returns an OK status. """ test_app = authentication.app.test_client() signup = test_app.post('/users', data={}) self.assertEqual(signup.headers['Content-Type'], 'application/json') def test_missing_username(self): pass class LoginTests(unittest.TestCase): """ Tests for logging in. """ if __name__ == '__main__': unittest.main()
Test that there is a json content type
Test that there is a json content type
Python
mit
jenca-cloud/jenca-authentication
import unittest import tempfile from authentication import authentication class SignupTests(unittest.TestCase): """ Signup tests. """ def test_signup(self): """ Test that a valid signup request returns an OK status. """ test_app = authentication.app.test_client() def test_missing_username(self): pass class LoginTests(unittest.TestCase): """ Tests for logging in. """ if __name__ == '__main__': unittest.main() Test that there is a json content type
import unittest import tempfile from authentication import authentication class SignupTests(unittest.TestCase): """ Signup tests. """ def test_signup(self): """ Test that a valid signup request returns an OK status. """ test_app = authentication.app.test_client() signup = test_app.post('/users', data={}) self.assertEqual(signup.headers['Content-Type'], 'application/json') def test_missing_username(self): pass class LoginTests(unittest.TestCase): """ Tests for logging in. """ if __name__ == '__main__': unittest.main()
<commit_before>import unittest import tempfile from authentication import authentication class SignupTests(unittest.TestCase): """ Signup tests. """ def test_signup(self): """ Test that a valid signup request returns an OK status. """ test_app = authentication.app.test_client() def test_missing_username(self): pass class LoginTests(unittest.TestCase): """ Tests for logging in. """ if __name__ == '__main__': unittest.main() <commit_msg>Test that there is a json content type<commit_after>
import unittest import tempfile from authentication import authentication class SignupTests(unittest.TestCase): """ Signup tests. """ def test_signup(self): """ Test that a valid signup request returns an OK status. """ test_app = authentication.app.test_client() signup = test_app.post('/users', data={}) self.assertEqual(signup.headers['Content-Type'], 'application/json') def test_missing_username(self): pass class LoginTests(unittest.TestCase): """ Tests for logging in. """ if __name__ == '__main__': unittest.main()
import unittest import tempfile from authentication import authentication class SignupTests(unittest.TestCase): """ Signup tests. """ def test_signup(self): """ Test that a valid signup request returns an OK status. """ test_app = authentication.app.test_client() def test_missing_username(self): pass class LoginTests(unittest.TestCase): """ Tests for logging in. """ if __name__ == '__main__': unittest.main() Test that there is a json content typeimport unittest import tempfile from authentication import authentication class SignupTests(unittest.TestCase): """ Signup tests. """ def test_signup(self): """ Test that a valid signup request returns an OK status. """ test_app = authentication.app.test_client() signup = test_app.post('/users', data={}) self.assertEqual(signup.headers['Content-Type'], 'application/json') def test_missing_username(self): pass class LoginTests(unittest.TestCase): """ Tests for logging in. """ if __name__ == '__main__': unittest.main()
<commit_before>import unittest import tempfile from authentication import authentication class SignupTests(unittest.TestCase): """ Signup tests. """ def test_signup(self): """ Test that a valid signup request returns an OK status. """ test_app = authentication.app.test_client() def test_missing_username(self): pass class LoginTests(unittest.TestCase): """ Tests for logging in. """ if __name__ == '__main__': unittest.main() <commit_msg>Test that there is a json content type<commit_after>import unittest import tempfile from authentication import authentication class SignupTests(unittest.TestCase): """ Signup tests. """ def test_signup(self): """ Test that a valid signup request returns an OK status. """ test_app = authentication.app.test_client() signup = test_app.post('/users', data={}) self.assertEqual(signup.headers['Content-Type'], 'application/json') def test_missing_username(self): pass class LoginTests(unittest.TestCase): """ Tests for logging in. """ if __name__ == '__main__': unittest.main()
b82d67fa5f4b0ccb9b31a640e65226fea5887c67
typhon/__init__.py
typhon/__init__.py
# -*- coding: utf-8 -*- from .version import __version__ try: __TYPHON_SETUP__ except: __TYPHON_SETUP__ = False if not __TYPHON_SETUP__: from . import arts from . import cloudmask from . import config from . import constants from . import files from . import geodesy from . import geographical from . import latex from . import math from . import nonlte from . import physics from . import plots from . import spectroscopy from . import trees from . import utils from .environment import environ def test(): """Use pytest to collect and run all tests in typhon.tests.""" import pytest return pytest.main(['--pyargs', 'typhon.tests'])
import functools import logging from .version import __version__ try: __TYPHON_SETUP__ except: __TYPHON_SETUP__ = False if not __TYPHON_SETUP__: from . import arts from . import cloudmask from . import config from . import constants from . import files from . import geodesy from . import geographical from . import latex from . import math from . import nonlte from . import physics from . import plots from . import spectroscopy from . import trees from . import utils from .environment import environ def test(): """Use pytest to collect and run all tests in typhon.tests.""" import pytest return pytest.main(['--pyargs', 'typhon.tests']) _logger = logging.getLogger(__name__) @functools.lru_cache() def _ensure_handler(handler=None, formatter=None): """Make sure that a handler is attached to the root logger. The LRU cache ensures that a new handler is only created during the first call of the function. From then on, this handler is reused. """ if handler is None: handler = logging.StreamHandler() if formatter is None: formatter = logging.Formatter(logging.BASIC_FORMAT) handler.setFormatter(formatter) _logger.addHandler(handler) return handler def set_loglevel(level, handler=None, formatter=None): """Set the loglevel of the package. Parameters: level (int): Loglevel according to the ``logging`` module. handler (``logging.Handler``): Logging handler. formatter (``logging.Formatter``): Logging formatter. """ _logger.setLevel(level) _ensure_handler(handler, formatter).setLevel(level)
Add top-level function to control the loglevel
Add top-level function to control the loglevel
Python
mit
atmtools/typhon,atmtools/typhon
# -*- coding: utf-8 -*- from .version import __version__ try: __TYPHON_SETUP__ except: __TYPHON_SETUP__ = False if not __TYPHON_SETUP__: from . import arts from . import cloudmask from . import config from . import constants from . import files from . import geodesy from . import geographical from . import latex from . import math from . import nonlte from . import physics from . import plots from . import spectroscopy from . import trees from . import utils from .environment import environ def test(): """Use pytest to collect and run all tests in typhon.tests.""" import pytest return pytest.main(['--pyargs', 'typhon.tests']) Add top-level function to control the loglevel
import functools import logging from .version import __version__ try: __TYPHON_SETUP__ except: __TYPHON_SETUP__ = False if not __TYPHON_SETUP__: from . import arts from . import cloudmask from . import config from . import constants from . import files from . import geodesy from . import geographical from . import latex from . import math from . import nonlte from . import physics from . import plots from . import spectroscopy from . import trees from . import utils from .environment import environ def test(): """Use pytest to collect and run all tests in typhon.tests.""" import pytest return pytest.main(['--pyargs', 'typhon.tests']) _logger = logging.getLogger(__name__) @functools.lru_cache() def _ensure_handler(handler=None, formatter=None): """Make sure that a handler is attached to the root logger. The LRU cache ensures that a new handler is only created during the first call of the function. From then on, this handler is reused. """ if handler is None: handler = logging.StreamHandler() if formatter is None: formatter = logging.Formatter(logging.BASIC_FORMAT) handler.setFormatter(formatter) _logger.addHandler(handler) return handler def set_loglevel(level, handler=None, formatter=None): """Set the loglevel of the package. Parameters: level (int): Loglevel according to the ``logging`` module. handler (``logging.Handler``): Logging handler. formatter (``logging.Formatter``): Logging formatter. """ _logger.setLevel(level) _ensure_handler(handler, formatter).setLevel(level)
<commit_before># -*- coding: utf-8 -*- from .version import __version__ try: __TYPHON_SETUP__ except: __TYPHON_SETUP__ = False if not __TYPHON_SETUP__: from . import arts from . import cloudmask from . import config from . import constants from . import files from . import geodesy from . import geographical from . import latex from . import math from . import nonlte from . import physics from . import plots from . import spectroscopy from . import trees from . import utils from .environment import environ def test(): """Use pytest to collect and run all tests in typhon.tests.""" import pytest return pytest.main(['--pyargs', 'typhon.tests']) <commit_msg>Add top-level function to control the loglevel<commit_after>
import functools import logging from .version import __version__ try: __TYPHON_SETUP__ except: __TYPHON_SETUP__ = False if not __TYPHON_SETUP__: from . import arts from . import cloudmask from . import config from . import constants from . import files from . import geodesy from . import geographical from . import latex from . import math from . import nonlte from . import physics from . import plots from . import spectroscopy from . import trees from . import utils from .environment import environ def test(): """Use pytest to collect and run all tests in typhon.tests.""" import pytest return pytest.main(['--pyargs', 'typhon.tests']) _logger = logging.getLogger(__name__) @functools.lru_cache() def _ensure_handler(handler=None, formatter=None): """Make sure that a handler is attached to the root logger. The LRU cache ensures that a new handler is only created during the first call of the function. From then on, this handler is reused. """ if handler is None: handler = logging.StreamHandler() if formatter is None: formatter = logging.Formatter(logging.BASIC_FORMAT) handler.setFormatter(formatter) _logger.addHandler(handler) return handler def set_loglevel(level, handler=None, formatter=None): """Set the loglevel of the package. Parameters: level (int): Loglevel according to the ``logging`` module. handler (``logging.Handler``): Logging handler. formatter (``logging.Formatter``): Logging formatter. """ _logger.setLevel(level) _ensure_handler(handler, formatter).setLevel(level)
# -*- coding: utf-8 -*- from .version import __version__ try: __TYPHON_SETUP__ except: __TYPHON_SETUP__ = False if not __TYPHON_SETUP__: from . import arts from . import cloudmask from . import config from . import constants from . import files from . import geodesy from . import geographical from . import latex from . import math from . import nonlte from . import physics from . import plots from . import spectroscopy from . import trees from . import utils from .environment import environ def test(): """Use pytest to collect and run all tests in typhon.tests.""" import pytest return pytest.main(['--pyargs', 'typhon.tests']) Add top-level function to control the loglevelimport functools import logging from .version import __version__ try: __TYPHON_SETUP__ except: __TYPHON_SETUP__ = False if not __TYPHON_SETUP__: from . import arts from . import cloudmask from . import config from . import constants from . import files from . import geodesy from . import geographical from . import latex from . import math from . import nonlte from . import physics from . import plots from . import spectroscopy from . import trees from . import utils from .environment import environ def test(): """Use pytest to collect and run all tests in typhon.tests.""" import pytest return pytest.main(['--pyargs', 'typhon.tests']) _logger = logging.getLogger(__name__) @functools.lru_cache() def _ensure_handler(handler=None, formatter=None): """Make sure that a handler is attached to the root logger. The LRU cache ensures that a new handler is only created during the first call of the function. From then on, this handler is reused. """ if handler is None: handler = logging.StreamHandler() if formatter is None: formatter = logging.Formatter(logging.BASIC_FORMAT) handler.setFormatter(formatter) _logger.addHandler(handler) return handler def set_loglevel(level, handler=None, formatter=None): """Set the loglevel of the package. Parameters: level (int): Loglevel according to the ``logging`` module. handler (``logging.Handler``): Logging handler. formatter (``logging.Formatter``): Logging formatter. """ _logger.setLevel(level) _ensure_handler(handler, formatter).setLevel(level)
<commit_before># -*- coding: utf-8 -*- from .version import __version__ try: __TYPHON_SETUP__ except: __TYPHON_SETUP__ = False if not __TYPHON_SETUP__: from . import arts from . import cloudmask from . import config from . import constants from . import files from . import geodesy from . import geographical from . import latex from . import math from . import nonlte from . import physics from . import plots from . import spectroscopy from . import trees from . import utils from .environment import environ def test(): """Use pytest to collect and run all tests in typhon.tests.""" import pytest return pytest.main(['--pyargs', 'typhon.tests']) <commit_msg>Add top-level function to control the loglevel<commit_after>import functools import logging from .version import __version__ try: __TYPHON_SETUP__ except: __TYPHON_SETUP__ = False if not __TYPHON_SETUP__: from . import arts from . import cloudmask from . import config from . import constants from . import files from . import geodesy from . import geographical from . import latex from . import math from . import nonlte from . import physics from . import plots from . import spectroscopy from . import trees from . import utils from .environment import environ def test(): """Use pytest to collect and run all tests in typhon.tests.""" import pytest return pytest.main(['--pyargs', 'typhon.tests']) _logger = logging.getLogger(__name__) @functools.lru_cache() def _ensure_handler(handler=None, formatter=None): """Make sure that a handler is attached to the root logger. The LRU cache ensures that a new handler is only created during the first call of the function. From then on, this handler is reused. """ if handler is None: handler = logging.StreamHandler() if formatter is None: formatter = logging.Formatter(logging.BASIC_FORMAT) handler.setFormatter(formatter) _logger.addHandler(handler) return handler def set_loglevel(level, handler=None, formatter=None): """Set the loglevel of the package. Parameters: level (int): Loglevel according to the ``logging`` module. handler (``logging.Handler``): Logging handler. formatter (``logging.Formatter``): Logging formatter. """ _logger.setLevel(level) _ensure_handler(handler, formatter).setLevel(level)
4a1bf1bfce80a7ee25e6a60ebf350f86d89a0b58
report.py
report.py
import os from libraries.models import Tweet, User from config import app_config as cfg from libraries.graphs.graph import Graph # Twitter API configuration consumer_key = cfg.twitter["consumer_key"] consumer_secret = cfg.twitter["consumer_secret"] access_token = cfg.twitter["access_token"] access_token_secret = cfg.twitter["access_token_secret"] # Start current_path = os.path.dirname(os.path.abspath(__file__)) # Average mentions per user path ="{}/images/avg_mentions.png".format(current_path) graph = Graph(path) avg_mentions_per_user = Tweet.avg_mentions_per_user().values() avg_mentions_per_bot = Tweet.avg_mentions_per_user(True).values() graph.avg_tweets(avg_mentions_per_user, avg_mentions_per_bot, path) path ="{}/images/vocabulary.png".format(current_path) graph.vocabulary(Tweet.vocabulary_size().values(), Tweet.vocabulary_size(True).values(), path) path ="{}/images/followers_following.png".format(current_path) graph.ratio_followers_following( User.ratio_followers_following_per_users(), User.ratio_followers_following_per_users(), path )
import os from libraries.models import Tweet, User from config import app_config as cfg from libraries.graphs.graph import Graph # Twitter API configuration consumer_key = cfg.twitter["consumer_key"] consumer_secret = cfg.twitter["consumer_secret"] access_token = cfg.twitter["access_token"] access_token_secret = cfg.twitter["access_token_secret"] # Start current_path = os.path.dirname(os.path.abspath(__file__)) # Average mentions per user path ="{}/images/avg_mentions.png".format(current_path) graph = Graph(path) avg_mentions_per_user = Tweet.avg_mentions_per_user().values() avg_mentions_per_bot = Tweet.avg_mentions_per_user(True).values() graph.avg_tweets(avg_mentions_per_user, avg_mentions_per_bot, path) path ="{}/images/vocabulary.png".format(current_path) graph.vocabulary(Tweet.vocabulary_size().values(), Tweet.vocabulary_size(True).values(), path) path ="{}/images/followers_following.png".format(current_path) graph.ratio_followers_following( User.ratio_followers_following_per_users(), User.ratio_followers_following_per_users(is_bot=True), path )
Fix ratio followers/following only displayed for "humans"
Fix ratio followers/following only displayed for "humans"
Python
mit
franckbrignoli/twitter-bot-detection
import os from libraries.models import Tweet, User from config import app_config as cfg from libraries.graphs.graph import Graph # Twitter API configuration consumer_key = cfg.twitter["consumer_key"] consumer_secret = cfg.twitter["consumer_secret"] access_token = cfg.twitter["access_token"] access_token_secret = cfg.twitter["access_token_secret"] # Start current_path = os.path.dirname(os.path.abspath(__file__)) # Average mentions per user path ="{}/images/avg_mentions.png".format(current_path) graph = Graph(path) avg_mentions_per_user = Tweet.avg_mentions_per_user().values() avg_mentions_per_bot = Tweet.avg_mentions_per_user(True).values() graph.avg_tweets(avg_mentions_per_user, avg_mentions_per_bot, path) path ="{}/images/vocabulary.png".format(current_path) graph.vocabulary(Tweet.vocabulary_size().values(), Tweet.vocabulary_size(True).values(), path) path ="{}/images/followers_following.png".format(current_path) graph.ratio_followers_following( User.ratio_followers_following_per_users(), User.ratio_followers_following_per_users(), path ) Fix ratio followers/following only displayed for "humans"
import os from libraries.models import Tweet, User from config import app_config as cfg from libraries.graphs.graph import Graph # Twitter API configuration consumer_key = cfg.twitter["consumer_key"] consumer_secret = cfg.twitter["consumer_secret"] access_token = cfg.twitter["access_token"] access_token_secret = cfg.twitter["access_token_secret"] # Start current_path = os.path.dirname(os.path.abspath(__file__)) # Average mentions per user path ="{}/images/avg_mentions.png".format(current_path) graph = Graph(path) avg_mentions_per_user = Tweet.avg_mentions_per_user().values() avg_mentions_per_bot = Tweet.avg_mentions_per_user(True).values() graph.avg_tweets(avg_mentions_per_user, avg_mentions_per_bot, path) path ="{}/images/vocabulary.png".format(current_path) graph.vocabulary(Tweet.vocabulary_size().values(), Tweet.vocabulary_size(True).values(), path) path ="{}/images/followers_following.png".format(current_path) graph.ratio_followers_following( User.ratio_followers_following_per_users(), User.ratio_followers_following_per_users(is_bot=True), path )
<commit_before>import os from libraries.models import Tweet, User from config import app_config as cfg from libraries.graphs.graph import Graph # Twitter API configuration consumer_key = cfg.twitter["consumer_key"] consumer_secret = cfg.twitter["consumer_secret"] access_token = cfg.twitter["access_token"] access_token_secret = cfg.twitter["access_token_secret"] # Start current_path = os.path.dirname(os.path.abspath(__file__)) # Average mentions per user path ="{}/images/avg_mentions.png".format(current_path) graph = Graph(path) avg_mentions_per_user = Tweet.avg_mentions_per_user().values() avg_mentions_per_bot = Tweet.avg_mentions_per_user(True).values() graph.avg_tweets(avg_mentions_per_user, avg_mentions_per_bot, path) path ="{}/images/vocabulary.png".format(current_path) graph.vocabulary(Tweet.vocabulary_size().values(), Tweet.vocabulary_size(True).values(), path) path ="{}/images/followers_following.png".format(current_path) graph.ratio_followers_following( User.ratio_followers_following_per_users(), User.ratio_followers_following_per_users(), path ) <commit_msg>Fix ratio followers/following only displayed for "humans"<commit_after>
import os from libraries.models import Tweet, User from config import app_config as cfg from libraries.graphs.graph import Graph # Twitter API configuration consumer_key = cfg.twitter["consumer_key"] consumer_secret = cfg.twitter["consumer_secret"] access_token = cfg.twitter["access_token"] access_token_secret = cfg.twitter["access_token_secret"] # Start current_path = os.path.dirname(os.path.abspath(__file__)) # Average mentions per user path ="{}/images/avg_mentions.png".format(current_path) graph = Graph(path) avg_mentions_per_user = Tweet.avg_mentions_per_user().values() avg_mentions_per_bot = Tweet.avg_mentions_per_user(True).values() graph.avg_tweets(avg_mentions_per_user, avg_mentions_per_bot, path) path ="{}/images/vocabulary.png".format(current_path) graph.vocabulary(Tweet.vocabulary_size().values(), Tweet.vocabulary_size(True).values(), path) path ="{}/images/followers_following.png".format(current_path) graph.ratio_followers_following( User.ratio_followers_following_per_users(), User.ratio_followers_following_per_users(is_bot=True), path )
import os from libraries.models import Tweet, User from config import app_config as cfg from libraries.graphs.graph import Graph # Twitter API configuration consumer_key = cfg.twitter["consumer_key"] consumer_secret = cfg.twitter["consumer_secret"] access_token = cfg.twitter["access_token"] access_token_secret = cfg.twitter["access_token_secret"] # Start current_path = os.path.dirname(os.path.abspath(__file__)) # Average mentions per user path ="{}/images/avg_mentions.png".format(current_path) graph = Graph(path) avg_mentions_per_user = Tweet.avg_mentions_per_user().values() avg_mentions_per_bot = Tweet.avg_mentions_per_user(True).values() graph.avg_tweets(avg_mentions_per_user, avg_mentions_per_bot, path) path ="{}/images/vocabulary.png".format(current_path) graph.vocabulary(Tweet.vocabulary_size().values(), Tweet.vocabulary_size(True).values(), path) path ="{}/images/followers_following.png".format(current_path) graph.ratio_followers_following( User.ratio_followers_following_per_users(), User.ratio_followers_following_per_users(), path ) Fix ratio followers/following only displayed for "humans"import os from libraries.models import Tweet, User from config import app_config as cfg from libraries.graphs.graph import Graph # Twitter API configuration consumer_key = cfg.twitter["consumer_key"] consumer_secret = cfg.twitter["consumer_secret"] access_token = cfg.twitter["access_token"] access_token_secret = cfg.twitter["access_token_secret"] # Start current_path = os.path.dirname(os.path.abspath(__file__)) # Average mentions per user path ="{}/images/avg_mentions.png".format(current_path) graph = Graph(path) avg_mentions_per_user = Tweet.avg_mentions_per_user().values() avg_mentions_per_bot = Tweet.avg_mentions_per_user(True).values() graph.avg_tweets(avg_mentions_per_user, avg_mentions_per_bot, path) path ="{}/images/vocabulary.png".format(current_path) graph.vocabulary(Tweet.vocabulary_size().values(), Tweet.vocabulary_size(True).values(), path) path ="{}/images/followers_following.png".format(current_path) graph.ratio_followers_following( User.ratio_followers_following_per_users(), User.ratio_followers_following_per_users(is_bot=True), path )
<commit_before>import os from libraries.models import Tweet, User from config import app_config as cfg from libraries.graphs.graph import Graph # Twitter API configuration consumer_key = cfg.twitter["consumer_key"] consumer_secret = cfg.twitter["consumer_secret"] access_token = cfg.twitter["access_token"] access_token_secret = cfg.twitter["access_token_secret"] # Start current_path = os.path.dirname(os.path.abspath(__file__)) # Average mentions per user path ="{}/images/avg_mentions.png".format(current_path) graph = Graph(path) avg_mentions_per_user = Tweet.avg_mentions_per_user().values() avg_mentions_per_bot = Tweet.avg_mentions_per_user(True).values() graph.avg_tweets(avg_mentions_per_user, avg_mentions_per_bot, path) path ="{}/images/vocabulary.png".format(current_path) graph.vocabulary(Tweet.vocabulary_size().values(), Tweet.vocabulary_size(True).values(), path) path ="{}/images/followers_following.png".format(current_path) graph.ratio_followers_following( User.ratio_followers_following_per_users(), User.ratio_followers_following_per_users(), path ) <commit_msg>Fix ratio followers/following only displayed for "humans"<commit_after>import os from libraries.models import Tweet, User from config import app_config as cfg from libraries.graphs.graph import Graph # Twitter API configuration consumer_key = cfg.twitter["consumer_key"] consumer_secret = cfg.twitter["consumer_secret"] access_token = cfg.twitter["access_token"] access_token_secret = cfg.twitter["access_token_secret"] # Start current_path = os.path.dirname(os.path.abspath(__file__)) # Average mentions per user path ="{}/images/avg_mentions.png".format(current_path) graph = Graph(path) avg_mentions_per_user = Tweet.avg_mentions_per_user().values() avg_mentions_per_bot = Tweet.avg_mentions_per_user(True).values() graph.avg_tweets(avg_mentions_per_user, avg_mentions_per_bot, path) path ="{}/images/vocabulary.png".format(current_path) graph.vocabulary(Tweet.vocabulary_size().values(), Tweet.vocabulary_size(True).values(), path) path ="{}/images/followers_following.png".format(current_path) graph.ratio_followers_following( User.ratio_followers_following_per_users(), User.ratio_followers_following_per_users(is_bot=True), path )
d2793192f88cfc7f5054048583fb514ac1904ffd
posts.py
posts.py
import json import pprint import requests def sample_valid_reddit_response(): r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json') response_json = r.json() if 'data' not in response_json: print("Trying again") response_json = sample_valid_reddit_response() return response_json response_json = sample_valid_reddit_response() del response_json['data']['children'] with open('sample_response.json', 'w+') as f: json.dump(response_json, f, indent=5)
import json import pprint import requests def sample_valid_reddit_response(): r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json') response_json = r.json() if 'data' not in response_json: print("Trying again") response_json = sample_valid_reddit_response() return response_json def save_sample(): response_json = sample_valid_reddit_response() del response_json['data']['children'] with open('sample_response.json', 'w+') as f: json.dump(response_json, f, indent=5)
Move stuff to function for ross
Move stuff to function for ross
Python
mit
RossCarriga/repost-data
import json import pprint import requests def sample_valid_reddit_response(): r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json') response_json = r.json() if 'data' not in response_json: print("Trying again") response_json = sample_valid_reddit_response() return response_json response_json = sample_valid_reddit_response() del response_json['data']['children'] with open('sample_response.json', 'w+') as f: json.dump(response_json, f, indent=5) Move stuff to function for ross
import json import pprint import requests def sample_valid_reddit_response(): r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json') response_json = r.json() if 'data' not in response_json: print("Trying again") response_json = sample_valid_reddit_response() return response_json def save_sample(): response_json = sample_valid_reddit_response() del response_json['data']['children'] with open('sample_response.json', 'w+') as f: json.dump(response_json, f, indent=5)
<commit_before>import json import pprint import requests def sample_valid_reddit_response(): r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json') response_json = r.json() if 'data' not in response_json: print("Trying again") response_json = sample_valid_reddit_response() return response_json response_json = sample_valid_reddit_response() del response_json['data']['children'] with open('sample_response.json', 'w+') as f: json.dump(response_json, f, indent=5) <commit_msg>Move stuff to function for ross<commit_after>
import json import pprint import requests def sample_valid_reddit_response(): r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json') response_json = r.json() if 'data' not in response_json: print("Trying again") response_json = sample_valid_reddit_response() return response_json def save_sample(): response_json = sample_valid_reddit_response() del response_json['data']['children'] with open('sample_response.json', 'w+') as f: json.dump(response_json, f, indent=5)
import json import pprint import requests def sample_valid_reddit_response(): r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json') response_json = r.json() if 'data' not in response_json: print("Trying again") response_json = sample_valid_reddit_response() return response_json response_json = sample_valid_reddit_response() del response_json['data']['children'] with open('sample_response.json', 'w+') as f: json.dump(response_json, f, indent=5) Move stuff to function for rossimport json import pprint import requests def sample_valid_reddit_response(): r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json') response_json = r.json() if 'data' not in response_json: print("Trying again") response_json = sample_valid_reddit_response() return response_json def save_sample(): response_json = sample_valid_reddit_response() del response_json['data']['children'] with open('sample_response.json', 'w+') as f: json.dump(response_json, f, indent=5)
<commit_before>import json import pprint import requests def sample_valid_reddit_response(): r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json') response_json = r.json() if 'data' not in response_json: print("Trying again") response_json = sample_valid_reddit_response() return response_json response_json = sample_valid_reddit_response() del response_json['data']['children'] with open('sample_response.json', 'w+') as f: json.dump(response_json, f, indent=5) <commit_msg>Move stuff to function for ross<commit_after>import json import pprint import requests def sample_valid_reddit_response(): r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json') response_json = r.json() if 'data' not in response_json: print("Trying again") response_json = sample_valid_reddit_response() return response_json def save_sample(): response_json = sample_valid_reddit_response() del response_json['data']['children'] with open('sample_response.json', 'w+') as f: json.dump(response_json, f, indent=5)
81e236f81343f7e4f21cf6b01329d3d1ac738f9f
tests/test_pulse_types.py
tests/test_pulse_types.py
import unittest from QGL import * from QGL.PulseSequencer import * from .helpers import setup_test_lib class PulseTypes(unittest.TestCase): def setUp(self): setup_test_lib() self.q1 = QubitFactory('q1') self.q2 = QubitFactory('q2') self.q3 = QubitFactory('q3') self.q4 = QubitFactory('q4') def test_promotion_rules(self): q1, q2, q3, q4 = self.q1, self.q2, self.q3, self.q4 assert( type(X(q1)) == Pulse ) assert( type(X(q1) + Y(q1)) == CompositePulse ) assert( type(X(q1) * X(q2)) == PulseBlock ) assert( type((X(q1) + Y(q1)) * X(q2)) == PulseBlock ) assert( type(CNOT(q1, q2) * X(q3)) == CompoundGate ) assert( type(CNOT(q1, q2) * CNOT(q3, q4)) == CompoundGate )
import unittest from QGL import * from QGL.PulseSequencer import * import QGL.config from .helpers import setup_test_lib class PulseTypes(unittest.TestCase): def setUp(self): setup_test_lib() QGL.config.cnot_implementation = 'CNOT_CR' self.q1 = QubitFactory('q1') self.q2 = QubitFactory('q2') self.q3 = QubitFactory('q3') self.q4 = QubitFactory('q4') def test_promotion_rules(self): q1, q2, q3, q4 = self.q1, self.q2, self.q3, self.q4 assert( type(X(q1)) == Pulse ) assert( type(X(q1) + Y(q1)) == CompositePulse ) assert( type(X(q1) * X(q2)) == PulseBlock ) assert( type((X(q1) + Y(q1)) * X(q2)) == PulseBlock ) assert( type(CNOT(q1, q2) * X(q3)) == CompoundGate ) assert( type(CNOT(q1, q2) * CNOT(q3, q4)) == CompoundGate )
Make test environment use CNOT_CR implementation of CNOT.
Make test environment use CNOT_CR implementation of CNOT. At least for the test_pulse_types tests.
Python
apache-2.0
BBN-Q/QGL,BBN-Q/QGL
import unittest from QGL import * from QGL.PulseSequencer import * from .helpers import setup_test_lib class PulseTypes(unittest.TestCase): def setUp(self): setup_test_lib() self.q1 = QubitFactory('q1') self.q2 = QubitFactory('q2') self.q3 = QubitFactory('q3') self.q4 = QubitFactory('q4') def test_promotion_rules(self): q1, q2, q3, q4 = self.q1, self.q2, self.q3, self.q4 assert( type(X(q1)) == Pulse ) assert( type(X(q1) + Y(q1)) == CompositePulse ) assert( type(X(q1) * X(q2)) == PulseBlock ) assert( type((X(q1) + Y(q1)) * X(q2)) == PulseBlock ) assert( type(CNOT(q1, q2) * X(q3)) == CompoundGate ) assert( type(CNOT(q1, q2) * CNOT(q3, q4)) == CompoundGate ) Make test environment use CNOT_CR implementation of CNOT. At least for the test_pulse_types tests.
import unittest from QGL import * from QGL.PulseSequencer import * import QGL.config from .helpers import setup_test_lib class PulseTypes(unittest.TestCase): def setUp(self): setup_test_lib() QGL.config.cnot_implementation = 'CNOT_CR' self.q1 = QubitFactory('q1') self.q2 = QubitFactory('q2') self.q3 = QubitFactory('q3') self.q4 = QubitFactory('q4') def test_promotion_rules(self): q1, q2, q3, q4 = self.q1, self.q2, self.q3, self.q4 assert( type(X(q1)) == Pulse ) assert( type(X(q1) + Y(q1)) == CompositePulse ) assert( type(X(q1) * X(q2)) == PulseBlock ) assert( type((X(q1) + Y(q1)) * X(q2)) == PulseBlock ) assert( type(CNOT(q1, q2) * X(q3)) == CompoundGate ) assert( type(CNOT(q1, q2) * CNOT(q3, q4)) == CompoundGate )
<commit_before>import unittest from QGL import * from QGL.PulseSequencer import * from .helpers import setup_test_lib class PulseTypes(unittest.TestCase): def setUp(self): setup_test_lib() self.q1 = QubitFactory('q1') self.q2 = QubitFactory('q2') self.q3 = QubitFactory('q3') self.q4 = QubitFactory('q4') def test_promotion_rules(self): q1, q2, q3, q4 = self.q1, self.q2, self.q3, self.q4 assert( type(X(q1)) == Pulse ) assert( type(X(q1) + Y(q1)) == CompositePulse ) assert( type(X(q1) * X(q2)) == PulseBlock ) assert( type((X(q1) + Y(q1)) * X(q2)) == PulseBlock ) assert( type(CNOT(q1, q2) * X(q3)) == CompoundGate ) assert( type(CNOT(q1, q2) * CNOT(q3, q4)) == CompoundGate ) <commit_msg>Make test environment use CNOT_CR implementation of CNOT. At least for the test_pulse_types tests.<commit_after>
import unittest from QGL import * from QGL.PulseSequencer import * import QGL.config from .helpers import setup_test_lib class PulseTypes(unittest.TestCase): def setUp(self): setup_test_lib() QGL.config.cnot_implementation = 'CNOT_CR' self.q1 = QubitFactory('q1') self.q2 = QubitFactory('q2') self.q3 = QubitFactory('q3') self.q4 = QubitFactory('q4') def test_promotion_rules(self): q1, q2, q3, q4 = self.q1, self.q2, self.q3, self.q4 assert( type(X(q1)) == Pulse ) assert( type(X(q1) + Y(q1)) == CompositePulse ) assert( type(X(q1) * X(q2)) == PulseBlock ) assert( type((X(q1) + Y(q1)) * X(q2)) == PulseBlock ) assert( type(CNOT(q1, q2) * X(q3)) == CompoundGate ) assert( type(CNOT(q1, q2) * CNOT(q3, q4)) == CompoundGate )
import unittest from QGL import * from QGL.PulseSequencer import * from .helpers import setup_test_lib class PulseTypes(unittest.TestCase): def setUp(self): setup_test_lib() self.q1 = QubitFactory('q1') self.q2 = QubitFactory('q2') self.q3 = QubitFactory('q3') self.q4 = QubitFactory('q4') def test_promotion_rules(self): q1, q2, q3, q4 = self.q1, self.q2, self.q3, self.q4 assert( type(X(q1)) == Pulse ) assert( type(X(q1) + Y(q1)) == CompositePulse ) assert( type(X(q1) * X(q2)) == PulseBlock ) assert( type((X(q1) + Y(q1)) * X(q2)) == PulseBlock ) assert( type(CNOT(q1, q2) * X(q3)) == CompoundGate ) assert( type(CNOT(q1, q2) * CNOT(q3, q4)) == CompoundGate ) Make test environment use CNOT_CR implementation of CNOT. At least for the test_pulse_types tests.import unittest from QGL import * from QGL.PulseSequencer import * import QGL.config from .helpers import setup_test_lib class PulseTypes(unittest.TestCase): def setUp(self): setup_test_lib() QGL.config.cnot_implementation = 'CNOT_CR' self.q1 = QubitFactory('q1') self.q2 = QubitFactory('q2') self.q3 = QubitFactory('q3') self.q4 = QubitFactory('q4') def test_promotion_rules(self): q1, q2, q3, q4 = self.q1, self.q2, self.q3, self.q4 assert( type(X(q1)) == Pulse ) assert( type(X(q1) + Y(q1)) == CompositePulse ) assert( type(X(q1) * X(q2)) == PulseBlock ) assert( type((X(q1) + Y(q1)) * X(q2)) == PulseBlock ) assert( type(CNOT(q1, q2) * X(q3)) == CompoundGate ) assert( type(CNOT(q1, q2) * CNOT(q3, q4)) == CompoundGate )
<commit_before>import unittest from QGL import * from QGL.PulseSequencer import * from .helpers import setup_test_lib class PulseTypes(unittest.TestCase): def setUp(self): setup_test_lib() self.q1 = QubitFactory('q1') self.q2 = QubitFactory('q2') self.q3 = QubitFactory('q3') self.q4 = QubitFactory('q4') def test_promotion_rules(self): q1, q2, q3, q4 = self.q1, self.q2, self.q3, self.q4 assert( type(X(q1)) == Pulse ) assert( type(X(q1) + Y(q1)) == CompositePulse ) assert( type(X(q1) * X(q2)) == PulseBlock ) assert( type((X(q1) + Y(q1)) * X(q2)) == PulseBlock ) assert( type(CNOT(q1, q2) * X(q3)) == CompoundGate ) assert( type(CNOT(q1, q2) * CNOT(q3, q4)) == CompoundGate ) <commit_msg>Make test environment use CNOT_CR implementation of CNOT. At least for the test_pulse_types tests.<commit_after>import unittest from QGL import * from QGL.PulseSequencer import * import QGL.config from .helpers import setup_test_lib class PulseTypes(unittest.TestCase): def setUp(self): setup_test_lib() QGL.config.cnot_implementation = 'CNOT_CR' self.q1 = QubitFactory('q1') self.q2 = QubitFactory('q2') self.q3 = QubitFactory('q3') self.q4 = QubitFactory('q4') def test_promotion_rules(self): q1, q2, q3, q4 = self.q1, self.q2, self.q3, self.q4 assert( type(X(q1)) == Pulse ) assert( type(X(q1) + Y(q1)) == CompositePulse ) assert( type(X(q1) * X(q2)) == PulseBlock ) assert( type((X(q1) + Y(q1)) * X(q2)) == PulseBlock ) assert( type(CNOT(q1, q2) * X(q3)) == CompoundGate ) assert( type(CNOT(q1, q2) * CNOT(q3, q4)) == CompoundGate )
cab417f187b66b5ec2f98fc69dcb8f8e98c43b86
tests/tests/middleware.py
tests/tests/middleware.py
from oauth2_consumer.middleware import AuthenticationMiddleware from .test_cases import MiddlewareTestCase class TestMiddleware(MiddlewareTestCase): def test_no_token(self): request = self.factory.get("/") AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, None) self.assertFalse(hasattr(request, "acess_token")) self.assertFalse(hasattr(request, "user")) def test_invalid_handler(self): request = self.factory.get("/") request.META["HTTP_AUTHORIZATION"] = "type token" AuthenticationMiddleware().process_request(request) print request self.assertEqual(request.auth_type, "type")
from oauth2_consumer.middleware import AuthenticationMiddleware from .test_cases import MiddlewareTestCase class TestMiddleware(MiddlewareTestCase): def test_no_token(self): request = self.factory.get("/") AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, None) self.assertFalse(hasattr(request, "acess_token")) self.assertFalse(hasattr(request, "user")) def test_invalid_handler(self): request = self.factory.get("/") request.META["HTTP_AUTHORIZATION"] = "type token" AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, "type") def test_invalid_bearer_token(self): request = self.factory.get("/") request.META["HTTP_AUTHORIZATION"] = "bearer invalid" AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, "bearer")
Add test for invalid bearer token
Add test for invalid bearer token
Python
mit
Rediker-Software/doac
from oauth2_consumer.middleware import AuthenticationMiddleware from .test_cases import MiddlewareTestCase class TestMiddleware(MiddlewareTestCase): def test_no_token(self): request = self.factory.get("/") AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, None) self.assertFalse(hasattr(request, "acess_token")) self.assertFalse(hasattr(request, "user")) def test_invalid_handler(self): request = self.factory.get("/") request.META["HTTP_AUTHORIZATION"] = "type token" AuthenticationMiddleware().process_request(request) print request self.assertEqual(request.auth_type, "type") Add test for invalid bearer token
from oauth2_consumer.middleware import AuthenticationMiddleware from .test_cases import MiddlewareTestCase class TestMiddleware(MiddlewareTestCase): def test_no_token(self): request = self.factory.get("/") AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, None) self.assertFalse(hasattr(request, "acess_token")) self.assertFalse(hasattr(request, "user")) def test_invalid_handler(self): request = self.factory.get("/") request.META["HTTP_AUTHORIZATION"] = "type token" AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, "type") def test_invalid_bearer_token(self): request = self.factory.get("/") request.META["HTTP_AUTHORIZATION"] = "bearer invalid" AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, "bearer")
<commit_before>from oauth2_consumer.middleware import AuthenticationMiddleware from .test_cases import MiddlewareTestCase class TestMiddleware(MiddlewareTestCase): def test_no_token(self): request = self.factory.get("/") AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, None) self.assertFalse(hasattr(request, "acess_token")) self.assertFalse(hasattr(request, "user")) def test_invalid_handler(self): request = self.factory.get("/") request.META["HTTP_AUTHORIZATION"] = "type token" AuthenticationMiddleware().process_request(request) print request self.assertEqual(request.auth_type, "type") <commit_msg>Add test for invalid bearer token<commit_after>
from oauth2_consumer.middleware import AuthenticationMiddleware from .test_cases import MiddlewareTestCase class TestMiddleware(MiddlewareTestCase): def test_no_token(self): request = self.factory.get("/") AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, None) self.assertFalse(hasattr(request, "acess_token")) self.assertFalse(hasattr(request, "user")) def test_invalid_handler(self): request = self.factory.get("/") request.META["HTTP_AUTHORIZATION"] = "type token" AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, "type") def test_invalid_bearer_token(self): request = self.factory.get("/") request.META["HTTP_AUTHORIZATION"] = "bearer invalid" AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, "bearer")
from oauth2_consumer.middleware import AuthenticationMiddleware from .test_cases import MiddlewareTestCase class TestMiddleware(MiddlewareTestCase): def test_no_token(self): request = self.factory.get("/") AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, None) self.assertFalse(hasattr(request, "acess_token")) self.assertFalse(hasattr(request, "user")) def test_invalid_handler(self): request = self.factory.get("/") request.META["HTTP_AUTHORIZATION"] = "type token" AuthenticationMiddleware().process_request(request) print request self.assertEqual(request.auth_type, "type") Add test for invalid bearer tokenfrom oauth2_consumer.middleware import AuthenticationMiddleware from .test_cases import MiddlewareTestCase class TestMiddleware(MiddlewareTestCase): def test_no_token(self): request = self.factory.get("/") AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, None) self.assertFalse(hasattr(request, "acess_token")) self.assertFalse(hasattr(request, "user")) def test_invalid_handler(self): request = self.factory.get("/") request.META["HTTP_AUTHORIZATION"] = "type token" AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, "type") def test_invalid_bearer_token(self): request = self.factory.get("/") request.META["HTTP_AUTHORIZATION"] = "bearer invalid" AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, "bearer")
<commit_before>from oauth2_consumer.middleware import AuthenticationMiddleware from .test_cases import MiddlewareTestCase class TestMiddleware(MiddlewareTestCase): def test_no_token(self): request = self.factory.get("/") AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, None) self.assertFalse(hasattr(request, "acess_token")) self.assertFalse(hasattr(request, "user")) def test_invalid_handler(self): request = self.factory.get("/") request.META["HTTP_AUTHORIZATION"] = "type token" AuthenticationMiddleware().process_request(request) print request self.assertEqual(request.auth_type, "type") <commit_msg>Add test for invalid bearer token<commit_after>from oauth2_consumer.middleware import AuthenticationMiddleware from .test_cases import MiddlewareTestCase class TestMiddleware(MiddlewareTestCase): def test_no_token(self): request = self.factory.get("/") AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, None) self.assertFalse(hasattr(request, "acess_token")) self.assertFalse(hasattr(request, "user")) def test_invalid_handler(self): request = self.factory.get("/") request.META["HTTP_AUTHORIZATION"] = "type token" AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, "type") def test_invalid_bearer_token(self): request = self.factory.get("/") request.META["HTTP_AUTHORIZATION"] = "bearer invalid" AuthenticationMiddleware().process_request(request) self.assertEqual(request.auth_type, "bearer")
f31f17da75557ce45977589d7da0e1b1fd6612dd
niftianon/cli.py
niftianon/cli.py
from __future__ import absolute_import import click import niftianon.anonymiser @click.command() @click.argument('identifiable_image', type=click.Path(exists=True)) @click.argument('anonymised_image', type=click.Path(exists=False)) def anonymise(identifiable_image, anonymised_image): niftianon.anonymiser.anonymise(identifiable_image, anonymised_image)
from __future__ import absolute_import import click import niftianon.anonymiser @click.command() @click.argument('identifiable_image', type=click.Path(exists=True)) @click.argument('anonymised_image', type=click.Path(exists=False)) def anonymise(identifiable_image, anonymised_image): """Anonymise IDENTIFIABLE_IMAGE and save the result to ANONYMISED_IMAGE IDENTIFIABLE_IMAGE must be the path to a NIFTI or NIFTI_GZ format image ANONYMISED_IMAGE must be a path that does not currently exist """ niftianon.anonymiser.anonymise(identifiable_image, anonymised_image)
Add docstring to command line entrypoint function
Add docstring to command line entrypoint function
Python
mit
jstutters/niftianon
from __future__ import absolute_import import click import niftianon.anonymiser @click.command() @click.argument('identifiable_image', type=click.Path(exists=True)) @click.argument('anonymised_image', type=click.Path(exists=False)) def anonymise(identifiable_image, anonymised_image): niftianon.anonymiser.anonymise(identifiable_image, anonymised_image) Add docstring to command line entrypoint function
from __future__ import absolute_import import click import niftianon.anonymiser @click.command() @click.argument('identifiable_image', type=click.Path(exists=True)) @click.argument('anonymised_image', type=click.Path(exists=False)) def anonymise(identifiable_image, anonymised_image): """Anonymise IDENTIFIABLE_IMAGE and save the result to ANONYMISED_IMAGE IDENTIFIABLE_IMAGE must be the path to a NIFTI or NIFTI_GZ format image ANONYMISED_IMAGE must be a path that does not currently exist """ niftianon.anonymiser.anonymise(identifiable_image, anonymised_image)
<commit_before>from __future__ import absolute_import import click import niftianon.anonymiser @click.command() @click.argument('identifiable_image', type=click.Path(exists=True)) @click.argument('anonymised_image', type=click.Path(exists=False)) def anonymise(identifiable_image, anonymised_image): niftianon.anonymiser.anonymise(identifiable_image, anonymised_image) <commit_msg>Add docstring to command line entrypoint function<commit_after>
from __future__ import absolute_import import click import niftianon.anonymiser @click.command() @click.argument('identifiable_image', type=click.Path(exists=True)) @click.argument('anonymised_image', type=click.Path(exists=False)) def anonymise(identifiable_image, anonymised_image): """Anonymise IDENTIFIABLE_IMAGE and save the result to ANONYMISED_IMAGE IDENTIFIABLE_IMAGE must be the path to a NIFTI or NIFTI_GZ format image ANONYMISED_IMAGE must be a path that does not currently exist """ niftianon.anonymiser.anonymise(identifiable_image, anonymised_image)
from __future__ import absolute_import import click import niftianon.anonymiser @click.command() @click.argument('identifiable_image', type=click.Path(exists=True)) @click.argument('anonymised_image', type=click.Path(exists=False)) def anonymise(identifiable_image, anonymised_image): niftianon.anonymiser.anonymise(identifiable_image, anonymised_image) Add docstring to command line entrypoint functionfrom __future__ import absolute_import import click import niftianon.anonymiser @click.command() @click.argument('identifiable_image', type=click.Path(exists=True)) @click.argument('anonymised_image', type=click.Path(exists=False)) def anonymise(identifiable_image, anonymised_image): """Anonymise IDENTIFIABLE_IMAGE and save the result to ANONYMISED_IMAGE IDENTIFIABLE_IMAGE must be the path to a NIFTI or NIFTI_GZ format image ANONYMISED_IMAGE must be a path that does not currently exist """ niftianon.anonymiser.anonymise(identifiable_image, anonymised_image)
<commit_before>from __future__ import absolute_import import click import niftianon.anonymiser @click.command() @click.argument('identifiable_image', type=click.Path(exists=True)) @click.argument('anonymised_image', type=click.Path(exists=False)) def anonymise(identifiable_image, anonymised_image): niftianon.anonymiser.anonymise(identifiable_image, anonymised_image) <commit_msg>Add docstring to command line entrypoint function<commit_after>from __future__ import absolute_import import click import niftianon.anonymiser @click.command() @click.argument('identifiable_image', type=click.Path(exists=True)) @click.argument('anonymised_image', type=click.Path(exists=False)) def anonymise(identifiable_image, anonymised_image): """Anonymise IDENTIFIABLE_IMAGE and save the result to ANONYMISED_IMAGE IDENTIFIABLE_IMAGE must be the path to a NIFTI or NIFTI_GZ format image ANONYMISED_IMAGE must be a path that does not currently exist """ niftianon.anonymiser.anonymise(identifiable_image, anonymised_image)
ca19a982f5302fa0aefbaad2b97fa338b01103b3
queue.py
queue.py
from __future__ import unicode_literals from linked_list import LinkedList class Queue(): def __init__(self, iterable=()): self.other = LinkedList() self.other_init__(iterable) self.tail = None def __repr__(self): pass def __len__(self): pass def enqueue(self, value): """Add a value to the tail of a queue args: value: The value to add to the queue """ pass def dequeue(self): """Remove a value from the head of the queue""" pass
from __future__ import unicode_literals from linked_list import LinkedList, Node class Queue(): def __init__(self, iterable=()): self.other = LinkedList() self.header = None self.tail = None self.length = None for val in (iterable): self.enqueue(val) def __repr__(self): return repr(self.other) def __len__(self): return self.length def enqueue(self, value): """Add a value to the tail of a queue. args: value: The value to add to the queue """ new_node = Node(value) self.tail.next = new_node self.tail = new_node self.length += 1 def dequeue(self): """Remove and return a value from the head of the queue.""" return self.other.pop() def size(self): return len(self)
Complete first pass of functions
Complete first pass of functions
Python
mit
jay-tyler/data-structures,jonathanstallings/data-structures
from __future__ import unicode_literals from linked_list import LinkedList class Queue(): def __init__(self, iterable=()): self.other = LinkedList() self.other_init__(iterable) self.tail = None def __repr__(self): pass def __len__(self): pass def enqueue(self, value): """Add a value to the tail of a queue args: value: The value to add to the queue """ pass def dequeue(self): """Remove a value from the head of the queue""" pass Complete first pass of functions
from __future__ import unicode_literals from linked_list import LinkedList, Node class Queue(): def __init__(self, iterable=()): self.other = LinkedList() self.header = None self.tail = None self.length = None for val in (iterable): self.enqueue(val) def __repr__(self): return repr(self.other) def __len__(self): return self.length def enqueue(self, value): """Add a value to the tail of a queue. args: value: The value to add to the queue """ new_node = Node(value) self.tail.next = new_node self.tail = new_node self.length += 1 def dequeue(self): """Remove and return a value from the head of the queue.""" return self.other.pop() def size(self): return len(self)
<commit_before>from __future__ import unicode_literals from linked_list import LinkedList class Queue(): def __init__(self, iterable=()): self.other = LinkedList() self.other_init__(iterable) self.tail = None def __repr__(self): pass def __len__(self): pass def enqueue(self, value): """Add a value to the tail of a queue args: value: The value to add to the queue """ pass def dequeue(self): """Remove a value from the head of the queue""" pass <commit_msg>Complete first pass of functions<commit_after>
from __future__ import unicode_literals from linked_list import LinkedList, Node class Queue(): def __init__(self, iterable=()): self.other = LinkedList() self.header = None self.tail = None self.length = None for val in (iterable): self.enqueue(val) def __repr__(self): return repr(self.other) def __len__(self): return self.length def enqueue(self, value): """Add a value to the tail of a queue. args: value: The value to add to the queue """ new_node = Node(value) self.tail.next = new_node self.tail = new_node self.length += 1 def dequeue(self): """Remove and return a value from the head of the queue.""" return self.other.pop() def size(self): return len(self)
from __future__ import unicode_literals from linked_list import LinkedList class Queue(): def __init__(self, iterable=()): self.other = LinkedList() self.other_init__(iterable) self.tail = None def __repr__(self): pass def __len__(self): pass def enqueue(self, value): """Add a value to the tail of a queue args: value: The value to add to the queue """ pass def dequeue(self): """Remove a value from the head of the queue""" pass Complete first pass of functionsfrom __future__ import unicode_literals from linked_list import LinkedList, Node class Queue(): def __init__(self, iterable=()): self.other = LinkedList() self.header = None self.tail = None self.length = None for val in (iterable): self.enqueue(val) def __repr__(self): return repr(self.other) def __len__(self): return self.length def enqueue(self, value): """Add a value to the tail of a queue. args: value: The value to add to the queue """ new_node = Node(value) self.tail.next = new_node self.tail = new_node self.length += 1 def dequeue(self): """Remove and return a value from the head of the queue.""" return self.other.pop() def size(self): return len(self)
<commit_before>from __future__ import unicode_literals from linked_list import LinkedList class Queue(): def __init__(self, iterable=()): self.other = LinkedList() self.other_init__(iterable) self.tail = None def __repr__(self): pass def __len__(self): pass def enqueue(self, value): """Add a value to the tail of a queue args: value: The value to add to the queue """ pass def dequeue(self): """Remove a value from the head of the queue""" pass <commit_msg>Complete first pass of functions<commit_after>from __future__ import unicode_literals from linked_list import LinkedList, Node class Queue(): def __init__(self, iterable=()): self.other = LinkedList() self.header = None self.tail = None self.length = None for val in (iterable): self.enqueue(val) def __repr__(self): return repr(self.other) def __len__(self): return self.length def enqueue(self, value): """Add a value to the tail of a queue. args: value: The value to add to the queue """ new_node = Node(value) self.tail.next = new_node self.tail = new_node self.length += 1 def dequeue(self): """Remove and return a value from the head of the queue.""" return self.other.pop() def size(self): return len(self)
0a4057a1c220076a34182327de9b01e8412ad68e
neutron_fwaas/tests/functional/test_fwaas_driver.py
neutron_fwaas/tests/functional/test_fwaas_driver.py
# Copyright (c) 2015 Cisco Systems, Inc. # 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. # NOTE: The purpose of this module is to provide a nop test to verify that # the functional gate is working. from neutron.tests.functional.agent.linux import base class TestFWaaSDriver(base.BaseLinuxTestCase): """Test the Iptables implmentation of the FWaaS driver.""" # NOTE: Tests may be added/removed/changed, when this is fleshed out # in future commits. def test_status_reporting(self): """Test status reported correctly to agent.""" pass
# Copyright (c) 2015 Cisco Systems, Inc. # 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. # NOTE: The purpose of this module is to provide a nop test to verify that # the functional gate is working. from neutron.tests.functional import base class TestFWaaSDriver(base.BaseSudoTestCase): """Test the Iptables implmentation of the FWaaS driver.""" # NOTE: Tests may be added/removed/changed, when this is fleshed out # in future commits. def test_status_reporting(self): """Test status reported correctly to agent.""" pass
Use BaseSudoTestCase instead of BaseLinuxTestCase
Use BaseSudoTestCase instead of BaseLinuxTestCase BaseLinuxTestCase will be removed from neutron code[1]. This change uses BaseSudoTestCase instead of BaseLinuxTestCase as helper methods have been transformed into fixtures. [1] https://review.openstack.org/161913 Change-Id: I23398c56c9cd71f617bde9167b9d32d126f16628
Python
apache-2.0
openstack/neutron-fwaas,gaolichuang/neutron-fwaas,gaolichuang/neutron-fwaas,openstack/neutron-fwaas
# Copyright (c) 2015 Cisco Systems, Inc. # 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. # NOTE: The purpose of this module is to provide a nop test to verify that # the functional gate is working. from neutron.tests.functional.agent.linux import base class TestFWaaSDriver(base.BaseLinuxTestCase): """Test the Iptables implmentation of the FWaaS driver.""" # NOTE: Tests may be added/removed/changed, when this is fleshed out # in future commits. def test_status_reporting(self): """Test status reported correctly to agent.""" pass Use BaseSudoTestCase instead of BaseLinuxTestCase BaseLinuxTestCase will be removed from neutron code[1]. This change uses BaseSudoTestCase instead of BaseLinuxTestCase as helper methods have been transformed into fixtures. [1] https://review.openstack.org/161913 Change-Id: I23398c56c9cd71f617bde9167b9d32d126f16628
# Copyright (c) 2015 Cisco Systems, Inc. # 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. # NOTE: The purpose of this module is to provide a nop test to verify that # the functional gate is working. from neutron.tests.functional import base class TestFWaaSDriver(base.BaseSudoTestCase): """Test the Iptables implmentation of the FWaaS driver.""" # NOTE: Tests may be added/removed/changed, when this is fleshed out # in future commits. def test_status_reporting(self): """Test status reported correctly to agent.""" pass
<commit_before># Copyright (c) 2015 Cisco Systems, Inc. # 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. # NOTE: The purpose of this module is to provide a nop test to verify that # the functional gate is working. from neutron.tests.functional.agent.linux import base class TestFWaaSDriver(base.BaseLinuxTestCase): """Test the Iptables implmentation of the FWaaS driver.""" # NOTE: Tests may be added/removed/changed, when this is fleshed out # in future commits. def test_status_reporting(self): """Test status reported correctly to agent.""" pass <commit_msg>Use BaseSudoTestCase instead of BaseLinuxTestCase BaseLinuxTestCase will be removed from neutron code[1]. This change uses BaseSudoTestCase instead of BaseLinuxTestCase as helper methods have been transformed into fixtures. [1] https://review.openstack.org/161913 Change-Id: I23398c56c9cd71f617bde9167b9d32d126f16628<commit_after>
# Copyright (c) 2015 Cisco Systems, Inc. # 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. # NOTE: The purpose of this module is to provide a nop test to verify that # the functional gate is working. from neutron.tests.functional import base class TestFWaaSDriver(base.BaseSudoTestCase): """Test the Iptables implmentation of the FWaaS driver.""" # NOTE: Tests may be added/removed/changed, when this is fleshed out # in future commits. def test_status_reporting(self): """Test status reported correctly to agent.""" pass
# Copyright (c) 2015 Cisco Systems, Inc. # 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. # NOTE: The purpose of this module is to provide a nop test to verify that # the functional gate is working. from neutron.tests.functional.agent.linux import base class TestFWaaSDriver(base.BaseLinuxTestCase): """Test the Iptables implmentation of the FWaaS driver.""" # NOTE: Tests may be added/removed/changed, when this is fleshed out # in future commits. def test_status_reporting(self): """Test status reported correctly to agent.""" pass Use BaseSudoTestCase instead of BaseLinuxTestCase BaseLinuxTestCase will be removed from neutron code[1]. This change uses BaseSudoTestCase instead of BaseLinuxTestCase as helper methods have been transformed into fixtures. [1] https://review.openstack.org/161913 Change-Id: I23398c56c9cd71f617bde9167b9d32d126f16628# Copyright (c) 2015 Cisco Systems, Inc. # 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. # NOTE: The purpose of this module is to provide a nop test to verify that # the functional gate is working. from neutron.tests.functional import base class TestFWaaSDriver(base.BaseSudoTestCase): """Test the Iptables implmentation of the FWaaS driver.""" # NOTE: Tests may be added/removed/changed, when this is fleshed out # in future commits. def test_status_reporting(self): """Test status reported correctly to agent.""" pass
<commit_before># Copyright (c) 2015 Cisco Systems, Inc. # 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. # NOTE: The purpose of this module is to provide a nop test to verify that # the functional gate is working. from neutron.tests.functional.agent.linux import base class TestFWaaSDriver(base.BaseLinuxTestCase): """Test the Iptables implmentation of the FWaaS driver.""" # NOTE: Tests may be added/removed/changed, when this is fleshed out # in future commits. def test_status_reporting(self): """Test status reported correctly to agent.""" pass <commit_msg>Use BaseSudoTestCase instead of BaseLinuxTestCase BaseLinuxTestCase will be removed from neutron code[1]. This change uses BaseSudoTestCase instead of BaseLinuxTestCase as helper methods have been transformed into fixtures. [1] https://review.openstack.org/161913 Change-Id: I23398c56c9cd71f617bde9167b9d32d126f16628<commit_after># Copyright (c) 2015 Cisco Systems, Inc. # 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. # NOTE: The purpose of this module is to provide a nop test to verify that # the functional gate is working. from neutron.tests.functional import base class TestFWaaSDriver(base.BaseSudoTestCase): """Test the Iptables implmentation of the FWaaS driver.""" # NOTE: Tests may be added/removed/changed, when this is fleshed out # in future commits. def test_status_reporting(self): """Test status reported correctly to agent.""" pass
624c52c63084f91429400fcc590e70b9c122ba7c
oslo/__init__.py
oslo/__init__.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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. __import__('pkg_resources').declare_namespace(__name__)
# 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. __import__('pkg_resources').declare_namespace(__name__)
Remove extraneous vim editor configuration comments
Remove extraneous vim editor configuration comments Change-Id: Id34b3ed02b6ef34b92d0cae9791f6e1b2d6cd4d8 Partial-Bug: #1229324
Python
apache-2.0
varunarya10/oslo.i18n,openstack/oslo.i18n
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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. __import__('pkg_resources').declare_namespace(__name__) Remove extraneous vim editor configuration comments Change-Id: Id34b3ed02b6ef34b92d0cae9791f6e1b2d6cd4d8 Partial-Bug: #1229324
# 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. __import__('pkg_resources').declare_namespace(__name__)
<commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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. __import__('pkg_resources').declare_namespace(__name__) <commit_msg>Remove extraneous vim editor configuration comments Change-Id: Id34b3ed02b6ef34b92d0cae9791f6e1b2d6cd4d8 Partial-Bug: #1229324<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. __import__('pkg_resources').declare_namespace(__name__)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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. __import__('pkg_resources').declare_namespace(__name__) Remove extraneous vim editor configuration comments Change-Id: Id34b3ed02b6ef34b92d0cae9791f6e1b2d6cd4d8 Partial-Bug: #1229324# 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. __import__('pkg_resources').declare_namespace(__name__)
<commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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. __import__('pkg_resources').declare_namespace(__name__) <commit_msg>Remove extraneous vim editor configuration comments Change-Id: Id34b3ed02b6ef34b92d0cae9791f6e1b2d6cd4d8 Partial-Bug: #1229324<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. __import__('pkg_resources').declare_namespace(__name__)
e334f80c5252aabacff5b14df368f4326056c81c
lib/weblogic/wlst/create_oia_domain.py
lib/weblogic/wlst/create_oia_domain.py
import os createDomain=os.path.dirname(sys.argv[0]) +'/heinz/createDomain.py' if os.path.exists(createDomain): execfile(createDomain) def updateNmProperties(): print "Updating NodeManager username and password for " + DomainLocation edit() startEdit() cd("SecurityConfiguration/oia_iamv2") cmo.setNodeManagerUsername("admin") cmo.setNodeManagerPassword(adminPassword) save() activate() # ================================================================ # Main Code Execution # ================================================================ if __name__== "main": print '###################################################################' print '# Domain Creation #' print '###################################################################' print '' intialize() createCustomDomain() createAllBootProperties() startAndConnnectToAdminServer() # do enroll on local machine print ' Do enroll '+ domainLocation +' - '+ domainProps.getProperty('nmDir')+' !\n' nmEnroll(domainLocation, domainProps.getProperty('nmDir')) updateNmProperties() setJTATimeout() createAllDatasources()
import os createDomain=os.path.dirname(sys.argv[0]) +'/heinz/createDomain.py' if os.path.exists(createDomain): execfile(createDomain) # ================================================================ # Main Code Execution # ================================================================ if __name__== "main": print '###################################################################' print '# Domain Creation #' print '###################################################################' print '' intialize() createCustomDomain() createAllBootProperties() startAndConnnectToAdminServer() # do enroll on local machine print ' Do enroll '+ domainLocation +' - '+ domainProps.getProperty('nmDir')+' !\n' nmEnroll(domainLocation, domainProps.getProperty('nmDir')) setJTATimeout() createAllDatasources()
Revert "added function to change OIA AdminServer nodemanager credentials"
Revert "added function to change OIA AdminServer nodemanager credentials" This reverts commit 134562138847b55853d22e4fa86c8a17e83d4b1d.
Python
bsd-2-clause
kapfenho/iam-deployer,kapfenho/iam-deployer,kapfenho/iam-deployer,kapfenho/iam-deployer
import os createDomain=os.path.dirname(sys.argv[0]) +'/heinz/createDomain.py' if os.path.exists(createDomain): execfile(createDomain) def updateNmProperties(): print "Updating NodeManager username and password for " + DomainLocation edit() startEdit() cd("SecurityConfiguration/oia_iamv2") cmo.setNodeManagerUsername("admin") cmo.setNodeManagerPassword(adminPassword) save() activate() # ================================================================ # Main Code Execution # ================================================================ if __name__== "main": print '###################################################################' print '# Domain Creation #' print '###################################################################' print '' intialize() createCustomDomain() createAllBootProperties() startAndConnnectToAdminServer() # do enroll on local machine print ' Do enroll '+ domainLocation +' - '+ domainProps.getProperty('nmDir')+' !\n' nmEnroll(domainLocation, domainProps.getProperty('nmDir')) updateNmProperties() setJTATimeout() createAllDatasources() Revert "added function to change OIA AdminServer nodemanager credentials" This reverts commit 134562138847b55853d22e4fa86c8a17e83d4b1d.
import os createDomain=os.path.dirname(sys.argv[0]) +'/heinz/createDomain.py' if os.path.exists(createDomain): execfile(createDomain) # ================================================================ # Main Code Execution # ================================================================ if __name__== "main": print '###################################################################' print '# Domain Creation #' print '###################################################################' print '' intialize() createCustomDomain() createAllBootProperties() startAndConnnectToAdminServer() # do enroll on local machine print ' Do enroll '+ domainLocation +' - '+ domainProps.getProperty('nmDir')+' !\n' nmEnroll(domainLocation, domainProps.getProperty('nmDir')) setJTATimeout() createAllDatasources()
<commit_before>import os createDomain=os.path.dirname(sys.argv[0]) +'/heinz/createDomain.py' if os.path.exists(createDomain): execfile(createDomain) def updateNmProperties(): print "Updating NodeManager username and password for " + DomainLocation edit() startEdit() cd("SecurityConfiguration/oia_iamv2") cmo.setNodeManagerUsername("admin") cmo.setNodeManagerPassword(adminPassword) save() activate() # ================================================================ # Main Code Execution # ================================================================ if __name__== "main": print '###################################################################' print '# Domain Creation #' print '###################################################################' print '' intialize() createCustomDomain() createAllBootProperties() startAndConnnectToAdminServer() # do enroll on local machine print ' Do enroll '+ domainLocation +' - '+ domainProps.getProperty('nmDir')+' !\n' nmEnroll(domainLocation, domainProps.getProperty('nmDir')) updateNmProperties() setJTATimeout() createAllDatasources() <commit_msg>Revert "added function to change OIA AdminServer nodemanager credentials" This reverts commit 134562138847b55853d22e4fa86c8a17e83d4b1d.<commit_after>
import os createDomain=os.path.dirname(sys.argv[0]) +'/heinz/createDomain.py' if os.path.exists(createDomain): execfile(createDomain) # ================================================================ # Main Code Execution # ================================================================ if __name__== "main": print '###################################################################' print '# Domain Creation #' print '###################################################################' print '' intialize() createCustomDomain() createAllBootProperties() startAndConnnectToAdminServer() # do enroll on local machine print ' Do enroll '+ domainLocation +' - '+ domainProps.getProperty('nmDir')+' !\n' nmEnroll(domainLocation, domainProps.getProperty('nmDir')) setJTATimeout() createAllDatasources()
import os createDomain=os.path.dirname(sys.argv[0]) +'/heinz/createDomain.py' if os.path.exists(createDomain): execfile(createDomain) def updateNmProperties(): print "Updating NodeManager username and password for " + DomainLocation edit() startEdit() cd("SecurityConfiguration/oia_iamv2") cmo.setNodeManagerUsername("admin") cmo.setNodeManagerPassword(adminPassword) save() activate() # ================================================================ # Main Code Execution # ================================================================ if __name__== "main": print '###################################################################' print '# Domain Creation #' print '###################################################################' print '' intialize() createCustomDomain() createAllBootProperties() startAndConnnectToAdminServer() # do enroll on local machine print ' Do enroll '+ domainLocation +' - '+ domainProps.getProperty('nmDir')+' !\n' nmEnroll(domainLocation, domainProps.getProperty('nmDir')) updateNmProperties() setJTATimeout() createAllDatasources() Revert "added function to change OIA AdminServer nodemanager credentials" This reverts commit 134562138847b55853d22e4fa86c8a17e83d4b1d.import os createDomain=os.path.dirname(sys.argv[0]) +'/heinz/createDomain.py' if os.path.exists(createDomain): execfile(createDomain) # ================================================================ # Main Code Execution # ================================================================ if __name__== "main": print '###################################################################' print '# Domain Creation #' print '###################################################################' print '' intialize() createCustomDomain() createAllBootProperties() startAndConnnectToAdminServer() # do enroll on local machine print ' Do enroll '+ domainLocation +' - '+ domainProps.getProperty('nmDir')+' !\n' nmEnroll(domainLocation, domainProps.getProperty('nmDir')) setJTATimeout() createAllDatasources()
<commit_before>import os createDomain=os.path.dirname(sys.argv[0]) +'/heinz/createDomain.py' if os.path.exists(createDomain): execfile(createDomain) def updateNmProperties(): print "Updating NodeManager username and password for " + DomainLocation edit() startEdit() cd("SecurityConfiguration/oia_iamv2") cmo.setNodeManagerUsername("admin") cmo.setNodeManagerPassword(adminPassword) save() activate() # ================================================================ # Main Code Execution # ================================================================ if __name__== "main": print '###################################################################' print '# Domain Creation #' print '###################################################################' print '' intialize() createCustomDomain() createAllBootProperties() startAndConnnectToAdminServer() # do enroll on local machine print ' Do enroll '+ domainLocation +' - '+ domainProps.getProperty('nmDir')+' !\n' nmEnroll(domainLocation, domainProps.getProperty('nmDir')) updateNmProperties() setJTATimeout() createAllDatasources() <commit_msg>Revert "added function to change OIA AdminServer nodemanager credentials" This reverts commit 134562138847b55853d22e4fa86c8a17e83d4b1d.<commit_after>import os createDomain=os.path.dirname(sys.argv[0]) +'/heinz/createDomain.py' if os.path.exists(createDomain): execfile(createDomain) # ================================================================ # Main Code Execution # ================================================================ if __name__== "main": print '###################################################################' print '# Domain Creation #' print '###################################################################' print '' intialize() createCustomDomain() createAllBootProperties() startAndConnnectToAdminServer() # do enroll on local machine print ' Do enroll '+ domainLocation +' - '+ domainProps.getProperty('nmDir')+' !\n' nmEnroll(domainLocation, domainProps.getProperty('nmDir')) setJTATimeout() createAllDatasources()
96f229ce62ea16588621bdbf760558af56595cef
packetmorpher.py
packetmorpher.py
""" Provides code to morph a chunk of data to a given probability distribution. The class provides an interface to morph network packet lengths to a previously generated probability distribution. The packet lengths of the morphed network data should then match the probability distribution. """ import random import probdist import const import obfsproxy.common.log as logging log = logging.get_obfslogger() class PacketMorpher( object ): """Provides an interface to morph large chunks of bytes to a given target probability distribution. This is implemented by naively sampling the target probability distribution.""" def __init__( self, dist=None ): """Initialise the PacketMorpher with a discrete probability distribution. If none is given, a distribution is randomly generated.""" if dist: self.dist = dist else: self.dist = probdist.new(lambda: random.randint(const.HDR_LENGTH, const.MTU)) def calcPadding( self, dataLen ): # The source and target length of the burst's last packet. dataLen = dataLen % const.MTU sampleLen = self.dist.randomSample() if sampleLen >= dataLen: padLen = sampleLen - dataLen else: padLen = (const.MTU - dataLen) + sampleLen log.debug("Morphing the last %d-byte packet to %d bytes by adding %d " "bytes of padding." % (dataLen % const.MTU, sampleLen, padLen)) return padLen def randomSample( self ): """Return a random sample of the stored probability distribution.""" return self.dist.randomSample() # Alias class name in order to provide a more intuitive API. new = PacketMorpher
""" Provides code to morph a chunk of data to a given probability distribution. The class provides an interface to morph network packet lengths to a previously generated probability distribution. The packet lengths of the morphed network data should then match the probability distribution. """ import random import probdist import const import obfsproxy.common.log as logging log = logging.get_obfslogger() class PacketMorpher( object ): """Provides an interface to morph large chunks of bytes to a given target probability distribution. This is implemented by naively sampling the target probability distribution.""" def __init__( self, dist=None ): """Initialise the PacketMorpher with a discrete probability distribution. If none is given, a distribution is randomly generated.""" if dist: self.dist = dist else: self.dist = probdist.new(lambda: random.randint(const.HDR_LENGTH, const.MTU)) def calcPadding( self, dataLen ): # The source and target length of the burst's last packet. dataLen = dataLen % const.MTU sampleLen = self.dist.randomSample() if sampleLen >= dataLen: padLen = sampleLen - dataLen else: padLen = (const.MTU - dataLen) + sampleLen log.debug("Morphing the last %d-byte packet to %d bytes by adding %d " "bytes of padding." % (dataLen % const.MTU, sampleLen, padLen)) return padLen # Alias class name in order to provide a more intuitive API. new = PacketMorpher
Delete `randomSample()' because it is no longer used.
Delete `randomSample()' because it is no longer used.
Python
bsd-3-clause
isislovecruft/scramblesuit,isislovecruft/scramblesuit
""" Provides code to morph a chunk of data to a given probability distribution. The class provides an interface to morph network packet lengths to a previously generated probability distribution. The packet lengths of the morphed network data should then match the probability distribution. """ import random import probdist import const import obfsproxy.common.log as logging log = logging.get_obfslogger() class PacketMorpher( object ): """Provides an interface to morph large chunks of bytes to a given target probability distribution. This is implemented by naively sampling the target probability distribution.""" def __init__( self, dist=None ): """Initialise the PacketMorpher with a discrete probability distribution. If none is given, a distribution is randomly generated.""" if dist: self.dist = dist else: self.dist = probdist.new(lambda: random.randint(const.HDR_LENGTH, const.MTU)) def calcPadding( self, dataLen ): # The source and target length of the burst's last packet. dataLen = dataLen % const.MTU sampleLen = self.dist.randomSample() if sampleLen >= dataLen: padLen = sampleLen - dataLen else: padLen = (const.MTU - dataLen) + sampleLen log.debug("Morphing the last %d-byte packet to %d bytes by adding %d " "bytes of padding." % (dataLen % const.MTU, sampleLen, padLen)) return padLen def randomSample( self ): """Return a random sample of the stored probability distribution.""" return self.dist.randomSample() # Alias class name in order to provide a more intuitive API. new = PacketMorpher Delete `randomSample()' because it is no longer used.
""" Provides code to morph a chunk of data to a given probability distribution. The class provides an interface to morph network packet lengths to a previously generated probability distribution. The packet lengths of the morphed network data should then match the probability distribution. """ import random import probdist import const import obfsproxy.common.log as logging log = logging.get_obfslogger() class PacketMorpher( object ): """Provides an interface to morph large chunks of bytes to a given target probability distribution. This is implemented by naively sampling the target probability distribution.""" def __init__( self, dist=None ): """Initialise the PacketMorpher with a discrete probability distribution. If none is given, a distribution is randomly generated.""" if dist: self.dist = dist else: self.dist = probdist.new(lambda: random.randint(const.HDR_LENGTH, const.MTU)) def calcPadding( self, dataLen ): # The source and target length of the burst's last packet. dataLen = dataLen % const.MTU sampleLen = self.dist.randomSample() if sampleLen >= dataLen: padLen = sampleLen - dataLen else: padLen = (const.MTU - dataLen) + sampleLen log.debug("Morphing the last %d-byte packet to %d bytes by adding %d " "bytes of padding." % (dataLen % const.MTU, sampleLen, padLen)) return padLen # Alias class name in order to provide a more intuitive API. new = PacketMorpher
<commit_before>""" Provides code to morph a chunk of data to a given probability distribution. The class provides an interface to morph network packet lengths to a previously generated probability distribution. The packet lengths of the morphed network data should then match the probability distribution. """ import random import probdist import const import obfsproxy.common.log as logging log = logging.get_obfslogger() class PacketMorpher( object ): """Provides an interface to morph large chunks of bytes to a given target probability distribution. This is implemented by naively sampling the target probability distribution.""" def __init__( self, dist=None ): """Initialise the PacketMorpher with a discrete probability distribution. If none is given, a distribution is randomly generated.""" if dist: self.dist = dist else: self.dist = probdist.new(lambda: random.randint(const.HDR_LENGTH, const.MTU)) def calcPadding( self, dataLen ): # The source and target length of the burst's last packet. dataLen = dataLen % const.MTU sampleLen = self.dist.randomSample() if sampleLen >= dataLen: padLen = sampleLen - dataLen else: padLen = (const.MTU - dataLen) + sampleLen log.debug("Morphing the last %d-byte packet to %d bytes by adding %d " "bytes of padding." % (dataLen % const.MTU, sampleLen, padLen)) return padLen def randomSample( self ): """Return a random sample of the stored probability distribution.""" return self.dist.randomSample() # Alias class name in order to provide a more intuitive API. new = PacketMorpher <commit_msg>Delete `randomSample()' because it is no longer used.<commit_after>
""" Provides code to morph a chunk of data to a given probability distribution. The class provides an interface to morph network packet lengths to a previously generated probability distribution. The packet lengths of the morphed network data should then match the probability distribution. """ import random import probdist import const import obfsproxy.common.log as logging log = logging.get_obfslogger() class PacketMorpher( object ): """Provides an interface to morph large chunks of bytes to a given target probability distribution. This is implemented by naively sampling the target probability distribution.""" def __init__( self, dist=None ): """Initialise the PacketMorpher with a discrete probability distribution. If none is given, a distribution is randomly generated.""" if dist: self.dist = dist else: self.dist = probdist.new(lambda: random.randint(const.HDR_LENGTH, const.MTU)) def calcPadding( self, dataLen ): # The source and target length of the burst's last packet. dataLen = dataLen % const.MTU sampleLen = self.dist.randomSample() if sampleLen >= dataLen: padLen = sampleLen - dataLen else: padLen = (const.MTU - dataLen) + sampleLen log.debug("Morphing the last %d-byte packet to %d bytes by adding %d " "bytes of padding." % (dataLen % const.MTU, sampleLen, padLen)) return padLen # Alias class name in order to provide a more intuitive API. new = PacketMorpher
""" Provides code to morph a chunk of data to a given probability distribution. The class provides an interface to morph network packet lengths to a previously generated probability distribution. The packet lengths of the morphed network data should then match the probability distribution. """ import random import probdist import const import obfsproxy.common.log as logging log = logging.get_obfslogger() class PacketMorpher( object ): """Provides an interface to morph large chunks of bytes to a given target probability distribution. This is implemented by naively sampling the target probability distribution.""" def __init__( self, dist=None ): """Initialise the PacketMorpher with a discrete probability distribution. If none is given, a distribution is randomly generated.""" if dist: self.dist = dist else: self.dist = probdist.new(lambda: random.randint(const.HDR_LENGTH, const.MTU)) def calcPadding( self, dataLen ): # The source and target length of the burst's last packet. dataLen = dataLen % const.MTU sampleLen = self.dist.randomSample() if sampleLen >= dataLen: padLen = sampleLen - dataLen else: padLen = (const.MTU - dataLen) + sampleLen log.debug("Morphing the last %d-byte packet to %d bytes by adding %d " "bytes of padding." % (dataLen % const.MTU, sampleLen, padLen)) return padLen def randomSample( self ): """Return a random sample of the stored probability distribution.""" return self.dist.randomSample() # Alias class name in order to provide a more intuitive API. new = PacketMorpher Delete `randomSample()' because it is no longer used.""" Provides code to morph a chunk of data to a given probability distribution. The class provides an interface to morph network packet lengths to a previously generated probability distribution. The packet lengths of the morphed network data should then match the probability distribution. """ import random import probdist import const import obfsproxy.common.log as logging log = logging.get_obfslogger() class PacketMorpher( object ): """Provides an interface to morph large chunks of bytes to a given target probability distribution. This is implemented by naively sampling the target probability distribution.""" def __init__( self, dist=None ): """Initialise the PacketMorpher with a discrete probability distribution. If none is given, a distribution is randomly generated.""" if dist: self.dist = dist else: self.dist = probdist.new(lambda: random.randint(const.HDR_LENGTH, const.MTU)) def calcPadding( self, dataLen ): # The source and target length of the burst's last packet. dataLen = dataLen % const.MTU sampleLen = self.dist.randomSample() if sampleLen >= dataLen: padLen = sampleLen - dataLen else: padLen = (const.MTU - dataLen) + sampleLen log.debug("Morphing the last %d-byte packet to %d bytes by adding %d " "bytes of padding." % (dataLen % const.MTU, sampleLen, padLen)) return padLen # Alias class name in order to provide a more intuitive API. new = PacketMorpher
<commit_before>""" Provides code to morph a chunk of data to a given probability distribution. The class provides an interface to morph network packet lengths to a previously generated probability distribution. The packet lengths of the morphed network data should then match the probability distribution. """ import random import probdist import const import obfsproxy.common.log as logging log = logging.get_obfslogger() class PacketMorpher( object ): """Provides an interface to morph large chunks of bytes to a given target probability distribution. This is implemented by naively sampling the target probability distribution.""" def __init__( self, dist=None ): """Initialise the PacketMorpher with a discrete probability distribution. If none is given, a distribution is randomly generated.""" if dist: self.dist = dist else: self.dist = probdist.new(lambda: random.randint(const.HDR_LENGTH, const.MTU)) def calcPadding( self, dataLen ): # The source and target length of the burst's last packet. dataLen = dataLen % const.MTU sampleLen = self.dist.randomSample() if sampleLen >= dataLen: padLen = sampleLen - dataLen else: padLen = (const.MTU - dataLen) + sampleLen log.debug("Morphing the last %d-byte packet to %d bytes by adding %d " "bytes of padding." % (dataLen % const.MTU, sampleLen, padLen)) return padLen def randomSample( self ): """Return a random sample of the stored probability distribution.""" return self.dist.randomSample() # Alias class name in order to provide a more intuitive API. new = PacketMorpher <commit_msg>Delete `randomSample()' because it is no longer used.<commit_after>""" Provides code to morph a chunk of data to a given probability distribution. The class provides an interface to morph network packet lengths to a previously generated probability distribution. The packet lengths of the morphed network data should then match the probability distribution. """ import random import probdist import const import obfsproxy.common.log as logging log = logging.get_obfslogger() class PacketMorpher( object ): """Provides an interface to morph large chunks of bytes to a given target probability distribution. This is implemented by naively sampling the target probability distribution.""" def __init__( self, dist=None ): """Initialise the PacketMorpher with a discrete probability distribution. If none is given, a distribution is randomly generated.""" if dist: self.dist = dist else: self.dist = probdist.new(lambda: random.randint(const.HDR_LENGTH, const.MTU)) def calcPadding( self, dataLen ): # The source and target length of the burst's last packet. dataLen = dataLen % const.MTU sampleLen = self.dist.randomSample() if sampleLen >= dataLen: padLen = sampleLen - dataLen else: padLen = (const.MTU - dataLen) + sampleLen log.debug("Morphing the last %d-byte packet to %d bytes by adding %d " "bytes of padding." % (dataLen % const.MTU, sampleLen, padLen)) return padLen # Alias class name in order to provide a more intuitive API. new = PacketMorpher
e6e121e1756d215bcf452522e268899d8669614c
dev_settings.py
dev_settings.py
""" This is a home for shared dev settings. Feel free to add anything that all devs should have set. Add `from dev_settings import *` to the top of your localsettings file to use. You can then override or append to any of these settings there. """ LOCAL_APPS = ( 'django_extensions', ) ####### Django Extensions ####### # These things will be imported when you run ./manage.py shell_plus SHELL_PLUS_POST_IMPORTS = ( # Models ('corehq.apps.domain.models', 'Domain'), ('corehq.apps.groups.models', 'Group'), ('corehq.apps.locations.models', 'Location'), ('corehq.apps.users.models', ('CommCareUser', 'CommCareCase')), ('couchforms.models', 'XFormInstance'), # Data querying utils ('dimagi.utils.couch.database', 'get_db'), ('corehq.apps.sofabed.models', ('FormData', 'CaseData')), ('corehq.apps.es', '*'), ) ALLOWED_HOSTS = ['*'] FIX_LOGGER_ERROR_OBFUSCATION = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'commcarehq', 'USER': 'commcarehq', 'PASSWORD': 'commcarehq', 'HOST': 'localhost', 'PORT': '5432' } }
""" This is a home for shared dev settings. Feel free to add anything that all devs should have set. Add `from dev_settings import *` to the top of your localsettings file to use. You can then override or append to any of these settings there. """ import os LOCAL_APPS = ( 'django_extensions', ) ####### Django Extensions ####### # These things will be imported when you run ./manage.py shell_plus SHELL_PLUS_POST_IMPORTS = ( # Models ('corehq.apps.domain.models', 'Domain'), ('corehq.apps.groups.models', 'Group'), ('corehq.apps.locations.models', 'Location'), ('corehq.apps.users.models', ('CommCareUser', 'CommCareCase')), ('couchforms.models', 'XFormInstance'), # Data querying utils ('dimagi.utils.couch.database', 'get_db'), ('corehq.apps.sofabed.models', ('FormData', 'CaseData')), ('corehq.apps.es', '*'), ) ALLOWED_HOSTS = ['*'] FIX_LOGGER_ERROR_OBFUSCATION = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'commcarehq', 'USER': 'commcarehq', 'PASSWORD': 'commcarehq', 'HOST': 'localhost', 'PORT': '5432' } } BOWER_PATH = os.popen('which bower').read().strip()
Use `$ which bower` by default
Use `$ which bower` by default @benrudolph What do you think of this approach?
Python
bsd-3-clause
qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq
""" This is a home for shared dev settings. Feel free to add anything that all devs should have set. Add `from dev_settings import *` to the top of your localsettings file to use. You can then override or append to any of these settings there. """ LOCAL_APPS = ( 'django_extensions', ) ####### Django Extensions ####### # These things will be imported when you run ./manage.py shell_plus SHELL_PLUS_POST_IMPORTS = ( # Models ('corehq.apps.domain.models', 'Domain'), ('corehq.apps.groups.models', 'Group'), ('corehq.apps.locations.models', 'Location'), ('corehq.apps.users.models', ('CommCareUser', 'CommCareCase')), ('couchforms.models', 'XFormInstance'), # Data querying utils ('dimagi.utils.couch.database', 'get_db'), ('corehq.apps.sofabed.models', ('FormData', 'CaseData')), ('corehq.apps.es', '*'), ) ALLOWED_HOSTS = ['*'] FIX_LOGGER_ERROR_OBFUSCATION = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'commcarehq', 'USER': 'commcarehq', 'PASSWORD': 'commcarehq', 'HOST': 'localhost', 'PORT': '5432' } } Use `$ which bower` by default @benrudolph What do you think of this approach?
""" This is a home for shared dev settings. Feel free to add anything that all devs should have set. Add `from dev_settings import *` to the top of your localsettings file to use. You can then override or append to any of these settings there. """ import os LOCAL_APPS = ( 'django_extensions', ) ####### Django Extensions ####### # These things will be imported when you run ./manage.py shell_plus SHELL_PLUS_POST_IMPORTS = ( # Models ('corehq.apps.domain.models', 'Domain'), ('corehq.apps.groups.models', 'Group'), ('corehq.apps.locations.models', 'Location'), ('corehq.apps.users.models', ('CommCareUser', 'CommCareCase')), ('couchforms.models', 'XFormInstance'), # Data querying utils ('dimagi.utils.couch.database', 'get_db'), ('corehq.apps.sofabed.models', ('FormData', 'CaseData')), ('corehq.apps.es', '*'), ) ALLOWED_HOSTS = ['*'] FIX_LOGGER_ERROR_OBFUSCATION = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'commcarehq', 'USER': 'commcarehq', 'PASSWORD': 'commcarehq', 'HOST': 'localhost', 'PORT': '5432' } } BOWER_PATH = os.popen('which bower').read().strip()
<commit_before>""" This is a home for shared dev settings. Feel free to add anything that all devs should have set. Add `from dev_settings import *` to the top of your localsettings file to use. You can then override or append to any of these settings there. """ LOCAL_APPS = ( 'django_extensions', ) ####### Django Extensions ####### # These things will be imported when you run ./manage.py shell_plus SHELL_PLUS_POST_IMPORTS = ( # Models ('corehq.apps.domain.models', 'Domain'), ('corehq.apps.groups.models', 'Group'), ('corehq.apps.locations.models', 'Location'), ('corehq.apps.users.models', ('CommCareUser', 'CommCareCase')), ('couchforms.models', 'XFormInstance'), # Data querying utils ('dimagi.utils.couch.database', 'get_db'), ('corehq.apps.sofabed.models', ('FormData', 'CaseData')), ('corehq.apps.es', '*'), ) ALLOWED_HOSTS = ['*'] FIX_LOGGER_ERROR_OBFUSCATION = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'commcarehq', 'USER': 'commcarehq', 'PASSWORD': 'commcarehq', 'HOST': 'localhost', 'PORT': '5432' } } <commit_msg>Use `$ which bower` by default @benrudolph What do you think of this approach?<commit_after>
""" This is a home for shared dev settings. Feel free to add anything that all devs should have set. Add `from dev_settings import *` to the top of your localsettings file to use. You can then override or append to any of these settings there. """ import os LOCAL_APPS = ( 'django_extensions', ) ####### Django Extensions ####### # These things will be imported when you run ./manage.py shell_plus SHELL_PLUS_POST_IMPORTS = ( # Models ('corehq.apps.domain.models', 'Domain'), ('corehq.apps.groups.models', 'Group'), ('corehq.apps.locations.models', 'Location'), ('corehq.apps.users.models', ('CommCareUser', 'CommCareCase')), ('couchforms.models', 'XFormInstance'), # Data querying utils ('dimagi.utils.couch.database', 'get_db'), ('corehq.apps.sofabed.models', ('FormData', 'CaseData')), ('corehq.apps.es', '*'), ) ALLOWED_HOSTS = ['*'] FIX_LOGGER_ERROR_OBFUSCATION = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'commcarehq', 'USER': 'commcarehq', 'PASSWORD': 'commcarehq', 'HOST': 'localhost', 'PORT': '5432' } } BOWER_PATH = os.popen('which bower').read().strip()
""" This is a home for shared dev settings. Feel free to add anything that all devs should have set. Add `from dev_settings import *` to the top of your localsettings file to use. You can then override or append to any of these settings there. """ LOCAL_APPS = ( 'django_extensions', ) ####### Django Extensions ####### # These things will be imported when you run ./manage.py shell_plus SHELL_PLUS_POST_IMPORTS = ( # Models ('corehq.apps.domain.models', 'Domain'), ('corehq.apps.groups.models', 'Group'), ('corehq.apps.locations.models', 'Location'), ('corehq.apps.users.models', ('CommCareUser', 'CommCareCase')), ('couchforms.models', 'XFormInstance'), # Data querying utils ('dimagi.utils.couch.database', 'get_db'), ('corehq.apps.sofabed.models', ('FormData', 'CaseData')), ('corehq.apps.es', '*'), ) ALLOWED_HOSTS = ['*'] FIX_LOGGER_ERROR_OBFUSCATION = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'commcarehq', 'USER': 'commcarehq', 'PASSWORD': 'commcarehq', 'HOST': 'localhost', 'PORT': '5432' } } Use `$ which bower` by default @benrudolph What do you think of this approach?""" This is a home for shared dev settings. Feel free to add anything that all devs should have set. Add `from dev_settings import *` to the top of your localsettings file to use. You can then override or append to any of these settings there. """ import os LOCAL_APPS = ( 'django_extensions', ) ####### Django Extensions ####### # These things will be imported when you run ./manage.py shell_plus SHELL_PLUS_POST_IMPORTS = ( # Models ('corehq.apps.domain.models', 'Domain'), ('corehq.apps.groups.models', 'Group'), ('corehq.apps.locations.models', 'Location'), ('corehq.apps.users.models', ('CommCareUser', 'CommCareCase')), ('couchforms.models', 'XFormInstance'), # Data querying utils ('dimagi.utils.couch.database', 'get_db'), ('corehq.apps.sofabed.models', ('FormData', 'CaseData')), ('corehq.apps.es', '*'), ) ALLOWED_HOSTS = ['*'] FIX_LOGGER_ERROR_OBFUSCATION = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'commcarehq', 'USER': 'commcarehq', 'PASSWORD': 'commcarehq', 'HOST': 'localhost', 'PORT': '5432' } } BOWER_PATH = os.popen('which bower').read().strip()
<commit_before>""" This is a home for shared dev settings. Feel free to add anything that all devs should have set. Add `from dev_settings import *` to the top of your localsettings file to use. You can then override or append to any of these settings there. """ LOCAL_APPS = ( 'django_extensions', ) ####### Django Extensions ####### # These things will be imported when you run ./manage.py shell_plus SHELL_PLUS_POST_IMPORTS = ( # Models ('corehq.apps.domain.models', 'Domain'), ('corehq.apps.groups.models', 'Group'), ('corehq.apps.locations.models', 'Location'), ('corehq.apps.users.models', ('CommCareUser', 'CommCareCase')), ('couchforms.models', 'XFormInstance'), # Data querying utils ('dimagi.utils.couch.database', 'get_db'), ('corehq.apps.sofabed.models', ('FormData', 'CaseData')), ('corehq.apps.es', '*'), ) ALLOWED_HOSTS = ['*'] FIX_LOGGER_ERROR_OBFUSCATION = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'commcarehq', 'USER': 'commcarehq', 'PASSWORD': 'commcarehq', 'HOST': 'localhost', 'PORT': '5432' } } <commit_msg>Use `$ which bower` by default @benrudolph What do you think of this approach?<commit_after>""" This is a home for shared dev settings. Feel free to add anything that all devs should have set. Add `from dev_settings import *` to the top of your localsettings file to use. You can then override or append to any of these settings there. """ import os LOCAL_APPS = ( 'django_extensions', ) ####### Django Extensions ####### # These things will be imported when you run ./manage.py shell_plus SHELL_PLUS_POST_IMPORTS = ( # Models ('corehq.apps.domain.models', 'Domain'), ('corehq.apps.groups.models', 'Group'), ('corehq.apps.locations.models', 'Location'), ('corehq.apps.users.models', ('CommCareUser', 'CommCareCase')), ('couchforms.models', 'XFormInstance'), # Data querying utils ('dimagi.utils.couch.database', 'get_db'), ('corehq.apps.sofabed.models', ('FormData', 'CaseData')), ('corehq.apps.es', '*'), ) ALLOWED_HOSTS = ['*'] FIX_LOGGER_ERROR_OBFUSCATION = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'commcarehq', 'USER': 'commcarehq', 'PASSWORD': 'commcarehq', 'HOST': 'localhost', 'PORT': '5432' } } BOWER_PATH = os.popen('which bower').read().strip()
97f84c2e7643e295623ccd09d1b447d405fd5bfa
wal_e/blobstore/s3/s3_credentials.py
wal_e/blobstore/s3/s3_credentials.py
from boto import provider from functools import partial from wal_e.exception import UserException class InstanceProfileProvider(provider.Provider): """Override boto Provider to control use of the AWS metadata store In particular, prevent boto from looking in a series of places for keys outside off WAL-E's control (e.g. boto.cfg, environment variables, and so on). As-is that precedence and detection code is in one big ream, and so a method override and some internal symbols are used to excise most of that cleverness. Also take this opportunity to inject a WAL-E-friendly exception to help the user with missing keys. """ def get_credentials(self, access_key=None, secret_key=None, security_token=None): if self.MetadataServiceSupport[self.name]: self._populate_keys_from_metadata_server() if not self._secret_key: raise UserException('Could not retrieve secret key from instance ' 'profile.', hint='Check that your instance has an IAM ' 'profile or set --aws-access-key-id') Credentials = partial(provider.Provider, "aws") InstanceProfileCredentials = partial(InstanceProfileProvider, 'aws')
from boto import provider from functools import partial from wal_e.exception import UserException class InstanceProfileProvider(provider.Provider): """Override boto Provider to control use of the AWS metadata store In particular, prevent boto from looking in a series of places for keys outside off WAL-E's control (e.g. boto.cfg, environment variables, and so on). As-is that precedence and detection code is in one big ream, and so a method override and some internal symbols are used to excise most of that cleverness. Also take this opportunity to inject a WAL-E-friendly exception to help the user with missing keys. """ def get_credentials(self, access_key=None, secret_key=None, security_token=None, profile_name=None): if self.MetadataServiceSupport[self.name]: self._populate_keys_from_metadata_server() if not self._secret_key: raise UserException('Could not retrieve secret key from instance ' 'profile.', hint='Check that your instance has an IAM ' 'profile or set --aws-access-key-id') Credentials = partial(provider.Provider, "aws") InstanceProfileCredentials = partial(InstanceProfileProvider, 'aws')
Fix InstanceProfileProvider class for boto 2.24
Fix InstanceProfileProvider class for boto 2.24 "profile_name" is now a parameter that must be supported in "get_credentials". Yes, this is exactly the "fragile base class" problem, but let's hope that the mechanisms there become dormant again for a long stretch again. Or, switch to botocore or something like that to avoid the crazy amount of credential management logic hard to opt-out of in boto.
Python
bsd-3-clause
heroku/wal-e,ajmarks/wal-e,DataDog/wal-e,x86Labs/wal-e,modulexcite/wal-e,ArtemZ/wal-e,fdr/wal-e,tenstartups/wal-e,intoximeters/wal-e,equa/wal-e,wal-e/wal-e,RichardKnop/wal-e,nagual13/wal-e
from boto import provider from functools import partial from wal_e.exception import UserException class InstanceProfileProvider(provider.Provider): """Override boto Provider to control use of the AWS metadata store In particular, prevent boto from looking in a series of places for keys outside off WAL-E's control (e.g. boto.cfg, environment variables, and so on). As-is that precedence and detection code is in one big ream, and so a method override and some internal symbols are used to excise most of that cleverness. Also take this opportunity to inject a WAL-E-friendly exception to help the user with missing keys. """ def get_credentials(self, access_key=None, secret_key=None, security_token=None): if self.MetadataServiceSupport[self.name]: self._populate_keys_from_metadata_server() if not self._secret_key: raise UserException('Could not retrieve secret key from instance ' 'profile.', hint='Check that your instance has an IAM ' 'profile or set --aws-access-key-id') Credentials = partial(provider.Provider, "aws") InstanceProfileCredentials = partial(InstanceProfileProvider, 'aws') Fix InstanceProfileProvider class for boto 2.24 "profile_name" is now a parameter that must be supported in "get_credentials". Yes, this is exactly the "fragile base class" problem, but let's hope that the mechanisms there become dormant again for a long stretch again. Or, switch to botocore or something like that to avoid the crazy amount of credential management logic hard to opt-out of in boto.
from boto import provider from functools import partial from wal_e.exception import UserException class InstanceProfileProvider(provider.Provider): """Override boto Provider to control use of the AWS metadata store In particular, prevent boto from looking in a series of places for keys outside off WAL-E's control (e.g. boto.cfg, environment variables, and so on). As-is that precedence and detection code is in one big ream, and so a method override and some internal symbols are used to excise most of that cleverness. Also take this opportunity to inject a WAL-E-friendly exception to help the user with missing keys. """ def get_credentials(self, access_key=None, secret_key=None, security_token=None, profile_name=None): if self.MetadataServiceSupport[self.name]: self._populate_keys_from_metadata_server() if not self._secret_key: raise UserException('Could not retrieve secret key from instance ' 'profile.', hint='Check that your instance has an IAM ' 'profile or set --aws-access-key-id') Credentials = partial(provider.Provider, "aws") InstanceProfileCredentials = partial(InstanceProfileProvider, 'aws')
<commit_before>from boto import provider from functools import partial from wal_e.exception import UserException class InstanceProfileProvider(provider.Provider): """Override boto Provider to control use of the AWS metadata store In particular, prevent boto from looking in a series of places for keys outside off WAL-E's control (e.g. boto.cfg, environment variables, and so on). As-is that precedence and detection code is in one big ream, and so a method override and some internal symbols are used to excise most of that cleverness. Also take this opportunity to inject a WAL-E-friendly exception to help the user with missing keys. """ def get_credentials(self, access_key=None, secret_key=None, security_token=None): if self.MetadataServiceSupport[self.name]: self._populate_keys_from_metadata_server() if not self._secret_key: raise UserException('Could not retrieve secret key from instance ' 'profile.', hint='Check that your instance has an IAM ' 'profile or set --aws-access-key-id') Credentials = partial(provider.Provider, "aws") InstanceProfileCredentials = partial(InstanceProfileProvider, 'aws') <commit_msg>Fix InstanceProfileProvider class for boto 2.24 "profile_name" is now a parameter that must be supported in "get_credentials". Yes, this is exactly the "fragile base class" problem, but let's hope that the mechanisms there become dormant again for a long stretch again. Or, switch to botocore or something like that to avoid the crazy amount of credential management logic hard to opt-out of in boto.<commit_after>
from boto import provider from functools import partial from wal_e.exception import UserException class InstanceProfileProvider(provider.Provider): """Override boto Provider to control use of the AWS metadata store In particular, prevent boto from looking in a series of places for keys outside off WAL-E's control (e.g. boto.cfg, environment variables, and so on). As-is that precedence and detection code is in one big ream, and so a method override and some internal symbols are used to excise most of that cleverness. Also take this opportunity to inject a WAL-E-friendly exception to help the user with missing keys. """ def get_credentials(self, access_key=None, secret_key=None, security_token=None, profile_name=None): if self.MetadataServiceSupport[self.name]: self._populate_keys_from_metadata_server() if not self._secret_key: raise UserException('Could not retrieve secret key from instance ' 'profile.', hint='Check that your instance has an IAM ' 'profile or set --aws-access-key-id') Credentials = partial(provider.Provider, "aws") InstanceProfileCredentials = partial(InstanceProfileProvider, 'aws')
from boto import provider from functools import partial from wal_e.exception import UserException class InstanceProfileProvider(provider.Provider): """Override boto Provider to control use of the AWS metadata store In particular, prevent boto from looking in a series of places for keys outside off WAL-E's control (e.g. boto.cfg, environment variables, and so on). As-is that precedence and detection code is in one big ream, and so a method override and some internal symbols are used to excise most of that cleverness. Also take this opportunity to inject a WAL-E-friendly exception to help the user with missing keys. """ def get_credentials(self, access_key=None, secret_key=None, security_token=None): if self.MetadataServiceSupport[self.name]: self._populate_keys_from_metadata_server() if not self._secret_key: raise UserException('Could not retrieve secret key from instance ' 'profile.', hint='Check that your instance has an IAM ' 'profile or set --aws-access-key-id') Credentials = partial(provider.Provider, "aws") InstanceProfileCredentials = partial(InstanceProfileProvider, 'aws') Fix InstanceProfileProvider class for boto 2.24 "profile_name" is now a parameter that must be supported in "get_credentials". Yes, this is exactly the "fragile base class" problem, but let's hope that the mechanisms there become dormant again for a long stretch again. Or, switch to botocore or something like that to avoid the crazy amount of credential management logic hard to opt-out of in boto.from boto import provider from functools import partial from wal_e.exception import UserException class InstanceProfileProvider(provider.Provider): """Override boto Provider to control use of the AWS metadata store In particular, prevent boto from looking in a series of places for keys outside off WAL-E's control (e.g. boto.cfg, environment variables, and so on). As-is that precedence and detection code is in one big ream, and so a method override and some internal symbols are used to excise most of that cleverness. Also take this opportunity to inject a WAL-E-friendly exception to help the user with missing keys. """ def get_credentials(self, access_key=None, secret_key=None, security_token=None, profile_name=None): if self.MetadataServiceSupport[self.name]: self._populate_keys_from_metadata_server() if not self._secret_key: raise UserException('Could not retrieve secret key from instance ' 'profile.', hint='Check that your instance has an IAM ' 'profile or set --aws-access-key-id') Credentials = partial(provider.Provider, "aws") InstanceProfileCredentials = partial(InstanceProfileProvider, 'aws')
<commit_before>from boto import provider from functools import partial from wal_e.exception import UserException class InstanceProfileProvider(provider.Provider): """Override boto Provider to control use of the AWS metadata store In particular, prevent boto from looking in a series of places for keys outside off WAL-E's control (e.g. boto.cfg, environment variables, and so on). As-is that precedence and detection code is in one big ream, and so a method override and some internal symbols are used to excise most of that cleverness. Also take this opportunity to inject a WAL-E-friendly exception to help the user with missing keys. """ def get_credentials(self, access_key=None, secret_key=None, security_token=None): if self.MetadataServiceSupport[self.name]: self._populate_keys_from_metadata_server() if not self._secret_key: raise UserException('Could not retrieve secret key from instance ' 'profile.', hint='Check that your instance has an IAM ' 'profile or set --aws-access-key-id') Credentials = partial(provider.Provider, "aws") InstanceProfileCredentials = partial(InstanceProfileProvider, 'aws') <commit_msg>Fix InstanceProfileProvider class for boto 2.24 "profile_name" is now a parameter that must be supported in "get_credentials". Yes, this is exactly the "fragile base class" problem, but let's hope that the mechanisms there become dormant again for a long stretch again. Or, switch to botocore or something like that to avoid the crazy amount of credential management logic hard to opt-out of in boto.<commit_after>from boto import provider from functools import partial from wal_e.exception import UserException class InstanceProfileProvider(provider.Provider): """Override boto Provider to control use of the AWS metadata store In particular, prevent boto from looking in a series of places for keys outside off WAL-E's control (e.g. boto.cfg, environment variables, and so on). As-is that precedence and detection code is in one big ream, and so a method override and some internal symbols are used to excise most of that cleverness. Also take this opportunity to inject a WAL-E-friendly exception to help the user with missing keys. """ def get_credentials(self, access_key=None, secret_key=None, security_token=None, profile_name=None): if self.MetadataServiceSupport[self.name]: self._populate_keys_from_metadata_server() if not self._secret_key: raise UserException('Could not retrieve secret key from instance ' 'profile.', hint='Check that your instance has an IAM ' 'profile or set --aws-access-key-id') Credentials = partial(provider.Provider, "aws") InstanceProfileCredentials = partial(InstanceProfileProvider, 'aws')