When a tracking category is serialized as part of an invoice it may only have a single
 option, and the Options tag is omitted
426706
def to_xml_for_invoice_messages(b = Builder::XmlMarkup.new)
      b.TrackingCategory {
        b.TrackingCategoryID self.tracking_category_id unless tracking_category_id.nil?
        b.Name self.name
        b.Option self.options.is_a?(Array) ? self.options.first : self.options.to_s
      }
    end
1284221
private function addInvoice($trans, $invoice_no, $ref_no, $options)
    {
        $trans->addChild('InvoiceNo', $invoice_no);
        $trans->addChild('RefNo', $ref_no ?: $invoice_no);
        if ($options['merchant']) {
            $trans->addChild('OperatorID', $options['merchant']);
        }
        if ($options['description']) {
            $trans->addChild('Memo', $options['description']);
        }
    }
376669
def to_s(filter = nil, version = nil)
      payload = PayloadFormatter.log(@type, @payload)
      log_msg = "#{super(filter, version)} #{trace} #{@type}"
      log_msg += " #{payload}" if payload
      log_msg += " from #{id_to_s(@from)}" if filter.nil? || filter.include?(:from)
      log_msg += ", target #{ids_to_s(@target)}" if @target && (filter.nil? || filter.include?(:target))
      log_msg += ", scope #{@scope.inspect}" if @scope && (filter.nil? || filter.include?(:scope))
      log_msg += ", fanout" if (filter.nil? || filter.include?(:fanout)) && fanout?
      log_msg += ", reply_to #{id_to_s(@reply_to)}" if @reply_to && (filter.nil? || filter.include?(:reply_to))
      log_msg += ", tags #{@tags.inspect}" if @tags && !@tags.empty? && (filter.nil? || filter.include?(:tags))
      log_msg += ", persistent" if @persistent && (filter.nil? || filter.include?(:persistent))
      log_msg += ", tries #{tries_to_s}" if @tries && !@tries.empty? && (filter.nil? || filter.include?(:tries))
      log_msg += ", payload #{@payload.inspect}" if filter && filter.include?(:payload)
      log_msg
    end
70157
def get_indic_positional_category_property(value, is_bytes=False):
    """"""

    if PY35:
        obj = unidata.ascii_indic_positional_category if is_bytes else unidata.unicode_indic_positional_category
        alias_key = 'indicpositionalcategory'
    else:
        obj = unidata.ascii_indic_matra_category if is_bytes else unidata.unicode_indic_matra_category
        alias_key = 'indicmatracategory'

    if value.startswith('^'):
        negated = value[1:]
        value = '^' + unidata.unicode_alias[alias_key].get(negated, negated)
    else:
        value = unidata.unicode_alias[alias_key].get(value, value)

    return obj[value]
724355
function (invoiceitem, cb) {

		Invoiceitem.findOrCreate(invoiceitem.id, invoiceitem)
	    .exec(function (err, foundInvoiceitem){
	      if (err) return cb(err);
	      if (foundInvoiceitem.lastStripeEvent > invoiceitem.lastStripeEvent) return cb(null, foundInvoiceitem);
	      if (foundInvoiceitem.lastStripeEvent == invoiceitem.lastStripeEvent) return Invoiceitem.afterStripeInvoiceitemUpdated(foundInvoiceitem, function(err, invoiceitem){ return cb(err, invoiceitem)});
	      Invoiceitem.update(foundInvoiceitem.id, invoiceitem)
	      .exec(function(err, updatedInvoiceitem){
	      	if (err) return cb(err);
	      	if (!updatedInvoiceitem) return cb(null,null);
	      	Invoiceitem.afterStripeInvoiceitemUpdated(updatedInvoiceitem[0], function(err, invoiceitem){
	      		cb(err, invoiceitem);
	      	});
	      });
	    });
	}
1152346
private void mapSerialFieldTagImplsToFieldDocImpls(FieldDocImpl spfDoc,
                                                       DocEnv env,
                                                       ClassSymbol def) {
        Names names = def.name.table.names;
        for (SerialFieldTag tag : spfDoc.serialFieldTags()) {
            if (tag.fieldName() == null || tag.fieldType() == null) // ignore malformed @serialField tags
                continue;

            Name fieldName = names.fromString(tag.fieldName());

            // Look for a FieldDocImpl that is documented by serialFieldTagImpl.
            for (Symbol sym : def.members().getSymbolsByName(fieldName)) {
                if (sym.kind == VAR) {
                    VarSymbol f = (VarSymbol) sym;
                    FieldDocImpl fdi = env.getFieldDoc(f);
                    ((SerialFieldTagImpl) (tag)).mapToFieldDocImpl(fdi);
                    break;
                }
            }
        }
    }
418734
def to_xml
      raise RuntimeError, "Empty cart" if self.empty?

      xml = Builder::XmlMarkup.new
      xml.instruct!
      @xml = xml.tag!('checkout-shopping-cart', :xmlns => "http://checkout.google.com/schema/2") {
        xml.tag!("shopping-cart") {
          xml.items {
            @contents.each { |item|
              xml.item {
                if item.key?(:item_id)
                  xml.tag!('merchant-item-id', item[:item_id])
                end
                xml.tag!('item-name') {
                  xml.text! item[:name].to_s
                }
                xml.tag!('item-description') {
                  xml.text! item[:description].to_s
                }
                xml.tag!('unit-price', :currency => (item[:currency] || 'USD')) {
                  xml.text! item[:price].to_s
                }
                xml.quantity {
                  xml.text! item[:quantity].to_s
                }
              }
            }
          }
          unless @merchant_private_data.empty?
            xml.tag!("merchant-private-data") {
              @merchant_private_data.each do |key, value|
                xml.tag!(key, value)
              end
            }
          end
        }
        xml.tag!('checkout-flow-support') {
          xml.tag!('merchant-checkout-flow-support') {
            xml.tag!('edit-cart-url', @edit_cart_url) if @edit_cart_url
            xml.tag!('continue-shopping-url', @continue_shopping_url) if @continue_shopping_url

            xml.tag!("request-buyer-phone-number", false)

            # TODO tax-tables
            xml.tag!("tax-tables") {
              xml.tag!("default-tax-table") {
                xml.tag!("tax-rules") {
                  xml.tag!("default-tax-rule") {
                    xml.tag!("shipping-taxed", false)
                    xml.tag!("rate", "0.00")
                    xml.tag!("tax-area") {
                      xml.tag!("world-area")
                    }
                  }
                }
              }
            }

            xml.tag!('shipping-methods') {
              if @shipping_methods
                @shipping_methods.each { |method|
                  xml.tag!("pickup", :name => method[:name]) {
                    xml.tag!('price', method[:price], :currency => method[:currency] || 'USD')
                  }
                }
              end
            }
            
            
          }
        }
      }
      @xml.dup
    end
580481
function(apiKey, pieceTitle, categories,
        fromAddress, toAddress, ccAddress, bccAddress, subject, textBody,
        htmlBody, contentType, mergeContext) {}
215040
protected function removeEmptyShipping()
    {
        $invoiceSettings = $this->config->getInvoiceSettings();
        if (!$invoiceSettings['sendEmptyShipping']) {
            $this->invoice[Tag::Customer][Tag::Invoice][Tag::Line] = array_filter($this->invoice[Tag::Customer][Tag::Invoice][Tag::Line],
                function ($line) {
                    return $line[Meta::LineType] !== Creator::LineType_Shipping || !Number::isZero($line[Tag::UnitPrice]);
                });
        }
    }
593272
function (dom, kb, tracker, superIssue) {
      var form = dom.createElement('div') // form is broken as HTML behaviour can resurface on js error
      var stateStore = kb.any(tracker, WF('stateStore'))

      var sendNewIssue = function () {
        titlefield.setAttribute('class', 'pendingedit')
        titlefield.disabled = true
        var sts = []
        var issue

        var expandTemplate = function (template) {
          const now = new $rdf.Literal(new Date())
          const nnnn = '' + (new Date()).getTime()
          let YYYY = now.value.slice(0, 4)
          var MM = now.value.slice(5, 7)
          var DD = now.value.slice(8, 10)
          return template.replace('{N}', nnnn).replace('{YYYY}', YYYY).replace('{MM}', MM).replace('{DD}', DD)
        }
        // Where to store the new issue?
        var template = kb.anyValue(tracker, WF('issueURITemplate'))
        var issueDoc
        if (template) { // Does each issue do in its own file?
          template = $rdf.uri.join(template, stateStore.uri) // Template is relative
          issue = kb.sym(expandTemplate(template))
        } else {
          issue = kb.sym(stateStore.uri + '#' + 'Iss' + timestring())
        }
        issueDoc = issue.doc()

        // Basic 9 core predicates are stored in the main stateStore

        var title = kb.literal(titlefield.value)
        sts.push(new $rdf.Statement(issue, WF('tracker'), tracker, stateStore))
        sts.push(new $rdf.Statement(issue, DC('title'), title, stateStore))
        sts.push(new $rdf.Statement(issue, DCT('created'), new Date(), stateStore))
        var initialStates = kb.each(tracker, WF('initialState'))
        if (initialStates.length === 0) console.log('This tracker has no initialState')
        for (var i = 0; i < initialStates.length; i++) {
          sts.push(new $rdf.Statement(issue, ns.rdf('type'), initialStates[i], stateStore))
        }
        if (superIssue) sts.push(new $rdf.Statement(superIssue, WF('dependent'), issue, stateStore))

        // Other things are stores in the individual
        if (template) {
          sts.push(new $rdf.Statement(issue, WF('tracker'), tracker, issueDoc))
          sts.push(new $rdf.Statement(issue, ns.rdfs('seeAlso'), stateStore, issueDoc))
        }

        var sendComplete = function (uri, success, body) {
          if (!success) {
            console.log("Error: can't save new issue:" + body)
          } else {
            form.parentNode.removeChild(form)
            rerender(div)
            outliner.GotoSubject(issue, true, undefined, true, undefined)
          }
        }
        updater.update([], sts, sendComplete)
      }
      // form.addEventListener('submit', function() {try {sendNewIssue} catch(e){console.log('sendNewIssue: '+e)}}, false)
      // form.setAttribute('onsubmit', "function xx(){return false;}")

      UI.store.fetcher.removeCallback('done', 'expand') // @@ experimental -- does this kill the re-paint? no
      UI.store.fetcher.removeCallback('fail', 'expand')

      var states = kb.any(tracker, WF('issueClass'))
      var classLabel = UI.utils.label(states)
      form.innerHTML = '<h2>Add new ' + (superIssue ? 'sub ' : '') +
        classLabel + '</h2><p>Title of new ' + classLabel + ':</p>'
      var titlefield = dom.createElement('input')
      titlefield.setAttribute('type', 'text')
      titlefield.setAttribute('style', 'margin: 0.5em; font-size: 100%; padding: 0.3em;')
      titlefield.setAttribute('size', '100')
      titlefield.setAttribute('maxLength', '2048') // No arbitrary limits
      titlefield.select() // focus next user input
      titlefield.addEventListener('keyup', function (e) {
        if (e.keyCode === 13) {
          sendNewIssue()
        }
      }, false)
      form.appendChild(titlefield)
      return form
    }
562128
def _check_categorical_option_type(option_name, option_value, possible_values):
    
    err_msg = '{0} is not a valid option for {1}. '.format(option_value, option_name)
    err_msg += ' Expected one of: '.format(possible_values)

    err_msg += ', '.join(map(str, possible_values))
    if option_value not in possible_values:
        raise ToolkitError(err_msg)
429020
def filter_event(tag, data, defaults):
    '''
    
    '''
    ret = {}
    keys = []
    use_defaults = True

    for ktag in __opts__.get('filter_events', {}):
        if tag != ktag:
            continue
        keys = __opts__['filter_events'][ktag]['keys']
        use_defaults = __opts__['filter_events'][ktag].get('use_defaults', True)

    if use_defaults is False:
        defaults = []

    # For PY3, if something like ".keys()" or ".values()" is used on a dictionary,
    # it returns a dict_view and not a list like in PY2. "defaults" should be passed
    # in with the correct data type, but don't stack-trace in case it wasn't.
    if not isinstance(defaults, list):
        defaults = list(defaults)

    defaults = list(set(defaults + keys))

    for key in defaults:
        if key in data:
            ret[key] = data[key]

    return ret
643560
public Invoice markUncollectible() throws StripeException {
    return markUncollectible((Map<String, Object>) null, (RequestOptions) null);
  }
573066
function serializeTags( lineNumber, tags ) {

        return tags.split( /\n/ )
        .reduce( function ( acc, line, index ) {

            if ( !index || rTagName.test( line ) ) {
                acc.push( `${line}\n` );
            }
            else {
                acc[ acc.length - 1 ] += `${line}\n`;
            }

            return acc;

        }, [] )
        .map( function ( block ) {

            const trimmed = block.trim();
            const tag = block.match( rTagName )[0];

            const result = {
                line: lineNumber,
                tag: tag.replace( patterns.tagPrefix, '' ),
                value: trimmed.replace( tag, '' ).replace( rLeadSpaces, '' ),
                valueParsed: [],
                source: trimmed
            };

            lineNumber = lineNumber + getLinesLength( block );

            return result;
        })
        .map( function ( tag ) {

            const parser = parsers[ tag.tag ];

            if ( parser ) {

                try {

                    tag.valueParsed = parser( tag.value );
                }
                catch ( err ) {

                    tag.error = err;
                }
            }

            return tag;
        });
    }
431298
def invoice!(attrs={})
      InvoiceCollection.from_response API.post(invoices.uri, attrs.empty? ? nil : Invoice.to_xml(attrs))
    rescue Recurly::API::UnprocessableEntity => e
      raise Invalid, e.message
    end
25618
def save(self, *args, **kwargs):
        '''
        
        '''

        # Set the received date if the payment was just marked received
        if not hasattr(self,'__received'):
            if self.received and not self.receivedDate:
                self.receivedDate = timezone.now()
        else:
            if self.received and not self.receivedDate and not self.__receivedDate:
                self.receivedDate = timezone.now()

        # Set the accrual date.  The method for series/events ensures that the accrualDate month
        # is the same as the reported month of the event/series by accruing to the start date of the first
        # occurrence in that month.
        if not self.accrualDate:
            if self.invoiceItem and self.invoiceItem.finalEventRegistration:
                min_event_time = self.invoiceItem.finalEventRegistration.event.eventoccurrence_set.filter(**{'startTime__month':self.invoiceItem.finalEventRegistration.event.month}).first().startTime
                self.accrualDate = min_event_time
            elif self.event:
                self.accrualDate = self.event.eventoccurrence_set.order_by('startTime').filter(**{'startTime__month': self.event.month}).last().startTime
            elif self.invoiceItem:
                self.accrualDate = self.invoiceItem.invoice.creationDate
            elif self.receivedDate:
                self.accrualDate = self.receivedDate
            elif self.submissionDate:
                self.accrualDate = self.submissionDate
            else:
                self.submissionDate = timezone.now()
                self.accrualDate = self.submissionDate

        # Now, set the registration property and check that this item is not attributed
        # to multiple categories.
        if self.invoiceItem and self.invoiceItem.finalEventRegistration:
            self.event = self.invoiceItem.finalEventRegistration.event
        elif self.invoiceItem and self.invoiceItem.temporaryEventRegistration:
            self.event = self.invoiceItem.temporaryEventRegistration.event

        # If no grossTotal is reported, use the net total.  If no net total is reported, use the grossTotal
        if self.grossTotal is None and self.total:
            self.grossTotal = self.total
        if self.total is None and self.grossTotal:
            self.total = self.grossTotal

        super(RevenueItem, self).save(*args, **kwargs)
        self.__received = self.received
        self.__receivedDate = self.receivedDate

        # If a file is attached, ensure that it is not public, and that it is saved in the 'Expense Receipts' folder
        if self.attachment:
            try:
                self.attachment.folder = Folder.objects.get(name=_('Revenue Receipts'))
            except ObjectDoesNotExist:
                pass
            self.attachment.is_public = False
            self.attachment.save()
873860
def to_raw
      tag_data = tags.map do |tag|
        case tag
        when Tags::OverloadTag
          tag_text = "@#{tag.tag_name} #{tag.signature}\n"
          unless tag.docstring.blank?
            tag_text += "\n  " + tag.docstring.all.gsub(/\r?\n/, "\n  ")
          end
        when Tags::OptionTag
          tag_text = "@#{tag.tag_name} #{tag.name}"
          tag_text += ' [' + tag.pair.types.join(', ') + ']' if tag.pair.types
          tag_text += ' ' + tag.pair.name.to_s if tag.pair.name
          tag_text += "\n " if tag.name && tag.text
          tag_text += ' (' + tag.pair.defaults.join(', ') + ')' if tag.pair.defaults
          tag_text += " " + tag.pair.text.strip.gsub(/\n/, "\n  ") if tag.pair.text
        else
          tag_text = '@' + tag.tag_name
          tag_text += ' [' + tag.types.join(', ') + ']' if tag.types
          tag_text += ' ' + tag.name.to_s if tag.name
          tag_text += "\n " if tag.name && tag.text
          tag_text += ' ' + tag.text.strip.gsub(/\n/, "\n  ") if tag.text
        end
        tag_text
      end
      [strip, tag_data.join("\n")].reject(&:empty?).compact.join("\n")
    end