Encode the given request object in CSV format.
435302
private <T> String serializeToCsv(T obj) {
	  if(obj == null) {
	        return "";
	  }
	  
	  for (Method method: obj.getClass().getMethods()) {
		  if ("java.util.List".equals(method.getReturnType().getName())) {
			  try {
		          @SuppressWarnings("rawtypes")
				  java.util.List itemList = (java.util.List) method.invoke(obj);
		          Object entry = itemList.get(0);
		          
		          List<String> stringList = new ArrayList<String>();
		          char delimiter = ',';
				  String lineSep = "\n";
	
				  CsvMapper mapper = new CsvMapper();
				  mapper.enable(JsonGenerator.Feature.IGNORE_UNKNOWN);
				  CsvSchema schema = mapper.schemaFor(entry.getClass());
				  for (int i = 0; i < itemList.size(); i++) {
					  if (i == 0) {
						  schema = schema.withHeader();
					  } else {
						  schema = schema.withoutHeader();
					  }
					  String csv = mapper.writer(schema
			                .withColumnSeparator(delimiter)
			                .withoutQuoteChar()
			                .withLineSeparator(lineSep)).writeValueAsString(itemList.get(i));
	
					  stringList.add(csv);
				  }
				  return StringUtil.join(stringList.toArray(new String[0]), "");
		  	  } catch (JsonProcessingException e) {
		          System.out.println(e);
		  	  } catch (IllegalAccessException e) {
		          System.out.println(e);
			} catch (IllegalArgumentException e) {
		          System.out.println(e);
			} catch (InvocationTargetException e) {
		          System.out.println(e);
			}
		  }
	  }
	  
	  return "";
  }
475078
def do_encode(cls, obj):
        # type: (Any) -> Any
        """"""
        if isinstance(obj, ConjureBeanType):
            return cls.encode_conjure_bean_type(obj)

        elif isinstance(obj, ConjureUnionType):
            return cls.encode_conjure_union_type(obj)

        elif isinstance(obj, ConjureEnumType):
            return obj.value

        elif isinstance(obj, list):
            return list(map(cls.do_encode, obj))

        elif isinstance(obj, dict):
            return {cls.do_encode(key): cls.do_encode(value)
                    for key, value in obj.items()}

        else:
            return cls.encode_primitive(obj)
700987
def encode(raw):
    """"""
    return raw \
        .replace(bytes([SLIP_ESC]), bytes([SLIP_ESC, SLIP_ESC_ESC])) \
        .replace(bytes([SLIP_END]), bytes([SLIP_ESC, SLIP_ESC_END]))
508198
def _request(self, data):
        """"""
        return requests.post(self.endpoint, data=data.encode("ascii")).content
34104
function encode(cache, API_URL, obj) {
  if (!obj) return null;
  if (!obj.href) return obj;

  var href = API_URL ?
    pack(obj.href, API_URL) :
    obj.href;

  var cached = cache.get(href);
  if (cached) return cached;

  var encoded = base64.encode(new Buffer(href)).toString();
  cache.set(href, encoded);
  return encoded;
}
859357
def formdata_encode(fields):
    
    BOUNDARY = '----form-data-boundary-ZmRkNzJkMjUtMjkyMC00'
    out = []
    for (key, value) in fields.items():
        out.append('--' + BOUNDARY)
        out.append('Content-Disposition: form-data; name="%s"' % key)
        out.append('')
        out.append(value)
    out.append('--' + BOUNDARY + '--')
    out.append('')
    body = '\r\n'.join(out)
    content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
    return content_type, body
224372
def encode_request(name, attribute, ordered):
    
    client_message = ClientMessage(payload_size=calculate_size(name, attribute, ordered))
    client_message.set_message_type(REQUEST_TYPE)
    client_message.set_retryable(RETRYABLE)
    client_message.append_str(name)
    client_message.append_str(attribute)
    client_message.append_bool(ordered)
    client_message.update_frame_length()
    return client_message
162949
def encode_request(name, max_size):
    
    client_message = ClientMessage(payload_size=calculate_size(name, max_size))
    client_message.set_message_type(REQUEST_TYPE)
    client_message.set_retryable(RETRYABLE)
    client_message.append_str(name)
    client_message.append_int(max_size)
    client_message.update_frame_length()
    return client_message
847457
def encode_params(self, data=None, **kwargs):
        
        collection_format = kwargs.get("collection_format", self.collection_format)
        output_str = kwargs.get("output_str", self.output_str)
        sort = kwargs.get("sort", self.sort)

        if data is None:
            return "", self.content_type
        elif isinstance(data, (str, bytes)):
            return data, self.content_type
        elif hasattr(data, 'read'):
            return data, self.content_type
        elif collection_format == 'multi' and hasattr(data, '__iter__'):
            result = []
            for k, vs in to_key_val_list(data, sort=sort):
                if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):
                    vs = [vs]
                for v in vs:
                    result.append(
                        (k.encode('utf-8') if isinstance(k, str) else k,
                         v.encode('utf-8') if isinstance(v, str) else to_string(v, lang=output_str)))
            return urlencode(result, doseq=True), self.content_type
        elif collection_format == 'encoded' and hasattr(data, '__iter__'):
            return urlencode(data, doseq=False), self.content_type
        elif hasattr(data, '__iter__'):
            results = []
            for k, vs in to_key_val_dict(data).items():
                if isinstance(vs, list):
                    v = self.COLLECTION_SEPARATORS[collection_format].join(quote_plus(e) for e in vs)
                    key = k + '[]'
                else:
                    v = quote_plus(vs)
                    key = k
                results.append("%s=%s" % (key, v))

            return '&'.join(results), self.content_type
        else:
            return data, self.content_type
1125899
def encode_request(name, data_list):
    
    client_message = ClientMessage(payload_size=calculate_size(name, data_list))
    client_message.set_message_type(REQUEST_TYPE)
    client_message.set_retryable(RETRYABLE)
    client_message.append_str(name)
    client_message.append_int(len(data_list))
    for data_list_item in data_list:
        client_message.append_data(data_list_item)
    client_message.update_frame_length()
    return client_message
190547
def encode_data(data):
    '''
    
    '''
    if isinstance(data, (six.string_types, bytes)):
        return encode_string(data)
    elif isinstance(data, (six.integer_types, bool, float)):
        return data
    elif data is None:
        return data
    elif isinstance(data, list):
        return [encode_data(x) for x in data]
    elif isinstance(data, dict):
        return {k: encode_data(v) for k, v in data.items()}
    else:
        raise ValueError('Cannot encode data of type %s' % type(data))
10344
def encode_contents(self):
        

        header = struct.pack("<LL", self.offset, len(self.raw_data))
        return bytearray(header) + self.raw_data
18694
def serialize(self, request):
        

        def serialize(anything):

            def serialize_dictionary(dictionary):
                """Dictionaries are serialized recursively."""
                data = OrderedDict()

                # Serialize each of the dictionary's keys
                for key, value in dictionary.items():
                    data.update({ key: serialize(value) })

                return data

            def serialize_list(list):
                """Lists are serialized recursively."""
                data = []

                # Serialize each of the list's items
                for item in list:
                    data.append(serialize(item))

                return data

            def serialize_queryset(queryset):
                """Querysets are serialized as lists of models."""
                data = []

                # Serialize queryset as a list of models
                for model in queryset:
                    data.append(serialize_model(model))

                return data

            def serialize_datequeryset(datequeryset):
                """DateQuerysets are serialized as lists of dates."""
                data = []

                # Serialize datequeryset as a list of datetime objects
                for date in datequeryset:
                    data.append(serialize_date(date))

                return data

            def serialize_valueslistqueryset(valueslistqueryset):
                """DateQuerysets are serialized as lists of values."""
                data = []

                # Serialize valueslistqueryset as a list of values
                for value in valueslistqueryset:
                    if isinstance(value, tuple):
                        data.append(serialize_list(value))
                    else:
                        data.append(serialize(value))

                return data

            def serialize_manager(manager):
                """Managers are serialized as list of models."""
                data = []

                for model in manager.all():
                    data.append(serialize_model(model))

                return data

            def serialize_model(model):
                """
                Models are serialized by calling their 'serialize' method.

                Models that don't define a 'serialize' method are
                serialized as a dictionary of fields.

                Example:

                    {
                        'id': 1,
                        'title': 'Mmmm pie',
                        'content: 'Pie is good!'
                    }

                """

                if hasattr(model, 'serialize'):
                    return serialize(model.serialize())
                else:
                    data = OrderedDict()
                    for field in model._meta.fields + model._meta.many_to_many:
                        data.update({
                            field.name: serialize(getattr(model, field.name ))
                        })

                    return data

            def serialize_form(form):
                """
                Forms are serialized as a dictionary of fields and errors (if any).

                Example:

                    {
                        'fields': ['title', 'content'],
                        'errors': {
                            'content': 'Must describe pie.'
                        }
                    }

                """
                data = OrderedDict()

                # Serialize form fields as a list of strings
                data['fields'] = []
                for field in form.fields:
                    data['fields'].append(field)

                # Serialize form errors as a dictionary with keys 'field' and 'error'
                if form.errors:
                    data['errors'] = []
                    for field in form:
                        data['errors'].append(
                            {
                                'field': field.name,
                                'error': field.errors.as_text()
                            }
                        )

                return data

            def serialize_date(datetime):
                """Dates are serialized as ISO 8601-compatible strings."""
                return datetime.isoformat()

            def serialize_field_file(field_file):
                """Filefields are serialized as strings describing their URL."""
                try:
                    return field_file.url
                except ValueError:
                    return None

            def serialize_image_field_file(image_field_file):
                """Imagefields are serialized as strings describing their URL."""
                try:
                    return image_field_file.url
                except ValueError:
                    return None

            def serialize_decimal_field(decimal_field):
                """Decimal fields are serialized as strings."""
                try:
                    return str(decimal_field)
                except ValueError:
                    return None

            if isinstance(anything, dict):
                return serialize_dictionary(anything)

            if isinstance(anything, (list, set)):
                return serialize_list(anything)

            if isinstance(anything, django.db.models.query.DateQuerySet):
                return serialize_datequeryset(anything)

            if isinstance(anything, django.db.models.query.DateTimeQuerySet):
                return serialize_datequeryset(anything)

            if isinstance(anything, django.db.models.query.ValuesListQuerySet):
                return serialize_valueslistqueryset(anything)

            if isinstance(anything, django.db.models.query.QuerySet):
                return serialize_queryset(anything)

            if isinstance(anything, django.db.models.Model):
                return serialize_model(anything)

            if isinstance(anything, (django.forms.Form, django.forms.ModelForm)):
                return serialize_form(anything)

            if isinstance(anything, (str, unicode)):
                return anything

            if isinstance(anything, (int, float, long)):
                return anything

            if isinstance(anything, (datetime.date, datetime.datetime)):
                return serialize_date(anything)

            if isinstance(anything, django.db.models.manager.Manager):
                return serialize_manager(anything)

            if isinstance(anything, Decimal):
                return serialize_decimal_field(anything)

            if isinstance(anything, django.core.files.base.File):
                return serialize_field_file(anything)

            if anything is None:
                return None

            if hasattr(anything, 'serialize'):
                return serialize(anything.serialize())

            raise TypeError("Respite doesn't know how to serialize %s" % anything.__class__.__name__)

        return serialize(self.source)
1007749
def to_curl(request, compressed=False, verify=True):
    
    parts = [
        ('curl', None),
        ('-X', request.method),
    ]

    for k, v in sorted(request.headers.items()):
        parts += [('-H', '{0}: {1}'.format(k, v))]

    if request.body:
        body = request.body
        if isinstance(body, bytes):
            body = body.decode('utf-8')
        parts += [('-d', body)]

    if compressed:
        parts += [('--compressed', None)]

    if not verify:
        parts += [('--insecure', None)]

    parts += [(None, request.url)]

    flat_parts = []
    for k, v in parts:
        if k:
            flat_parts.append(k)
        if v:
            flat_parts.append("'{0}'".format(v))

    return ' '.join(flat_parts)
832051
function formatRequestString_(o) {
  var ret;
  if (typeof o === 'object') {
    if (isArray_(o)) {
      ret = [];
      for (var i = 0, I = o.length; i < I; i++) {
        ret.push(formatRequestString_(o[i]));
      }
      return '[' + ret.join(',') + ']';
    } else if (isOverlay_(o)) {
      return fromOverlaysToJSON_(o);
    } else if (o.toJSON) {
      return o.toJSON();
    } else {
      ret = '';
      for (var x in o) {
        if (o.hasOwnProperty(x)) {
          if (ret.length > 0) {
            ret += ', ';
          }
          ret += x + ':' + formatRequestString_(o[x]);
        }
      }
      return '{' + ret + '}';
    }
  }
  return o.toString();
}
1122045
def encode(self):
        
        result = bytearray()
        result.append(self.id)
        result.append(self.dataLength)
        result.extend(self.data)
        return result
951396
function encodeParams(params) {
    var queryString;
    if (params && Object.keys(params)) {
        queryString = [].slice.call(arguments).reduce(function (a, b) {
            return a.concat(b instanceof Array ? b : [b]);
        }, []).filter(function (c) {
            return "object" === typeof c;
        }).reduce(function (p, c) {
            !(c instanceof Array) ? p = p.concat(Object.keys(c).map(function (key) {
                return [key, c[key]];
            })) : p.push(c);
            return p;
        }, []).reduce(function (p, c) {
            c.length === 2 ? p.push(c) : p = p.concat(c);
            return p;
        }, []).reduce(function (p, c) {
            c[1] instanceof Array ? c[1].forEach(function (v) {
                p.push([c[0], v]);
            }) : p.push(c);
            return p;
        }, []).map(function (c) {
            c[1] = encodeURIComponent(c[1]);
            return c.join("=");
        }).join("&");
    }
    return queryString;
}