For Task overall stock display
        一行顯示資訊，用於終端機顯示樣式。
481472
def Cmd_display(self):
    
    re = "%(stock_no)s %(stock_name)s %(stock_date)s %(stock_price)s %(stock_range)s %(stock_range_per).2f%% %(RABC)s %(stock_vol)s" % {
        'stock_name': unicode(self.stock_name),
        'stock_no': unicode(self.stock_no),
        'stock_date': unicode(self.data_date[-1]),
        'stock_price': unicode(self.raw_data[-1]),
        'stock_range': unicode(self.stock_range[-1]),
        'stock_range_per': self.range_per,
        'stock_vol': self.stock_vol[-1]/1000,
        'RABC': self.RABC
      }
    return re
388903
def QA_SU_save_stock_day(client=DATABASE, ui_log=None, ui_progress=None):
    '''
     
    '''
    stock_list = QA_fetch_get_stock_list().code.unique().tolist()
    coll_stock_day = client.stock_day
    coll_stock_day.create_index(
        [("code",
          pymongo.ASCENDING),
         ("date_stamp",
          pymongo.ASCENDING)]
    )
    err = []

    # saveing result

    def __gen_param(stock_list, coll_stock_day, ip_list=[]):
        results = []
        count = len(ip_list)
        total = len(stock_list)
        for item in range(len(stock_list)):
            try:
                code = stock_list[item]
                QA_util_log_info(
                    '##JOB01 Now Saving STOCK_DAY==== {}'.format(str(code)),
                    ui_log
                )

                # 首选查找数据库 是否 有 这个代码的数据
                search_cond = {'code': str(code)[0:6]}
                ref = coll_stock_day.find(search_cond)
                end_date = str(now_time())[0:10]
                ref_count = coll_stock_day.count_documents(search_cond)

                # 当前数据库已经包含了这个代码的数据， 继续增量更新
                # 加入这个判断的原因是因为如果股票是刚上市的 数据库会没有数据 所以会有负索引问题出现
                if ref_count > 0:
                    # 接着上次获取的日期继续更新
                    start_date = ref[ref_count - 1]['date']
                    # print("ref[ref.count() - 1]['date'] {} {}".format(ref.count(), coll_stock_day.count_documents({'code': str(code)[0:6]})))
                else:
                    # 当前数据库中没有这个代码的股票数据， 从1990-01-01 开始下载所有的数据
                    start_date = '1990-01-01'
                QA_util_log_info(
                    'UPDATE_STOCK_DAY \n Trying updating {} from {} to {}'
                        .format(code,
                                start_date,
                                end_date),
                    ui_log
                )
                if start_date != end_date:
                    # 更新过的，不更新
                    results.extend([(code, start_date, end_date, '00', 'day', ip_list[item % count]['ip'],
                                     ip_list[item % count]['port'], item, total, ui_log, ui_progress)])
            except Exception as error0:
                print('Exception:{}'.format(error0))
                err.append(code)
        return results

    ips = get_ip_list_by_multi_process_ping(stock_ip_list, _type='stock')[:cpu_count() * 2 + 1]
    param = __gen_param(stock_list, coll_stock_day, ips)
    ps = QA_SU_save_stock_day_parallelism(processes=cpu_count() if len(ips) >= cpu_count() else len(ips),
                                          client=client, ui_log=ui_log)
    ps.add(do_saving_work, param)
    ps.run()

    if len(err) < 1:
        QA_util_log_info('SUCCESS save stock day ^_^', ui_log)
    else:
        QA_util_log_info('ERROR CODE \n ', ui_log)
        QA_util_log_info(err, ui_log)
1131362
def QA_SU_save_stock_info(client=DATABASE, ui_log=None, ui_progress=None):
    

    client.drop_collection('stock_info')
    stock_list = QA_fetch_get_stock_list().code.unique().tolist()
    coll = client.stock_info
    coll.create_index('code')
    err = []

    def __saving_work(code, coll):
        QA_util_log_info(
            '##JOB10 Now Saving STOCK INFO ==== {}'.format(str(code)),
            ui_log=ui_log
        )
        try:
            coll.insert_many(
                QA_util_to_json_from_pandas(QA_fetch_get_stock_info(str(code)))
            )

        except:
            err.append(str(code))

    for i_ in range(len(stock_list)):
        # __saving_work('000001')

        strLogProgress = 'DOWNLOAD PROGRESS {} '.format(
            str(float(i_ / len(stock_list) * 100))[0:4] + '%'
        )
        intLogProgress = int(float(i_ / len(stock_list) * 10000.0))
        QA_util_log_info('The {} of Total {}'.format(i_, len(stock_list)))
        QA_util_log_info(
            strLogProgress,
            ui_log=ui_log,
            ui_progress=ui_progress,
            ui_progress_int_value=intLogProgress
        )

        __saving_work(stock_list[i_], coll)
    if len(err) < 1:
        QA_util_log_info('SUCCESS', ui_log=ui_log)
    else:
        QA_util_log_info(' ERROR CODE \n ', ui_log=ui_log)
        QA_util_log_info(err, ui_log=ui_log)
305018
def QA_SU_save_stock_terminated(client=DATABASE):
    '''
    
    '''

    # 🛠todo 已经失效从wind 资讯里获取
    # 这个函数已经失效
    print("！！！ tushare 这个函数已经失效！！！")
    df = QATs.get_terminated()
    #df = QATs.get_suspended()
    print(
        " Get stock terminated from tushare,stock count is %d  (终止上市股票列表)" %
        len(df)
    )
    coll = client.stock_terminated
    client.drop_collection(coll)
    json_data = json.loads(df.reset_index().to_json(orient='records'))
    coll.insert(json_data)
    print(" 保存终止上市股票列表 到 stock_terminated collection， OK")
1263338
def upcoming_data(self, broker, data):
        '''
        
        '''
        # main thread'
        # if self.running_time is not None and self.running_time!= data.datetime[0]:
        #     for item in self.broker.keys():
        #         self._settle(item)
        self.running_time = data.datetime[0]
        for account in self.session.values():
            account.run(QA_Event(
                event_type=ENGINE_EVENT.UPCOMING_DATA,
                # args 附加的参数
                market_data=data,
                broker_name=broker,
                send_order=self.insert_order,  # 🛠todo insert_order = insert_order
                query_data=self.query_data_no_wait,
                query_order=self.query_order,
                query_assets=self.query_assets,
                query_trade=self.query_trade
            ))
122863
def QA_SU_save_etf_list(client=DATABASE, ui_log=None, ui_progress=None):
    
    try:
        QA_util_log_info(
            '##JOB16 Now Saving ETF_LIST ====',
            ui_log=ui_log,
            ui_progress=ui_progress,
            ui_progress_int_value=5000
        )
        etf_list_from_tdx = QA_fetch_get_stock_list(type_="etf")
        pandas_data = QA_util_to_json_from_pandas(etf_list_from_tdx)

        if len(pandas_data) > 0:
            # 获取到数据后才进行drop collection 操作
            client.drop_collection('etf_list')
            coll = client.etf_list
            coll.create_index('code')
            coll.insert_many(pandas_data)
        QA_util_log_info(
            "完成ETF列表获取",
            ui_log=ui_log,
            ui_progress=ui_progress,
            ui_progress_int_value=10000
        )
    except Exception as e:
        QA_util_log_info(e, ui_log=ui_log)
        print(" Error save_tdx.QA_SU_save_etf_list exception!")
        pass
563197
def track_strategy_worker(self, strategy, name, interval=10, **kwargs):
        """"""
        while True:
            try:
                transactions = self.query_strategy_transaction(
                    strategy, **kwargs
                )
            # pylint: disable=broad-except
            except Exception as e:
                log.exception("无法获取策略 %s 调仓信息, 错误: %s, 跳过此次调仓查询", name, e)
                time.sleep(3)
                continue
            for transaction in transactions:
                trade_cmd = {
                    "strategy": strategy,
                    "strategy_name": name,
                    "action": transaction["action"],
                    "stock_code": transaction["stock_code"],
                    "amount": transaction["amount"],
                    "price": transaction["price"],
                    "datetime": transaction["datetime"],
                }
                if self.is_cmd_expired(trade_cmd):
                    continue
                log.info(
                    "策略 [%s] 发送指令到交易队列, 股票: %s 动作: %s 数量: %s 价格: %s 信号产生时间: %s",
                    name,
                    trade_cmd["stock_code"],
                    trade_cmd["action"],
                    trade_cmd["amount"],
                    trade_cmd["price"],
                    trade_cmd["datetime"],
                )
                self.trade_queue.put(trade_cmd)
                self.add_cmd_to_expired_cmds(trade_cmd)
            try:
                for _ in range(interval):
                    time.sleep(1)
            except KeyboardInterrupt:
                log.info("程序退出")
                break
77769
def show(format, full):
    
    # load asset allocation
    app = AppAggregate()
    app.logger = logger
    model = app.get_asset_allocation()

    if format == "ascii":
        formatter = AsciiFormatter()
    elif format == "html":
        formatter = HtmlFormatter
    else:
        raise ValueError(f"Unknown formatter {format}")

    # formatters can display stock information with --full
    output = formatter.format(model, full=full)
    print(output)
539631
private void display(ResultSet rows) {

    final int width1 = 38;
    final int width2 = 12;
    final int width3 = 30;
    final int width4 = 21;

    String format = "%-" + width1 + "s%-" + width2 + "s%-" + width3 + "s%-" + width4 + "s%n";

    // headings
    System.out.printf(format, "sensor_id", "date", "timestamp", "value");

    // separators
    drawLine(width1, width2, width3, width4);

    // data
    for (Row row : rows) {

      System.out.printf(
          format,
          row.getUuid("sensor_id"),
          row.getLocalDate("date"),
          row.getInstant("timestamp"),
          row.getDouble("value"));
    }
  }
659396
def allck():
  '''  '''
  for i in twseno().allstockno:
    a = goristock.goristock(i)
    try:
      if a.stock_vol[-1] > 1000*1000 and a.raw_data[-1] > 10:
        #a.goback(3) ## 倒退天數
        ck4m(a)
    except:
      pass
324805
def display(self):
        """"""
        def render(line):
            is_wide_char = False
            for x in range(self.columns):
                if is_wide_char:  # Skip stub
                    is_wide_char = False
                    continue
                char = line[x].data
                assert sum(map(wcwidth, char[1:])) == 0
                is_wide_char = wcwidth(char[0]) == 2
                yield char

        return ["".join(render(self.buffer[y])) for y in range(self.lines)]
783238
def _example_rt_data(quote_ctx):
    
    stock_code_list = ["US.AAPL", "HK.00700"]

    ret_status, ret_data = quote_ctx.subscribe(stock_code_list, ft.SubType.RT_DATA)
    if ret_status != ft.RET_OK:
        print(ret_data)
        exit()

    for stk_code in stock_code_list:
        ret_status, ret_data = quote_ctx.get_rt_data(stk_code)
        if ret_status != ft.RET_OK:
            print(stk_code, ret_data)
            exit()

        print("%s RT_DATA" % stk_code)
        print(ret_data)
        print("\n\n")
1294349
def output_text(account, all_data, show_hourly=False):
    """"""
    print("""
#################################
# Hydro Quebec data for account #
# {}
#################################""".format(account))
    for contract, data in all_data.items():
        data['contract'] = contract
        if data['period_total_bill'] is None:
            data['period_total_bill'] = 0.0
        if data['period_projection'] is None:
            data['period_projection'] = 0.0
        if data['period_mean_daily_bill'] is None:
            data['period_mean_daily_bill'] = 0.0
        output = ("""
----------------------------------------------------------------

Contract: {d[contract]}
===================

Balance: {d[balance]:.2f} $

Period Info
===========
Period day number:      {d[period_length]:d}
Period total days:      {d[period_total_days]:d} days

Period current bill
===================
Total Bill:             {d[period_total_bill]:.2f} $
Projection bill:        {d[period_projection]:.2f} $
Mean Daily Bill:        {d[period_mean_daily_bill]:.2f} $

Total period consumption
========================
Lower price:            {d[period_lower_price_consumption]:.2f} kWh
Higher price:           {d[period_higher_price_consumption]:.2f} kWh
Total:                  {d[period_total_consumption]:.2f} kWh
Mean daily:             {d[period_mean_daily_consumption]:.2f} kWh""")
        print(output.format(d=data))
        if data.get("period_average_temperature") is not None:
            output2 = ("""Temperature:            {d[period_average_temperature]:d} °C""")
            print(output2.format(d=data))
        if data.get("yesterday_average_temperature") is not None:
            output3 = ("""
Yesterday consumption
=====================
Temperature:            {d[yesterday_average_temperature]:d} °C
Lower price:            {d[yesterday_lower_price_consumption]:.2f} kWh
Higher price:           {d[yesterday_higher_price_consumption]:.2f} kWh
Total:                  {d[yesterday_total_consumption]:.2f} kWh""")
            print(output3.format(d=data))
        if show_hourly:
            msg = ("""
Yesterday consumption details
-----------------------------
   Hour  | Temperature | Lower price consumption | Higher price consumption | total comsumption
""")
            for hdata in data['yesterday_hourly_consumption']:
                msg += ("{d[hour]} | {d[temp]:8d} °C | {d[lower]:19.2f} kWh | "
                        "{d[high]:20.2f} kWh | {d[total]:.2f} kWh\n").format(d=hdata)
            print(msg)

        if data['annual_total_bill']:
            output3 = ("""
    Annual Total
    ============

    Start date:             {d[annual_date_start]}
    End date:               {d[annual_date_end]}
    Total bill:             {d[annual_total_bill]} $
    Mean daily bill:        {d[annual_mean_daily_bill]} $
    Total consumption:      {d[annual_total_consumption]} kWh
    Mean dailyconsumption:  {d[annual_mean_daily_consumption]} kWh
    kWh price:              {d[annual_kwh_price_cent]} ¢
    """)
            print(output3.format(d=data))
315974
def mkCuttingStock(s):
    """"""
    w,q = [],[]   # list of different widths (sizes) of items, their quantities
    for item in sorted(s):
        if w == [] or item != w[-1]:
            w.append(item)
            q.append(1)
        else:
            q[-1] += 1
    return w,q
837175
def display(self, typ, data):
        
        if hasattr(self, 'print_' + typ):
            getattr(self, 'print_' + typ)(data)

        elif not data:
            self._print("%s: %s" % (typ, data))

        elif isinstance(data, collections.Mapping):
            self._print("\n", typ)
            for k, v in data.items():
                self.print(k, v)

        elif isinstance(data, (list, tuple)):
            # tabular data layout for lists of dicts
            if isinstance(data[0], collections.Mapping):
                self.display_set(typ, data, self._get_columns(data[0]))
            else:
                for each in data:
                    self.print(typ, each)
        else:
            self._print("%s: %s" % (typ, data))

        self.fobj.flush()
1189341
def loop_get_mkt_snapshot(api_svr_ip, api_svr_port, market):
    
    # 创建行情api
    quote_ctx = ft.OpenQuoteContext(host=api_svr_ip, port=api_svr_port)
    stock_type = [ft.SecurityType.STOCK, ft.SecurityType.IDX, ft.SecurityType.ETF, ft.SecurityType.WARRANT,
                  ft.SecurityType.BOND]

    stock_codes = []
    # 枚举所有的股票类型，获取股票codes
    for sub_type in stock_type:
        ret_code, ret_data = quote_ctx.get_stock_basicinfo(market, sub_type)
        if ret_code == 0:
            print("get_stock_basicinfo: market={}, sub_type={}, count={}".format(market, sub_type, len(ret_data)))
            for ix, row in ret_data.iterrows():
                stock_codes.append(row['code'])

    if len(stock_codes) == 0:
        quote_ctx.close()
        print("Error market:'{}' can not get stock info".format(market))
        return

    # 按频率限制获取股票快照: 每5秒200支股票
    for i in range(1, len(stock_codes), 200):
        print("from {}, total {}".format(i, len(stock_codes)))
        ret_code, ret_data = quote_ctx.get_market_snapshot(stock_codes[i:i + 200])
        if ret_code != 0:
            print(ret_data)
        time.sleep(3)

    quote_ctx.close()
655252
private void displayNode(JspWriter out, ViewNode node, String url_Path, int level, int width) throws IOException {

		// ----------------------------------------显示节点本身信息，如节点名称等开始
		String encodedNodeKey = URLEncoder.encode(node.getKey(), "UTF-8");
		String action = replace(nodeAction, "${key}", encodedNodeKey);
		StringBuilder url = new StringBuilder(url_Path);
		url.append(action);
		if (nodeAction.indexOf("?") < 0)
			url.append("?");
		else
			url.append("&");
		url.append("key=").append(node.getKey());
		String treeNodeAction = url.toString();

		url = new StringBuilder(url_Path);
		url.append(treeAction);
		if (treeAction.indexOf("?") < 0)
			url.append("?");
		else
			url.append("&");
		url.append("select=").append(node.getKey());
		String updateNodeAction = url.toString();

		// Render the label for this node (if any)
		out.print("    <td colspan=\"");
		out.print(width - level + 1);
		out.print("\">");

		// 这里省略了icon

		if (node.getLabel() != null) {
			String labelStyle = null;
			if (node.isSelected())
				labelStyle = CSS_STYLE_SELECTED;
			else if (!node.isSelected())
				labelStyle = CSS_STYLE_UN_SELECTED;
			if (treeNodeAction != null) {
				// Note the leading space so that the text has some space
				// between it and any preceding images
				out.print(" <a href=\"");
				out.print(treeNodeAction);
				out.print("\"");
				if (target != null) {
					out.print(" target=\"");
					out.print(target);
					out.print("\"");
				}
				if (labelStyle != null) {
					out.print(" class=\"");
					out.print(labelStyle);
					out.print("\"");
				}
				// to refresh the tree in the same 'self' frame
				out.print(" onclick=\"");
				out.print("self.location.href='" + updateNodeAction + "'");
				out.print("\"");
				out.print(">");
			} else if (labelStyle != null) {
				out.print("<span class=\"");
				out.print(labelStyle);
				out.print("\">");
			}
			out.print(node.getLabel());
			if (treeNodeAction != null)
				out.print("</a>");
			else if (labelStyle != null)
				out.print("</span>");
		}

		out.println("</td>");

		// ----------------------------------------显示节点本身信息，如节点名称等结束

	}