Convert a response from Google Analytics into a comma-separated values
 format file.
 @return [String] The result of the query formatted as a comma-separated
   values string.
776291
def csv
      @csv ||= CSV.generate do |csv|
        reports.each(&:report).each do |report|
          # If there are no dimensions, but totals, we need to put an extra
          # column at the start for the word "Total".
          # I don't see how totals will be different than the metrics if you
          # don't specify dimensions, but whatever.
          totals_column = report.totals? && !report.dimensions? ? [nil] : []
          csv << totals_column + report.headers
          report.rows.each { |row| csv << totals_column + row.to_a }
          next unless report.totals? # Rubocop did this. Not sure I like it.
          csv << ["Totals"] + if !report.dimensions?
                                report.totals
                              else
                                report.totals[1..-1]
                              end
        end
      end
    end
693498
def get_rets_response(rets)
      code, text = nil, nil
      rets.attributes.each do |attr|
        key = attr.first.downcase
        if key == "replycode"
          code = attr.last.value
        elsif key == "replytext"
          text = attr.last.value
        end
      end
  #    puts "replycode: #{code}"
      return code, text
    end
715901
def _parse_response(self, results):
        

        dict_response = results.get("response")
        result_obj = SolrResults()
        result_obj.query_time = results.get("responseHeader").get("QTime", None)
        result_obj.results_count = dict_response.get("numFound", 0)
        result_obj.start_index = dict_response.get("start", 0)

        for doc in dict_response.get("docs", []):
            result_obj.documents.append(doc)

        # Process facets
        if "facet_counts" in results:
            facet_types = ["facet_fields", "facet_dates", "facet_ranges", "facet_queries"]
            for type in facet_types:
                assert type in results.get("facet_counts")
                items = results.get("facet_counts").get(type)
                for field, values in items.items():
                    result_obj.facets[field] = []

                    # Range facets have results in "counts" subkey and "between/after" on top level. Flatten this.
                    if type == "facet_ranges":
                        if not "counts" in values:
                            continue

                        for facet, value in values["counts"].items():
                            result_obj.facets[field].append((facet, value))

                        if "before" in values:
                            result_obj.facets[field].append(("before", values["before"]))

                        if "after" in values:
                            result_obj.facets[field].append(("after", values["after"]))
                    else:
                        for facet, value in values.items():
                            # Date facets have metadata fields between the results, skip the params, keep "before" and "after" fields for other
                            if type == "facet_dates" and \
                            (facet == "gap" or facet == "between" or facet == "start" or facet == "end"):
                                continue
                            result_obj.facets[field].append((facet, value))

        # Process highlights
        if "highlighting" in results:
            for key, value in results.get("highlighting").items():
                result_obj.highlights[key] = value

        return result_obj
452141
function (source) {
            if (!Array.isArray(source)) {
                source = [source];
            }
            if (!source || !source.length) {
                throw new QueryError("No source specified for the query");
            }
            return " " + source.map(
                    function (s) {
                        return this.__tableRef(s);
                    }, this).join(this._static.COMMA_SEPARATOR);
        }
570881
function summariser(results) {
    var response = [],
        callback = function(output) {
            response.push(output);
        };

    var passed = 0;
    if (results.hasOwnProperty('passed')) {
        passed = countSpecs(results.passed);
    }
    var failed = 0;
    if (results.hasOwnProperty('failed')) {
        failed = countSpecs(results.failed);
    }
    var pending = 0;

    if (results.hasOwnProperty('pending')) {
        pending = countSpecs(results.pending);
    }
    var total = passed + failed + pending;

    coloriseOutput(total + ' Specs defined', 'bold', callback);
    if (total > 0) {
        coloriseOutput(passed + ' Passed' + displayPercentage(total, passed), 'green', callback);
        coloriseOutput(failed + ' Failed' + displayPercentage(total, failed), 'red', callback);
        coloriseOutput(pending + ' Pending' + displayPercentage(total, pending), 'yellow', callback);
    }
    return response;
}
308182
def format(input, **params):
    
    PARAM_FORMAT_STRING = 'format.string'
    PARAM_FORMAT_INPUT = 'format.input'
    PARAM_RESULT_FIELD = 'result.field'
    IN_DESC_FIELD = 'field'
    IN_DESC_TYPE = 'type'

    format_string = params.get(PARAM_FORMAT_STRING)
    format_inputs = params.get(PARAM_FORMAT_INPUT)
    result_field = params.get(PARAM_RESULT_FIELD)
    for row in input:
        row_input = []
        for desc in format_inputs:
            row_input.append(Converter.convert(row[desc[IN_DESC_FIELD]], desc[IN_DESC_TYPE]))
        row[result_field] = format_string.format(*row_input)
    return input
159320
def to_array(self):
        
        array = super(InlineQueryResultGif, self).to_array()
        # 'type' and 'id' given by superclass
        array['gif_url'] = u(self.gif_url)  # py2: type unicode, py3: type str
        array['thumb_url'] = u(self.thumb_url)  # py2: type unicode, py3: type str
        if self.gif_width is not None:
            array['gif_width'] = int(self.gif_width)  # type int
        if self.gif_height is not None:
            array['gif_height'] = int(self.gif_height)  # type int
        if self.gif_duration is not None:
            array['gif_duration'] = int(self.gif_duration)  # type int
        if self.title is not None:
            array['title'] = u(self.title)  # py2: type unicode, py3: type str
        if self.caption is not None:
            array['caption'] = u(self.caption)  # py2: type unicode, py3: type str
        if self.parse_mode is not None:
            array['parse_mode'] = u(self.parse_mode)  # py2: type unicode, py3: type str
        if self.reply_markup is not None:
            array['reply_markup'] = self.reply_markup.to_array()  # type InlineKeyboardMarkup
        if self.input_message_content is not None:
            array['input_message_content'] = self.input_message_content.to_array()  # type InputMessageContent
        return array
10274
def parse_url(url)
      s = url

      # remove entities
      s = HTML_ENTITIES.decode(s)

      # fix a couple of common encoding bugs
      s = s.gsub(' ', '%20')
      s = s.gsub("'", '%27')

      # append query manually (instead of letting HTTParty handle it) so we can
      # include it in cache_key
      query = options.delete(:query)
      if query.present?
        q = HTTParty::HashConversions.to_params(query)
        separator = s.include?('?') ? '&' : '?'
        s = "#{s}#{separator}#{q}"
      end

      URI.parse(s)
    end
6907
def to_s
      str = ''
      if @width > 0
        fmt = @width.truncate == @width ? '%d' : '%.2f'
        str << format(fmt, @width)
        str << '%' if @flag == PercentGeometry
      end

      str << 'x' if (@width > 0 && @flag != PercentGeometry) || (@height > 0)

      if @height > 0
        fmt = @height.truncate == @height ? '%d' : '%.2f'
        str << format(fmt, @height)
        str << '%' if @flag == PercentGeometry
      end
      str << format('%+d%+d', @x, @y) if @x != 0 || @y != 0
      str << FLAGS[@flag.to_i] if @flag != PercentGeometry
      str
    end
974795
def render_string
      result = '<?xml version="1.0" encoding="UTF-8"?>' + "\n<urlset"

      XmlSitemap::MAP_SCHEMA_OPTIONS.each do |key, val|
        result << ' ' + key + '="' + val + '"'
      end

      result << ">\n"

      item_results = []
      @items.each do |item|
        item_string  = "  <url>\n"
        item_string << "    <loc>#{CGI::escapeHTML(item.target)}</loc>\n"

        # Format and image tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=178636
        if item.image_location
          item_string << "    <image:image>\n"
          item_string << "      <image:loc>#{CGI::escapeHTML(item.image_location)}</image:loc>\n"
          item_string << "      <image:caption>#{CGI::escapeHTML(item.image_caption)}</image:caption>\n"               if item.image_caption
          item_string << "      <image:title>#{CGI::escapeHTML(item.image_title)}</image:title>\n"                     if item.image_title
          item_string << "      <image:license>#{CGI::escapeHTML(item.image_license)}</image:license>\n"               if item.image_license
          item_string << "      <image:geo_location>#{CGI::escapeHTML(item.image_geolocation)}</image:geo_location>\n" if item.image_geolocation
          item_string << "    </image:image>\n"
        end

        # Format and video tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=80472&topic=10079&ctx=topic#2
        if item.video_thumbnail_location && item.video_title && item.video_description && (item.video_content_location || item.video_player_location)
          item_string << "    <video:video>\n"
          item_string << "      <video:thumbnail_loc>#{CGI::escapeHTML(item.video_thumbnail_location)}</video:thumbnail_loc>\n"
          item_string << "      <video:title>#{CGI::escapeHTML(item.video_title)}</video:title>\n"
          item_string << "      <video:description>#{CGI::escapeHTML(item.video_description)}</video:description>\n"
          item_string << "      <video:content_loc>#{CGI::escapeHTML(item.video_content_location)}</video:content_loc>\n"                           if item.video_content_location
          item_string << "      <video:player_loc>#{CGI::escapeHTML(item.video_player_location)}</video:player_loc>\n"                              if item.video_player_location
          item_string << "      <video:duration>#{CGI::escapeHTML(item.video_duration.to_s)}</video:duration>\n"                                    if item.video_duration
          item_string << "      <video:expiration_date>#{item.video_expiration_date_value}</video:expiration_date>\n"                               if item.video_expiration_date
          item_string << "      <video:rating>#{CGI::escapeHTML(item.video_rating.to_s)}</video:rating>\n"                                          if item.video_rating
          item_string << "      <video:view_count>#{CGI::escapeHTML(item.video_view_count.to_s)}</video:view_count>\n"                              if item.video_view_count
          item_string << "      <video:publication_date>#{item.video_publication_date_value}</video:publication_date>\n"                            if item.video_publication_date
          item_string << "      <video:family_friendly>#{CGI::escapeHTML(item.video_family_friendly)}</video:family_friendly>\n"                    if item.video_family_friendly
          item_string << "      <video:category>#{CGI::escapeHTML(item.video_category)}</video:category>\n"                                         if item.video_category
          item_string << "      <video:restriction relationship=\"allow\">#{CGI::escapeHTML(item.video_restriction)}</video:restriction>\n"         if item.video_restriction
          item_string << "      <video:gallery_loc>#{CGI::escapeHTML(item.video_gallery_location)}</video:gallery_loc>\n"                           if item.video_gallery_location
          item_string << "      <video:price currency=\"USD\">#{CGI::escapeHTML(item.video_price.to_s)}</video:price>\n"                            if item.video_price
          item_string << "      <video:requires_subscription>#{CGI::escapeHTML(item.video_requires_subscription)}</video:requires_subscription>\n"  if item.video_requires_subscription
          item_string << "      <video:uploader>#{CGI::escapeHTML(item.video_uploader)}</video:uploader>\n"                                         if item.video_uploader
          item_string << "      <video:platform relationship=\"allow\">#{CGI::escapeHTML(item.video_platform)}</video:platform>\n"                  if item.video_platform
          item_string << "      <video:live>#{CGI::escapeHTML(item.video_live)}</video:live>\n"                                                     if item.video_live
          item_string << "    </video:video>\n"
        end

        item_string << "    <lastmod>#{item.lastmod_value}</lastmod>\n"
        item_string << "    <changefreq>#{item.changefreq}</changefreq>\n" if item.changefreq
        item_string << "    <priority>#{item.priority}</priority>\n" if item.priority
        item_string << "  </url>\n"

        item_results << item_string
      end

      result << item_results.join("")
      result << "</urlset>\n"

      result
    end
187731
def hash_to_rets_query_string(hash)
      [].tap do |str|
        hash.each_pair do |k,v|
          val = value_map(v)
          str << "(#{k.to_s.camelize}=#{val})"
        end
      end.join(',')
    end
239597
def get_result_as_array(self):
        

        if self.formatter is not None:
            return np.array([self.formatter(x) for x in self.values])

        if self.fixed_width:
            threshold = get_option("display.chop_threshold")
        else:
            threshold = None

        # if we have a fixed_width, we'll need to try different float_format
        def format_values_with(float_format):
            formatter = self._value_formatter(float_format, threshold)

            # default formatter leaves a space to the left when formatting
            # floats, must be consistent for left-justifying NaNs (GH #25061)
            if self.justify == 'left':
                na_rep = ' ' + self.na_rep
            else:
                na_rep = self.na_rep

            # separate the wheat from the chaff
            values = self.values
            is_complex = is_complex_dtype(values)
            mask = isna(values)
            if hasattr(values, 'to_dense'):  # sparse numpy ndarray
                values = values.to_dense()
            values = np.array(values, dtype='object')
            values[mask] = na_rep
            imask = (~mask).ravel()
            values.flat[imask] = np.array([formatter(val)
                                           for val in values.ravel()[imask]])

            if self.fixed_width:
                if is_complex:
                    return _trim_zeros_complex(values, na_rep)
                else:
                    return _trim_zeros_float(values, na_rep)

            return values

        # There is a special default string when we are fixed-width
        # The default is otherwise to use str instead of a formatting string
        if self.float_format is None:
            if self.fixed_width:
                float_format = partial('{value: .{digits:d}f}'.format,
                                       digits=self.digits)
            else:
                float_format = self.float_format
        else:
            float_format = lambda value: self.float_format % value

        formatted_values = format_values_with(float_format)

        if not self.fixed_width:
            return formatted_values

        # we need do convert to engineering format if some values are too small
        # and would appear as 0, or if some values are too big and take too
        # much space

        if len(formatted_values) > 0:
            maxlen = max(len(x) for x in formatted_values)
            too_long = maxlen > self.digits + 6
        else:
            too_long = False

        with np.errstate(invalid='ignore'):
            abs_vals = np.abs(self.values)
            # this is pretty arbitrary for now
            # large values: more that 8 characters including decimal symbol
            # and first digit, hence > 1e6
            has_large_values = (abs_vals > 1e6).any()
            has_small_values = ((abs_vals < 10**(-self.digits)) &
                                (abs_vals > 0)).any()

        if has_small_values or (too_long and has_large_values):
            float_format = partial('{value: .{digits:d}e}'.format,
                                   digits=self.digits)
            formatted_values = format_values_with(float_format)

        return formatted_values
955206
def parse_quantitationesultsline(self, line):
        

        if line == ',,,,,,,,,,,,,,,,,,':
            return 0

        if line.startswith('SampleID'):
            self._end_header = True
            self._quantitationresultsheader = [token.strip() for token
                                               in line.split(self.COMMAS)
                                               if token.strip()]
            return 0

        splitted = [token.strip() for token in line.split(self.COMMAS)]
        quantitation = {'DefaultResult': 'FinalConcentration'}
        for colname in self._quantitationresultsheader:
            quantitation[colname] = ''

        for i in range(len(splitted)):
            token = splitted[i]
            if i < len(self._quantitationresultsheader):
                colname = self._quantitationresultsheader[i]
                if colname in self.QUANTITATIONRESULTS_NUMERICHEADERS:
                    try:
                        quantitation[colname] = float(token)
                    except ValueError:
                        self.warn(
                            "No valid number ${token} in column "
                            "${index} (${column_name})",
                            mapping={"token": token,
                                     "index": str(i + 1),
                                     "column_name": colname},
                            numline=self._numline, line=line)
                        quantitation[colname] = token
                else:
                    quantitation[colname] = token

            elif token:
                self.err("Orphan value in column ${index} (${token})",
                         mapping={"index": str(i+1),
                                  "token": token},
                         numline=self._numline, line=line)

        result = quantitation[quantitation['DefaultResult']]
        column_name = quantitation['DefaultResult']
        result = self.zeroValueDefaultInstrumentResults(column_name,
                                                        result, line)
        quantitation[quantitation['DefaultResult']] = result

        d = datetime.strptime(quantitation['AcqDateTime'], "%m/%d/%Y %H:%M")
        quantitation['AcqDateTime'] = d
        val = re.sub(r"\W", "", quantitation['Compound'])
        self._addRawResult(quantitation['DataFileName'],
                           values={val: quantitation},
                           override=False)
827280
def parse_response(response, format = 'json')
      result = nil

      if format == 'json'
        result = JSON.parse(response)
      elsif format == 'xml'
        result = Nokogiri::XML(response)
      end

      return result
    end
1112561
def collate_results(results)
    ret = []
    results.size.times do |i|
      ret << results[i]
    end
    return ret
  end
1100202
def to_array(self):
        
        array = super(InlineQueryResultMpeg4Gif, self).to_array()
        array['type'] = u(self.type)  # py2: type unicode, py3: type str

        array['id'] = u(self.id)  # py2: type unicode, py3: type str

        array['mpeg4_url'] = u(self.mpeg4_url)  # py2: type unicode, py3: type str

        array['thumb_url'] = u(self.thumb_url)  # py2: type unicode, py3: type str

        if self.mpeg4_width is not None:
            array['mpeg4_width'] = int(self.mpeg4_width)  # type int
        if self.mpeg4_height is not None:
            array['mpeg4_height'] = int(self.mpeg4_height)  # type int
        if self.mpeg4_duration is not None:
            array['mpeg4_duration'] = int(self.mpeg4_duration)  # type int
        if self.title is not None:
            array['title'] = u(self.title)  # py2: type unicode, py3: type str

        if self.caption is not None:
            array['caption'] = u(self.caption)  # py2: type unicode, py3: type str

        if self.parse_mode is not None:
            array['parse_mode'] = u(self.parse_mode)  # py2: type unicode, py3: type str

        if self.reply_markup is not None:
            array['reply_markup'] = self.reply_markup.to_array()  # type InlineKeyboardMarkup

        if self.input_message_content is not None:
            array['input_message_content'] = self.input_message_content.to_array()  # type InputMessageContent

        return array
153276
def csv(self, text=TEXT, sep=',', index=True, float_fmt="%.2g"):
        
        return self._data.to_csv(sep=sep, index=index, float_format=float_fmt)