prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>emailer_plugin.py<|end_file_name|><|fim▁begin|>from gi.repository import Gtk import gourmet.gtk_extras.dialog_extras as de from gourmet.plugin import RecDisplayModule, UIPlugin, MainPlugin, ToolPlugin from .recipe_emailer import RecipeEmailer from gettext import gettext as _ class EmailRecipePlugin (MainPlugin, UIPlugin): ui_string = ''' <menubar name="RecipeIndexMenuBar"> <menu name="Tools" action="Tools"> <placeholder name="StandaloneTool"> <menuitem action="EmailRecipes"/> </placeholder> </menu> </menubar> ''' def setup_action_groups (self): self.actionGroup = Gtk.ActionGroup(name='RecipeEmailerActionGroup') self.actionGroup.add_actions([ ('EmailRecipes',None,_('Email recipes'), None,_('Email all selected recipes (or all recipes if no recipes are selected'),self.email_selected), ]) self.action_groups.append(self.actionGroup) def activate (self, pluggable): self.rg = self.pluggable = pluggable self.add_to_uimanager(pluggable.ui_manager) def get_selected_recs (self): recs = self.rg.get_selected_recs_from_rec_tree() if not recs: recs = self.rd.fetch_all(self.rd.recipe_table, deleted=False, sort_by=[('title',1)]) return recs def email_selected (self, *args): <|fim_middle|> <|fim▁end|>
recs = self.get_selected_recs() l = len(recs) if l > 20: if not de.getBoolean( title=_('Email recipes'), # only called for l>20, so fancy gettext methods # shouldn't be necessary if my knowledge of # linguistics serves me sublabel=_('Do you really want to email all %s selected recipes?')%l, custom_yes=_('Yes, e_mail them'), cancel=False, ): return re = RecipeEmailer(recs) re.send_email_with_attachments()
<|file_name|>emailer_plugin.py<|end_file_name|><|fim▁begin|>from gi.repository import Gtk import gourmet.gtk_extras.dialog_extras as de from gourmet.plugin import RecDisplayModule, UIPlugin, MainPlugin, ToolPlugin from .recipe_emailer import RecipeEmailer from gettext import gettext as _ class EmailRecipePlugin (MainPlugin, UIPlugin): ui_string = ''' <menubar name="RecipeIndexMenuBar"> <menu name="Tools" action="Tools"> <placeholder name="StandaloneTool"> <menuitem action="EmailRecipes"/> </placeholder> </menu> </menubar> ''' def setup_action_groups (self): self.actionGroup = Gtk.ActionGroup(name='RecipeEmailerActionGroup') self.actionGroup.add_actions([ ('EmailRecipes',None,_('Email recipes'), None,_('Email all selected recipes (or all recipes if no recipes are selected'),self.email_selected), ]) self.action_groups.append(self.actionGroup) def activate (self, pluggable): self.rg = self.pluggable = pluggable self.add_to_uimanager(pluggable.ui_manager) def get_selected_recs (self): recs = self.rg.get_selected_recs_from_rec_tree() if not recs: <|fim_middle|> return recs def email_selected (self, *args): recs = self.get_selected_recs() l = len(recs) if l > 20: if not de.getBoolean( title=_('Email recipes'), # only called for l>20, so fancy gettext methods # shouldn't be necessary if my knowledge of # linguistics serves me sublabel=_('Do you really want to email all %s selected recipes?')%l, custom_yes=_('Yes, e_mail them'), cancel=False, ): return re = RecipeEmailer(recs) re.send_email_with_attachments() <|fim▁end|>
recs = self.rd.fetch_all(self.rd.recipe_table, deleted=False, sort_by=[('title',1)])
<|file_name|>emailer_plugin.py<|end_file_name|><|fim▁begin|>from gi.repository import Gtk import gourmet.gtk_extras.dialog_extras as de from gourmet.plugin import RecDisplayModule, UIPlugin, MainPlugin, ToolPlugin from .recipe_emailer import RecipeEmailer from gettext import gettext as _ class EmailRecipePlugin (MainPlugin, UIPlugin): ui_string = ''' <menubar name="RecipeIndexMenuBar"> <menu name="Tools" action="Tools"> <placeholder name="StandaloneTool"> <menuitem action="EmailRecipes"/> </placeholder> </menu> </menubar> ''' def setup_action_groups (self): self.actionGroup = Gtk.ActionGroup(name='RecipeEmailerActionGroup') self.actionGroup.add_actions([ ('EmailRecipes',None,_('Email recipes'), None,_('Email all selected recipes (or all recipes if no recipes are selected'),self.email_selected), ]) self.action_groups.append(self.actionGroup) def activate (self, pluggable): self.rg = self.pluggable = pluggable self.add_to_uimanager(pluggable.ui_manager) def get_selected_recs (self): recs = self.rg.get_selected_recs_from_rec_tree() if not recs: recs = self.rd.fetch_all(self.rd.recipe_table, deleted=False, sort_by=[('title',1)]) return recs def email_selected (self, *args): recs = self.get_selected_recs() l = len(recs) if l > 20: <|fim_middle|> re = RecipeEmailer(recs) re.send_email_with_attachments() <|fim▁end|>
if not de.getBoolean( title=_('Email recipes'), # only called for l>20, so fancy gettext methods # shouldn't be necessary if my knowledge of # linguistics serves me sublabel=_('Do you really want to email all %s selected recipes?')%l, custom_yes=_('Yes, e_mail them'), cancel=False, ): return
<|file_name|>emailer_plugin.py<|end_file_name|><|fim▁begin|>from gi.repository import Gtk import gourmet.gtk_extras.dialog_extras as de from gourmet.plugin import RecDisplayModule, UIPlugin, MainPlugin, ToolPlugin from .recipe_emailer import RecipeEmailer from gettext import gettext as _ class EmailRecipePlugin (MainPlugin, UIPlugin): ui_string = ''' <menubar name="RecipeIndexMenuBar"> <menu name="Tools" action="Tools"> <placeholder name="StandaloneTool"> <menuitem action="EmailRecipes"/> </placeholder> </menu> </menubar> ''' def setup_action_groups (self): self.actionGroup = Gtk.ActionGroup(name='RecipeEmailerActionGroup') self.actionGroup.add_actions([ ('EmailRecipes',None,_('Email recipes'), None,_('Email all selected recipes (or all recipes if no recipes are selected'),self.email_selected), ]) self.action_groups.append(self.actionGroup) def activate (self, pluggable): self.rg = self.pluggable = pluggable self.add_to_uimanager(pluggable.ui_manager) def get_selected_recs (self): recs = self.rg.get_selected_recs_from_rec_tree() if not recs: recs = self.rd.fetch_all(self.rd.recipe_table, deleted=False, sort_by=[('title',1)]) return recs def email_selected (self, *args): recs = self.get_selected_recs() l = len(recs) if l > 20: if not de.getBoolean( title=_('Email recipes'), # only called for l>20, so fancy gettext methods # shouldn't be necessary if my knowledge of # linguistics serves me sublabel=_('Do you really want to email all %s selected recipes?')%l, custom_yes=_('Yes, e_mail them'), cancel=False, ): <|fim_middle|> re = RecipeEmailer(recs) re.send_email_with_attachments() <|fim▁end|>
return
<|file_name|>emailer_plugin.py<|end_file_name|><|fim▁begin|>from gi.repository import Gtk import gourmet.gtk_extras.dialog_extras as de from gourmet.plugin import RecDisplayModule, UIPlugin, MainPlugin, ToolPlugin from .recipe_emailer import RecipeEmailer from gettext import gettext as _ class EmailRecipePlugin (MainPlugin, UIPlugin): ui_string = ''' <menubar name="RecipeIndexMenuBar"> <menu name="Tools" action="Tools"> <placeholder name="StandaloneTool"> <menuitem action="EmailRecipes"/> </placeholder> </menu> </menubar> ''' def <|fim_middle|> (self): self.actionGroup = Gtk.ActionGroup(name='RecipeEmailerActionGroup') self.actionGroup.add_actions([ ('EmailRecipes',None,_('Email recipes'), None,_('Email all selected recipes (or all recipes if no recipes are selected'),self.email_selected), ]) self.action_groups.append(self.actionGroup) def activate (self, pluggable): self.rg = self.pluggable = pluggable self.add_to_uimanager(pluggable.ui_manager) def get_selected_recs (self): recs = self.rg.get_selected_recs_from_rec_tree() if not recs: recs = self.rd.fetch_all(self.rd.recipe_table, deleted=False, sort_by=[('title',1)]) return recs def email_selected (self, *args): recs = self.get_selected_recs() l = len(recs) if l > 20: if not de.getBoolean( title=_('Email recipes'), # only called for l>20, so fancy gettext methods # shouldn't be necessary if my knowledge of # linguistics serves me sublabel=_('Do you really want to email all %s selected recipes?')%l, custom_yes=_('Yes, e_mail them'), cancel=False, ): return re = RecipeEmailer(recs) re.send_email_with_attachments() <|fim▁end|>
setup_action_groups
<|file_name|>emailer_plugin.py<|end_file_name|><|fim▁begin|>from gi.repository import Gtk import gourmet.gtk_extras.dialog_extras as de from gourmet.plugin import RecDisplayModule, UIPlugin, MainPlugin, ToolPlugin from .recipe_emailer import RecipeEmailer from gettext import gettext as _ class EmailRecipePlugin (MainPlugin, UIPlugin): ui_string = ''' <menubar name="RecipeIndexMenuBar"> <menu name="Tools" action="Tools"> <placeholder name="StandaloneTool"> <menuitem action="EmailRecipes"/> </placeholder> </menu> </menubar> ''' def setup_action_groups (self): self.actionGroup = Gtk.ActionGroup(name='RecipeEmailerActionGroup') self.actionGroup.add_actions([ ('EmailRecipes',None,_('Email recipes'), None,_('Email all selected recipes (or all recipes if no recipes are selected'),self.email_selected), ]) self.action_groups.append(self.actionGroup) def <|fim_middle|> (self, pluggable): self.rg = self.pluggable = pluggable self.add_to_uimanager(pluggable.ui_manager) def get_selected_recs (self): recs = self.rg.get_selected_recs_from_rec_tree() if not recs: recs = self.rd.fetch_all(self.rd.recipe_table, deleted=False, sort_by=[('title',1)]) return recs def email_selected (self, *args): recs = self.get_selected_recs() l = len(recs) if l > 20: if not de.getBoolean( title=_('Email recipes'), # only called for l>20, so fancy gettext methods # shouldn't be necessary if my knowledge of # linguistics serves me sublabel=_('Do you really want to email all %s selected recipes?')%l, custom_yes=_('Yes, e_mail them'), cancel=False, ): return re = RecipeEmailer(recs) re.send_email_with_attachments() <|fim▁end|>
activate
<|file_name|>emailer_plugin.py<|end_file_name|><|fim▁begin|>from gi.repository import Gtk import gourmet.gtk_extras.dialog_extras as de from gourmet.plugin import RecDisplayModule, UIPlugin, MainPlugin, ToolPlugin from .recipe_emailer import RecipeEmailer from gettext import gettext as _ class EmailRecipePlugin (MainPlugin, UIPlugin): ui_string = ''' <menubar name="RecipeIndexMenuBar"> <menu name="Tools" action="Tools"> <placeholder name="StandaloneTool"> <menuitem action="EmailRecipes"/> </placeholder> </menu> </menubar> ''' def setup_action_groups (self): self.actionGroup = Gtk.ActionGroup(name='RecipeEmailerActionGroup') self.actionGroup.add_actions([ ('EmailRecipes',None,_('Email recipes'), None,_('Email all selected recipes (or all recipes if no recipes are selected'),self.email_selected), ]) self.action_groups.append(self.actionGroup) def activate (self, pluggable): self.rg = self.pluggable = pluggable self.add_to_uimanager(pluggable.ui_manager) def <|fim_middle|> (self): recs = self.rg.get_selected_recs_from_rec_tree() if not recs: recs = self.rd.fetch_all(self.rd.recipe_table, deleted=False, sort_by=[('title',1)]) return recs def email_selected (self, *args): recs = self.get_selected_recs() l = len(recs) if l > 20: if not de.getBoolean( title=_('Email recipes'), # only called for l>20, so fancy gettext methods # shouldn't be necessary if my knowledge of # linguistics serves me sublabel=_('Do you really want to email all %s selected recipes?')%l, custom_yes=_('Yes, e_mail them'), cancel=False, ): return re = RecipeEmailer(recs) re.send_email_with_attachments() <|fim▁end|>
get_selected_recs
<|file_name|>emailer_plugin.py<|end_file_name|><|fim▁begin|>from gi.repository import Gtk import gourmet.gtk_extras.dialog_extras as de from gourmet.plugin import RecDisplayModule, UIPlugin, MainPlugin, ToolPlugin from .recipe_emailer import RecipeEmailer from gettext import gettext as _ class EmailRecipePlugin (MainPlugin, UIPlugin): ui_string = ''' <menubar name="RecipeIndexMenuBar"> <menu name="Tools" action="Tools"> <placeholder name="StandaloneTool"> <menuitem action="EmailRecipes"/> </placeholder> </menu> </menubar> ''' def setup_action_groups (self): self.actionGroup = Gtk.ActionGroup(name='RecipeEmailerActionGroup') self.actionGroup.add_actions([ ('EmailRecipes',None,_('Email recipes'), None,_('Email all selected recipes (or all recipes if no recipes are selected'),self.email_selected), ]) self.action_groups.append(self.actionGroup) def activate (self, pluggable): self.rg = self.pluggable = pluggable self.add_to_uimanager(pluggable.ui_manager) def get_selected_recs (self): recs = self.rg.get_selected_recs_from_rec_tree() if not recs: recs = self.rd.fetch_all(self.rd.recipe_table, deleted=False, sort_by=[('title',1)]) return recs def <|fim_middle|> (self, *args): recs = self.get_selected_recs() l = len(recs) if l > 20: if not de.getBoolean( title=_('Email recipes'), # only called for l>20, so fancy gettext methods # shouldn't be necessary if my knowledge of # linguistics serves me sublabel=_('Do you really want to email all %s selected recipes?')%l, custom_yes=_('Yes, e_mail them'), cancel=False, ): return re = RecipeEmailer(recs) re.send_email_with_attachments() <|fim▁end|>
email_selected
<|file_name|>output.py<|end_file_name|><|fim▁begin|>#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors.<|fim▁hole|># All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- import logging # isort:skip log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from .notebook import run_notebook_hook from .state import curstate #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- __all__ = ( 'output_file', 'output_notebook', 'reset_output', ) #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- def output_file(filename, title="Bokeh Plot", mode=None, root_dir=None): '''Configure the default output state to generate output saved to a file when :func:`show` is called. Does not change the current ``Document`` from ``curdoc()``. File and notebook output may be active at the same time, so e.g., this does not clear the effects of ``output_notebook()``. Args: filename (str) : a filename for saving the HTML document title (str, optional) : a title for the HTML document (default: "Bokeh Plot") mode (str, optional) : how to include BokehJS (default: ``'cdn'``) One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or ``'absolute(-dev)'``. See :class:`bokeh.resources.Resources` for more details. root_dir (str, optional) : root directory to use for 'absolute' resources. (default: None) This value is ignored for other resource types, e.g. ``INLINE`` or ``CDN``. Returns: None .. note:: Generally, this should be called at the beginning of an interactive session or the top of a script. .. warning:: This output file will be overwritten on every save, e.g., each time show() or save() is invoked. ''' curstate().output_file( filename, title=title, mode=mode, root_dir=root_dir ) def output_notebook(resources=None, verbose=False, hide_banner=False, load_timeout=5000, notebook_type='jupyter'): ''' Configure the default output state to generate output in notebook cells when :func:`show` is called. Note that, :func:`show` may be called multiple times in a single cell to display multiple objects in the output cell. The objects will be displayed in order. Args: resources (Resource, optional) : How and where to load BokehJS from (default: CDN) verbose (bool, optional) : whether to display detailed BokehJS banner (default: False) hide_banner (bool, optional): whether to hide the Bokeh banner (default: False) load_timeout (int, optional) : Timeout in milliseconds when plots assume load timed out (default: 5000) notebook_type (string, optional): Notebook type (default: jupyter) Returns: None .. note:: Generally, this should be called at the beginning of an interactive session or the top of a script. ''' # verify notebook_type first in curstate().output_notebook curstate().output_notebook(notebook_type) run_notebook_hook(notebook_type, 'load', resources, verbose, hide_banner, load_timeout) def reset_output(state=None): ''' Clear the default state of all output modes. Returns: None ''' curstate().reset() #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------<|fim▁end|>
<|file_name|>output.py<|end_file_name|><|fim▁begin|>#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- import logging # isort:skip log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from .notebook import run_notebook_hook from .state import curstate #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- __all__ = ( 'output_file', 'output_notebook', 'reset_output', ) #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- def output_file(filename, title="Bokeh Plot", mode=None, root_dir=None): <|fim_middle|> def output_notebook(resources=None, verbose=False, hide_banner=False, load_timeout=5000, notebook_type='jupyter'): ''' Configure the default output state to generate output in notebook cells when :func:`show` is called. Note that, :func:`show` may be called multiple times in a single cell to display multiple objects in the output cell. The objects will be displayed in order. Args: resources (Resource, optional) : How and where to load BokehJS from (default: CDN) verbose (bool, optional) : whether to display detailed BokehJS banner (default: False) hide_banner (bool, optional): whether to hide the Bokeh banner (default: False) load_timeout (int, optional) : Timeout in milliseconds when plots assume load timed out (default: 5000) notebook_type (string, optional): Notebook type (default: jupyter) Returns: None .. note:: Generally, this should be called at the beginning of an interactive session or the top of a script. ''' # verify notebook_type first in curstate().output_notebook curstate().output_notebook(notebook_type) run_notebook_hook(notebook_type, 'load', resources, verbose, hide_banner, load_timeout) def reset_output(state=None): ''' Clear the default state of all output modes. Returns: None ''' curstate().reset() #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- <|fim▁end|>
'''Configure the default output state to generate output saved to a file when :func:`show` is called. Does not change the current ``Document`` from ``curdoc()``. File and notebook output may be active at the same time, so e.g., this does not clear the effects of ``output_notebook()``. Args: filename (str) : a filename for saving the HTML document title (str, optional) : a title for the HTML document (default: "Bokeh Plot") mode (str, optional) : how to include BokehJS (default: ``'cdn'``) One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or ``'absolute(-dev)'``. See :class:`bokeh.resources.Resources` for more details. root_dir (str, optional) : root directory to use for 'absolute' resources. (default: None) This value is ignored for other resource types, e.g. ``INLINE`` or ``CDN``. Returns: None .. note:: Generally, this should be called at the beginning of an interactive session or the top of a script. .. warning:: This output file will be overwritten on every save, e.g., each time show() or save() is invoked. ''' curstate().output_file( filename, title=title, mode=mode, root_dir=root_dir )
<|file_name|>output.py<|end_file_name|><|fim▁begin|>#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- import logging # isort:skip log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from .notebook import run_notebook_hook from .state import curstate #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- __all__ = ( 'output_file', 'output_notebook', 'reset_output', ) #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- def output_file(filename, title="Bokeh Plot", mode=None, root_dir=None): '''Configure the default output state to generate output saved to a file when :func:`show` is called. Does not change the current ``Document`` from ``curdoc()``. File and notebook output may be active at the same time, so e.g., this does not clear the effects of ``output_notebook()``. Args: filename (str) : a filename for saving the HTML document title (str, optional) : a title for the HTML document (default: "Bokeh Plot") mode (str, optional) : how to include BokehJS (default: ``'cdn'``) One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or ``'absolute(-dev)'``. See :class:`bokeh.resources.Resources` for more details. root_dir (str, optional) : root directory to use for 'absolute' resources. (default: None) This value is ignored for other resource types, e.g. ``INLINE`` or ``CDN``. Returns: None .. note:: Generally, this should be called at the beginning of an interactive session or the top of a script. .. warning:: This output file will be overwritten on every save, e.g., each time show() or save() is invoked. ''' curstate().output_file( filename, title=title, mode=mode, root_dir=root_dir ) def output_notebook(resources=None, verbose=False, hide_banner=False, load_timeout=5000, notebook_type='jupyter'): <|fim_middle|> def reset_output(state=None): ''' Clear the default state of all output modes. Returns: None ''' curstate().reset() #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- <|fim▁end|>
''' Configure the default output state to generate output in notebook cells when :func:`show` is called. Note that, :func:`show` may be called multiple times in a single cell to display multiple objects in the output cell. The objects will be displayed in order. Args: resources (Resource, optional) : How and where to load BokehJS from (default: CDN) verbose (bool, optional) : whether to display detailed BokehJS banner (default: False) hide_banner (bool, optional): whether to hide the Bokeh banner (default: False) load_timeout (int, optional) : Timeout in milliseconds when plots assume load timed out (default: 5000) notebook_type (string, optional): Notebook type (default: jupyter) Returns: None .. note:: Generally, this should be called at the beginning of an interactive session or the top of a script. ''' # verify notebook_type first in curstate().output_notebook curstate().output_notebook(notebook_type) run_notebook_hook(notebook_type, 'load', resources, verbose, hide_banner, load_timeout)
<|file_name|>output.py<|end_file_name|><|fim▁begin|>#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- import logging # isort:skip log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from .notebook import run_notebook_hook from .state import curstate #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- __all__ = ( 'output_file', 'output_notebook', 'reset_output', ) #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- def output_file(filename, title="Bokeh Plot", mode=None, root_dir=None): '''Configure the default output state to generate output saved to a file when :func:`show` is called. Does not change the current ``Document`` from ``curdoc()``. File and notebook output may be active at the same time, so e.g., this does not clear the effects of ``output_notebook()``. Args: filename (str) : a filename for saving the HTML document title (str, optional) : a title for the HTML document (default: "Bokeh Plot") mode (str, optional) : how to include BokehJS (default: ``'cdn'``) One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or ``'absolute(-dev)'``. See :class:`bokeh.resources.Resources` for more details. root_dir (str, optional) : root directory to use for 'absolute' resources. (default: None) This value is ignored for other resource types, e.g. ``INLINE`` or ``CDN``. Returns: None .. note:: Generally, this should be called at the beginning of an interactive session or the top of a script. .. warning:: This output file will be overwritten on every save, e.g., each time show() or save() is invoked. ''' curstate().output_file( filename, title=title, mode=mode, root_dir=root_dir ) def output_notebook(resources=None, verbose=False, hide_banner=False, load_timeout=5000, notebook_type='jupyter'): ''' Configure the default output state to generate output in notebook cells when :func:`show` is called. Note that, :func:`show` may be called multiple times in a single cell to display multiple objects in the output cell. The objects will be displayed in order. Args: resources (Resource, optional) : How and where to load BokehJS from (default: CDN) verbose (bool, optional) : whether to display detailed BokehJS banner (default: False) hide_banner (bool, optional): whether to hide the Bokeh banner (default: False) load_timeout (int, optional) : Timeout in milliseconds when plots assume load timed out (default: 5000) notebook_type (string, optional): Notebook type (default: jupyter) Returns: None .. note:: Generally, this should be called at the beginning of an interactive session or the top of a script. ''' # verify notebook_type first in curstate().output_notebook curstate().output_notebook(notebook_type) run_notebook_hook(notebook_type, 'load', resources, verbose, hide_banner, load_timeout) def reset_output(state=None): <|fim_middle|> #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- <|fim▁end|>
''' Clear the default state of all output modes. Returns: None ''' curstate().reset()
<|file_name|>output.py<|end_file_name|><|fim▁begin|>#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- import logging # isort:skip log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from .notebook import run_notebook_hook from .state import curstate #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- __all__ = ( 'output_file', 'output_notebook', 'reset_output', ) #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- def <|fim_middle|>(filename, title="Bokeh Plot", mode=None, root_dir=None): '''Configure the default output state to generate output saved to a file when :func:`show` is called. Does not change the current ``Document`` from ``curdoc()``. File and notebook output may be active at the same time, so e.g., this does not clear the effects of ``output_notebook()``. Args: filename (str) : a filename for saving the HTML document title (str, optional) : a title for the HTML document (default: "Bokeh Plot") mode (str, optional) : how to include BokehJS (default: ``'cdn'``) One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or ``'absolute(-dev)'``. See :class:`bokeh.resources.Resources` for more details. root_dir (str, optional) : root directory to use for 'absolute' resources. (default: None) This value is ignored for other resource types, e.g. ``INLINE`` or ``CDN``. Returns: None .. note:: Generally, this should be called at the beginning of an interactive session or the top of a script. .. warning:: This output file will be overwritten on every save, e.g., each time show() or save() is invoked. ''' curstate().output_file( filename, title=title, mode=mode, root_dir=root_dir ) def output_notebook(resources=None, verbose=False, hide_banner=False, load_timeout=5000, notebook_type='jupyter'): ''' Configure the default output state to generate output in notebook cells when :func:`show` is called. Note that, :func:`show` may be called multiple times in a single cell to display multiple objects in the output cell. The objects will be displayed in order. Args: resources (Resource, optional) : How and where to load BokehJS from (default: CDN) verbose (bool, optional) : whether to display detailed BokehJS banner (default: False) hide_banner (bool, optional): whether to hide the Bokeh banner (default: False) load_timeout (int, optional) : Timeout in milliseconds when plots assume load timed out (default: 5000) notebook_type (string, optional): Notebook type (default: jupyter) Returns: None .. note:: Generally, this should be called at the beginning of an interactive session or the top of a script. ''' # verify notebook_type first in curstate().output_notebook curstate().output_notebook(notebook_type) run_notebook_hook(notebook_type, 'load', resources, verbose, hide_banner, load_timeout) def reset_output(state=None): ''' Clear the default state of all output modes. Returns: None ''' curstate().reset() #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- <|fim▁end|>
output_file
<|file_name|>output.py<|end_file_name|><|fim▁begin|>#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- import logging # isort:skip log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from .notebook import run_notebook_hook from .state import curstate #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- __all__ = ( 'output_file', 'output_notebook', 'reset_output', ) #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- def output_file(filename, title="Bokeh Plot", mode=None, root_dir=None): '''Configure the default output state to generate output saved to a file when :func:`show` is called. Does not change the current ``Document`` from ``curdoc()``. File and notebook output may be active at the same time, so e.g., this does not clear the effects of ``output_notebook()``. Args: filename (str) : a filename for saving the HTML document title (str, optional) : a title for the HTML document (default: "Bokeh Plot") mode (str, optional) : how to include BokehJS (default: ``'cdn'``) One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or ``'absolute(-dev)'``. See :class:`bokeh.resources.Resources` for more details. root_dir (str, optional) : root directory to use for 'absolute' resources. (default: None) This value is ignored for other resource types, e.g. ``INLINE`` or ``CDN``. Returns: None .. note:: Generally, this should be called at the beginning of an interactive session or the top of a script. .. warning:: This output file will be overwritten on every save, e.g., each time show() or save() is invoked. ''' curstate().output_file( filename, title=title, mode=mode, root_dir=root_dir ) def <|fim_middle|>(resources=None, verbose=False, hide_banner=False, load_timeout=5000, notebook_type='jupyter'): ''' Configure the default output state to generate output in notebook cells when :func:`show` is called. Note that, :func:`show` may be called multiple times in a single cell to display multiple objects in the output cell. The objects will be displayed in order. Args: resources (Resource, optional) : How and where to load BokehJS from (default: CDN) verbose (bool, optional) : whether to display detailed BokehJS banner (default: False) hide_banner (bool, optional): whether to hide the Bokeh banner (default: False) load_timeout (int, optional) : Timeout in milliseconds when plots assume load timed out (default: 5000) notebook_type (string, optional): Notebook type (default: jupyter) Returns: None .. note:: Generally, this should be called at the beginning of an interactive session or the top of a script. ''' # verify notebook_type first in curstate().output_notebook curstate().output_notebook(notebook_type) run_notebook_hook(notebook_type, 'load', resources, verbose, hide_banner, load_timeout) def reset_output(state=None): ''' Clear the default state of all output modes. Returns: None ''' curstate().reset() #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- <|fim▁end|>
output_notebook
<|file_name|>output.py<|end_file_name|><|fim▁begin|>#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- import logging # isort:skip log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from .notebook import run_notebook_hook from .state import curstate #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- __all__ = ( 'output_file', 'output_notebook', 'reset_output', ) #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- def output_file(filename, title="Bokeh Plot", mode=None, root_dir=None): '''Configure the default output state to generate output saved to a file when :func:`show` is called. Does not change the current ``Document`` from ``curdoc()``. File and notebook output may be active at the same time, so e.g., this does not clear the effects of ``output_notebook()``. Args: filename (str) : a filename for saving the HTML document title (str, optional) : a title for the HTML document (default: "Bokeh Plot") mode (str, optional) : how to include BokehJS (default: ``'cdn'``) One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or ``'absolute(-dev)'``. See :class:`bokeh.resources.Resources` for more details. root_dir (str, optional) : root directory to use for 'absolute' resources. (default: None) This value is ignored for other resource types, e.g. ``INLINE`` or ``CDN``. Returns: None .. note:: Generally, this should be called at the beginning of an interactive session or the top of a script. .. warning:: This output file will be overwritten on every save, e.g., each time show() or save() is invoked. ''' curstate().output_file( filename, title=title, mode=mode, root_dir=root_dir ) def output_notebook(resources=None, verbose=False, hide_banner=False, load_timeout=5000, notebook_type='jupyter'): ''' Configure the default output state to generate output in notebook cells when :func:`show` is called. Note that, :func:`show` may be called multiple times in a single cell to display multiple objects in the output cell. The objects will be displayed in order. Args: resources (Resource, optional) : How and where to load BokehJS from (default: CDN) verbose (bool, optional) : whether to display detailed BokehJS banner (default: False) hide_banner (bool, optional): whether to hide the Bokeh banner (default: False) load_timeout (int, optional) : Timeout in milliseconds when plots assume load timed out (default: 5000) notebook_type (string, optional): Notebook type (default: jupyter) Returns: None .. note:: Generally, this should be called at the beginning of an interactive session or the top of a script. ''' # verify notebook_type first in curstate().output_notebook curstate().output_notebook(notebook_type) run_notebook_hook(notebook_type, 'load', resources, verbose, hide_banner, load_timeout) def <|fim_middle|>(state=None): ''' Clear the default state of all output modes. Returns: None ''' curstate().reset() #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- <|fim▁end|>
reset_output
<|file_name|>setup_helper.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google 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. # ============================================================================== """Provides the setup for the experiments.""" from pytorch_pretrained_bert import modeling from pytorch_pretrained_bert import tokenization import torch import embeddings_helper def setup_uncased(model_config): """Setup the uncased bert model. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. embedding_map: Holding all token embeddings. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertModel.from_pretrained(model_config) _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) # Initialize the embedding map embedding_map = embeddings_helper.EmbeddingMap(device, model) return tokenizer, model, device, embedding_map def setup_bert_vanilla(model_config): """Setup the uncased bert model without embedding maps. Args: model_config: The model configuration to be loaded.<|fim▁hole|> Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertModel.from_pretrained(model_config) _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) return tokenizer, model, device def setup_bert_mlm(model_config): """Setup the uncased bert model with classification head. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertForMaskedLM.from_pretrained('bert-base-uncased') _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) # Initialize the embedding map embedding_map = embeddings_helper.EmbeddingMap(device, model.bert) return tokenizer, model, device, embedding_map<|fim▁end|>
<|file_name|>setup_helper.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google 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. # ============================================================================== """Provides the setup for the experiments.""" from pytorch_pretrained_bert import modeling from pytorch_pretrained_bert import tokenization import torch import embeddings_helper def setup_uncased(model_config): <|fim_middle|> def setup_bert_vanilla(model_config): """Setup the uncased bert model without embedding maps. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertModel.from_pretrained(model_config) _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) return tokenizer, model, device def setup_bert_mlm(model_config): """Setup the uncased bert model with classification head. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertForMaskedLM.from_pretrained('bert-base-uncased') _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) # Initialize the embedding map embedding_map = embeddings_helper.EmbeddingMap(device, model.bert) return tokenizer, model, device, embedding_map <|fim▁end|>
"""Setup the uncased bert model. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. embedding_map: Holding all token embeddings. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertModel.from_pretrained(model_config) _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) # Initialize the embedding map embedding_map = embeddings_helper.EmbeddingMap(device, model) return tokenizer, model, device, embedding_map
<|file_name|>setup_helper.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google 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. # ============================================================================== """Provides the setup for the experiments.""" from pytorch_pretrained_bert import modeling from pytorch_pretrained_bert import tokenization import torch import embeddings_helper def setup_uncased(model_config): """Setup the uncased bert model. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. embedding_map: Holding all token embeddings. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertModel.from_pretrained(model_config) _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) # Initialize the embedding map embedding_map = embeddings_helper.EmbeddingMap(device, model) return tokenizer, model, device, embedding_map def setup_bert_vanilla(model_config): <|fim_middle|> def setup_bert_mlm(model_config): """Setup the uncased bert model with classification head. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertForMaskedLM.from_pretrained('bert-base-uncased') _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) # Initialize the embedding map embedding_map = embeddings_helper.EmbeddingMap(device, model.bert) return tokenizer, model, device, embedding_map <|fim▁end|>
"""Setup the uncased bert model without embedding maps. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertModel.from_pretrained(model_config) _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) return tokenizer, model, device
<|file_name|>setup_helper.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google 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. # ============================================================================== """Provides the setup for the experiments.""" from pytorch_pretrained_bert import modeling from pytorch_pretrained_bert import tokenization import torch import embeddings_helper def setup_uncased(model_config): """Setup the uncased bert model. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. embedding_map: Holding all token embeddings. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertModel.from_pretrained(model_config) _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) # Initialize the embedding map embedding_map = embeddings_helper.EmbeddingMap(device, model) return tokenizer, model, device, embedding_map def setup_bert_vanilla(model_config): """Setup the uncased bert model without embedding maps. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertModel.from_pretrained(model_config) _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) return tokenizer, model, device def setup_bert_mlm(model_config): <|fim_middle|> <|fim▁end|>
"""Setup the uncased bert model with classification head. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertForMaskedLM.from_pretrained('bert-base-uncased') _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) # Initialize the embedding map embedding_map = embeddings_helper.EmbeddingMap(device, model.bert) return tokenizer, model, device, embedding_map
<|file_name|>setup_helper.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google 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. # ============================================================================== """Provides the setup for the experiments.""" from pytorch_pretrained_bert import modeling from pytorch_pretrained_bert import tokenization import torch import embeddings_helper def <|fim_middle|>(model_config): """Setup the uncased bert model. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. embedding_map: Holding all token embeddings. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertModel.from_pretrained(model_config) _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) # Initialize the embedding map embedding_map = embeddings_helper.EmbeddingMap(device, model) return tokenizer, model, device, embedding_map def setup_bert_vanilla(model_config): """Setup the uncased bert model without embedding maps. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertModel.from_pretrained(model_config) _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) return tokenizer, model, device def setup_bert_mlm(model_config): """Setup the uncased bert model with classification head. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertForMaskedLM.from_pretrained('bert-base-uncased') _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) # Initialize the embedding map embedding_map = embeddings_helper.EmbeddingMap(device, model.bert) return tokenizer, model, device, embedding_map <|fim▁end|>
setup_uncased
<|file_name|>setup_helper.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google 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. # ============================================================================== """Provides the setup for the experiments.""" from pytorch_pretrained_bert import modeling from pytorch_pretrained_bert import tokenization import torch import embeddings_helper def setup_uncased(model_config): """Setup the uncased bert model. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. embedding_map: Holding all token embeddings. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertModel.from_pretrained(model_config) _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) # Initialize the embedding map embedding_map = embeddings_helper.EmbeddingMap(device, model) return tokenizer, model, device, embedding_map def <|fim_middle|>(model_config): """Setup the uncased bert model without embedding maps. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertModel.from_pretrained(model_config) _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) return tokenizer, model, device def setup_bert_mlm(model_config): """Setup the uncased bert model with classification head. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertForMaskedLM.from_pretrained('bert-base-uncased') _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) # Initialize the embedding map embedding_map = embeddings_helper.EmbeddingMap(device, model.bert) return tokenizer, model, device, embedding_map <|fim▁end|>
setup_bert_vanilla
<|file_name|>setup_helper.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google 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. # ============================================================================== """Provides the setup for the experiments.""" from pytorch_pretrained_bert import modeling from pytorch_pretrained_bert import tokenization import torch import embeddings_helper def setup_uncased(model_config): """Setup the uncased bert model. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. embedding_map: Holding all token embeddings. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertModel.from_pretrained(model_config) _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) # Initialize the embedding map embedding_map = embeddings_helper.EmbeddingMap(device, model) return tokenizer, model, device, embedding_map def setup_bert_vanilla(model_config): """Setup the uncased bert model without embedding maps. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertModel.from_pretrained(model_config) _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) return tokenizer, model, device def <|fim_middle|>(model_config): """Setup the uncased bert model with classification head. Args: model_config: The model configuration to be loaded. Returns: tokenizer: The tokenizer to be used to convert between tokens and ids. model: The model that has been initialized. device: The device to be used in this run. """ # Load pre-trained model tokenizer (vocabulary) tokenizer = tokenization.BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertForMaskedLM.from_pretrained('bert-base-uncased') _ = model.eval() # Set up the device in use device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) # Initialize the embedding map embedding_map = embeddings_helper.EmbeddingMap(device, model.bert) return tokenizer, model, device, embedding_map <|fim▁end|>
setup_bert_mlm
<|file_name|>test_is_thue_morse.py<|end_file_name|><|fim▁begin|>"""Test.""" import pytest TM_TABLE = [ ([0, 1, 1, 0, 1], True), ([0], True), ([1], False), ([0, 1, 0, 0], False), ] <|fim▁hole|>def test_is_thue_morse(n, result): """Test.""" from is_thue_morse import is_thue_morse assert is_thue_morse(n) == result<|fim▁end|>
@pytest.mark.parametrize("n, result", TM_TABLE)
<|file_name|>test_is_thue_morse.py<|end_file_name|><|fim▁begin|>"""Test.""" import pytest TM_TABLE = [ ([0, 1, 1, 0, 1], True), ([0], True), ([1], False), ([0, 1, 0, 0], False), ] @pytest.mark.parametrize("n, result", TM_TABLE) def test_is_thue_morse(n, result): <|fim_middle|> <|fim▁end|>
"""Test.""" from is_thue_morse import is_thue_morse assert is_thue_morse(n) == result
<|file_name|>test_is_thue_morse.py<|end_file_name|><|fim▁begin|>"""Test.""" import pytest TM_TABLE = [ ([0, 1, 1, 0, 1], True), ([0], True), ([1], False), ([0, 1, 0, 0], False), ] @pytest.mark.parametrize("n, result", TM_TABLE) def <|fim_middle|>(n, result): """Test.""" from is_thue_morse import is_thue_morse assert is_thue_morse(n) == result <|fim▁end|>
test_is_thue_morse
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente.<|fim▁hole|> """ from anagrafica.models import Persona return Persona.objects.none()<|fim▁end|>
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): <|fim_middle|> class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
""" Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id')
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: <|fim_middle|> autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), )
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): <|fim_middle|> class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
""" Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: <|fim_middle|> autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), )
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): <|fim_middle|> class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
""" Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: <|fim_middle|> giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
abstract = True
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): <|fim_middle|> def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
""" Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): <|fim_middle|> def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
""" Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): <|fim_middle|> @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
""" Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save()
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): <|fim_middle|> @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
""" Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): <|fim_middle|> def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
""" Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): <|fim_middle|> def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
""" Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count()
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): <|fim_middle|> class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
""" Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): <|fim_middle|> <|fim▁end|>
""" Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none()
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: <|fim_middle|> commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
abstract = True
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): <|fim_middle|> <|fim▁end|>
""" SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none()
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo <|fim_middle|> else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
g.positivo = positivo
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo <|fim_middle|> g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
g = Giudizio( oggetto=self, positivo=positivo, autore=autore )
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: <|fim_middle|> return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
return g
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def <|fim_middle|>(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
giudizio_positivo
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def <|fim_middle|>(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
giudizio_negativo
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def <|fim_middle|>(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
_giudizio
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def <|fim_middle|>(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
giudizi_positivi
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def <|fim_middle|>(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
giudizi_negativi
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def <|fim_middle|>(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
_giudizi
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def <|fim_middle|>(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def commento_notifica_destinatari(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
giudizio_cerca
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from base.models import ModelloSemplice from base.tratti import ConMarcaTemporale class Giudizio(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un giudizio sociale ad un oggetto generico. Utilizzare tramite il tratto ConGiudizio ed i suoi metodi. """ class Meta: verbose_name_plural = "Giudizi" permissions = ( ("view_giudizio", "Can view giudizio"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE) positivo = models.BooleanField("Positivo", db_index=True, default=True) oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') class Commento(ModelloSemplice, ConMarcaTemporale): """ Rappresenta un commento sociale ad un oggetto generico. Utilizzare tramite il tratto ConCommento ed i suoi metodi. """ class Meta: verbose_name_plural = "Commenti" app_label = "social" abstract = False permissions = ( ("view_commento", "Can view commento"), ) autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE) commento = models.TextField("Testo del commento") oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True) oggetto_id = models.PositiveIntegerField(db_index=True) oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id') LUNGHEZZA_MASSIMA = 1024 class ConGiudizio(): """ Aggiunge le funzionalita' di giudizio, stile social, positivi o negativi. """ class Meta: abstract = True giudizi = GenericRelation( Giudizio, related_query_name='giudizi', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def giudizio_positivo(self, autore): """ Registra un giudizio positivo :param autore: Autore del giudizio """ self._giudizio(autore, True) def giudizio_negativo(self, autore): """ Registra un giudizio negativo :param autore: Autore del giudizio """ self._giudizio(autore, False) def _giudizio(self, autore, positivo): """ Registra un giudizio :param autore: Autore del giudizio :param positivo: Vero se positivo, falso se negativo """ g = self.giudizio_cerca(autore) if g: # Se gia' esiste un giudizio, modifico il tipo g.positivo = positivo else: # Altrimenti, ne registro uno nuovo g = Giudizio( oggetto=self, positivo=positivo, autore=autore ) g.save() @property def giudizi_positivi(self): """ Restituisce il numero di giudizi positivi associati all'oggetto. """ return self._giudizi(self, True) @property def giudizi_negativi(self): """ Restituisce il numero di giudizi negativi associati all'oggetto. """ return self._giudizi(self, False) def _giudizi(self, positivo): """ Restituisce il numero di giudizi positivi o negativi associati all'oggetto. """ return self.giudizi.filter(positivo=positivo).count() def giudizio_cerca(self, autore): """ Cerca il giudizio di un autore sull'oggetto. Se non presente, ritorna None. """ g = self.giudizi.filter(autore=autore)[:1] if g: return g return None class ConCommenti(models.Model): """ Aggiunge la possibilita' di aggiungere commenti ad un oggetto. """ class Meta: abstract = True commenti = GenericRelation( Commento, related_query_name='%(class)s', content_type_field='oggetto_tipo', object_id_field='oggetto_id' ) def <|fim_middle|>(self, mittente): """ SOVRASCRIVIMI! Ritorna il queryset di persone che devono ricevere una notifica ogni volta che un commento viene aggiunto da un dato mittente. """ from anagrafica.models import Persona return Persona.objects.none() <|fim▁end|>
commento_notifica_destinatari
<|file_name|>ipblock.py<|end_file_name|><|fim▁begin|><|fim▁hole|>import sys def ip2str(ip): l = [ (ip >> (3*8)) & 0xFF, (ip >> (2*8)) & 0xFF, (ip >> (1*8)) & 0xFF, (ip >> (0*8)) & 0xFF, ] return '.'.join([str(i) for i in l]) def str2ip(line): a, b, c, d = [int(s) for s in line.split('.')] ip = 0 ip += (a << (3*8)) ip += (b << (2*8)) ip += (c << (1*8)) ip += (d << (0*8)) return ip blockip = str2ip(sys.stdin.readline()) hostmask = 1 bitcount = 1 for line in sys.stdin.readlines(): try: ip = str2ip(line.strip()) except: print 'Ignored line:', line, continue while (blockip & (~hostmask)) != (ip & (~hostmask)): hostmask = (hostmask << 1) | 1 bitcount += 1 print ip2str(blockip & (~hostmask)) + '/' + str(bitcount), 'hostmask =', ip2str(hostmask) print 'wrong way around'<|fim▁end|>
#!/usr/bin/env python
<|file_name|>ipblock.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys def ip2str(ip): <|fim_middle|> def str2ip(line): a, b, c, d = [int(s) for s in line.split('.')] ip = 0 ip += (a << (3*8)) ip += (b << (2*8)) ip += (c << (1*8)) ip += (d << (0*8)) return ip blockip = str2ip(sys.stdin.readline()) hostmask = 1 bitcount = 1 for line in sys.stdin.readlines(): try: ip = str2ip(line.strip()) except: print 'Ignored line:', line, continue while (blockip & (~hostmask)) != (ip & (~hostmask)): hostmask = (hostmask << 1) | 1 bitcount += 1 print ip2str(blockip & (~hostmask)) + '/' + str(bitcount), 'hostmask =', ip2str(hostmask) print 'wrong way around' <|fim▁end|>
l = [ (ip >> (3*8)) & 0xFF, (ip >> (2*8)) & 0xFF, (ip >> (1*8)) & 0xFF, (ip >> (0*8)) & 0xFF, ] return '.'.join([str(i) for i in l])
<|file_name|>ipblock.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys def ip2str(ip): l = [ (ip >> (3*8)) & 0xFF, (ip >> (2*8)) & 0xFF, (ip >> (1*8)) & 0xFF, (ip >> (0*8)) & 0xFF, ] return '.'.join([str(i) for i in l]) def str2ip(line): <|fim_middle|> blockip = str2ip(sys.stdin.readline()) hostmask = 1 bitcount = 1 for line in sys.stdin.readlines(): try: ip = str2ip(line.strip()) except: print 'Ignored line:', line, continue while (blockip & (~hostmask)) != (ip & (~hostmask)): hostmask = (hostmask << 1) | 1 bitcount += 1 print ip2str(blockip & (~hostmask)) + '/' + str(bitcount), 'hostmask =', ip2str(hostmask) print 'wrong way around' <|fim▁end|>
a, b, c, d = [int(s) for s in line.split('.')] ip = 0 ip += (a << (3*8)) ip += (b << (2*8)) ip += (c << (1*8)) ip += (d << (0*8)) return ip
<|file_name|>ipblock.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys def <|fim_middle|>(ip): l = [ (ip >> (3*8)) & 0xFF, (ip >> (2*8)) & 0xFF, (ip >> (1*8)) & 0xFF, (ip >> (0*8)) & 0xFF, ] return '.'.join([str(i) for i in l]) def str2ip(line): a, b, c, d = [int(s) for s in line.split('.')] ip = 0 ip += (a << (3*8)) ip += (b << (2*8)) ip += (c << (1*8)) ip += (d << (0*8)) return ip blockip = str2ip(sys.stdin.readline()) hostmask = 1 bitcount = 1 for line in sys.stdin.readlines(): try: ip = str2ip(line.strip()) except: print 'Ignored line:', line, continue while (blockip & (~hostmask)) != (ip & (~hostmask)): hostmask = (hostmask << 1) | 1 bitcount += 1 print ip2str(blockip & (~hostmask)) + '/' + str(bitcount), 'hostmask =', ip2str(hostmask) print 'wrong way around' <|fim▁end|>
ip2str
<|file_name|>ipblock.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys def ip2str(ip): l = [ (ip >> (3*8)) & 0xFF, (ip >> (2*8)) & 0xFF, (ip >> (1*8)) & 0xFF, (ip >> (0*8)) & 0xFF, ] return '.'.join([str(i) for i in l]) def <|fim_middle|>(line): a, b, c, d = [int(s) for s in line.split('.')] ip = 0 ip += (a << (3*8)) ip += (b << (2*8)) ip += (c << (1*8)) ip += (d << (0*8)) return ip blockip = str2ip(sys.stdin.readline()) hostmask = 1 bitcount = 1 for line in sys.stdin.readlines(): try: ip = str2ip(line.strip()) except: print 'Ignored line:', line, continue while (blockip & (~hostmask)) != (ip & (~hostmask)): hostmask = (hostmask << 1) | 1 bitcount += 1 print ip2str(blockip & (~hostmask)) + '/' + str(bitcount), 'hostmask =', ip2str(hostmask) print 'wrong way around' <|fim▁end|>
str2ip
<|file_name|>gpmdp.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display currently playing song from Google Play Music Desktop Player. Configuration parameters: cache_timeout: how often we refresh this module in seconds (default 5) format: specify the items and ordering of the data in the status bar. These area 1:1 match to gpmdp-remote's options (default is '♫ {info}'). Format of status string placeholders: See `gpmdp-remote help`. Simply surround the items you want displayed (i.e. `album`) with curly braces (i.e. `{album}`) and place as-desired in the format string. {info} Print info about now playing song {title} Print current song title {artist} Print current song artist {album} Print current song album {album_art} Print current song album art URL {time_current} Print current song time in milliseconds<|fim▁hole|> {status} Print whether GPMDP is paused or playing {current} Print now playing song in "artist - song" format {help} Print this help message Requires: gpmdp: http://www.googleplaymusicdesktopplayer.com/ gpmdp-remote: https://github.com/iandrewt/gpmdp-remote @author Aaron Fields https://twitter.com/spirotot @license BSD """ from time import time from subprocess import check_output class Py3status: """ """ # available configuration parameters cache_timeout = 5 format = u'♫ {info}' @staticmethod def _run_cmd(cmd): return check_output(['gpmdp-remote', cmd]).decode('utf-8').strip() def gpmdp(self, i3s_output_list, i3s_config): if self._run_cmd('status') == 'Paused': result = '' else: cmds = ['info', 'title', 'artist', 'album', 'status', 'current', 'time_total', 'time_current', 'album_art'] data = {} for cmd in cmds: if '{%s}' % cmd in self.format: data[cmd] = self._run_cmd(cmd) result = self.format.format(**data) response = { 'cached_until': time() + self.cache_timeout, 'full_text': result } return response if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status)<|fim▁end|>
{time_total} Print total song time in milliseconds
<|file_name|>gpmdp.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display currently playing song from Google Play Music Desktop Player. Configuration parameters: cache_timeout: how often we refresh this module in seconds (default 5) format: specify the items and ordering of the data in the status bar. These area 1:1 match to gpmdp-remote's options (default is '♫ {info}'). Format of status string placeholders: See `gpmdp-remote help`. Simply surround the items you want displayed (i.e. `album`) with curly braces (i.e. `{album}`) and place as-desired in the format string. {info} Print info about now playing song {title} Print current song title {artist} Print current song artist {album} Print current song album {album_art} Print current song album art URL {time_current} Print current song time in milliseconds {time_total} Print total song time in milliseconds {status} Print whether GPMDP is paused or playing {current} Print now playing song in "artist - song" format {help} Print this help message Requires: gpmdp: http://www.googleplaymusicdesktopplayer.com/ gpmdp-remote: https://github.com/iandrewt/gpmdp-remote @author Aaron Fields https://twitter.com/spirotot @license BSD """ from time import time from subprocess import check_output class Py3status: ""<|fim_middle|> f __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status) <|fim▁end|>
" """ # available configuration parameters cache_timeout = 5 format = u'♫ {info}' @staticmethod def _run_cmd(cmd): return check_output(['gpmdp-remote', cmd]).decode('utf-8').strip() def gpmdp(self, i3s_output_list, i3s_config): if self._run_cmd('status') == 'Paused': result = '' else: cmds = ['info', 'title', 'artist', 'album', 'status', 'current', 'time_total', 'time_current', 'album_art'] data = {} for cmd in cmds: if '{%s}' % cmd in self.format: data[cmd] = self._run_cmd(cmd) result = self.format.format(**data) response = { 'cached_until': time() + self.cache_timeout, 'full_text': result } return response i
<|file_name|>gpmdp.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display currently playing song from Google Play Music Desktop Player. Configuration parameters: cache_timeout: how often we refresh this module in seconds (default 5) format: specify the items and ordering of the data in the status bar. These area 1:1 match to gpmdp-remote's options (default is '♫ {info}'). Format of status string placeholders: See `gpmdp-remote help`. Simply surround the items you want displayed (i.e. `album`) with curly braces (i.e. `{album}`) and place as-desired in the format string. {info} Print info about now playing song {title} Print current song title {artist} Print current song artist {album} Print current song album {album_art} Print current song album art URL {time_current} Print current song time in milliseconds {time_total} Print total song time in milliseconds {status} Print whether GPMDP is paused or playing {current} Print now playing song in "artist - song" format {help} Print this help message Requires: gpmdp: http://www.googleplaymusicdesktopplayer.com/ gpmdp-remote: https://github.com/iandrewt/gpmdp-remote @author Aaron Fields https://twitter.com/spirotot @license BSD """ from time import time from subprocess import check_output class Py3status: """ """ # available configuration parameters cache_timeout = 5 format = u'♫ {info}' @staticmethod def _run_cmd(cmd): retu<|fim_middle|> def gpmdp(self, i3s_output_list, i3s_config): if self._run_cmd('status') == 'Paused': result = '' else: cmds = ['info', 'title', 'artist', 'album', 'status', 'current', 'time_total', 'time_current', 'album_art'] data = {} for cmd in cmds: if '{%s}' % cmd in self.format: data[cmd] = self._run_cmd(cmd) result = self.format.format(**data) response = { 'cached_until': time() + self.cache_timeout, 'full_text': result } return response if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status) <|fim▁end|>
rn check_output(['gpmdp-remote', cmd]).decode('utf-8').strip()
<|file_name|>gpmdp.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display currently playing song from Google Play Music Desktop Player. Configuration parameters: cache_timeout: how often we refresh this module in seconds (default 5) format: specify the items and ordering of the data in the status bar. These area 1:1 match to gpmdp-remote's options (default is '♫ {info}'). Format of status string placeholders: See `gpmdp-remote help`. Simply surround the items you want displayed (i.e. `album`) with curly braces (i.e. `{album}`) and place as-desired in the format string. {info} Print info about now playing song {title} Print current song title {artist} Print current song artist {album} Print current song album {album_art} Print current song album art URL {time_current} Print current song time in milliseconds {time_total} Print total song time in milliseconds {status} Print whether GPMDP is paused or playing {current} Print now playing song in "artist - song" format {help} Print this help message Requires: gpmdp: http://www.googleplaymusicdesktopplayer.com/ gpmdp-remote: https://github.com/iandrewt/gpmdp-remote @author Aaron Fields https://twitter.com/spirotot @license BSD """ from time import time from subprocess import check_output class Py3status: """ """ # available configuration parameters cache_timeout = 5 format = u'♫ {info}' @staticmethod def _run_cmd(cmd): return check_output(['gpmdp-remote', cmd]).decode('utf-8').strip() def gpmdp(self, i3s_output_list, i3s_config): if s<|fim_middle|> f __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status) <|fim▁end|>
elf._run_cmd('status') == 'Paused': result = '' else: cmds = ['info', 'title', 'artist', 'album', 'status', 'current', 'time_total', 'time_current', 'album_art'] data = {} for cmd in cmds: if '{%s}' % cmd in self.format: data[cmd] = self._run_cmd(cmd) result = self.format.format(**data) response = { 'cached_until': time() + self.cache_timeout, 'full_text': result } return response i
<|file_name|>gpmdp.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display currently playing song from Google Play Music Desktop Player. Configuration parameters: cache_timeout: how often we refresh this module in seconds (default 5) format: specify the items and ordering of the data in the status bar. These area 1:1 match to gpmdp-remote's options (default is '♫ {info}'). Format of status string placeholders: See `gpmdp-remote help`. Simply surround the items you want displayed (i.e. `album`) with curly braces (i.e. `{album}`) and place as-desired in the format string. {info} Print info about now playing song {title} Print current song title {artist} Print current song artist {album} Print current song album {album_art} Print current song album art URL {time_current} Print current song time in milliseconds {time_total} Print total song time in milliseconds {status} Print whether GPMDP is paused or playing {current} Print now playing song in "artist - song" format {help} Print this help message Requires: gpmdp: http://www.googleplaymusicdesktopplayer.com/ gpmdp-remote: https://github.com/iandrewt/gpmdp-remote @author Aaron Fields https://twitter.com/spirotot @license BSD """ from time import time from subprocess import check_output class Py3status: """ """ # available configuration parameters cache_timeout = 5 format = u'♫ {info}' @staticmethod def _run_cmd(cmd): return check_output(['gpmdp-remote', cmd]).decode('utf-8').strip() def gpmdp(self, i3s_output_list, i3s_config): if self._run_cmd('status') == 'Paused': resu <|fim_middle|> else: cmds = ['info', 'title', 'artist', 'album', 'status', 'current', 'time_total', 'time_current', 'album_art'] data = {} for cmd in cmds: if '{%s}' % cmd in self.format: data[cmd] = self._run_cmd(cmd) result = self.format.format(**data) response = { 'cached_until': time() + self.cache_timeout, 'full_text': result } return response if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status) <|fim▁end|>
lt = ''
<|file_name|>gpmdp.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display currently playing song from Google Play Music Desktop Player. Configuration parameters: cache_timeout: how often we refresh this module in seconds (default 5) format: specify the items and ordering of the data in the status bar. These area 1:1 match to gpmdp-remote's options (default is '♫ {info}'). Format of status string placeholders: See `gpmdp-remote help`. Simply surround the items you want displayed (i.e. `album`) with curly braces (i.e. `{album}`) and place as-desired in the format string. {info} Print info about now playing song {title} Print current song title {artist} Print current song artist {album} Print current song album {album_art} Print current song album art URL {time_current} Print current song time in milliseconds {time_total} Print total song time in milliseconds {status} Print whether GPMDP is paused or playing {current} Print now playing song in "artist - song" format {help} Print this help message Requires: gpmdp: http://www.googleplaymusicdesktopplayer.com/ gpmdp-remote: https://github.com/iandrewt/gpmdp-remote @author Aaron Fields https://twitter.com/spirotot @license BSD """ from time import time from subprocess import check_output class Py3status: """ """ # available configuration parameters cache_timeout = 5 format = u'♫ {info}' @staticmethod def _run_cmd(cmd): return check_output(['gpmdp-remote', cmd]).decode('utf-8').strip() def gpmdp(self, i3s_output_list, i3s_config): if self._run_cmd('status') == 'Paused': result = '' else: cmds <|fim_middle|> response = { 'cached_until': time() + self.cache_timeout, 'full_text': result } return response if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status) <|fim▁end|>
= ['info', 'title', 'artist', 'album', 'status', 'current', 'time_total', 'time_current', 'album_art'] data = {} for cmd in cmds: if '{%s}' % cmd in self.format: data[cmd] = self._run_cmd(cmd) result = self.format.format(**data)
<|file_name|>gpmdp.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display currently playing song from Google Play Music Desktop Player. Configuration parameters: cache_timeout: how often we refresh this module in seconds (default 5) format: specify the items and ordering of the data in the status bar. These area 1:1 match to gpmdp-remote's options (default is '♫ {info}'). Format of status string placeholders: See `gpmdp-remote help`. Simply surround the items you want displayed (i.e. `album`) with curly braces (i.e. `{album}`) and place as-desired in the format string. {info} Print info about now playing song {title} Print current song title {artist} Print current song artist {album} Print current song album {album_art} Print current song album art URL {time_current} Print current song time in milliseconds {time_total} Print total song time in milliseconds {status} Print whether GPMDP is paused or playing {current} Print now playing song in "artist - song" format {help} Print this help message Requires: gpmdp: http://www.googleplaymusicdesktopplayer.com/ gpmdp-remote: https://github.com/iandrewt/gpmdp-remote @author Aaron Fields https://twitter.com/spirotot @license BSD """ from time import time from subprocess import check_output class Py3status: """ """ # available configuration parameters cache_timeout = 5 format = u'♫ {info}' @staticmethod def _run_cmd(cmd): return check_output(['gpmdp-remote', cmd]).decode('utf-8').strip() def gpmdp(self, i3s_output_list, i3s_config): if self._run_cmd('status') == 'Paused': result = '' else: cmds = ['info', 'title', 'artist', 'album', 'status', 'current', 'time_total', 'time_current', 'album_art'] data = {} for cmd in cmds: if '{%s}' % cmd in self.format: data <|fim_middle|> result = self.format.format(**data) response = { 'cached_until': time() + self.cache_timeout, 'full_text': result } return response if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status) <|fim▁end|>
[cmd] = self._run_cmd(cmd)
<|file_name|>gpmdp.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display currently playing song from Google Play Music Desktop Player. Configuration parameters: cache_timeout: how often we refresh this module in seconds (default 5) format: specify the items and ordering of the data in the status bar. These area 1:1 match to gpmdp-remote's options (default is '♫ {info}'). Format of status string placeholders: See `gpmdp-remote help`. Simply surround the items you want displayed (i.e. `album`) with curly braces (i.e. `{album}`) and place as-desired in the format string. {info} Print info about now playing song {title} Print current song title {artist} Print current song artist {album} Print current song album {album_art} Print current song album art URL {time_current} Print current song time in milliseconds {time_total} Print total song time in milliseconds {status} Print whether GPMDP is paused or playing {current} Print now playing song in "artist - song" format {help} Print this help message Requires: gpmdp: http://www.googleplaymusicdesktopplayer.com/ gpmdp-remote: https://github.com/iandrewt/gpmdp-remote @author Aaron Fields https://twitter.com/spirotot @license BSD """ from time import time from subprocess import check_output class Py3status: """ """ # available configuration parameters cache_timeout = 5 format = u'♫ {info}' @staticmethod def _run_cmd(cmd): return check_output(['gpmdp-remote', cmd]).decode('utf-8').strip() def gpmdp(self, i3s_output_list, i3s_config): if self._run_cmd('status') == 'Paused': result = '' else: cmds = ['info', 'title', 'artist', 'album', 'status', 'current', 'time_total', 'time_current', 'album_art'] data = {} for cmd in cmds: if '{%s}' % cmd in self.format: data[cmd] = self._run_cmd(cmd) result = self.format.format(**data) response = { 'cached_until': time() + self.cache_timeout, 'full_text': result } return response if __name__ == "__main__": """ <|fim_middle|> <|fim▁end|>
Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status)
<|file_name|>gpmdp.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display currently playing song from Google Play Music Desktop Player. Configuration parameters: cache_timeout: how often we refresh this module in seconds (default 5) format: specify the items and ordering of the data in the status bar. These area 1:1 match to gpmdp-remote's options (default is '♫ {info}'). Format of status string placeholders: See `gpmdp-remote help`. Simply surround the items you want displayed (i.e. `album`) with curly braces (i.e. `{album}`) and place as-desired in the format string. {info} Print info about now playing song {title} Print current song title {artist} Print current song artist {album} Print current song album {album_art} Print current song album art URL {time_current} Print current song time in milliseconds {time_total} Print total song time in milliseconds {status} Print whether GPMDP is paused or playing {current} Print now playing song in "artist - song" format {help} Print this help message Requires: gpmdp: http://www.googleplaymusicdesktopplayer.com/ gpmdp-remote: https://github.com/iandrewt/gpmdp-remote @author Aaron Fields https://twitter.com/spirotot @license BSD """ from time import time from subprocess import check_output class Py3status: """ """ # available configuration parameters cache_timeout = 5 format = u'♫ {info}' @staticmethod def _run<|fim_middle|>): return check_output(['gpmdp-remote', cmd]).decode('utf-8').strip() def gpmdp(self, i3s_output_list, i3s_config): if self._run_cmd('status') == 'Paused': result = '' else: cmds = ['info', 'title', 'artist', 'album', 'status', 'current', 'time_total', 'time_current', 'album_art'] data = {} for cmd in cmds: if '{%s}' % cmd in self.format: data[cmd] = self._run_cmd(cmd) result = self.format.format(**data) response = { 'cached_until': time() + self.cache_timeout, 'full_text': result } return response if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status) <|fim▁end|>
_cmd(cmd
<|file_name|>gpmdp.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Display currently playing song from Google Play Music Desktop Player. Configuration parameters: cache_timeout: how often we refresh this module in seconds (default 5) format: specify the items and ordering of the data in the status bar. These area 1:1 match to gpmdp-remote's options (default is '♫ {info}'). Format of status string placeholders: See `gpmdp-remote help`. Simply surround the items you want displayed (i.e. `album`) with curly braces (i.e. `{album}`) and place as-desired in the format string. {info} Print info about now playing song {title} Print current song title {artist} Print current song artist {album} Print current song album {album_art} Print current song album art URL {time_current} Print current song time in milliseconds {time_total} Print total song time in milliseconds {status} Print whether GPMDP is paused or playing {current} Print now playing song in "artist - song" format {help} Print this help message Requires: gpmdp: http://www.googleplaymusicdesktopplayer.com/ gpmdp-remote: https://github.com/iandrewt/gpmdp-remote @author Aaron Fields https://twitter.com/spirotot @license BSD """ from time import time from subprocess import check_output class Py3status: """ """ # available configuration parameters cache_timeout = 5 format = u'♫ {info}' @staticmethod def _run_cmd(cmd): return check_output(['gpmdp-remote', cmd]).decode('utf-8').strip() def gpmd<|fim_middle|>f, i3s_output_list, i3s_config): if self._run_cmd('status') == 'Paused': result = '' else: cmds = ['info', 'title', 'artist', 'album', 'status', 'current', 'time_total', 'time_current', 'album_art'] data = {} for cmd in cmds: if '{%s}' % cmd in self.format: data[cmd] = self._run_cmd(cmd) result = self.format.format(**data) response = { 'cached_until': time() + self.cache_timeout, 'full_text': result } return response if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status) <|fim▁end|>
p(sel
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"]<|fim▁hole|> @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers)<|fim▁end|>
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): <|fim_middle|> <|fim▁end|>
class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers)
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): <|fim_middle|> class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers) <|fim▁end|>
fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): <|fim_middle|> class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers) <|fim▁end|>
fields = ["id"] pass
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): <|fim_middle|> class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers) <|fim▁end|>
fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): <|fim_middle|> fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers) <|fim▁end|>
fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def create(params, env=None, headers=None): <|fim_middle|> @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers) <|fim▁end|>
return request.send('post', request.uri_path("plans"), params, env, headers)
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): <|fim_middle|> @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers) <|fim▁end|>
return request.send('post', request.uri_path("plans",id), params, env, headers)
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): <|fim_middle|> @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers) <|fim▁end|>
return request.send_list_request('get', request.uri_path("plans"), params, env, headers)
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): <|fim_middle|> @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers) <|fim▁end|>
return request.send('get', request.uri_path("plans",id), None, env, headers)
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): <|fim_middle|> @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers) <|fim▁end|>
return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers)
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def copy(params, env=None, headers=None): <|fim_middle|> @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers) <|fim▁end|>
return request.send('post', request.uri_path("plans","copy"), params, env, headers)
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): <|fim_middle|> <|fim▁end|>
return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers)
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def <|fim_middle|>(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers) <|fim▁end|>
create
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def <|fim_middle|>(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers) <|fim▁end|>
update
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def <|fim_middle|>(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers) <|fim▁end|>
list
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def <|fim_middle|>(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers) <|fim▁end|>
retrieve
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def <|fim_middle|>(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers) <|fim▁end|>
delete
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def <|fim_middle|>(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers) <|fim▁end|>
copy
<|file_name|>plan.py<|end_file_name|><|fim▁begin|>import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Plan(Model): class Tier(Model): fields = ["starting_unit", "ending_unit", "price", "starting_unit_in_decimal", "ending_unit_in_decimal", "price_in_decimal"] pass class ApplicableAddon(Model): fields = ["id"] pass class AttachedAddon(Model): fields = ["id", "quantity", "billing_cycles", "type", "quantity_in_decimal"] pass class EventBasedAddon(Model): fields = ["id", "quantity", "on_event", "charge_once", "quantity_in_decimal"] pass fields = ["id", "name", "invoice_name", "description", "price", "currency_code", "period", \ "period_unit", "trial_period", "trial_period_unit", "trial_end_action", "pricing_model", "charge_model", \ "free_quantity", "setup_cost", "downgrade_penalty", "status", "archived_at", "billing_cycles", \ "redirect_url", "enabled_in_hosted_pages", "enabled_in_portal", "addon_applicability", "tax_code", \ "hsn_code", "taxjar_product_code", "avalara_sale_type", "avalara_transaction_type", "avalara_service_type", \ "sku", "accounting_code", "accounting_category1", "accounting_category2", "accounting_category3", \ "accounting_category4", "is_shippable", "shipping_frequency_period", "shipping_frequency_period_unit", \ "resource_version", "updated_at", "giftable", "claim_url", "free_quantity_in_decimal", "price_in_decimal", \ "invoice_notes", "taxable", "tax_profile_id", "meta_data", "tiers", "applicable_addons", "attached_addons", \ "event_based_addons", "show_description_in_invoices", "show_description_in_quotes"] @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path("plans"), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path("plans",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path("plans"), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path("plans",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path("plans","copy"), params, env, headers) @staticmethod def <|fim_middle|>(id, env=None, headers=None): return request.send('post', request.uri_path("plans",id,"unarchive"), None, env, headers) <|fim▁end|>
unarchive
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components.""" import logging import voluptuous as vol from homeassistant.components.switch import ( ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, CONF_ENTITY_PICTURE_TEMPLATE, CONF_ICON_TEMPLATE, CONF_SWITCHES, CONF_UNIQUE_ID, CONF_VALUE_TEMPLATE, STATE_OFF, STATE_ON, ) from homeassistant.core import callback from homeassistant.exceptions import TemplateError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import async_generate_entity_id from homeassistant.helpers.reload import async_setup_reload_service from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.script import Script from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS from .template_entity import TemplateEntity _LOGGER = logging.getLogger(__name__) _VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"] ON_ACTION = "turn_on" OFF_ACTION = "turn_off" SWITCH_SCHEMA = vol.Schema( { vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_ICON_TEMPLATE): cv.template, vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template, vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template, vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA, vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA, vol.Optional(ATTR_FRIENDLY_NAME): cv.string, vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(CONF_UNIQUE_ID): cv.string, } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)} ) async def _async_create_entities(hass, config): """Create the Template switches.""" switches = [] for device, device_config in config[CONF_SWITCHES].items(): friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device) state_template = device_config.get(CONF_VALUE_TEMPLATE) icon_template = device_config.get(CONF_ICON_TEMPLATE) entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE) availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE) on_action = device_config[ON_ACTION] off_action = device_config[OFF_ACTION] unique_id = device_config.get(CONF_UNIQUE_ID) switches.append( SwitchTemplate( hass, device, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ) ) return switches async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the template switches.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) async_add_entities(await _async_create_entities(hass, config)) class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity): """Representation of a Template switch.""" def __init__( self, hass, device_id, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ): """Initialize the Template switch.""" super().__init__( availability_template=availability_template, icon_template=icon_template, entity_picture_template=entity_picture_template, ) self.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, device_id, hass=hass ) self._name = friendly_name self._template = state_template domain = __name__.split(".")[-2] self._on_script = Script(hass, on_action, friendly_name, domain) self._off_script = Script(hass, off_action, friendly_name, domain) self._state = False self._unique_id = unique_id @callback def _update_state(self, result): super()._update_state(result) if isinstance(result, TemplateError): self._state = None return<|fim▁hole|> async def async_added_to_hass(self): """Register callbacks.""" if self._template is None: # restore state after startup await super().async_added_to_hass() state = await self.async_get_last_state() if state: self._state = state.state == STATE_ON # no need to listen for events else: self.add_template_attribute( "_state", self._template, None, self._update_state ) await super().async_added_to_hass() @property def name(self): """Return the name of the switch.""" return self._name @property def unique_id(self): """Return the unique id of this switch.""" return self._unique_id @property def is_on(self): """Return true if device is on.""" return self._state @property def should_poll(self): """Return the polling state.""" return False async def async_turn_on(self, **kwargs): """Fire the on action.""" await self._on_script.async_run(context=self._context) if self._template is None: self._state = True self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Fire the off action.""" await self._off_script.async_run(context=self._context) if self._template is None: self._state = False self.async_write_ha_state() @property def assumed_state(self): """State is assumed, if no template given.""" return self._template is None<|fim▁end|>
self._state = result.lower() in ("true", STATE_ON)
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components.""" import logging import voluptuous as vol from homeassistant.components.switch import ( ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, CONF_ENTITY_PICTURE_TEMPLATE, CONF_ICON_TEMPLATE, CONF_SWITCHES, CONF_UNIQUE_ID, CONF_VALUE_TEMPLATE, STATE_OFF, STATE_ON, ) from homeassistant.core import callback from homeassistant.exceptions import TemplateError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import async_generate_entity_id from homeassistant.helpers.reload import async_setup_reload_service from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.script import Script from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS from .template_entity import TemplateEntity _LOGGER = logging.getLogger(__name__) _VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"] ON_ACTION = "turn_on" OFF_ACTION = "turn_off" SWITCH_SCHEMA = vol.Schema( { vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_ICON_TEMPLATE): cv.template, vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template, vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template, vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA, vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA, vol.Optional(ATTR_FRIENDLY_NAME): cv.string, vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(CONF_UNIQUE_ID): cv.string, } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)} ) async def _async_create_entities(hass, config): <|fim_middle|> async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the template switches.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) async_add_entities(await _async_create_entities(hass, config)) class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity): """Representation of a Template switch.""" def __init__( self, hass, device_id, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ): """Initialize the Template switch.""" super().__init__( availability_template=availability_template, icon_template=icon_template, entity_picture_template=entity_picture_template, ) self.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, device_id, hass=hass ) self._name = friendly_name self._template = state_template domain = __name__.split(".")[-2] self._on_script = Script(hass, on_action, friendly_name, domain) self._off_script = Script(hass, off_action, friendly_name, domain) self._state = False self._unique_id = unique_id @callback def _update_state(self, result): super()._update_state(result) if isinstance(result, TemplateError): self._state = None return self._state = result.lower() in ("true", STATE_ON) async def async_added_to_hass(self): """Register callbacks.""" if self._template is None: # restore state after startup await super().async_added_to_hass() state = await self.async_get_last_state() if state: self._state = state.state == STATE_ON # no need to listen for events else: self.add_template_attribute( "_state", self._template, None, self._update_state ) await super().async_added_to_hass() @property def name(self): """Return the name of the switch.""" return self._name @property def unique_id(self): """Return the unique id of this switch.""" return self._unique_id @property def is_on(self): """Return true if device is on.""" return self._state @property def should_poll(self): """Return the polling state.""" return False async def async_turn_on(self, **kwargs): """Fire the on action.""" await self._on_script.async_run(context=self._context) if self._template is None: self._state = True self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Fire the off action.""" await self._off_script.async_run(context=self._context) if self._template is None: self._state = False self.async_write_ha_state() @property def assumed_state(self): """State is assumed, if no template given.""" return self._template is None <|fim▁end|>
"""Create the Template switches.""" switches = [] for device, device_config in config[CONF_SWITCHES].items(): friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device) state_template = device_config.get(CONF_VALUE_TEMPLATE) icon_template = device_config.get(CONF_ICON_TEMPLATE) entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE) availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE) on_action = device_config[ON_ACTION] off_action = device_config[OFF_ACTION] unique_id = device_config.get(CONF_UNIQUE_ID) switches.append( SwitchTemplate( hass, device, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ) ) return switches
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components.""" import logging import voluptuous as vol from homeassistant.components.switch import ( ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, CONF_ENTITY_PICTURE_TEMPLATE, CONF_ICON_TEMPLATE, CONF_SWITCHES, CONF_UNIQUE_ID, CONF_VALUE_TEMPLATE, STATE_OFF, STATE_ON, ) from homeassistant.core import callback from homeassistant.exceptions import TemplateError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import async_generate_entity_id from homeassistant.helpers.reload import async_setup_reload_service from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.script import Script from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS from .template_entity import TemplateEntity _LOGGER = logging.getLogger(__name__) _VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"] ON_ACTION = "turn_on" OFF_ACTION = "turn_off" SWITCH_SCHEMA = vol.Schema( { vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_ICON_TEMPLATE): cv.template, vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template, vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template, vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA, vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA, vol.Optional(ATTR_FRIENDLY_NAME): cv.string, vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(CONF_UNIQUE_ID): cv.string, } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)} ) async def _async_create_entities(hass, config): """Create the Template switches.""" switches = [] for device, device_config in config[CONF_SWITCHES].items(): friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device) state_template = device_config.get(CONF_VALUE_TEMPLATE) icon_template = device_config.get(CONF_ICON_TEMPLATE) entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE) availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE) on_action = device_config[ON_ACTION] off_action = device_config[OFF_ACTION] unique_id = device_config.get(CONF_UNIQUE_ID) switches.append( SwitchTemplate( hass, device, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ) ) return switches async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): <|fim_middle|> class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity): """Representation of a Template switch.""" def __init__( self, hass, device_id, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ): """Initialize the Template switch.""" super().__init__( availability_template=availability_template, icon_template=icon_template, entity_picture_template=entity_picture_template, ) self.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, device_id, hass=hass ) self._name = friendly_name self._template = state_template domain = __name__.split(".")[-2] self._on_script = Script(hass, on_action, friendly_name, domain) self._off_script = Script(hass, off_action, friendly_name, domain) self._state = False self._unique_id = unique_id @callback def _update_state(self, result): super()._update_state(result) if isinstance(result, TemplateError): self._state = None return self._state = result.lower() in ("true", STATE_ON) async def async_added_to_hass(self): """Register callbacks.""" if self._template is None: # restore state after startup await super().async_added_to_hass() state = await self.async_get_last_state() if state: self._state = state.state == STATE_ON # no need to listen for events else: self.add_template_attribute( "_state", self._template, None, self._update_state ) await super().async_added_to_hass() @property def name(self): """Return the name of the switch.""" return self._name @property def unique_id(self): """Return the unique id of this switch.""" return self._unique_id @property def is_on(self): """Return true if device is on.""" return self._state @property def should_poll(self): """Return the polling state.""" return False async def async_turn_on(self, **kwargs): """Fire the on action.""" await self._on_script.async_run(context=self._context) if self._template is None: self._state = True self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Fire the off action.""" await self._off_script.async_run(context=self._context) if self._template is None: self._state = False self.async_write_ha_state() @property def assumed_state(self): """State is assumed, if no template given.""" return self._template is None <|fim▁end|>
"""Set up the template switches.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) async_add_entities(await _async_create_entities(hass, config))
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components.""" import logging import voluptuous as vol from homeassistant.components.switch import ( ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, CONF_ENTITY_PICTURE_TEMPLATE, CONF_ICON_TEMPLATE, CONF_SWITCHES, CONF_UNIQUE_ID, CONF_VALUE_TEMPLATE, STATE_OFF, STATE_ON, ) from homeassistant.core import callback from homeassistant.exceptions import TemplateError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import async_generate_entity_id from homeassistant.helpers.reload import async_setup_reload_service from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.script import Script from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS from .template_entity import TemplateEntity _LOGGER = logging.getLogger(__name__) _VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"] ON_ACTION = "turn_on" OFF_ACTION = "turn_off" SWITCH_SCHEMA = vol.Schema( { vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_ICON_TEMPLATE): cv.template, vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template, vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template, vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA, vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA, vol.Optional(ATTR_FRIENDLY_NAME): cv.string, vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(CONF_UNIQUE_ID): cv.string, } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)} ) async def _async_create_entities(hass, config): """Create the Template switches.""" switches = [] for device, device_config in config[CONF_SWITCHES].items(): friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device) state_template = device_config.get(CONF_VALUE_TEMPLATE) icon_template = device_config.get(CONF_ICON_TEMPLATE) entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE) availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE) on_action = device_config[ON_ACTION] off_action = device_config[OFF_ACTION] unique_id = device_config.get(CONF_UNIQUE_ID) switches.append( SwitchTemplate( hass, device, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ) ) return switches async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the template switches.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) async_add_entities(await _async_create_entities(hass, config)) class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity): <|fim_middle|> <|fim▁end|>
"""Representation of a Template switch.""" def __init__( self, hass, device_id, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ): """Initialize the Template switch.""" super().__init__( availability_template=availability_template, icon_template=icon_template, entity_picture_template=entity_picture_template, ) self.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, device_id, hass=hass ) self._name = friendly_name self._template = state_template domain = __name__.split(".")[-2] self._on_script = Script(hass, on_action, friendly_name, domain) self._off_script = Script(hass, off_action, friendly_name, domain) self._state = False self._unique_id = unique_id @callback def _update_state(self, result): super()._update_state(result) if isinstance(result, TemplateError): self._state = None return self._state = result.lower() in ("true", STATE_ON) async def async_added_to_hass(self): """Register callbacks.""" if self._template is None: # restore state after startup await super().async_added_to_hass() state = await self.async_get_last_state() if state: self._state = state.state == STATE_ON # no need to listen for events else: self.add_template_attribute( "_state", self._template, None, self._update_state ) await super().async_added_to_hass() @property def name(self): """Return the name of the switch.""" return self._name @property def unique_id(self): """Return the unique id of this switch.""" return self._unique_id @property def is_on(self): """Return true if device is on.""" return self._state @property def should_poll(self): """Return the polling state.""" return False async def async_turn_on(self, **kwargs): """Fire the on action.""" await self._on_script.async_run(context=self._context) if self._template is None: self._state = True self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Fire the off action.""" await self._off_script.async_run(context=self._context) if self._template is None: self._state = False self.async_write_ha_state() @property def assumed_state(self): """State is assumed, if no template given.""" return self._template is None
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components.""" import logging import voluptuous as vol from homeassistant.components.switch import ( ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, CONF_ENTITY_PICTURE_TEMPLATE, CONF_ICON_TEMPLATE, CONF_SWITCHES, CONF_UNIQUE_ID, CONF_VALUE_TEMPLATE, STATE_OFF, STATE_ON, ) from homeassistant.core import callback from homeassistant.exceptions import TemplateError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import async_generate_entity_id from homeassistant.helpers.reload import async_setup_reload_service from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.script import Script from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS from .template_entity import TemplateEntity _LOGGER = logging.getLogger(__name__) _VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"] ON_ACTION = "turn_on" OFF_ACTION = "turn_off" SWITCH_SCHEMA = vol.Schema( { vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_ICON_TEMPLATE): cv.template, vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template, vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template, vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA, vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA, vol.Optional(ATTR_FRIENDLY_NAME): cv.string, vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(CONF_UNIQUE_ID): cv.string, } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)} ) async def _async_create_entities(hass, config): """Create the Template switches.""" switches = [] for device, device_config in config[CONF_SWITCHES].items(): friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device) state_template = device_config.get(CONF_VALUE_TEMPLATE) icon_template = device_config.get(CONF_ICON_TEMPLATE) entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE) availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE) on_action = device_config[ON_ACTION] off_action = device_config[OFF_ACTION] unique_id = device_config.get(CONF_UNIQUE_ID) switches.append( SwitchTemplate( hass, device, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ) ) return switches async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the template switches.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) async_add_entities(await _async_create_entities(hass, config)) class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity): """Representation of a Template switch.""" def __init__( self, hass, device_id, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ): <|fim_middle|> @callback def _update_state(self, result): super()._update_state(result) if isinstance(result, TemplateError): self._state = None return self._state = result.lower() in ("true", STATE_ON) async def async_added_to_hass(self): """Register callbacks.""" if self._template is None: # restore state after startup await super().async_added_to_hass() state = await self.async_get_last_state() if state: self._state = state.state == STATE_ON # no need to listen for events else: self.add_template_attribute( "_state", self._template, None, self._update_state ) await super().async_added_to_hass() @property def name(self): """Return the name of the switch.""" return self._name @property def unique_id(self): """Return the unique id of this switch.""" return self._unique_id @property def is_on(self): """Return true if device is on.""" return self._state @property def should_poll(self): """Return the polling state.""" return False async def async_turn_on(self, **kwargs): """Fire the on action.""" await self._on_script.async_run(context=self._context) if self._template is None: self._state = True self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Fire the off action.""" await self._off_script.async_run(context=self._context) if self._template is None: self._state = False self.async_write_ha_state() @property def assumed_state(self): """State is assumed, if no template given.""" return self._template is None <|fim▁end|>
"""Initialize the Template switch.""" super().__init__( availability_template=availability_template, icon_template=icon_template, entity_picture_template=entity_picture_template, ) self.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, device_id, hass=hass ) self._name = friendly_name self._template = state_template domain = __name__.split(".")[-2] self._on_script = Script(hass, on_action, friendly_name, domain) self._off_script = Script(hass, off_action, friendly_name, domain) self._state = False self._unique_id = unique_id
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components.""" import logging import voluptuous as vol from homeassistant.components.switch import ( ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, CONF_ENTITY_PICTURE_TEMPLATE, CONF_ICON_TEMPLATE, CONF_SWITCHES, CONF_UNIQUE_ID, CONF_VALUE_TEMPLATE, STATE_OFF, STATE_ON, ) from homeassistant.core import callback from homeassistant.exceptions import TemplateError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import async_generate_entity_id from homeassistant.helpers.reload import async_setup_reload_service from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.script import Script from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS from .template_entity import TemplateEntity _LOGGER = logging.getLogger(__name__) _VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"] ON_ACTION = "turn_on" OFF_ACTION = "turn_off" SWITCH_SCHEMA = vol.Schema( { vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_ICON_TEMPLATE): cv.template, vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template, vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template, vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA, vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA, vol.Optional(ATTR_FRIENDLY_NAME): cv.string, vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(CONF_UNIQUE_ID): cv.string, } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)} ) async def _async_create_entities(hass, config): """Create the Template switches.""" switches = [] for device, device_config in config[CONF_SWITCHES].items(): friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device) state_template = device_config.get(CONF_VALUE_TEMPLATE) icon_template = device_config.get(CONF_ICON_TEMPLATE) entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE) availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE) on_action = device_config[ON_ACTION] off_action = device_config[OFF_ACTION] unique_id = device_config.get(CONF_UNIQUE_ID) switches.append( SwitchTemplate( hass, device, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ) ) return switches async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the template switches.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) async_add_entities(await _async_create_entities(hass, config)) class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity): """Representation of a Template switch.""" def __init__( self, hass, device_id, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ): """Initialize the Template switch.""" super().__init__( availability_template=availability_template, icon_template=icon_template, entity_picture_template=entity_picture_template, ) self.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, device_id, hass=hass ) self._name = friendly_name self._template = state_template domain = __name__.split(".")[-2] self._on_script = Script(hass, on_action, friendly_name, domain) self._off_script = Script(hass, off_action, friendly_name, domain) self._state = False self._unique_id = unique_id @callback def _update_state(self, result): <|fim_middle|> async def async_added_to_hass(self): """Register callbacks.""" if self._template is None: # restore state after startup await super().async_added_to_hass() state = await self.async_get_last_state() if state: self._state = state.state == STATE_ON # no need to listen for events else: self.add_template_attribute( "_state", self._template, None, self._update_state ) await super().async_added_to_hass() @property def name(self): """Return the name of the switch.""" return self._name @property def unique_id(self): """Return the unique id of this switch.""" return self._unique_id @property def is_on(self): """Return true if device is on.""" return self._state @property def should_poll(self): """Return the polling state.""" return False async def async_turn_on(self, **kwargs): """Fire the on action.""" await self._on_script.async_run(context=self._context) if self._template is None: self._state = True self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Fire the off action.""" await self._off_script.async_run(context=self._context) if self._template is None: self._state = False self.async_write_ha_state() @property def assumed_state(self): """State is assumed, if no template given.""" return self._template is None <|fim▁end|>
super()._update_state(result) if isinstance(result, TemplateError): self._state = None return self._state = result.lower() in ("true", STATE_ON)
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components.""" import logging import voluptuous as vol from homeassistant.components.switch import ( ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, CONF_ENTITY_PICTURE_TEMPLATE, CONF_ICON_TEMPLATE, CONF_SWITCHES, CONF_UNIQUE_ID, CONF_VALUE_TEMPLATE, STATE_OFF, STATE_ON, ) from homeassistant.core import callback from homeassistant.exceptions import TemplateError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import async_generate_entity_id from homeassistant.helpers.reload import async_setup_reload_service from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.script import Script from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS from .template_entity import TemplateEntity _LOGGER = logging.getLogger(__name__) _VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"] ON_ACTION = "turn_on" OFF_ACTION = "turn_off" SWITCH_SCHEMA = vol.Schema( { vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_ICON_TEMPLATE): cv.template, vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template, vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template, vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA, vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA, vol.Optional(ATTR_FRIENDLY_NAME): cv.string, vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(CONF_UNIQUE_ID): cv.string, } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)} ) async def _async_create_entities(hass, config): """Create the Template switches.""" switches = [] for device, device_config in config[CONF_SWITCHES].items(): friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device) state_template = device_config.get(CONF_VALUE_TEMPLATE) icon_template = device_config.get(CONF_ICON_TEMPLATE) entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE) availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE) on_action = device_config[ON_ACTION] off_action = device_config[OFF_ACTION] unique_id = device_config.get(CONF_UNIQUE_ID) switches.append( SwitchTemplate( hass, device, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ) ) return switches async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the template switches.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) async_add_entities(await _async_create_entities(hass, config)) class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity): """Representation of a Template switch.""" def __init__( self, hass, device_id, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ): """Initialize the Template switch.""" super().__init__( availability_template=availability_template, icon_template=icon_template, entity_picture_template=entity_picture_template, ) self.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, device_id, hass=hass ) self._name = friendly_name self._template = state_template domain = __name__.split(".")[-2] self._on_script = Script(hass, on_action, friendly_name, domain) self._off_script = Script(hass, off_action, friendly_name, domain) self._state = False self._unique_id = unique_id @callback def _update_state(self, result): super()._update_state(result) if isinstance(result, TemplateError): self._state = None return self._state = result.lower() in ("true", STATE_ON) async def async_added_to_hass(self): <|fim_middle|> @property def name(self): """Return the name of the switch.""" return self._name @property def unique_id(self): """Return the unique id of this switch.""" return self._unique_id @property def is_on(self): """Return true if device is on.""" return self._state @property def should_poll(self): """Return the polling state.""" return False async def async_turn_on(self, **kwargs): """Fire the on action.""" await self._on_script.async_run(context=self._context) if self._template is None: self._state = True self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Fire the off action.""" await self._off_script.async_run(context=self._context) if self._template is None: self._state = False self.async_write_ha_state() @property def assumed_state(self): """State is assumed, if no template given.""" return self._template is None <|fim▁end|>
"""Register callbacks.""" if self._template is None: # restore state after startup await super().async_added_to_hass() state = await self.async_get_last_state() if state: self._state = state.state == STATE_ON # no need to listen for events else: self.add_template_attribute( "_state", self._template, None, self._update_state ) await super().async_added_to_hass()
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components.""" import logging import voluptuous as vol from homeassistant.components.switch import ( ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, CONF_ENTITY_PICTURE_TEMPLATE, CONF_ICON_TEMPLATE, CONF_SWITCHES, CONF_UNIQUE_ID, CONF_VALUE_TEMPLATE, STATE_OFF, STATE_ON, ) from homeassistant.core import callback from homeassistant.exceptions import TemplateError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import async_generate_entity_id from homeassistant.helpers.reload import async_setup_reload_service from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.script import Script from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS from .template_entity import TemplateEntity _LOGGER = logging.getLogger(__name__) _VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"] ON_ACTION = "turn_on" OFF_ACTION = "turn_off" SWITCH_SCHEMA = vol.Schema( { vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_ICON_TEMPLATE): cv.template, vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template, vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template, vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA, vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA, vol.Optional(ATTR_FRIENDLY_NAME): cv.string, vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(CONF_UNIQUE_ID): cv.string, } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)} ) async def _async_create_entities(hass, config): """Create the Template switches.""" switches = [] for device, device_config in config[CONF_SWITCHES].items(): friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device) state_template = device_config.get(CONF_VALUE_TEMPLATE) icon_template = device_config.get(CONF_ICON_TEMPLATE) entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE) availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE) on_action = device_config[ON_ACTION] off_action = device_config[OFF_ACTION] unique_id = device_config.get(CONF_UNIQUE_ID) switches.append( SwitchTemplate( hass, device, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ) ) return switches async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the template switches.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) async_add_entities(await _async_create_entities(hass, config)) class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity): """Representation of a Template switch.""" def __init__( self, hass, device_id, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ): """Initialize the Template switch.""" super().__init__( availability_template=availability_template, icon_template=icon_template, entity_picture_template=entity_picture_template, ) self.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, device_id, hass=hass ) self._name = friendly_name self._template = state_template domain = __name__.split(".")[-2] self._on_script = Script(hass, on_action, friendly_name, domain) self._off_script = Script(hass, off_action, friendly_name, domain) self._state = False self._unique_id = unique_id @callback def _update_state(self, result): super()._update_state(result) if isinstance(result, TemplateError): self._state = None return self._state = result.lower() in ("true", STATE_ON) async def async_added_to_hass(self): """Register callbacks.""" if self._template is None: # restore state after startup await super().async_added_to_hass() state = await self.async_get_last_state() if state: self._state = state.state == STATE_ON # no need to listen for events else: self.add_template_attribute( "_state", self._template, None, self._update_state ) await super().async_added_to_hass() @property def name(self): <|fim_middle|> @property def unique_id(self): """Return the unique id of this switch.""" return self._unique_id @property def is_on(self): """Return true if device is on.""" return self._state @property def should_poll(self): """Return the polling state.""" return False async def async_turn_on(self, **kwargs): """Fire the on action.""" await self._on_script.async_run(context=self._context) if self._template is None: self._state = True self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Fire the off action.""" await self._off_script.async_run(context=self._context) if self._template is None: self._state = False self.async_write_ha_state() @property def assumed_state(self): """State is assumed, if no template given.""" return self._template is None <|fim▁end|>
"""Return the name of the switch.""" return self._name
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components.""" import logging import voluptuous as vol from homeassistant.components.switch import ( ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, CONF_ENTITY_PICTURE_TEMPLATE, CONF_ICON_TEMPLATE, CONF_SWITCHES, CONF_UNIQUE_ID, CONF_VALUE_TEMPLATE, STATE_OFF, STATE_ON, ) from homeassistant.core import callback from homeassistant.exceptions import TemplateError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import async_generate_entity_id from homeassistant.helpers.reload import async_setup_reload_service from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.script import Script from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS from .template_entity import TemplateEntity _LOGGER = logging.getLogger(__name__) _VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"] ON_ACTION = "turn_on" OFF_ACTION = "turn_off" SWITCH_SCHEMA = vol.Schema( { vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_ICON_TEMPLATE): cv.template, vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template, vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template, vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA, vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA, vol.Optional(ATTR_FRIENDLY_NAME): cv.string, vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(CONF_UNIQUE_ID): cv.string, } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)} ) async def _async_create_entities(hass, config): """Create the Template switches.""" switches = [] for device, device_config in config[CONF_SWITCHES].items(): friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device) state_template = device_config.get(CONF_VALUE_TEMPLATE) icon_template = device_config.get(CONF_ICON_TEMPLATE) entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE) availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE) on_action = device_config[ON_ACTION] off_action = device_config[OFF_ACTION] unique_id = device_config.get(CONF_UNIQUE_ID) switches.append( SwitchTemplate( hass, device, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ) ) return switches async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the template switches.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) async_add_entities(await _async_create_entities(hass, config)) class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity): """Representation of a Template switch.""" def __init__( self, hass, device_id, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ): """Initialize the Template switch.""" super().__init__( availability_template=availability_template, icon_template=icon_template, entity_picture_template=entity_picture_template, ) self.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, device_id, hass=hass ) self._name = friendly_name self._template = state_template domain = __name__.split(".")[-2] self._on_script = Script(hass, on_action, friendly_name, domain) self._off_script = Script(hass, off_action, friendly_name, domain) self._state = False self._unique_id = unique_id @callback def _update_state(self, result): super()._update_state(result) if isinstance(result, TemplateError): self._state = None return self._state = result.lower() in ("true", STATE_ON) async def async_added_to_hass(self): """Register callbacks.""" if self._template is None: # restore state after startup await super().async_added_to_hass() state = await self.async_get_last_state() if state: self._state = state.state == STATE_ON # no need to listen for events else: self.add_template_attribute( "_state", self._template, None, self._update_state ) await super().async_added_to_hass() @property def name(self): """Return the name of the switch.""" return self._name @property def unique_id(self): <|fim_middle|> @property def is_on(self): """Return true if device is on.""" return self._state @property def should_poll(self): """Return the polling state.""" return False async def async_turn_on(self, **kwargs): """Fire the on action.""" await self._on_script.async_run(context=self._context) if self._template is None: self._state = True self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Fire the off action.""" await self._off_script.async_run(context=self._context) if self._template is None: self._state = False self.async_write_ha_state() @property def assumed_state(self): """State is assumed, if no template given.""" return self._template is None <|fim▁end|>
"""Return the unique id of this switch.""" return self._unique_id
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components.""" import logging import voluptuous as vol from homeassistant.components.switch import ( ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, CONF_ENTITY_PICTURE_TEMPLATE, CONF_ICON_TEMPLATE, CONF_SWITCHES, CONF_UNIQUE_ID, CONF_VALUE_TEMPLATE, STATE_OFF, STATE_ON, ) from homeassistant.core import callback from homeassistant.exceptions import TemplateError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import async_generate_entity_id from homeassistant.helpers.reload import async_setup_reload_service from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.script import Script from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS from .template_entity import TemplateEntity _LOGGER = logging.getLogger(__name__) _VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"] ON_ACTION = "turn_on" OFF_ACTION = "turn_off" SWITCH_SCHEMA = vol.Schema( { vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_ICON_TEMPLATE): cv.template, vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template, vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template, vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA, vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA, vol.Optional(ATTR_FRIENDLY_NAME): cv.string, vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(CONF_UNIQUE_ID): cv.string, } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)} ) async def _async_create_entities(hass, config): """Create the Template switches.""" switches = [] for device, device_config in config[CONF_SWITCHES].items(): friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device) state_template = device_config.get(CONF_VALUE_TEMPLATE) icon_template = device_config.get(CONF_ICON_TEMPLATE) entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE) availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE) on_action = device_config[ON_ACTION] off_action = device_config[OFF_ACTION] unique_id = device_config.get(CONF_UNIQUE_ID) switches.append( SwitchTemplate( hass, device, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ) ) return switches async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the template switches.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) async_add_entities(await _async_create_entities(hass, config)) class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity): """Representation of a Template switch.""" def __init__( self, hass, device_id, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ): """Initialize the Template switch.""" super().__init__( availability_template=availability_template, icon_template=icon_template, entity_picture_template=entity_picture_template, ) self.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, device_id, hass=hass ) self._name = friendly_name self._template = state_template domain = __name__.split(".")[-2] self._on_script = Script(hass, on_action, friendly_name, domain) self._off_script = Script(hass, off_action, friendly_name, domain) self._state = False self._unique_id = unique_id @callback def _update_state(self, result): super()._update_state(result) if isinstance(result, TemplateError): self._state = None return self._state = result.lower() in ("true", STATE_ON) async def async_added_to_hass(self): """Register callbacks.""" if self._template is None: # restore state after startup await super().async_added_to_hass() state = await self.async_get_last_state() if state: self._state = state.state == STATE_ON # no need to listen for events else: self.add_template_attribute( "_state", self._template, None, self._update_state ) await super().async_added_to_hass() @property def name(self): """Return the name of the switch.""" return self._name @property def unique_id(self): """Return the unique id of this switch.""" return self._unique_id @property def is_on(self): <|fim_middle|> @property def should_poll(self): """Return the polling state.""" return False async def async_turn_on(self, **kwargs): """Fire the on action.""" await self._on_script.async_run(context=self._context) if self._template is None: self._state = True self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Fire the off action.""" await self._off_script.async_run(context=self._context) if self._template is None: self._state = False self.async_write_ha_state() @property def assumed_state(self): """State is assumed, if no template given.""" return self._template is None <|fim▁end|>
"""Return true if device is on.""" return self._state
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components.""" import logging import voluptuous as vol from homeassistant.components.switch import ( ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, CONF_ENTITY_PICTURE_TEMPLATE, CONF_ICON_TEMPLATE, CONF_SWITCHES, CONF_UNIQUE_ID, CONF_VALUE_TEMPLATE, STATE_OFF, STATE_ON, ) from homeassistant.core import callback from homeassistant.exceptions import TemplateError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import async_generate_entity_id from homeassistant.helpers.reload import async_setup_reload_service from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.script import Script from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS from .template_entity import TemplateEntity _LOGGER = logging.getLogger(__name__) _VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"] ON_ACTION = "turn_on" OFF_ACTION = "turn_off" SWITCH_SCHEMA = vol.Schema( { vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_ICON_TEMPLATE): cv.template, vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template, vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template, vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA, vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA, vol.Optional(ATTR_FRIENDLY_NAME): cv.string, vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(CONF_UNIQUE_ID): cv.string, } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)} ) async def _async_create_entities(hass, config): """Create the Template switches.""" switches = [] for device, device_config in config[CONF_SWITCHES].items(): friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device) state_template = device_config.get(CONF_VALUE_TEMPLATE) icon_template = device_config.get(CONF_ICON_TEMPLATE) entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE) availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE) on_action = device_config[ON_ACTION] off_action = device_config[OFF_ACTION] unique_id = device_config.get(CONF_UNIQUE_ID) switches.append( SwitchTemplate( hass, device, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ) ) return switches async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the template switches.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) async_add_entities(await _async_create_entities(hass, config)) class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity): """Representation of a Template switch.""" def __init__( self, hass, device_id, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ): """Initialize the Template switch.""" super().__init__( availability_template=availability_template, icon_template=icon_template, entity_picture_template=entity_picture_template, ) self.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, device_id, hass=hass ) self._name = friendly_name self._template = state_template domain = __name__.split(".")[-2] self._on_script = Script(hass, on_action, friendly_name, domain) self._off_script = Script(hass, off_action, friendly_name, domain) self._state = False self._unique_id = unique_id @callback def _update_state(self, result): super()._update_state(result) if isinstance(result, TemplateError): self._state = None return self._state = result.lower() in ("true", STATE_ON) async def async_added_to_hass(self): """Register callbacks.""" if self._template is None: # restore state after startup await super().async_added_to_hass() state = await self.async_get_last_state() if state: self._state = state.state == STATE_ON # no need to listen for events else: self.add_template_attribute( "_state", self._template, None, self._update_state ) await super().async_added_to_hass() @property def name(self): """Return the name of the switch.""" return self._name @property def unique_id(self): """Return the unique id of this switch.""" return self._unique_id @property def is_on(self): """Return true if device is on.""" return self._state @property def should_poll(self): <|fim_middle|> async def async_turn_on(self, **kwargs): """Fire the on action.""" await self._on_script.async_run(context=self._context) if self._template is None: self._state = True self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Fire the off action.""" await self._off_script.async_run(context=self._context) if self._template is None: self._state = False self.async_write_ha_state() @property def assumed_state(self): """State is assumed, if no template given.""" return self._template is None <|fim▁end|>
"""Return the polling state.""" return False
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for switches which integrates with other components.""" import logging import voluptuous as vol from homeassistant.components.switch import ( ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, CONF_ENTITY_PICTURE_TEMPLATE, CONF_ICON_TEMPLATE, CONF_SWITCHES, CONF_UNIQUE_ID, CONF_VALUE_TEMPLATE, STATE_OFF, STATE_ON, ) from homeassistant.core import callback from homeassistant.exceptions import TemplateError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import async_generate_entity_id from homeassistant.helpers.reload import async_setup_reload_service from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.script import Script from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS from .template_entity import TemplateEntity _LOGGER = logging.getLogger(__name__) _VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"] ON_ACTION = "turn_on" OFF_ACTION = "turn_off" SWITCH_SCHEMA = vol.Schema( { vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_ICON_TEMPLATE): cv.template, vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template, vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template, vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA, vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA, vol.Optional(ATTR_FRIENDLY_NAME): cv.string, vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(CONF_UNIQUE_ID): cv.string, } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)} ) async def _async_create_entities(hass, config): """Create the Template switches.""" switches = [] for device, device_config in config[CONF_SWITCHES].items(): friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device) state_template = device_config.get(CONF_VALUE_TEMPLATE) icon_template = device_config.get(CONF_ICON_TEMPLATE) entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE) availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE) on_action = device_config[ON_ACTION] off_action = device_config[OFF_ACTION] unique_id = device_config.get(CONF_UNIQUE_ID) switches.append( SwitchTemplate( hass, device, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ) ) return switches async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the template switches.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) async_add_entities(await _async_create_entities(hass, config)) class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity): """Representation of a Template switch.""" def __init__( self, hass, device_id, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ): """Initialize the Template switch.""" super().__init__( availability_template=availability_template, icon_template=icon_template, entity_picture_template=entity_picture_template, ) self.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, device_id, hass=hass ) self._name = friendly_name self._template = state_template domain = __name__.split(".")[-2] self._on_script = Script(hass, on_action, friendly_name, domain) self._off_script = Script(hass, off_action, friendly_name, domain) self._state = False self._unique_id = unique_id @callback def _update_state(self, result): super()._update_state(result) if isinstance(result, TemplateError): self._state = None return self._state = result.lower() in ("true", STATE_ON) async def async_added_to_hass(self): """Register callbacks.""" if self._template is None: # restore state after startup await super().async_added_to_hass() state = await self.async_get_last_state() if state: self._state = state.state == STATE_ON # no need to listen for events else: self.add_template_attribute( "_state", self._template, None, self._update_state ) await super().async_added_to_hass() @property def name(self): """Return the name of the switch.""" return self._name @property def unique_id(self): """Return the unique id of this switch.""" return self._unique_id @property def is_on(self): """Return true if device is on.""" return self._state @property def should_poll(self): """Return the polling state.""" return False async def async_turn_on(self, **kwargs): <|fim_middle|> async def async_turn_off(self, **kwargs): """Fire the off action.""" await self._off_script.async_run(context=self._context) if self._template is None: self._state = False self.async_write_ha_state() @property def assumed_state(self): """State is assumed, if no template given.""" return self._template is None <|fim▁end|>
"""Fire the on action.""" await self._on_script.async_run(context=self._context) if self._template is None: self._state = True self.async_write_ha_state()