unroll option orders like this,
        https://github.com/joshfraser/robinhood-to-csv/blob/master/csv-options-export.py
331009
def unroll_option_legs(cls, client, option_orders):
        '''
        
        '''

        #
        # @TODO write this with python threats to make concurrent HTTP requests
        #

        results = []

        for oo in option_orders:
            for index, leg in enumerate(oo['legs']):
                for execution in leg['executions']:
                    order = dict()

                    keys_in_question = ['legs', 'price', 'type', 'premium',
                                        'processed_premium',
                                        'response_category', 'cancel_url']
                    for k, v in oo.items():
                        if k not in keys_in_question:
                            order[k] = oo[k]

                    order['order_type'] = oo['type']

                    contract = client.get(leg['option'])
                    order['leg'] = index+1
                    order['symbol'] = contract['chain_symbol']
                    order['strike_price'] = contract['strike_price']
                    order['expiration_date'] = contract['expiration_date']
                    order['contract_type'] = contract['type']

                    for k, v in leg.items():
                        if k not in ['id', 'executions']:
                            order[k] = leg[k]

                    coef = (-1.0 if leg['side'] == 'buy' else 1.0)
                    order['price'] = float(execution['price']) * 100.0 * coef
                    order['execution_id'] = execution['id']

                    results.append(order)
        return results
851885
function csvWrapForExcel(encoder) {
  // Pipe the CSV encoder to the ucs2 converter
  var converter = new Stream.Transform();
  var csvStream = new Stream.PassThrough();
  converter._transform = function(chunk, encoding, cb) {
    this.push(new Buffer(chunk.toString(), 'ucs2'));
    cb();
  };
  // Write the UCS2 BOM http://www.unicode.org/faq/utf_bom.html#bom1
  csvStream.write(new Buffer([0xFF, 0xFE]));
  return encoder.pipe(converter).pipe(csvStream);
}
1096370
function LZ4_uncompress (input, options) {
	var output = []
	var decoder = new Decoder(options)

	decoder.on('data', function (chunk) {
		output.push(chunk)
	})

	decoder.end(input)

	return Buffer.concat(output)
}
560884
def warp(self, order):
        

        # 因为成交模式对时间的封装

        if order.order_model == ORDER_MODEL.MARKET:

            if order.frequence is FREQUENCE.DAY:
                # exact_time = str(datetime.datetime.strptime(
                #     str(order.datetime), '%Y-%m-%d %H-%M-%S') + datetime.timedelta(day=1))

                order.date = order.datetime[0:10]
                order.datetime = '{} 09:30:00'.format(order.date)
            elif order.frequence in [FREQUENCE.ONE_MIN,
                                     FREQUENCE.FIVE_MIN,
                                     FREQUENCE.FIFTEEN_MIN,
                                     FREQUENCE.THIRTY_MIN,
                                     FREQUENCE.SIXTY_MIN]:
                exact_time = str(
                    datetime.datetime
                    .strptime(str(order.datetime),
                              '%Y-%m-%d %H:%M:%S') +
                    datetime.timedelta(minutes=1)
                )
                order.date = exact_time[0:10]
                order.datetime = exact_time
            self.market_data = self.get_market(order)
            if self.market_data is None:
                return order
            order.price = (
                float(self.market_data["high"]) +
                float(self.market_data["low"])
            ) * 0.5
        elif order.order_model == ORDER_MODEL.NEXT_OPEN:
            try:
                exact_time = str(
                    datetime.datetime
                    .strptime(str(order.datetime),
                              '%Y-%m-%d %H-%M-%S') + datetime.timedelta(day=1)
                )
                order.date = exact_time[0:10]
                order.datetime = '{} 09:30:00'.format(order.date)
            except:
                order.datetime = '{} 15:00:00'.format(order.date)
            self.market_data = self.get_market(order)
            if self.market_data is None:
                return order
            order.price = float(self.market_data["close"])
        elif order.order_model == ORDER_MODEL.CLOSE:

            try:
                order.datetime = self.market_data.datetime
            except:
                if len(str(order.datetime)) == 19:
                    pass
                else:
                    order.datetime = '{} 15:00:00'.format(order.date)
            self.market_data = self.get_market(order)
            if self.market_data is None:
                return order
            order.price = float(self.market_data["close"])

        elif order.order_model == ORDER_MODEL.STRICT:
            '加入严格模式'
            if order.frequence is FREQUENCE.DAY:
                exact_time = str(
                    datetime.datetime
                    .strptime(order.datetime,
                              '%Y-%m-%d %H-%M-%S') + datetime.timedelta(day=1)
                )

                order.date = exact_time[0:10]
                order.datetime = '{} 09:30:00'.format(order.date)
            elif order.frequence in [FREQUENCE.ONE_MIN,
                                     FREQUENCE.FIVE_MIN,
                                     FREQUENCE.FIFTEEN_MIN,
                                     FREQUENCE.THIRTY_MIN,
                                     FREQUENCE.SIXTY_MIN]:
                exact_time = str(
                    datetime.datetime
                    .strptime(order.datetime,
                              '%Y-%m-%d %H-%M-%S') +
                    datetime.timedelta(minute=1)
                )
                order.date = exact_time[0:10]
                order.datetime = exact_time
            self.market_data = self.get_market(order)
            if self.market_data is None:
                return order
            if order.towards == 1:
                order.price = float(self.market_data["high"])
            else:
                order.price = float(self.market_data["low"])

        return order
752734
def allStockQoutation(self):
        '''
        
        '''
        logger = Logs().getNewLogger('allStockQoutation', QoutationAsynPush.dir)
        markets= [Market.HK,Market.US,Market.SH,Market.SZ] #,Market.HK_FUTURE,Market.US_OPTION
        stockTypes = [SecurityType.STOCK,SecurityType.WARRANT,SecurityType.IDX,SecurityType.BOND,SecurityType.ETF]

        for stockType in stockTypes:
            for market in markets:
                ret_code_stock_basicinfo ,ret_data_stock_basicinfo = self.quote_ctx.get_stock_basicinfo(market,stockType)
                codes = ret_data_stock_basicinfo['code'].tolist()
                codes_len = len(codes)
                code_sub = 0
                code_sub_succ = 0
                for code in codes:
                    ret_code = self.aStockQoutation(code)
                    code_sub += 1
                    if ret_code is RET_OK:
                        code_sub_succ += 1
                        logger.info('市场 = %s，股票类型 = %s, 股票总数 = %d, 已发起订阅 = %d，订阅成功 = %d' % (market, stockType, codes_len, code_sub,code_sub_succ))  # 记录
                logger.info('end-------->市场 = %s，股票类型 = %s, 股票总数 = %d, 已发起订阅 = %d，订阅成功 = %d' % ( market, stockType, codes_len, code_sub,code_sub_succ))  # 记录

        time.sleep(5)
        self.quote_ctx.stop()
        self.quote_ctx.close()
460196
def stock2one(stock):
    
    lines = {}
    for line in stock:
        line = line.strip()
        if print_line(line) is True:
            yield line
            continue
        if line.startswith('//'):
            continue
        ID, seq = line.rsplit(' ', 1)
        if ID not in lines:
            lines[ID] = ''
        else:
            # remove preceding white space
            seq = seq.strip()
        lines[ID] += seq
    for ID, line in lines.items():
        yield '\t'.join([ID, line])
    yield '\n//'
760980
def mergecsv(args):
    
    p = OptionParser(mergecsv.__doc__)
    p.set_outfile()
    opts, args = p.parse_args(args)

    if len(args) < 2:
        sys.exit(not p.print_help())

    tsvfiles = args
    outfile = opts.outfile

    if op.exists(outfile):
        os.remove(outfile)

    tsvfile = tsvfiles[0]
    fw = must_open(opts.outfile, "w")
    for i, tsvfile in enumerate(tsvfiles):
        fp = open(tsvfile)
        if i > 0:
            next(fp)
        for row in fp:
            fw.write(row)
    fw.close()
1173668
def cleanup_tail(options):
    

    if options.kwargs['omode'] == "csv":
        options.kwargs['fd'].write("\n")
    elif options.kwargs['omode'] == "xml":
        options.kwargs['fd'].write("\n</results>\n")
    else:
        options.kwargs['fd'].write("\n]\n")
738483
def export_aggregate_by_csv(ekey, dstore):
    
    token, what = ekey[0].split('/', 1)
    aw = extract(dstore, 'aggregate/' + what)
    fnames = []
    writer = writers.CsvWriter(fmt=writers.FIVEDIGITS)
    path = '%s.%s' % (sanitize(ekey[0]), ekey[1])
    fname = dstore.export_path(path)
    writer.save(aw.to_table(), fname)
    fnames.append(fname)
    return fnames
586834
def submit(cls, client, direction, legs, price, quantity, time_in_force,
               trigger, order_type, run_validations=True):
        '''
        
        '''

        if run_validations:
            assert(direction in ["debit", "credit"])
            assert(type(price) is str)
            assert(type(quantity) is int)
            assert(time_in_force in ["gfd", "gtc"])
            assert(trigger in ["immediate"])
            assert(order_type in ["limit", "market"])
            assert(cls._validate_legs(legs) is True)

        payload = json.dumps({
            "account": client.account_url,
            "direction": direction,
            "legs": legs,
            "price": price,
            "quantity": quantity,
            "time_in_force": time_in_force,
            "trigger": trigger,
            "type": order_type,
            "override_day_trade_checks": False,
            "override_dtbp_checks": False,
            "ref_id": str(uuid.uuid4())
        })

        request_url = "https://api.robinhood.com/options/orders/"
        data = client.post(request_url, payload=payload)
        return data
490629
def csv(options = {}, &block)
      options[:resource] = config

      config.csv_builder = CSVBuilder.new(options, &block)
    end
510090
def __unroll(self, rolled):
        """"""
        return np.array(np.concatenate([matrix.flatten() for matrix in rolled], axis=1)).reshape(-1)
1160852
def unroll( n = 1 )
      if n < 0
        roll -n
      else
        order = ( 0 ... dimension ).to_a
        n.times { order = [ order.last ] + order[ 0 ... -1 ] }
        transpose *order
      end
    end
1245545
def _convert_option(self):
        '''
        
        '''

        if sys.byteorder == 'little' and self._endian() == 'big-endian':
            # big->little
            order = '>'
        elif sys.byteorder == 'big' and self._endian() == 'little-endian':
            # little->big
            order = '<'
        else:
            # no conversion
            order = '='
        return order
292774
function csvToMapping(csvString) {
  const lines = csvString.split(/\n|\r|\r\n/);
  const header = lines.shift().split(',');
  const key = header.shift();
  const now = new Date();
  const headerIdx = [];
  const fields = [];
  header.forEach((h, i) => {
    if (h === '') return;
    headerIdx.push(i);
    fields.push({key: h, format: 'text'});
  });
  const mapping = {
    created: now.toString(),
    fields: fields,
    key: key,
    mapping: {}
  };
  lines.forEach(line => {
    const values = line.split(',');
    const k = values.shift();
    mapping.mapping[k] = Array(headerIdx.length);
    headerIdx.forEach(i => {
      mapping.mapping[k][i] = values[i];
    });
  });
  return mapping;
}
661131
def place_order(self, price, qty, code, trd_side, order_type=OrderType.NORMAL,
                    adjust_limit=0, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0):
        
        # ret, msg = self._check_trd_env(trd_env)
        # if ret != RET_OK:
        #     return ret, msg

        ret, msg, acc_id = self._check_acc_id_and_acc_index(trd_env, acc_id, acc_index)
        if ret != RET_OK:
            return ret, msg

        ret, content = self._split_stock_code(code)
        if ret != RET_OK:
            return ret, content

        market_str, stock_code = content

        query_processor = self._get_sync_query_processor(
            PlaceOrder.pack_req, PlaceOrder.unpack_rsp)

        # the keys of kargs should be corresponding to the actual function arguments
        kargs = {
            'trd_side': trd_side,
            'order_type': order_type,
            'price': float(price),
            'qty': float(qty),
            'code': stock_code,
            'adjust_limit': float(adjust_limit),
            'trd_mkt': self.__trd_mkt,
            'sec_mkt_str': market_str,
            'trd_env': trd_env,
            'acc_id': acc_id,
            'conn_id': self.get_sync_conn_id()
        }

        ret_code, msg, order_id = query_processor(**kargs)
        if ret_code != RET_OK:
            return RET_ERROR, msg

        order_item = {'trd_env': trd_env, 'order_id': order_id}

        # 保持跟v2.0兼容， 增加必要的订单字段
        for x in range(3):
            ret_code, ret_data = self._order_list_query_impl(order_id=order_id,status_filter_list=[],
                                            code="", start="", end="", trd_env=trd_env, acc_id=acc_id)
            if ret_code == RET_OK and len(ret_data) > 0:
                order_item = ret_data[0]
                order_item['trd_env'] = trd_env
                break

        col_list = [
            "code", "stock_name", "trd_side", "order_type", "order_status",
            "order_id", "qty", "price", "create_time", "updated_time",
            "dealt_qty", "dealt_avg_price", "last_err_msg"
        ]
        order_list = [order_item]
        order_table = pd.DataFrame(order_list, columns=col_list)

        return RET_OK, order_table
1331298
def to_vcf(in_tsv, data):
    
    call_convert = {"Amp": "DUP", "Del": "DEL"}
    out_file = "%s.vcf" % utils.splitext_plus(in_tsv)[0]
    if not utils.file_uptodate(out_file, in_tsv):
        with file_transaction(data, out_file) as tx_out_file:
            with open(in_tsv) as in_handle:
                with open(tx_out_file, "w") as out_handle:
                    out_handle.write(VCF_HEADER + "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t%s\n"
                                     % (dd.get_sample_name(data)))
                    header = in_handle.readline().split("\t")
                    for cur in (dict(zip(header, l.split("\t"))) for l in in_handle):
                        if cur["Amp_Del"] in call_convert:
                            svtype = call_convert[cur["Amp_Del"]]
                            info = "SVTYPE=%s;END=%s;SVLEN=%s;FOLD_CHANGE_LOG=%s;PROBES=%s;GENE=%s" % (
                                svtype, cur["End"], int(cur["End"]) - int(cur["Start"]),
                                cur["Log2ratio"], cur["Ab_Seg"], cur["Gene"])
                            out_handle.write("\t".join([cur["Chr"], cur["Start"], ".", "N", "<%s>" % (svtype),
                                                        ".", ".", info, "GT", "1/1"]) + "\n")
    return vcfutils.sort_by_ref(out_file, data)