def __init__(self, x, y, text, font_name=None, size=None, color=None, center=False): """ Args: x (int): y (int): text (str): font_name (str): size (int): color (tuple): center (bool): """ super(Text, self).__init__() self.font = pygame.font.Font(font_name or Text.FONT_NAME, int(round(size or Text.SIZE))) self._text = '' self.text_surfaces = [] self.center = center self.color = color or Text.COLOR self.x = int(round(x)) self.y = int(round(y)) self.text = text
def form_valid(self, form): if not self.request.user.is_authenticated(): return super(RegisterUserAddOrderView, self).form_invalid(form) basket = get_basket(self.request) if basket.count() < 1: return super(RegisterUserAddOrderView, self).form_invalid(form) addr = self.request.POST.get('addr') address = DeliveryAddress.objects.get(user=self.request.user, pk=int(addr)) self.object = form.save(commit=False) self.object.address = str(address) self.object.ip = self.request.META['REMOTE_ADDR'] self.object.user_agent = self.request.META['HTTP_USER_AGENT'] self.object.status = STATUS_WAIT self.object.lite = False self.object.first_name = address.first_name self.object.middle_name = address.middle_name self.object.last_name = address.last_name self.object.phone = address.phone self.object.email = self.request.user.email self.object.user = self.request.user self.object.save() success_add_items = make_order_from_basket(self.object, basket) if success_add_items is not True: self.object.delete() return super(RegisterUserAddOrderView, self).form_invalid(form) send_new_order_seller(self.object) send_new_order_buyer(self.object, [self.request.user.email]) return super(RegisterUserAddOrderView, self).form_valid(form)
def __init__(self, parent): super(TopWindow, self).__init__() def createWindow(): self.setWindowTitle(self._parent.settings['top window title']) self.setMinimumSize(400, 600) self.subWindows = [] def createMainLayout(): self._mdi_area = QtGui.QMdiArea() self.setCentralWidget(self._mdi_area) def createMenu(): if self._parent.settings and \ 'TopMenuGenerator' in self._parent.settings: self._parent.settings['TopMenuGenerator'](self) def createSatusBar(): self.status = QtGui.QStatusBar(self) self.setStatusBar(self.status) self._parent = parent createWindow() createMainLayout() createMenu() createSatusBar()
def configure_pipeline(self): """ The default binding keys, set in `default_binding_key` attribute, may be overridden in the pipeline configuration. """ self.input_queue['binding_keys'] = [self.default_binding_key] super(BaseParser, self).configure_pipeline()
def __init__(self, address, root): super(ZkClient,self).__init__(address) self.root = root self.jobs_root = self.root + "/jobs" self.master_root = self.root + "/masters" self.workers_root = self.root + "/workers" self.start()
def __init__(self, address, root): super(ZkClient, self).__init__(address) self.root = root self.jobs_root = self.root + "/jobs" self.master_root = self.root + "/masters" self.workers_root = self.root + "/workers" self.start()
def __init__(self, **kwargs): assert self.event_type in ('event', 'bl', 'hifreq') super(BaseParser, self).__init__(**kwargs) self.set_configuration() # the attribute is overridden in order to supply each parser # with an adjusted value of the prefetch count from its # config self.prefetch_count = self.config['prefetch_count']
def __init__(self, value, wp_item, adaptor): """Initialize WordPress list attribute from Evernoten note. :type wp_item: wordpress.WordPressItem :type adaptor: EvernoteApiWrapper """ super(WpEnListAttribute, self).__init__('', wp_item, adaptor) self._value = self._parse_values_from_string(value)
def __init__(self, base_url=PUBLIC_API_URL): """Initialize the object :param base_url: Override the end-point URL """ self.base_url = base_url super(SpecimensClient, self).__init__() self.specimen_list = []
def save(self): self.create_or_update_release() if not self.is_html: self.content_html = markdown(self.content, ['codehilite']) super(Blog, self).save() for tag in self.tags.all(): p, created = Tag.objects.get_or_create(name=tag.name, create_time=tag.create_time) if created: self.tags.add(p)
def __init__(self, parent=None, input=None): super(Button, self).__init__(parent=None) self.input_type = input path = resources.getInputPath(self.input_type) self.current_item = None read_data = read.Data(file=path) self.data = read_data.getData() self.current_item = None self.setupUi() self.getCurrentButton()
def __init__(self): super(DatabaseBook, self).__init__() #Variable used to hold a strings required to connect to database self.connection = mysql.connector.connect(user='******', password='******', db='contact_book', host='localhost') #Variable of type cursor required to execute MySQL queries in python self.db_cursor = self.connection.cursor()
def preinit_hook(self): # called after instance creation, before __init__() # (see: n6.base.queue.QueuedBase.__new__()) # some unit tests are over-zealous about patching super() from __builtin__ import super if self.default_binding_key is not None: # (not for an abstract class) assert 'input_queue' in vars(self) # ensured by QueuedBase.__new__() self.input_queue["queue_name"] = self.default_binding_key self.input_queue["binding_keys"] = self.make_binding_keys() super(BaseParser, self).preinit_hook()
def __init__(self, node, wp_item, adaptor): """Initialize WordPress content attribute from Evernoten note. Do not render the content on initialization, only on read. Do scan the a-tags in the content and update the underlying item ref-items list. :type node: xml.etree.ElementTree.Element :type wp_item: wordpress.WordPressItem :type adaptor: EvernoteApiWrapper """ super(WpEnContent, self).__init__('', wp_item, adaptor) self._cached_rendered_content = None self._content_node = node self._find_ref_items()
def __init__(self, **kwargs): super(QueuedBase, self).__init__(**kwargs) LOGGER.debug('input_queue: %r', self.input_queue) LOGGER.debug('output_queue: %r', self.output_queue) self._connection = None self._channel_in = None self._channel_out = None self._num_queues_bound = 0 self._declared_output_exchanges = set() self.output_ready = False self.waiting_for_reconnect = False self._closing = False self._consumer_tag = None self._conn_params_dict = self.get_connection_params_dict()
def post(self): self.check_currency_id() self._check_payment_ids_currency() current_inv_residual = defaultdict(list) for rec in self: residual = rec.to_pay_move_line_ids.mapped(lambda p: { p.id: rec.partner_type == 'supplier' and abs(p.amount_residual_currency) or p.amount_residual_currency}) current_inv_residual[rec.id].extend([x for x in residual]) exchanges_entries = self.search( [('partner_id', '=', rec.partner_id.id), ('state', '=', 'posted'), ('to_pay_move_line_ids', 'in', rec.to_pay_move_line_ids.ids)]).filtered( lambda p: p.exchange_difference_aml_id).mapped('exchange_difference_aml_id').filtered( lambda m: not m.reconciled) rec.to_pay_move_line_ids = exchanges_entries | rec.to_pay_move_line_ids super(AccountPaymentGroup, rec).post() if rec.currency2_id.id == rec.inv_currency_id.id != rec.currency_id.id: rec._check_difference_exchange_rate(current_inv_residual)
def __init__(self, objectified_element=None, specimen_record_xml=None): """Initialize Specimen object Either the specimen_record_xml or the objectified_element parameter must be provided. :param objectified_element: (optional) Objectified XML returned from BOLD specimen end-point :param specimen_record_xml: (optional) XML returned from BOLD specimen end-point""" if isinstance(specimen_record_xml, __builtin__.str): obj = objectify.fromstring(specimen_record_xml) elif isinstance(objectified_element, objectify.ObjectifiedElement): obj = objectified_element elif objectified_element is None and specimen_record_xml is None: raise ValueError() self.record = obj self.sequence = None self.tracefiles = None super(Specimen, self).__init__()
def get_context_data(self, **kwargs): kwargs['object'] = self.object context = super(ProductDetail, self).get_context_data(**kwargs) object_type = ContentType.objects.get_for_model(self.object) param = ProductParameterValue.objects.filter(content_type__pk=object_type.id, object_id=self.object.id).order_by( 'parameter__category','parameter__name') context['parameters'] = param return context
def dispatch(self, request, *args, **kwargs): obj = get_object_or_404(Order, pk=kwargs['pk']) if not request.user.is_authenticated(): if obj.session_key != get_session_from_request(request): raise Http404 else: if not request.user == obj.user and not request.user.is_superuser: raise Http404 return super(CurrentUserOrderAccess, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs): kwargs['object'] = self.object context = super(ProductDetail, self).get_context_data(**kwargs) object_type = ContentType.objects.get_for_model(self.object) param = ProductParameterValue.objects.filter(content_type__pk=object_type.id, object_id=self.object.id).order_by('parameter__category', 'parameter__name') context['parameters'] = param return context
def get_connection_params_dict(cls): params_dict = super(BaseParser, cls).get_connection_params_dict() config = Config(required={ cls.rabbitmq_config_section: ("heartbeat_interval_parsers", ) }) queue_conf = config[cls.rabbitmq_config_section] params_dict['heartbeat_interval'] = int( queue_conf['heartbeat_interval_parsers']) return params_dict
def __init__(self, x1, y1, x2, y2, width=None, color=None): """ Args: x1 (int): y1 (int): x2 (int): y2 (int): width (int): color (tuple): """ super(Line, self).__init__() self.start_pos = (int(round(x1)), int(round(y1))) self.end_pos = (int(round(x2)), int(round(y2))) self.width = int(round(width or Line.WIDTH)) self.color = color or Line.COLOR
def __init__(self, x, y, image_path, scale=1): """ Args: x (int): y (int): image_path (str): scale (int): """ super(Image, self).__init__() self.x = int(round(x)) self.y = int(round(y)) self.image = pygame.image.load(image_path).convert() new_size = (int(round(self.image.get_width() * scale)), int(round(self.image.get_height() * scale))) self.image = pygame.transform.smoothscale( self.image, new_size).convert()
def save(self): from microscope.settings import BASE_DIR job_save_log = BASE_DIR+"/gather/script/job_save_log.py" outputfile = open(job_save_log,"a") outputfile.write("#") outputfile.write(self.job_name) outputfile.write("\t") outputfile.write(self.placeholders) outputfile.write("\t") outputfile.write(str(self.thread_num)) outputfile.write("\t") outputfile.write(str(self.create_date)) outputfile.write("\n") outputfile.write(self.get_rules) outputfile.write("\n") outputfile.write("\n") outputfile.close() super(Job, self).save()
def default_get(self, fields): res = super(AccountPaymentGroup, self).default_get(fields) if 'currency_id' in res: res.update({ 'manual_currency_rate': 1, 'currency_rate': 1, 'currency2_id': res['currency_id'] }) return res
def __init__(self, x, y, w, h, text='', base_color=None, active_color=None, inactive_color=None, active_tcolor=None, inactive_tcolor=None, font_name=None, font_size=None, border_size=None): """ Args: x (int): y (int): w (int): h (int): text (str): base_color (tuple): active_color (tuple): inactive_color (tuple): active_tcolor (tuple): inactive_tcolor (tuple): font_name (str): font_size (int): border_size (int): """ super(InputBox, self).__init__() self.base_color = base_color or InputBox.COLOR_BASE self.active_color = active_color or InputBox.COLOR_ACTIVE self.inactive_color = inactive_color or InputBox.COLOR_INACTIVE self.active_tcolor = active_tcolor or InputBox.COLOR_TEXT_ACTIVE self.inactive_tcolor = inactive_tcolor or InputBox.COLOR_TEXT_INACTIVE self.color = self.inactive_color self.tcolor = self.inactive_tcolor self.font_size = int(round(font_size or InputBox.FONT_SIZE)) self.font = pygame.font.Font(font_name or InputBox.FONT_NAME, self.font_size) self.default_text = text self.text = text self.txt_surface = self.font.render(text, True, self.tcolor) self.border_size = int(round(border_size or InputBox.BORDER_SIZE)) self.rect = pygame.Rect(int(round(x)), int(round(y)), int(round(w)), int(round(h))) self.active = False self.done_action = False self.mirgins = [int(round(h)) / 2 - self.font.get_height() / 2, 0.4 * self.font_size] self.limit = 16
def __new__(cls, **kwargs): """ Create and pre-configure an instance. Normally, this special method should not be overridden in subclasses. (If you really need that please *extend* it by overridding and calling with super()). The method causes that immediately after creating of a QueuedBase-derived class instance -- before calling __init__() -- the following operations are performed on the instance: 1) (re)-making the `input_queue` and `output_queue` attributes as instance ones -- by deep-copying them (so they are exclusively owned by the instance and not by the class or any of its superclasses); note: whereas `input_queue` (both as the class attribute and the resultant instance attribute) should always be a dict (unless None), the `output_queue` *instance* attribute must always be a list of dicts (unless None) -- i.e.: if the `output_queue` *class* attribute is a dict the resultant *instance* attribute will be a one-element list (containing a deep copy of that dict); 2) the get_arg_parser() method is called to obtain the argument parser object; 3) the parse_known_args() method of the obtained argument parser is called and the obtained command-line argument container (produced by the argument parser as a argparse.Namespace instance) is set as the `cmdline_args` attribute. 4) the preinit_hook() method is called (see its docs...). """ # some unit tests are over-zealous about patching super() from __builtin__ import super self = super(QueuedBase, cls).__new__(cls, **kwargs) if cls.input_queue is not None and not isinstance(self.input_queue, dict): raise TypeError('The `input_queue` class attribute must be a dict or None') self.input_queue = copy.deepcopy(cls.input_queue) if cls.output_queue is not None and not ( isinstance(self.output_queue, dict) or isinstance(self.output_queue, list) and all( isinstance(item, dict) for item in self.output_queue)): raise TypeError('The `output_queue` class attribute must be ' 'a dict or a list of dicts, or None') output_queue = copy.deepcopy(cls.output_queue) if isinstance(output_queue, dict): output_queue = [output_queue] self.output_queue = output_queue self.cmdline_args = self.parse_cmdline_args() self.preinit_hook() return self
def __init__(self, x, y, w, h, text='', text_color=None, regular=None, hover=None, click=None, border_color=None, border_size=None, fnc=None, font_name=None, font_size=None): """ Args: x (int): y (int): w (int): h (int): text (str): text_color (tuple): regular (tuple): hover (tuple): click (tuple): border_color (tuple): border_size (int): fnc (function): font_name (str): font_size (int): """ super(Button, self).__init__() self.rect = pygame.Rect(int(round(x)), int(round(y)), int(round(w)), int(round(h))) self.text = text self.text_color = text_color or Button.COLOR_SECONDARY self.font = pygame.font.Font(font_name or Button.FONT_NAME, int(round(font_size or Button.FONT_SIZE))) self.txt_surface = self.font.render(self.text, True, self.text_color) self.regular = regular or Button.COLOR_REGULAR self.hover = hover or Button.COLOR_HOVER self.click = click or Button.COLOR_CLICK self.border_color = border_color or Button.COLOR_SECONDARY self.border_size = int(round(border_size or 0)) self.fnc = fnc
def form_valid(self, form): if not self.request.user.is_authenticated() and not settings.SHOP_ANONYMOUS_ORDERS: return super(AnonymousUserAddOrderView, self).form_invalid(form) basket = get_basket(self.request) if basket.count() < 1: return super(AnonymousUserAddOrderView, self).form_invalid(form) self.object = form.save(commit=False) self.object.ip = self.request.META['REMOTE_ADDR'] self.object.user_agent = self.request.META['HTTP_USER_AGENT'] self.object.status = STATUS_WAIT self.object.lite = True self.object.session_key = get_session_from_request(self.request) self.object.save() success_add_items = make_order_from_basket(self.object, basket) if success_add_items is not True: self.object.delete() return super(AnonymousUserAddOrderView, self).form_invalid(form) send_new_order_seller(self.object) send_new_order_buyer(self.object, [self.object.email]) return super(AnonymousUserAddOrderView, self).form_valid(form)
def postprocess_parsed(self, data, parsed, total, item_no): parsed = super(BlackListParser, self).postprocess_parsed(data, parsed, total, item_no) parsed.update({ "_bl-series-id": data["properties.message_id"], "_bl-series-total": total, "_bl-series-no": item_no, "_bl-time": data['properties.timestamp'], "_bl-current-time": self._get_bl_current_time(data, parsed) }) return parsed
def __init__(self, x, y, w, h, color=None, border_color=None, border_size=None): """ Args: x (int): y (int): w (int): h (int): color (tuple): border_color (tuple): border_size (int): """ super(Container, self).__init__() self.rect = pygame.Rect(int(round(x)), int(round(y)), int(round(w)), int(round(h))) self.color = color or Container.COLOR_BASE self.border_color = border_color or Container.COLOR_SECONDARY self.border_size = int(round(border_size or Container.BORDER_SIZE))
def super(type=Omitted, instance=Omitted): """Variant of :func:`python:super` that mimics the behavior in Python 3 with no arguments.""" if type is Omitted: frame = currentframe(1) instance = frame.f_locals[frame.f_code.co_varnames[0]] for type in getmro(builtins.type(instance)): for var in vars(type).itervalues(): if not isfunction(var): continue if var.__code__ is frame.f_code: break else: continue break else: raise SystemError('super(): no arguments') if instance is Omitted: return builtins.super(type) return builtins.super(type, instance)
def add_contact(self): #Tuple variable that holds return value for add_contact of abstract super class AddressBook contact_data = super(DatabaseBook, self).add_contact() #String variable that holds MySQL query for inserting a row into db sql_add_contact = ( "INSERT INTO contact_book.contacts(first_name, last_name, phone_number, email) VALUES(%s, %s, %s, %s)" ) self.db_cursor.execute(sql_add_contact, contact_data) self.connection.commit() print("\nContact Added Successfully")
def __init__(self, node, wp_item, adaptor): """Initialize WordPress link attribute from Evernoten note. The node is expected to contain only a link tag (a href). :type node: xml.etree.ElementTree.Element :type wp_item: wordpress.WordPressItem :type adaptor: EvernoteApiWrapper """ if '' != node.text: raise NoteParserError('Link "%s" should not have text' % (ET.tostring(node))) if not (node.tail is None or '' == node.tail): raise NoteParserError('Link "%s" should not have tail' % (ET.tostring(node))) if 0 == len(node): logger.warn('No link found for attribute') self._href = None super(WpEnLinkAttribute, self).__init__('', wp_item, adaptor) return if 1 != len(node): raise NoteParserError('Link "%s" should have one child' % (ET.tostring(node))) a_node = node[0] if 'a' != a_node.tag: raise NoteParserError('Link "%s" should have one <a> child' % (ET.tostring(node))) if not (a_node.tail is None or '' == a_node.tail): raise NoteParserError('Link "%s" should not have tail' % (ET.tostring(a_node))) self._href = a_node.get('href') if not self._href: raise NoteParserError('Link "%s" has no href' % (ET.tostring(a_node))) self._text = a_node.text self._ref_item = None super(WpEnLinkAttribute, self).__init__(self._href, wp_item, adaptor)
def form_valid(self, form): self.object = form.save(commit=False) self.object.save() try: recipients = [self.request.user.email] mail_dict = {'order': self.object} if self.object.status == STATUS_PROCESS: subject = 'emails/status_process_subject.txt' body = 'emails/status_process_body.txt' if self.object.status == STATUS_SENT: subject = 'emails/status_sent_subject.txt' body = 'emails/status_sent_body.txt' send_template_mail(subject,body,mail_dict,recipients) except: pass return super(OrderStatusChange, self).form_valid(form)
def delete_contact(self): #String variable that holds return value for search_contacts of abstract super class AddressBook key = super(DatabaseBook, self).search_contacts() #String variable that holds MySQL query for deleting a row from db if arguments are satisfied sql_delete_contact = ( "DELETE FROM contact_book.contacts WHERE first_name = '%s'") % key self.db_cursor.execute(sql_delete_contact) if self.db_cursor.rowcount != None: self.connection.commit() print("Successfully Deleted " + key) else: print("\nContact " + key + " was not found")
def postprocess_parsed(self, data, parsed, total, item_no): parsed = super(AggregatedEventParser, self).postprocess_parsed(data, parsed, total, item_no) group_id_components = ([self.group_id_components] if isinstance( self.group_id_components, basestring) else self.group_id_components) component_values = [ self._get_component_value(parsed, name) for name in group_id_components ] if all(v is None for v in component_values): raise ValueError('None of the group id components ({})' 'is set to a non-None value (in {!r})'.format( ', '.join(group_id_components), parsed)) parsed['_group'] = '_'.join(map(ascii_str, component_values)) return parsed
def form_valid(self, form): self.object = form.save(commit=False) self.object.save() try: recipients = [self.request.user.email] mail_dict = {'order': self.object} subject = body = '' if self.object.status == STATUS_PROCESS: subject = 'emails/status_process_subject.txt' body = 'emails/status_process_body.txt' if self.object.status == STATUS_SENT: subject = 'emails/status_sent_subject.txt' body = 'emails/status_sent_body.txt' send_template_mail(subject, body, mail_dict, recipients) except: pass return super(OrderStatusChange, self).form_valid(form)
def format(self, record): '''Appends the level specified color to the logging output.''' levelname = record.levelname if levelname in self.COLOR_TO_LEVEL_MAPPING: record.levelname = ( SET_ATTRIBUTE_MODE % RESET_ATTRIBUTE_MODE ) + ( SET_ATTRIBUTE_MODE % COLOR['foreground'][ self.COLOR_TO_LEVEL_MAPPING[levelname] ] ) + levelname + (SET_ATTRIBUTE_MODE % RESET_ATTRIBUTE_MODE) ''' Take this method type by another instance of this class via \ introspection. ''' return builtins.getattr(builtins.super( self.__class__, self ), inspect.stack()[0][3])(record)
def stop(self, *arguments, **keywords): # # ''' Closes all created web views. Note that in case of using the \ default installed browser fall-back this instance couldn't be \ destroyed. Examples: >>> Browser('google.de').stop() # doctest: +ELLIPSIS Object of "Browser" with url "http://google.de" in 800 pixel... ''' # # python3.5 # # pass reason, keywords = Dictionary(content=keywords).pop_from_keywords( name='reason', default_value='') # # if self.__dict__.get('window') is not None: if self.gui_toolkit == 'qt': self.window.closeAllWindows() if not (builtins.len(arguments) or reason): reason = 'clicking qt close button' elif self.gui_toolkit == 'gtk': self._gtk_close = True if builtins.len(arguments) and builtins.isinstance( arguments[0], gtk.Window ): reason = 'clicking gtk close button' else: ''' NOTE: We got a close trigger from another thread as \ where the main gtk loop is present. We have to wait \ until gtk has finished it's closing procedures. ''' self._close_gtk_windows_lock.acquire() __logger__.info('All "%s" windows closed.', self.gui_toolkit) '''Take this method type by the abstract class via introspection.''' return builtins.getattr( builtins.super(self.__class__, self), inspect.stack()[0][3] )(*arguments, reason=reason, **keywords)
def __new__( cls, class_name, base_classes, class_scope, *arguments, **keywords ): # # ''' Triggers if a new instance is created. Set the default name for \ an orm instance. **class_name** - Name of class to create. **base_classes** - A tuple of base classes for class to create. **class_scope** - A dictionary object to define properties and \ methods for new class. Additional arguments and keywords are forwarded to python's \ native "builtins.type" function. Returns the newly created class. Examples: >>> if sys.version_info.major < 3: ... class UserModel: __metaclass__ = Model ... else: ... exec('class UserModel(metaclass=Model): pass') ''' from boostnode.extension.native import String class_scope['__table_name__'] = String( class_name ).camel_case_to_delimited.content class_scope['__tablename__'] = class_scope['__table_name__'] class_scope['db_table'] = class_scope['__table_name__'] '''Take this method name via introspection.''' return builtins.getattr( builtins.super(Model, cls), inspect.stack()[0][3] )(cls, class_name, base_classes, class_scope, *arguments, **keywords)
def search_contacts(self): #String variable holds return value from overidden to_string method string = self.to_string() #String variable that holds return value for search_contacts of abstract super class AddressBook key = super(DatabaseBook, self).search_contacts() #String variable for MySQL query to display a row from db if arguments are satisfied sql_search_contacts = ( "SELECT * FROM contact_book.contacts WHERE first_name = '%s'" ) % key self.db_cursor.execute(sql_search_contacts) #List variable holds what db_cursor recieved upon execution data = self.db_cursor.fetchall() if self.db_cursor.rowcount != None: for column in data: print(string % (column[0], column[1], column[2], column[3])) else: print("\nNo Contacts Found")
def get( self, taxon=None, ids=None, bins=None, containers=None, institutions=None, researchers=None, geo=None, timeout=5 ): """Fetch specimen that match the provided criteria and assign it to self.specimen_list and return the list""" result = super(SpecimensClient, self).get( { "taxon": taxon, "ids": ids, "bin": bins, "container": containers, "institutions": institutions, "researchers": researchers, "geo": geo, "format": "xml", }, timeout=timeout, ) bold_specimens = objectify.fromstring(result) for record in bold_specimens.record: self.specimen_list.append(Specimen(record)) return self.specimen_list
def _amount_all(self): super(SaleOrder, self)._amount_all() def reset_coupon(): vals['coupon_discount_percentage'] = 0.0 vals['coupon_discount_percentage_amount'] = 0.0 vals['coupon_discount_fix'] = 0.0 vals['coupon_id'] = None return vals # compute to apply loyalty card for order in self: amount_total = order.amount_total vals = { 'amount_total': amount_total } if self.card_id and self.card_id.partner_id: order.partner_id = self.card_id.partner_id card = self.env['corefory.loyalty.card']._get_card(order.partner_id.id) if card: points = 0 remain_points = 0 remain_amount = 0 # if (order.changed_point == 0) : # is_convert, amount = card.convert_point_to_amount(card.convertible_point,card) # else: # is_convert, amount = card.convert_point_to_amount(order.changed_point,card) is_convert, convertible_amount = card.convert_point_to_amount(card.convertible_point, card) convertible_point = card.convertible_point if((order.amount_total - convertible_amount) > 0): amount_total = (order.amount_total - convertible_amount) else: amount_total = 0 remain_amount = convertible_amount - order.amount_total remain_is_converted, remain_points = card.convert_amount_to_point_base(remain_amount, card) # if (is_convert) : # is_converted, points = card.convert_amount_to_point_base(amount,card) # card.convertible_point = card.convertible_point - points vals['amount_total'] = amount_total vals['changed_point'] = convertible_point - remain_points vals['changed_money'] = convertible_amount - remain_amount if(order.apply_coupon): Coupon_object = self.env['corefory.coupon'] coupon = Coupon_object.get_coupon([('code','=',order.coupon_code)]) if(coupon): if(coupon.applied_on == '3_global'): coupon_discount_percentage = coupon.percentage coupon_discount_percentage_amount = 0.0 coupon_discount_fix = coupon.fixed_price if(coupon.compute_price == 'percentage'): coupon_discount_percentage_amount = ( amount_total*coupon_discount_percentage/100 ) amount_total = amount_total - coupon_discount_percentage_amount elif(coupon.compute_price == 'fixed'): amount_total = amount_total - coupon_discount_fix if(amount_total < 0) : amount_total = 0.0 vals['amount_total'] = amount_total vals['coupon_discount_percentage'] = coupon_discount_percentage vals['coupon_discount_percentage_amount'] = coupon_discount_percentage_amount vals['coupon_discount_fix'] = coupon_discount_fix vals['coupon_id'] = coupon.id elif(coupon.applied_on == '2_product_category' or coupon.applied_on=='1_product'): amount_need_discount = 0 amount_donot_need_discount = 0 number_product_can_apply = 0 for line in order.order_line: if(coupon.applied_on == '2_product_category'): if(line.product_id.categ_id.id == coupon.categ_id.id): amount_need_discount += line.price_total number_product_can_apply += 1 else: amount_donot_need_discount += line.price_total elif(coupon.applied_on=='1_product'): if (line.product_id.id in coupon.product_ids.ids): amount_need_discount += line.price_total number_product_can_apply += 1 else: amount_donot_need_discount += line.price_total if(coupon.number_product_can_apply <= number_product_can_apply): coupon_discount_percentage = coupon.percentage coupon_discount_percentage_amount = 0.0 coupon_discount_fix = coupon.fixed_price if (coupon.compute_price == 'percentage'): coupon_discount_percentage_amount = (amount_need_discount * coupon_discount_percentage / 100) amount_need_discount = amount_need_discount - coupon_discount_percentage_amount elif (coupon.compute_price == 'fixed'): amount_need_discount = amount_need_discount - coupon_discount_fix if (amount_need_discount < 0): amount_need_discount = 0.0 vals['amount_total'] = amount_need_discount + amount_donot_need_discount vals['coupon_discount_percentage'] = coupon_discount_percentage vals['coupon_discount_percentage_amount'] = coupon_discount_percentage_amount vals['coupon_discount_fix'] = coupon_discount_fix vals['coupon_id'] = coupon.id else: vals = reset_coupon() else: vals = reset_coupon() order.update(vals)
def __init__(self, **kwargs): super(TabDataParser, self).__init__(**kwargs)
def form_valid(self, form): self.object = form.save(commit=False) self.object.save() return super(EditProductFurniture, self).form_valid(form)
def __init__(self, **kwargs): super(AggregatedEventParser, self).__init__(**kwargs)
def get_context_data(self, **kwargs): context = super(EditProductFurniture, self).get_context_data(**kwargs) context['title_line'] = _('edit form') return context
def closeEvent(self, event): self._parent.close() return super(TopWindow, self).closeEvent(event)
def __init__(self): super(RestrictedBandAjaxForm, self).__init__() self.form = BandForm()
def dispatch(self, request, *args, **kwargs): obj = get_object_or_404(Order, pk=kwargs['pk']) if not request.user == obj.user and not request.user.is_superuser: raise Http404 return super(CurrentUserOrderAccess, self).dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): if self.request.user.basket_.count() < 1: return HttpResponseRedirect('/') return super(BasketView, self).dispatch(request, *args, **kwargs)
def __init__(self, value, wp_item, adaptor, *args, **kwargs): """Initialize WordPress attribute from Evernoten note.""" super(WpEnAttribute, self).__init__(value, wp_item, *args, **kwargs) self._adaptor = adaptor
def get_context_data(self, **kwargs): context = super(ShopSearch, self).get_context_data(**kwargs) context['search'] = True if self.q is not None: context['search_string'] = self.q return context
def get_context_data(self, **kwargs): context = super(ShopCategory, self).get_context_data(**kwargs) context['category'] = self.category context['sort'] = self.sort return context