text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommonLab;
using KFCC.ExchangeInterface;
using Newtonsoft.Json.Linq;
using RestSharp;
using System.Net;

namespace KFCC.Exchanges.EBinance
{
    public class EBinanceExchange : KFCC.ExchangeInterface.IExchanges
    {
        private static string _secret;
        private static string _key;
        private static string _uid;
        private static string _username;
        private Proxy _proxy = null;
        static private Dictionary<string, KFCC.ExchangeInterface.SubscribeInterface> _subscribedtradingpairs = null;
        static private string ApiUrl = @"https://api.binance.com/";

        public string Name { get { return "Binance"; } }
        public string ExchangeUrl { get { return "www.binance.com"; } }
        public string Remark { get { return "Binance exchange remark"; } }
        public string Secret { get { return _secret; } set { _secret = value; } }
        public string Key { get { return _key; } set { _key = value; } }
        public string UID { get { return _uid; } set { _uid = value; } }
        public string UserName { get { return _username; } set { _username = value; } }

        public Dictionary<string, KFCC.ExchangeInterface.SubscribeInterface> SubscribedTradingPairs { get { return _subscribedtradingpairs; } }
        public Fee eFee { get; set; }
        public Proxy proxy { get { return _proxy; } set { _proxy = value; } }
        private Account _account;
        public Account Account { get { return _account; } set { _account = value; } }
        //public bool SportWSS { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
        //public bool SportThirdPartWSS { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

        public event ExchangeEventWarper.TickerEventHander TickerEvent;
        public event ExchangeEventWarper.DepthEventHander DepthEvent;
        public event ExchangeEventWarper.TradeEventHander TradeEvent;
        public event ExchangeEventWarper.SubscribedEventHander SubscribedEvent;

        public EBinanceExchange(string key, string secret, string uid, string username)
        {
            _key = key;
            _secret = secret;
            _uid = uid;
            _username = username;
        }
        public EBinanceExchange()
        {

        }

        public void SetupExchage(string key, string secret, string uid, string username)
        {
            _key = key;
            _secret = secret;
            _uid = uid;
            _username = username;
        }
        public void SetupFee(string maker, string taker)
        {
            eFee = new Fee();
            eFee.MakerFee = Convert.ToDouble(maker) / 100;
            eFee.TakerFee = Convert.ToDouble(taker) / 100;
        }
        public bool Subscribe(CommonLab.TradePair tp, SubscribeTypes st)
        {
            //throw new NotImplementedException();
            //订阅
            string tradingpairs = GetLocalTradingPairString(tp, st);
            if (st == SubscribeTypes.WSS)
            {
                if (_subscribedtradingpairs == null)
                {
                    _subscribedtradingpairs = new Dictionary<string, KFCC.ExchangeInterface.SubscribeInterface>();

                }
                if (_subscribedtradingpairs.ContainsKey(tradingpairs))
                {
                    //有这个订阅
                }
                else
                {
                    string raw;
                    Ticker t = GetTicker(GetLocalTradingPairString(tp), out raw);
                    Depth d = GetDepth(GetLocalTradingPairString(tp), out raw);
                    _subscribedtradingpairs.Add(tradingpairs, new WssHelper(tp, t, d));
                    _subscribedtradingpairs[tradingpairs].TradeInfoEvent += BinanceExchange_TradeInfoEvent;
                }
            }
            else if (st == SubscribeTypes.RESTAPI)
            {
                if (_subscribedtradingpairs == null)
                {
                    _subscribedtradingpairs = new Dictionary<string, KFCC.ExchangeInterface.SubscribeInterface>();

                }
                if (_subscribedtradingpairs.ContainsKey(tradingpairs))
                {
                    //有这个订阅

                }
                else
                {
                    string raw;
                    Ticker t = GetTicker(GetLocalTradingPairString(tp), out raw);
                    Depth d = GetDepth(GetLocalTradingPairString(tp), out raw);
                    _subscribedtradingpairs.Add(tradingpairs, new RESTHelper(tp, t, d));
                    //_subscribedtradingpairs[tradingpairs].TradeInfoEvent += OkCoinExchange_TradeInfoEvent;
                }
            }
            if (SubscribedEvent != null)
                SubscribedEvent(this, st, tp);
            return true;
        }

        private void BinanceExchange_TradeInfoEvent(TradingInfo ti, TradeEventType tt)
        {
            if (TickerEvent != null && tt == TradeEventType.TICKER)
            {
                TickerEvent(this, ti.t, (CommonLab.EventTypes)ti.type, ti.tp);
            }
            if (DepthEvent != null && tt == TradeEventType.ORDERS)
            {
                DepthEvent(this, ti.d, (CommonLab.EventTypes)ti.type, ti.tp);
            }
            if (TradeEvent != null && tt == TradeEventType.TRADE)
            {
                TradeEvent(this, ti.trade, (CommonLab.EventTypes)ti.type, ti.tp);

            }
        }

        public Ticker GetTicker(string tradingpair, out string rawresponse)
        {
            DateTime st = DateTime.Now;
            //throw new NotImplementedException();
            string url = GetPublicApiURL("symbol="+tradingpair+ "&interval=1m&limit=1", "api/v1/klines");
            rawresponse = CommonLab.Utility.GetHttpContent(url, "GET", "", _proxy);
            CommonLab.Ticker t = new Ticker();
            JArray ticker = JArray.Parse(JArray.Parse(rawresponse)[0].ToString());
            try
            {

                t.High = Convert.ToDouble(ticker[2].ToString());
                t.Low = Convert.ToDouble(ticker[3].ToString());
                t.Last = Convert.ToDouble(ticker[4].ToString());
                //t.Sell = Convert.ToDouble(ticker["sell"].ToString());
                //t.Buy = Convert.ToDouble(ticker["buy"].ToString());
                t.Volume = Convert.ToDouble(ticker[5].ToString());
                t.Open = Convert.ToDouble(ticker[1].ToString());// Convert.ToDouble(ticker["open"].ToString());
                t.ExchangeTimeStamp = Convert.ToDouble(ticker[6]);
                t.LocalServerTimeStamp = CommonLab.TimerHelper.GetTimeStampMilliSeconds(DateTime.Now);
                t.Delay = (DateTime.Now - st).TotalMilliseconds;
                string r;
                Depth d = GetDepth(tradingpair, out r);
                if (d.Bids.Count > 0)
                    t.Buy = d.Bids[0].Price;
                if (d.Asks.Count > 0)
                    t.Sell = d.Asks[0].Price;
                UpdateTicker(tradingpair, t);
            }
            catch
            {

            }
            return t;
        }

        public Depth GetDepth(string tradingpair, out string rawresponse)
        {
            DateTime st = DateTime.Now;
            string url = GetPublicApiURL("symbol=" + tradingpair + "&limit=50", "api/v1/depth");
            rawresponse = CommonLab.Utility.GetHttpContent(url, "GET", "", _proxy);
            CommonLab.Depth d = new Depth();
            d.Asks = new List<MarketOrder>();
            d.Bids = new List<MarketOrder>();
            JObject obj = JObject.Parse(rawresponse);
            JArray jasks = JArray.Parse(obj["asks"].ToString());
            for (int i = 0; i < jasks.Count; i++)
            {
                MarketOrder m = new MarketOrder();
                m.Price = Convert.ToDouble(JArray.Parse(jasks[i].ToString())[0]);
                m.Amount = Convert.ToDouble(JArray.Parse(jasks[i].ToString())[1]);
                d.AddNewAsk(m);
            }

            JArray jbids = JArray.Parse(obj["bids"].ToString());
            for (int i = 0; i < jbids.Count; i++)
            {
                MarketOrder m = new MarketOrder();
                m.Price = Convert.ToDouble(JArray.Parse(jbids[i].ToString())[0]);
                m.Amount = Convert.ToDouble(JArray.Parse(jbids[i].ToString())[1]);
                d.AddNewBid(m);
            }
            d.ExchangeTimeStamp = 0;// Convert.ToDouble(obj["timestamp"].ToString());
            d.LocalServerTimeStamp = CommonLab.TimerHelper.GetTimeStampMilliSeconds(DateTime.Now);
            d.Delay = (DateTime.Now - st).TotalMilliseconds;
            UpdateDepth(tradingpair, d);
            return d;
        }

        public Trade[] GetTrades(string tradepair, out string rawresponse, string since = "0")
        {
            List<Trade> trades = new List<CommonLab.Trade>();
            string url = GetPublicApiURL("symbol=" + tradepair + "&limit=50", "api/v1/trades");
            if (since != "0")
            {
                url += "&since=" + since;
            }
            rawresponse = CommonLab.Utility.GetHttpContent(url, "GET", "", _proxy);

            JArray obj = JArray.Parse(rawresponse);
            for (int i = 0; i < obj.Count; i++)
            {
                JObject trade = JObject.Parse(obj[i].ToString());
                Trade t = new CommonLab.Trade();
                t.TradeID = trade["id"].ToString();
                t.Amount = Convert.ToDouble(trade["qty"].ToString());
                t.Price = Convert.ToDouble(trade["price"].ToString());
                if (Convert.ToBoolean(trade["isBuyerMaker"].ToString()))
                    t.Type = TradeType.Buy;
                else
                    t.Type = TradeType.Sell;

                t.ExchangeTimeStamp = Convert.ToDouble(trade["time"].ToString()) ; //时间戳 交易所返回的
                t.LocalServerTimeStamp = CommonLab.TimerHelper.GetTimeStampMilliSeconds(DateTime.Now); //本地时间戳
                t.BuyOrderID = "";//成交的交易号
                t.SellOrderID = "";//成交的交易号
                trades.Add(t);
            }
            if (trades.Count > 0)
                return trades.ToArray();
            return null;
        }
        /// <summary>
        /// 更新深度数据
        /// </summary>
        /// <param name="d"></param>
        protected void UpdateDepth(string tradingpair, Depth d)
        {
            if (SubscribedTradingPairs != null)
                if (SubscribedTradingPairs.ContainsKey(tradingpair))
            {
                ((RESTHelper)SubscribedTradingPairs[tradingpair]).UpdateDepth(d);
            }
        }
        /// <summary>
        /// 更新深度数据
        /// </summary>
        /// <param name="t"></param>
        protected void UpdateTicker(string tradingpair, Ticker t)
        {
            if (SubscribedTradingPairs != null)
                if (SubscribedTradingPairs.ContainsKey(tradingpair))
            {
                ((RESTHelper)SubscribedTradingPairs[tradingpair]).TradeInfo.t = t;
            }
        }
        protected string Trade(OrderType type, string tradingpair, double price, double amount)
        {
            CheckSet();
            price = CommonLab.Utility.ToFixed(price, 6);
            string url = GetPublicApiURL("", "api/v3/order");
            RestClient rc = new RestClient(url);
            if (_proxy != null)
            {
                rc.Proxy = new WebProxy(_proxy.IP, Convert.ToInt32(_proxy.Port));
            }
            RestRequest rr = new RestRequest(Method.POST);
            rr.AddHeader("X-MBX-APIKEY", _key);
            Dictionary<String, String> paras = new Dictionary<String, String>();
            paras.Add("symbol", tradingpair);
            rr.AddParameter("symbol", tradingpair);
            switch (type)
            {
                case OrderType.ORDER_TYPE_BUY:
                    paras.Add("side", "BUY");
                    paras.Add("type", "LIMIT");
                    paras.Add("timeInForce", "GTC");
                    paras.Add("quantity", amount.ToString());
                    paras.Add("price", price.ToString());
                    rr.AddParameter("side", "BUY");
                    rr.AddParameter("type", "LIMIT");
                    rr.AddParameter("timeInForce", "GTC");
                    rr.AddParameter("quantity", amount.ToString());
                    rr.AddParameter("price", price.ToString());

                    break;
                case OrderType.ORDER_TYPE_SELL:
                    paras.Add("side", "SELL");
                    paras.Add("type", "LIMIT");
                    paras.Add("timeInForce", "GTC");
                    paras.Add("quantity", amount.ToString());
                    paras.Add("price", price.ToString());
                    rr.AddParameter("side", "SELL");
                    rr.AddParameter("type", "LIMIT");
                    rr.AddParameter("timeInForce", "GTC");
                    rr.AddParameter("quantity", amount.ToString());
                    rr.AddParameter("price", price.ToString());
                    break;
                case OrderType.ORDER_TYPE_MARKETBUY:
                    paras.Add("side", "BUY");
                    paras.Add("type", "MARKET");
                    paras.Add("quantity", amount.ToString());
                    rr.AddParameter("side", "BUY");
                    rr.AddParameter("quantity", amount.ToString());
                    rr.AddParameter("type", "MARKET");
                    break;
                case OrderType.ORDER_TYPE_MARKETSELL:
                    paras.Add("side", "SELL");
                    paras.Add("type", "MARKET");
                    paras.Add("quantity", amount.ToString());
                    rr.AddParameter("side", "SELL");
                    rr.AddParameter("quantity", amount.ToString());
                    rr.AddParameter("type", "MARKET");
                    break;

            }
            string ts = CommonLab.TimerHelper.GetTimeStampMilliSeconds(DateTime.Now).ToString();
            paras.Add("recvWindow", "10000");
            paras.Add("timestamp", ts);
            String sign = CommonLab.TokenGen.CreateSign_Binance(paras, _secret);
            rr.AddParameter("recvWindow", "10000");
            rr.AddParameter("timestamp", ts);
            rr.AddParameter("signature", sign);

            var response =  rc.Execute(rr);

            string rawresponse = response.Content;

            try
            {
                JObject obj = JObject.Parse(rawresponse);

                return obj["orderId"].ToString();
            }
            catch (Exception e)
            {
                throw e;
            }

        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="tradepair"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public string GetPublicApiURL(string tradepair, string method)
        {
            //https://www.okex.com/api/v1/ticker.do?symbol=ltc_btc
            if (tradepair.Length > 0)
                return ApiUrl + method + "?" + tradepair;
            else
                return ApiUrl + method;
        }

        public string GetLocalTradingPairString(TradePair t, SubscribeTypes st = CommonLab.SubscribeTypes.RESTAPI)
        {
            if (t.FromSymbol.ToLower() == "bch")
                return "BCC" + t.ToSymbol.ToUpper();
            if (t.ToSymbol.ToLower() == "bch")
                return t.FromSymbol.ToUpper() + "BCC";
            return t.FromSymbol.ToUpper() + t.ToSymbol.ToUpper();
        }

        public Account GetAccount(out string rawresponse)
        {
            CheckSet();
            if (_account == null)
                _account = new Account();
            string url = GetPublicApiURL("", "api/v3/account");
            RestClient rc = new RestClient(url);
            if (_proxy != null)
            {
                rc.Proxy = new WebProxy(_proxy.IP, Convert.ToInt32(_proxy.Port));
            }
            RestRequest rr = new RestRequest(Method.GET);
            rr.AddHeader("X-MBX-APIKEY", _key);
            Dictionary<String, String> paras = new Dictionary<String, String>();
            string ts = CommonLab.TimerHelper.GetTimeStampMilliSeconds(DateTime.Now).ToString();
            paras.Add("timestamp", ts);
            paras.Add("recvWindow", "10000");
            String sign = CommonLab.TokenGen.CreateSign_Binance(paras, _secret);
            rr.AddParameter("timestamp", ts);
            rr.AddParameter("recvWindow", "10000");
            rr.AddParameter("signature", sign);

            var response = rc.Execute(rr);

            rawresponse = response.Content;
            //解析
            try
            {
                JObject obj = JObject.Parse(rawresponse);
                if (obj.Property("balances") == null)
                {
                    throw (new Exception("error:" + rawresponse));
                }

                JArray balances = JArray.Parse(obj["balances"].ToString());
                foreach (JObject jp in balances)
                {
                    string Name = jp["asset"].ToString();
                    double free = Convert.ToDouble(jp["free"].ToString());
                    double locked = Convert.ToDouble(jp["locked"].ToString());
                    if (_account.Balances.ContainsKey(Name))
                    {
                        _account.Balances[Name].borrow = 0;
                        _account.Balances[Name].available = free;
                        _account.Balances[Name].reserved = locked;
                        _account.Balances[Name].balance = free + locked;
                    }
                    else
                    {
                        Balance b = new Balance();
                        b.borrow = 0;
                        b.available = free;
                        b.reserved = locked;
                        b.balance = b.available + b.reserved;

                        _account.Balances.Add(Name, b);
                    }
                }
            }
            catch (Exception e)
            {

                throw e;
            }
            return _account;
        }

        public Order GetOrderStatus(string OrderID, string tradingpair, out string rawresponse)
        {
            CheckSet();
            Order order = null;
            string url = GetPublicApiURL("", "api/v3/order");
            RestClient rc = new RestClient(url);
            if (_proxy != null)
            {
                rc.Proxy = new WebProxy(_proxy.IP, Convert.ToInt32(_proxy.Port));
            }
            RestRequest rr = new RestRequest(Method.GET);
            rr.AddHeader("X-MBX-APIKEY", _key);
            Dictionary<String, String> paras = new Dictionary<String, String>();
            paras.Add("symbol", tradingpair);
            rr.AddParameter("symbol", tradingpair);
            paras.Add("orderId", OrderID);
            rr.AddParameter("orderId", OrderID);
            string ts = CommonLab.TimerHelper.GetTimeStampMilliSeconds(DateTime.Now).ToString();
            paras.Add("recvWindow", "10000");
            paras.Add("timestamp", ts);
            String sign = CommonLab.TokenGen.CreateSign_Binance(paras, _secret);
            rr.AddParameter("recvWindow", "10000");
            rr.AddParameter("timestamp", ts);
            rr.AddParameter("signature", sign);
            var response = rc.Execute(rr);
            rawresponse = response.Content;
            try
            {
                JObject orders = JObject.Parse(rawresponse);

                if (orders.Count > 0)
                {
                    order = new Order();
                    order.Id = orders["orderId"].ToString();
                    order.Amount = Convert.ToDouble(orders["origQty"].ToString());
                    order.DealAmount = Convert.ToDouble(orders["executedQty"].ToString());
                    order.Price = Convert.ToDouble(orders["price"].ToString());
                    order.Type = GetOrderTypeFromString(orders["type"].ToString(), orders["side"].ToString());
                    order.Status = GetOrderStatus(orders["status"].ToString());
                    order.TradingPair = orders["symbol"].ToString();
                    order.CreatDate = CommonLab.TimerHelper.ConvertStringToDateTime(Convert.ToDouble(orders["time"].ToString()) / 1000);
                }

            }
            catch (Exception e)
            {
                Exception err = new Exception("订单获取解析json失败" + e.Message);

                // throw err;
            }
            return order;

        }
        public List<Order> GetHisOrders(string tradingpair)
        {
            CheckSet();
            string rawresponse;
            Order order = null;
            List<Order> orders_array = new List<Order>();
            string url = GetPublicApiURL("", "order_history.do");
            RestClient rc = new RestClient(url);
            if (_proxy != null)
            {
                rc.Proxy = new WebProxy(_proxy.IP, Convert.ToInt32(_proxy.Port));
            }
            int page = 1;
            RestRequest rr = new RestRequest(Method.POST);
            rr.AddParameter("api_key", _key);
            rr.AddParameter("symbol", tradingpair);
            rr.AddParameter("status", 1);
            rr.AddParameter("current_page", page);
            rr.AddParameter("page_length", 200);

            Dictionary<String, String> paras = new Dictionary<String, String>();
            paras.Add("api_key", _key);
            paras.Add("symbol", tradingpair);
            paras.Add("status", "1");
            paras.Add("current_page", page.ToString());

            paras.Add("page_length", "200");
            String sign = CommonLab.TokenGen.CreateSign_Binance(paras, _secret);
            rr.AddParameter("sign", sign);
            var response = new RestClient(url).Execute(rr);

            int total;
            int totalpage = 0;
            rawresponse = response.Content;
            try
            {
                JObject obj = JObject.Parse(rawresponse);
                if (obj.Property("error_code") != null)
                    throw (new Exception(SpotErrcode2Msg.Prase(obj["error_code"].ToString())));
                if (!Convert.ToBoolean(obj["result"]))
                {
                    throw (new Exception("error:" + rawresponse));
                }
                JArray orders = JArray.Parse(obj["orders"].ToString());
                total = Convert.ToInt32(obj["total"].ToString());
                totalpage = total / 200 + 1;
                if (orders.Count > 0)
                {

                    for (int i = 0; i < orders.Count; i++)
                    {

                        order = new Order();
                        order.Id = orders[i]["order_id"].ToString();
                        order.Amount = Convert.ToDouble(orders[i]["amount"].ToString());
                        order.DealAmount = Convert.ToDouble(orders[i]["deal_amount"].ToString());
                        order.Price = Convert.ToDouble(orders[i]["price"].ToString());
                        order.Type = GetOrderTypeFromString(orders[i]["type"].ToString(),"");
                        order.Status = GetOrderStatus(orders[i]["status"].ToString());
                        order.TradingPair = orders[i]["symbol"].ToString();
                        order.CreatDate = CommonLab.TimerHelper.ConvertStringToDateTime(Convert.ToDouble(orders[i]["create_date"].ToString()) / 1000);
                        orders_array.Add(order);
                    }

                }
                for (page = 2; page <= totalpage; page++)
                {
                    rr.Parameters.Clear();
                    paras.Clear();
                    rr.AddParameter("api_key", _key);
                    rr.AddParameter("symbol", tradingpair);
                    rr.AddParameter("status", 1);
                    rr.AddParameter("current_page", page);
                    rr.AddParameter("page_length", 200);

                    paras.Add("api_key", _key);
                    paras.Add("symbol", tradingpair);
                    paras.Add("status", "1");
                    paras.Add("current_page", page.ToString());

                    paras.Add("page_length", "200");
                    sign = CommonLab.TokenGen.CreateSign_Binance(paras, _secret);
                    rr.AddParameter("sign", sign);
                    response = new RestClient(url).Execute(rr);

                    rawresponse = response.Content;
                    obj = JObject.Parse(rawresponse);
                    if (obj.Property("error_code") != null)
                        throw (new Exception(SpotErrcode2Msg.Prase(obj["error_code"].ToString())));
                    if (!Convert.ToBoolean(obj["result"]))
                    {
                        throw (new Exception("error:" + rawresponse));
                    }
                    orders = JArray.Parse(obj["orders"].ToString());
                    if (orders.Count > 0)
                    {

                        for (int i = 0; i < orders.Count; i++)
                        {

                            order = new Order();
                            order.Id = orders[i]["order_id"].ToString();
                            order.Amount = Convert.ToDouble(orders[i]["amount"].ToString());
                            order.DealAmount = Convert.ToDouble(orders[i]["deal_amount"].ToString());
                            order.Price = Convert.ToDouble(orders[i]["price"].ToString());
                            order.Type = GetOrderTypeFromString(orders[i]["type"].ToString(),"");
                            order.Status = GetOrderStatus(orders[i]["status"].ToString());
                            order.TradingPair = orders[i]["symbol"].ToString();
                            order.CreatDate = CommonLab.TimerHelper.ConvertStringToDateTime(Convert.ToDouble(orders[i]["create_date"].ToString()) / 1000);
                            orders_array.Add(order);
                        }

                    }
                }
                return orders_array;

            }
            catch (Exception e)
            {
                Exception err = new Exception("订单获取解析json失败" + e.Message);
                throw err;
            }

        }
        public List<Order> GetOrdersStatus(string tradingpair, out string rawresponse)
        {
            CheckSet();
            Order o = null;
            string url = GetPublicApiURL("", "api/v3/allOrders");
            RestClient rc = new RestClient(url);
            RestRequest rr = new RestRequest(Method.GET);
            rr.AddHeader("X-MBX-APIKEY", _key);
            Dictionary<String, String> paras = new Dictionary<String, String>();
            paras.Add("symbol", tradingpair);
            rr.AddParameter("symbol", tradingpair);

            string ts = CommonLab.TimerHelper.GetTimeStampMilliSeconds(DateTime.Now).ToString();
            paras.Add("recvWindow", "10000");
            paras.Add("timestamp", ts);
            String sign = CommonLab.TokenGen.CreateSign_Binance(paras, _secret);
            rr.AddParameter("recvWindow", "10000");
            rr.AddParameter("timestamp", ts);
            rr.AddParameter("signature", sign);
            var response = rc.Execute(rr);
            rawresponse = response.Content;
            try
            {

                JArray orders = JArray.Parse(rawresponse);
                if (orders.Count > 0)
                {
                    List<Order> orders_array = new List<Order>();
                    for (int i = 0; i < orders.Count; i++)
                    {

                        JObject order = JObject.Parse(orders[i].ToString());

                        o = new Order();
                        o.Id = order["orderId"].ToString();
                        o.Amount = Convert.ToDouble(order["origQty"].ToString());
                        o.DealAmount = Convert.ToDouble(order["executedQty"].ToString());
                        o.Price = Convert.ToDouble(order["price"].ToString());
                        o.Type = GetOrderTypeFromString(order["type"].ToString(), order["side"].ToString());
                        o.Status = GetOrderStatus(order["status"].ToString());
                        o.TradingPair = order["symbol"].ToString();
                        o.CreatDate = CommonLab.TimerHelper.ConvertStringToDateTime(Convert.ToDouble(order["time"].ToString()) / 1000);
                       orders_array.Add(o);
                    }
                    return orders_array;
                }

            }
            catch (Exception e)
            {
                Exception err = new Exception("订单获取解析json失败" + e.Message);
                throw err;
            }
            return null;

        }
        public bool CancelOrder(string OrderID, string tradingpair, out string rawresponse)
        {
            CheckSet();

            string url = GetPublicApiURL("", "api/v3/order");
            RestClient rc = new RestClient(url);
            if (_proxy != null)
            {
                rc.Proxy = new WebProxy(_proxy.IP, Convert.ToInt32(_proxy.Port));
            }
            RestRequest rr = new RestRequest(Method.DELETE);
            rr.AddHeader("X-MBX-APIKEY", _key);
            Dictionary<String, String> paras = new Dictionary<String, String>();
            paras.Add("symbol", tradingpair);
            rr.AddParameter("symbol", tradingpair);
            paras.Add("orderId", OrderID);
            rr.AddParameter("orderId", OrderID);
            string ts = CommonLab.TimerHelper.GetTimeStampMilliSeconds(DateTime.Now).ToString();
            paras.Add("recvWindow", "10000");
            paras.Add("timestamp", ts);
            String sign = CommonLab.TokenGen.CreateSign_Binance(paras, _secret);
            rr.AddParameter("recvWindow", "10000");
            rr.AddParameter("timestamp", ts);
            rr.AddParameter("signature", sign);
            var response = rc.Execute(rr);
            rawresponse = response.Content;
            try
            {
                JObject obj = JObject.Parse(rawresponse);
                if (obj["orderId"].ToString()==OrderID)
                {
                    return true;
                }

            }
            catch (Exception e)
            {
                //这里应该抛出错误
            }
            return false;
        }

        public bool CancelAllOrders(string tradingpair = "")
        {
            bool flag = false;
            try
            {
                if (SubscribedTradingPairs != null)
                {
                    foreach (KeyValuePair<string, SubscribeInterface> item in SubscribedTradingPairs)
                    {
                        string raw = "";
                        List<CommonLab.Order> orders = GetOrdersStatus(item.Key, out raw);
                        if (orders != null)
                        {
                            for (int i = 0; i < orders.Count; i++)
                            { CancelOrder(orders[i].Id, item.Key, out raw); }
                            flag = true;
                        }
                    }
                }
                return flag;
            }
            catch
            {
                return flag;
            }

        }

        public string Buy(string Symbol, double Price, double Amount)
        {
            if (Price > 0)
            {
                return Trade(OrderType.ORDER_TYPE_BUY, Symbol, Price, Amount);
            }
            else if (Price == 0)
            {
                return Trade(OrderType.ORDER_TYPE_MARKETBUY, Symbol, Price, Amount);
            }
            return "";
        }

        public string Sell(string Symbol, double Price, double Amount)
        {
            if (Price > 0)
            {
                return Trade(OrderType.ORDER_TYPE_SELL, Symbol, Price, Amount);
            }
            else if (Price == 0)
            {
                return Trade(OrderType.ORDER_TYPE_MARKETSELL, Symbol, Price, Amount);
            }
            return "";
        }

        public void CheckSet()
        {
            if (string.IsNullOrEmpty(_key) || string.IsNullOrEmpty(_secret))
            {
                throw new Exception("交易所设置有问题!");
            }
        }
        static public OrderType GetOrderTypeFromString(string str,string side)
        {
            if (str.ToUpper() == "LIMIT"&&side=="BUY")
                return OrderType.ORDER_TYPE_BUY;
            if (str.ToUpper() == "LIMIT" && side == "SELL")
                return OrderType.ORDER_TYPE_SELL;
            if (str.ToUpper() == "MARKET" && side == "BUY")
                return OrderType.ORDER_TYPE_MARKETBUY;
            if (str.ToUpper() == "MARKET" && side == "SELL")
                return OrderType.ORDER_TYPE_MARKETSELL;
            return OrderType.ORDER_TYPE_UNKOWN;
        }
        static public OrderStatus GetOrderStatus(string str)
        {
            //status:-1:已撤销  0:未成交  1:部分成交  2:完全成交 4:撤单处理中
            if (str.ToUpper() == "NEW")
                return OrderStatus.ORDER_STATE_PENDING;
            if (str.ToUpper() == "PARTIALLY_FILLED")
                return OrderStatus.ORDER_STATE_PARTITAL;
            if (str.ToUpper() == "FILLED")
                return OrderStatus.ORDER_STATE_SUCCESS;
            if (str.ToUpper() == "CANCELED")
                return OrderStatus.ORDER_STATE_CANCELED;
            if (str.ToUpper() == "PENDING_CANCEL ")
                return OrderStatus.ORDER_STATE_CANCELING;
            if (str.ToUpper() == "REJECTED ")
                return OrderStatus.ORDER_STATE_UNKOWN;
            if (str.ToUpper() == "EXPIRED ")
                return OrderStatus.ORDER_STATE_UNKOWN;
            return OrderStatus.ORDER_STATE_UNKOWN;
        }
        private Exception JsonError(JObject obj)
        {
            if (obj.Property("error_code") == null || obj.Property("error_code").ToString() == "")
            {
                return new Exception("\"error_code\" not found in raw json string!");
            }
            else
                return new Exception(SpotErrcode2Msg.Prase(obj["error_code"].ToString()));
        }

        public void DisSubcribe(TradePair tp, SubscribeTypes st)
        {
            throw new NotImplementedException();
        }

    }
}

redpajama_set_name: RedPajamaGithub


This web design/hosting provider was founded in 2005 and claims to be listed on INC. 5000's list. They also claim to serve around 5,000 customers who signed up for their ecommerce solutions. In 2011, they have won the Most Extensive Storefront Tools Award.
Since this company offers bundled services (design, hosting, payment gateway) this review will be a little bit different from the reviews on this website. Their current plans are called Steel, Bronze, Silver, Gold and Platinum. The following features differ from one plan to the next: number of products allowed, storage space and bandwidth allowance.
There are no mentions about any sort of money back guarantee on their website for more information about this, please contact their sales support representatives.
Support is provided in different channels including phone and ticketing system. Note that their phone support is only available during business hours and days. Community forums and knowledge base are just some of the self help options customers can use.
Since the services of this company is pretty unique, a unique control panel is available to use for customers to manage their online stores. Some of the features of this control panel include: quote creation, product upload and affiliate program management.
Some free features include: drag and drop website design and creation software, application and program integrations along with other pretty unique tools for online marketing and SEO uses.
Customers can cancel their accounts at any time they wish to. A 14 day trial is also available to those who wish to try the services and features first before they sign up for the services of this hosting provider.
This provider is one of those companies that offer innovative and unique services for online merchants. If you are looking for such services for some time now, this company might be who you have been looking for.


text:
package kafka.producer

import async.{CallbackHandler, EventHandler}
import org.apache.log4j.Logger
import kafka.serializer.Encoder
import kafka.utils._
import java.util.Properties
import kafka.cluster.{Partition, Broker}
import java.util.concurrent.atomic.AtomicBoolean
import kafka.api.ProducerRequest
import kafka.common.{NoBrokersForPartitionException, InvalidConfigException, InvalidPartitionException}

class Producer[K,V](config: ProducerConfig,
                    partitioner: Partitioner[K],
                    producerPool: ProducerPool[V],
                    populateProducerPool: Boolean,
                    private var brokerPartitionInfo: BrokerPartitionInfo) /* for testing purpose only. Applications should ideally */
                                                          /* use the other constructor*/
{
  private val logger = Logger.getLogger(classOf[Producer[K, V]])
  private val hasShutdown = new AtomicBoolean(false)
  if(!Utils.propertyExists(config.zkConnect) && !Utils.propertyExists(config.brokerPartitionInfo))
    throw new InvalidConfigException("At least one of zk.connect or broker.list must be specified")
  private val random = new java.util.Random
  // check if zookeeper based auto partition discovery is enabled
  private val zkEnabled = Utils.propertyExists(config.zkConnect)
  if(brokerPartitionInfo == null) {
    zkEnabled match {
      case true =>
        val zkProps = new Properties()
        zkProps.put("zk.connect", config.zkConnect)
        zkProps.put("zk.sessiontimeout.ms", config.zkSessionTimeoutMs.toString)
        zkProps.put("zk.connectiontimeout.ms", config.zkConnectionTimeoutMs.toString)
        zkProps.put("zk.synctime.ms", config.zkSyncTimeMs.toString)
        brokerPartitionInfo = new ZKBrokerPartitionInfo(new ZKConfig(zkProps), producerCbk)
      case false =>
        brokerPartitionInfo = new ConfigBrokerPartitionInfo(config)
    }
  }
  // pool of producers, one per broker
  if(populateProducerPool) {
    val allBrokers = brokerPartitionInfo.getAllBrokerInfo
    allBrokers.foreach(b => producerPool.addProducer(new Broker(b._1, b._2.host, b._2.host, b._2.port)))
  }

/**
 * This constructor can be used when all config parameters will be specified through the
 * ProducerConfig object
 * @param config Producer Configuration object
 */
  def this(config: ProducerConfig) =  this(config, Utils.getObject(config.partitionerClass),
    new ProducerPool[V](config, Utils.getObject(config.serializerClass)), true, null)

  /**
   * This constructor can be used to provide pre-instantiated objects for all config parameters
   * that would otherwise be instantiated via reflection. i.e. encoder, partitioner, event handler and
   * callback handler. If you use this constructor, encoder, eventHandler, callback handler and partitioner
   * will not be picked up from the config.
   * @param config Producer Configuration object
   * @param encoder Encoder used to convert an object of type V to a kafka.message.Message. If this is null it
   * throws an InvalidConfigException
   * @param eventHandler the class that implements kafka.producer.async.IEventHandler[T] used to
   * dispatch a batch of produce requests, using an instance of kafka.producer.SyncProducer. If this is null, it
   * uses the DefaultEventHandler
   * @param cbkHandler the class that implements kafka.producer.async.CallbackHandler[T] used to inject
   * callbacks at various stages of the kafka.producer.AsyncProducer pipeline. If this is null, the producer does
   * not use the callback handler and hence does not invoke any callbacks
   * @param partitioner class that implements the kafka.producer.Partitioner[K], used to supply a custom
   * partitioning strategy on the message key (of type K) that is specified through the ProducerData[K, T]
   * object in the  send API. If this is null, producer uses DefaultPartitioner
   */
  def this(config: ProducerConfig,
           encoder: Encoder[V],
           eventHandler: EventHandler[V],
           cbkHandler: CallbackHandler[V],
           partitioner: Partitioner[K]) =
    this(config, if(partitioner == null) new DefaultPartitioner[K] else partitioner,
         new ProducerPool[V](config, encoder, eventHandler, cbkHandler), true, null)
  /**
   * Sends the data, partitioned by key to the topic using either the
   * synchronous or the asynchronous producer
   * @param producerData the producer data object that encapsulates the topic, key and message data
   */
  def send(producerData: ProducerData[K,V]*) {
    val producerPoolRequests = producerData.map { pd =>
    // find the number of broker partitions registered for this topic
      logger.debug("Getting the number of broker partitions registered for topic: " + pd.getTopic)
      val numBrokerPartitions = brokerPartitionInfo.getBrokerPartitionInfo(pd.getTopic).toSeq
      logger.debug("Broker partitions registered for topic: " + pd.getTopic + " = " + numBrokerPartitions)
      val totalNumPartitions = numBrokerPartitions.length
      if(totalNumPartitions == 0) throw new NoBrokersForPartitionException("Partition = " + pd.getKey)

      var brokerIdPartition: Partition = null
      var partition: Int = 0
      if(zkEnabled) {
        // get the partition id
        val partitionId = getPartition(pd.getKey, totalNumPartitions)
        brokerIdPartition = numBrokerPartitions(partitionId)
        val brokerInfo = brokerPartitionInfo.getBrokerInfo(brokerIdPartition.brokerId).get
        logger.debug("Sending message to broker " + brokerInfo.host + ":" + brokerInfo.port +
                " on partition " + brokerIdPartition.partId)
        partition = brokerIdPartition.partId
      }else {
        // randomly select a broker
        val randomBrokerId = random.nextInt(totalNumPartitions)
        brokerIdPartition = numBrokerPartitions(randomBrokerId)
        val brokerInfo = brokerPartitionInfo.getBrokerInfo(brokerIdPartition.brokerId).get

        logger.debug("Sending message to broker " + brokerInfo.host + ":" + brokerInfo.port +
                " on a randomly chosen partition")
        partition = ProducerRequest.RandomPartition
      }
      producerPool.getProducerPoolData(pd.getTopic,
                                       new Partition(brokerIdPartition.brokerId, partition),
                                       pd.getData)
    }
    producerPool.send(producerPoolRequests: _*)
  }

  /**
   * Retrieves the partition id and throws an InvalidPartitionException if
   * the value of partition is not between 0 and numPartitions-1
   * @param key the partition key
   * @param numPartitions the total number of available partitions
   * @returns the partition id
   */
  private def getPartition(key: K, numPartitions: Int): Int = {
    if(numPartitions <= 0)
      throw new InvalidPartitionException("Invalid number of partitions: " + numPartitions +
              "\n Valid values are > 0")
    val partition = if(key == null) random.nextInt(numPartitions)
                    else partitioner.partition(key , numPartitions)
    if(partition < 0 || partition >= numPartitions)
      throw new InvalidPartitionException("Invalid partition id : " + partition +
              "\n Valid values are in the range inclusive [0, " + (numPartitions-1) + "]")
    partition
  }

  /**
   * Callback to add a new producer to the producer pool. Used by ZKBrokerPartitionInfo
   * on registration of new broker in zookeeper
   * @param bid the id of the broker
   * @param host the hostname of the broker
   * @param port the port of the broker
   */
  private def producerCbk(bid: Int, host: String, port: Int) =  {
    if(populateProducerPool) producerPool.addProducer(new Broker(bid, host, host, port))
    else logger.debug("Skipping the callback since populateProducerPool = false")
  }

  /**
   * Close API to close the producer pool connections to all Kafka brokers. Also closes
   * the zookeeper client connection if one exists
   */
  def close() = {
    val canShutdown = hasShutdown.compareAndSet(false, true)
    if(canShutdown) {
      producerPool.close
      brokerPartitionInfo.close
    }
  }
}


Cajun chicken, biltong, animal hide – this dram is ripe with meaty goodness! (and with a suggestion of 'bacon bits from Pizza hut' even the vegetarian is in agreement). It's reminiscent of snacks, but not in the generic sense, we're smelling Hot & Spicy Monster Munch and Willards Beef and Tomato crisps, not to mention the Cadbury's fudge bar eaten inconspicuously at the back of the classroom during chemistry. Speaking of chemistry (yes, a link was forged right before your very eyes), there are definite whiffs of iodine and formaldehyde, and a rather unsavoury smoked mouth-wash (an exclusive Shelly-brand). Let's take a culinary trip to the seaside with kippers for breakfast and smoked mackerel and dillisk for lunch - an elegant garnish of freshly diced green herbs classing it gourmet. It's earthy…but a kind of sandy earthy, 100m back from the sand dunes to be exact. From the sawmills to the farmyard, with undertones of burning turf and old leather, it's stylishly unrefined. And for those dessert enthusiasts, there's even a dollop of molasses in there to sweeten the deal.
Mmm, blue cheese and honey – so sweet and savoury meet again, but this time, English Mustard and green chillies add a little bit of heat to the mix. That and the Deep Heat, of course. Hardy vegetables like char-grilled parsnips and beetroot feature, along with coffee beans and dry-roasted peanuts. It's a robust and nutty dram, but also rather creamy – peanut butter is followed with a scoop of rum and raisin ice-cream. Yum. Bitumen (a certain viscosity), an old barn, then somehow Mike the headless chicken crops up (Google it)…moving on…well, with Chinese style barbeque ribs and candied sea-horses, this one has a bit of an oriental twist. It's spicy and sweet - paprika and ginger biscuits, a handful of honey-roasted almonds. But the seaside's never far away, and there's oysters on the menu.
It's our second virtual outing to Kilchoman, and look! Barrels!
TCP and wood varnish. Gingerish as opposed to gingery, smoked chillies and soya sauce. Jalfrezi and baba ganoush. Lots of savoury flavour here…and then some toffee. It's charred pine furniture from a broken home, no wait, maybe it's Parma ham from a middle-class, Guardian-reading household in the South of Edinburgh. Either way, it's slick – baby oil and engine oil sum up the mouth-feel. Medium to medium long to long…ok, mostly long, but it's fair to say we were undecided as a group. Like scoring from the half-way line.
Royal Mile Whiskies: Kilchoman Sherry 5yo | http://www.royalmilewhiskies.com/product.asp?


Do you have a love of animals? Are you a patient, caring person? Becoming a Veterinary Assistant is the perfect career path for you. Veterinary Assistant's help make a difference in the lives of animals and the people that love them! As a Veterinary Assistant, you will work alongside Veterinarians to provide routine care, health evaluation, and treatment for sickness or injury. Assistants perform a wide variety of duties including feeding, exercising, and bathing animals, cleaning and disinfecting exam rooms, restraining animals during examinations, administering medication or vaccinations, and most importantly providing affection and a safe environment for every animal in their care.
Certified Veterinary Office Assistants handle daily administrative duties of the veterinary team. This course outlines step-by-step instructions for completing these daily tasks such as scheduling appointments, billing and accounting, communicating effectively and compassionately with clients, managing medical records, budgeting, marketing, managing inventory, using outside diagnostic laboratory services, and more. Make a difference in the lives of animals and the people who love them while working as a Veterinary Office Assistant in a veterinary hospital, animal shelter, zoo, or university. The included Veterinary Medical Terminology program provides a visual approach to learning medical terms and understanding the basics of veterinary medicine.
Our Certified Wellness Coach Program will focus on helping people to improve their lifestyle behavior by applying the principles and processes of professional life coaching, to the goals of lifestyle improvement for higher levels of wellness. This program includes three courses covering all the areas required to successfully pursue a career as a Wellness Coach. Wellness coaching is about helping people improve their lifestyle behavior. As the field of Wellness Coaching emerges and the world discovers the value of it, it will continue to define and re-define itself. Wellness coaching applies the principles and processes of professional life coaching in order to help make lifestyle improvements.
Have you thought about working with other professionals providing health care to patients? Are you a good team player? As a Clinical Medical Assistant you will work closely with patients and physicians; take vital signs, interview patients, record patient information, and provide point-of-care testing. Clinical Medical Assistants are projected to be among the fastest growing occupations in the next 5 years. Our course will also provide you with the latest HIPAA regulations, the Electronic Health Record, and how to care for special populations.


VIETNAM-Passengers can pay their tickets of the budget airline, Jetstar Pacific, at more 400 cash-payment offices nationwide through the Bank for Foreign Trade of Vietnam (Vietcombank) from October 7th.
Namely, the passengers will book tickets at the airline's website or switchboard, then choose deferred payment and pay in cash at Vietcombank's nearest offices. The bank will give them vouchers that they can use as tickets when they check in at the airport.
On the occasion, between 2pm and 5pm on October 7 th , Jetstar Pacific will sell cheap tickets for flights from January 9 th to 23 rd , 2012 on routes Da Nang-HCMC and Hanoi/Vinh/Hai Phong-HCMC at prices from VND 200,000 and 400,000, respectively.


text:
The Street Fighter Collection (1974)
by Sara Michelle Fetters - April 2nd, 2019 - Blu-ray and DVD
How does the Blu-ray/DVD Disc stack up? (all ratings out of 10.)
Extras6
Overall8
The three-film saga (The Street Fighter, Return of the Street Fighter, The Street Fighter's Last Revenge) of assassin and antihero Tamuka "Terry" Tsurugi (Sonny Chiba), a legendary martial artist with his own distinct moral code who frequently finds himself at odds with the mafia. When that happens, a substantial body count of dead killers ordered to hunt Tsurugi down inevitably ensues.
The Street Fighter (1974)
After being hired to break out a notorious killer from prison, when the man's siblings are unable to pay him for his work Tamuka Tsurugi kills the younger brother and sells the sister into prostitution. Later, after he refuses to assist in the kidnapping of a young heiress, he instead convinces her protector, respected martial arts master Kendo Masaoka (Masafumi Suzuki), to allow him to shadow the woman during her travels in order to keep her safe from harm. What Tsurugi does not know is that the mafia is involved in this game of subterfuge and death, and they mean to make sure this notorious street fighter doesn't get the opportunity to spoil any of their plans.
The first film in The Street Fighter trilogy is a total hoot, with many considering it to be the best of the trio. Featuring plotting that goes beyond being simplistic in order to focus almost entirely on the numerous bone-crunching martial arts battles Tsurugi finds himself embroiled in. This is all well to the good, and it's easy to see why this series has garnered so many fans over the decades (including, probably most famously, Quentin Tarantino). As for Chiba, he became an international sensation after the release of this film and its sequels, his ferocious raw intensity a truly wondrous thing to behold.
This is the uncut international version of the film.
Revenge of the Street Fighter (1974)
Return of the Street Fighter (1974)
Tamuka "Terry" Tsurugi returns to action after he is hired to assassinate a pair of accountants. Turns out, they're involved in an illegal fundraising scheme involving a fictional martial arts school, the mastermind behind it all embezzling funds utilizing a variety of methods which include both blackmail and murder. It gets worse when Tsurugi discovers the mafia is in on this deal as well, and they've brought back an old nemesis he was certain he'd killed in order to do him in. They're also planning on murdering Masaoka, the wise martial arts master an additional hinderance to their overall plan who cannot be allowed to live.
Even more nonsensical than its predecessor, I actually enjoy this sequel a bit more than I did the first film. The action is even more spectacular and some of the deaths are literally eye-popping in their gruesome excess. The final 15 minutes is an extraordinary cacophony of carnage and bloodshed that showcases Chiba in all his viscerally violent glory. It's idiotic from a story standpoint, there's not denying that, but none of that makes the overall movie itself any less entertaining. I like this one a lot.
The Street Fighter's Last Revenge (1974)
This time out, Tamuka "Terry" Tsurugi is hired by a shady businessman to extract a person of vital importance as well as a mysterious mahjong case from a downtown building currently surrounded by the police who are currently engaged in a shootout with the gangsters within. While successful, his employer thinks he can get away with not paying Tsurugi, which as most should know is nothing short of a major mistake. Now he is in possession of an audio tape that if released would lead to a major political and corporate scandal the effects of which cannot be underestimated. But before he extract proper value for this recording it turns out a determined prosecutor also wants to get his hands on it as well, and if Tsurugi wants to get revenge against those who wronged him he's also going to have to deal with this mysterious law officer, a lethal martial artist himself, as well.
While featuring its fair share of incredible action, this is one entry in the Street Fighter series I can't help but mildly scratch my head about. There's a dude in a golden sombrero who has a laser weapon. There's a talented young female martial artist who is quickly introduced only to be casually disposed of in a manner that's unduly cruel and oddly thankless both at the exact same time. The film doesn't real feel all that connected to its predecessors other than a brief cameo from Suzuki, returning as Kendo Masaoka, where he gives Tsurugi insight into how defeating one adversary in a one-on-one bout. It's kind of a jumbled mess, and I can't say it held my interest near the same way the first two films in the trilogy did. Still, Chiba is still extraordinary, and the highs still outweigh the lows, all of which means even passing fans will likely want to give The Street Fighter's Last Revenge multiple looks, just not as many of them as they do either The Street Fighter or Return of the Street Fighter.
Both U.S. and Japanese cuts of the film are included with this release.
The Street Fighter, Return of the Street Fighter and The Street Fighter's Last Revenge are presented on separate 50GB Blu-rays (MPEG-4 AVC Video) each sporting 2.35:1 1080p transfers and new 2K scans of a variety of available source elements. Truth be told, none of these films has ever looked as good as they do here, Shout! Factory going above and beyond as far as I'm concerned.
THE AUDIO
Each films comes with dueling English Dub DTS-HD Master Audio Mono and Japanese DTS-HD Master Audio Mono soundtracks and sport optional English subtitles.
Extras here include:
The Street Fighter
Street Fighting Man – Interview with actor Sonny Chiba (27:10)
Cutting Moments: The Street Fighter Trailer and Other Tales from the Edit Room with Director Jack Sholder (13:03)
U.S. Theatrical Trailer (2:26)
Japanese Theatrical Trailer (3:00)
Still Gallery (6:32)
Return of the Street Fighter
U.S. Teaser Trailer (00:33)
The Street Fighter's Last Revenge
The Street Fighter films have stood the test of time for a reason as Sonny Chiba's magnetic ferocity simply cannot be denied. Shout! Factory's three-disc set features magnificent presentations of all three motion pictures, and while special features are relatively sparse, what is here is still pretty great. A collection that fans of the series certainly will want to add to their personal libraries.
actionMartial ArtsShout! Factory
Top 50 Films 2010 – 2019 (Part One: 50-41)
Shigehiro Ozawa
MPAA Rating: R / Not Rated
Runtime: 4 hours 56 minutes

redpajama_set_name: RedPajamaCommonCrawl


text:
Q: Moodle LDAP integration - LDAP-module cannot connect to any servers I managed to get my Active Directory up and running, and now I want to integrate my MS-AD into my Moodle server. I followed the steps from the Moodle docs as close as I can.
This is the error message I get when trying to log into my Moodle server with an Active Directory User:
LDAP-module cannot connect to any servers: Server: 'ldap://europe.domain.com/', Connection: 'Resource id #16', Bind result: ''

And here is my LDAP server configuration within Moodle:
LDAP server settings
Host URL: ldap://europe.domain.com/
Version: 3
Use TLS: No
Bind settings
Distinguished name: cn=ldap-user,dc=europe,dc=domain,dc=com
User lookup settings
User type: MS ActiveDirectory
Contexts: ou=moodleusers,dc=europe,dc=domain,dc=com
Thats what I have done so far:

*

*Created "moodleusers" OU

*Created ldap-user AD user account & set the password to "Password never expires."

What have I done wrong?

A: There's a possible answer here in the Moodle forums
https://moodle.org/mod/forum/discuss.php?d=427908#p1722336

Bind result normally refers to two things.

*

*Your bind user is entered incorrectly (perhaps an expired or changed password)

*Your bind user does not have the necessary permissions on the OU referenced in the context.

Maybe also try one of the LDAP tools to test the connection outside of Moodle
https://ldap.com/ldap-tools/
For example
http://phpldapadmin.sourceforge.net/wiki/index.php/Main_Page

redpajama_set_name: RedPajamaStackExchange


8 civilians died near Mosul - Did the US Air Force accidentally cause a fatal strike?
8 civilians died near Mosul | Did the US Air Force accidentally cause a fatal strike?
Fadhiliya – A tragic event took place in the village of Fadhiliya that is proving that driving out ISIS terrorists from Northern Iraq will be at the expense of human lives. Did the US Air Force cause a fatal strike?
On October 22, coalition warplanes were conducting at least "four airstrikes against five ISIS tactical units, 12 staging areas, six mortar positions, one rocket position and one heavy machine-gun position", according to information provided by the US-led coalition against ISIS. Apparently, these attacks were perpetrated only by US military jets.
The coalition did not report where exactly these attacks occured, and whether the village BILD visited was one of the targets.
However, US military confirmed to BILD that the events in Fadhiliya are currently being reviewed: "We know about the allegations and we are reviewing whether they are credible", said a US military spokesman.
Zivilisten sterben Tödlicher Irrtum der US-Luftwaffe?
Fadliyah – Schauplatz einer Tragödie, die zeigt, dass die Vertreibung der ISIS-Terroristen aus Mossul auch Zivilisten das Leben kosten kann.
Colonel John L. Dorrian, the spokesman for the anti-ISIS international coalition said to BILD: "We do not attack civilians." Before attacking ISIS, we had only been using precision weapons, utilizing special procedures and confirming targets, he said. Dorrian: "But these procedures are not perfect."
Like many village residents, the Yousif family were farmers. They didn't have anything to do with ISIS, according to relatives. However, ISIS terrorists got more and more violent with the war growing increasingly closer to Fadhiliya.
The Iraqi army made advances on ISIS' stronghold of Mosul, taking Bazwaya, the last village before the city's outskirts. Next step is to retake the outer suburban neighborhood of Gogjali. ISIS terrorists are defending themselves with booby traps, suicide bombers and snipers.
Observers estimate that the battle could take several months.


Scottsdale, Cave Creek, Fountain Hills, Phoenix, Rio Verde.
Arizona guide to real estate, StartSmart Properties search homes for sale (including MLS listings), housing market information, home values, school districts, including selling, renting, and financing.
Residential Real Estate Sales, representing Buyers and Sellers with Honesty, Integrity, and Unrelenting Dedication.
Browse North Scottsdale and Anthem properties. Get great expert advice and instant MLS access. Everything you need to find your dream home!
Experienced Realtor specializing in residential real estate in the Phoenix market, particularly the east valley cities including Chandler, Mesa, Gilbert, Tempe, Queen Creek.


Since 2014, Community Science has been working with AIR to help assess the NRC's performance in meeting the T/TA needs of SS/HS and Project LAUNCH grantees. We do this by 1) tracking the ongoing implementation of NRC activities, including T/TA methods and content; (2) identifying patterns of effective T/TA practice, focusing on which NRC methods worked well, for whom, and in what circumstances; and (3) assessing the extent to which NRC-identified outputs and outcomes are being achieved. We use a number of data sources to assess performance including evaluations of online learning events, online learning modules, and in-person trainings; an annual performance assessment survey; a database that tracks technical assistance requests and responses (TA Tracker); web analytic data; site visit assessments; and T/TA needs assessment interviews and focus groups. Information is provided by grant representatives and community partners whose staff participated in T/TA activities and from their resource specialists or any other TA provider, depending upon kind and level of need.
One of the more exciting parts of our work has been the development of capacity assessments of grantees (i.e., organizations and their partner organizations), which are developmentally based and can be used as part of the development of technical assistance plans. This assessment relies heavily on prior research and work in this area. Another innovative aspect of our work has been the development of self-assessment tools for TA providers to ensure that they are maintaining the quality that they defined for their work and to examine ways that they can use that information to provide continuous quality improvement.
Our role in this project has enabled us to contribute to a national initiative designed to build the capacity of school districts and other systems to address the three-part challenge of reducing youth violence, supporting the prevention of mental, emotional, and behavioral disorders, and promoting healthy development of children and youth, especially among vulnerable populations. We work closely with NRC staff to understand the full context of grantee services provided in over 35 different states and localities as well as the complexities of providing tailored capacity-building supports in these jurisdictions using a range of creative modalities. We addressed the challenge of synthesizing large amounts of needs assessment and performance assessment data to identify salient trends and develop recommendations to improve T/TA services and supports. Our work products provided timely feedback for continuous quality improvement of the NRC, facilitated mid-course adjustments, informed grantee-specific NRC plans for each year of operations, and helped to identify lessons learned in implementing national initiatives benefiting the fields of mental health promotion and positive youth development.


Mr Iain Miller of Bevan Brittan LLP appeared on behalf of the ARB.
Mr Jemmie Williams was not in attendance.
1. Mr Williams was called before the Professional Conduct Committee ("the Committee") of the Architects Registration Board ("the Board") having been convicted on 17 July 2014 of one count of dishonestly making a false statement to obtain benefit/advantage/payment.
3. Mr Williams claimed state benefits although he had capital to an extent that made him ineligible, and signed a declaration to obtain that benefit that was false. The benefit that he was paid and to which he was not entitled was £7926.14.
4. The Board brings the allegation following a self-referral by Mr Wiiliams by email on 30 September 2014, in which he described a "minor conviction". Mr Williams was requested to provide details of the conviction and did so on 23 October 2014.
5. The ARB is required to prove the allegations to the civil standard; that it is more likely than not that any event occurred. The Committee has in mind throughout its deliberations that the right to practise a profession is involved in these proceedings and proceeds upon the basis that the Human Rights Act 1998 will apply. In particular Mr Williams has the right to a fair trial and to respect for his private and family life under Articles 6 and 8 of the European Convention for the Protection of Human Rights and Fundamental Freedoms, as incorporated within UK law by that Act.
6. The conviction is proved by a certificate of conviction, and it is not open to Mr Williams to go behind that certificate.
7. Mr Williams did not attend the hearing. The Committee was referred to the service of the papers. The clerk advised the Committee that the provisions as to service set out in the rules, Rule 6a had been complied with, as the notice of the hearing, with the other documents required to be supplied, were sent to Mr Williams on 8 May 2015, so giving more than the required 42 days notice of this hearing. Accordingly the Committee found that the notice of hearing was properly served.
8. The Committee next considered whether to proceed in the absence of Mr Williams. The Clerk's advice was sought and accepted. The panel was referred to the case of R-v-Jones  UKHL 5, which Tait v The Royal College of Veterinary Surgeons (RCVS)  UKPC 34 states is also applicable to professional conduct proceedings.
9. The Committee considered carefully Mr Williams' letters asking for an adjournment, which are generalised and give no specific information. The Committee noted that the previous hearing on 30 April 2015 had been adjourned. Notice of this present hearing was served on 8 May 2015 and Mr Williams wrote on 29 May 2015 to request a further adjournment. The papers themselves were with Mr Williams by 8 April 2015 at the latest, as he said at the previous hearing on 30 April 2015.
10. Accordingly Mr Williams has known exactly what allegation he faces, with all the small number of supporting documents, for over three months, and has had over two months notice of today's hearing.
11. Where a person is ill it will usually be unfair to proceed in his absence. Mr Williams does not state that he is ill.
12. Mr Williams sets out no practical difficulty in attending: he states only that he has other legal cases for which he has to prepare and so has not the time to prepare for this hearing. Mr Williams provided no information as the cases with which he is involved. The only concrete information given by Mr Williams was in his letter to the Board of Friday 17 July 2015 where he stated that 20 July 2015 "coincides with the required filing date in the court proceedings" but gave no other information and did not state why such a date makes attendance at this hearing difficult for him. He did not say why the need to file a document in another case made it difficult for him to attend today.
13. There is a public interest in conducting professional regulatory proceedings expeditiously.
14. The Committee noted that in this case there would be no difficulty with the recollection of witnesses being impaired by delay, as there is no factual dispute to be decided.
– whether the person had requested an adjournment. Mr Williams had requested an adjournment.
– whether the person would be likely to attend any adjourned hearing. The Committee noted that Mr Williams attended the previous hearing. However he had not attended this hearing and there was no practical reason given as to why he could not have attended to explain precisely why he submitted that had been unable to prepare for the hearing today. The Committee considers it unlikely that Mr Williams would attend any adjourned hearing.
– at the previous hearing Mr Williams stated that he needed time to arrange legal representation. Mr Williams made no reference to legal representation in his present application for adjournment, and the Committee noted that Mr Williams stated that he is a litigant is person in the other litigation in which he says he is engaged. This is not now a reason given for seeking an adjournment.
– the case involves submissions as whether the conviction has "material relevance to your fitness to practise as an architect" and if so to hear mitigation from Mr Williams. This would not require preparation of such length that two or three months would not be long enough, even with other commitments.
– Mr Williams has made the time to write lengthy letters seeking adjournment that are replete with legal argument. That time would have enabled him to compose detailed submissions had he the mind so to do.
16. A decision to proceed in the absence of the person facing the allegation should be taken with the utmost care, and caution. An Article 8 right to a private life is engaged, as the proceedings impact on the practice of a profession. The risk of prejudice to the individual must be carefully weighed, and the conclusion that someone has deliberately and voluntarily absented himself from a hearing requires the Committee to find that there is a clear and unqualified – unequivocal – intention not to attend.
17. In this case the Committee finds that Mr Williams has intentionally absented himself from the hearing, and that the public interest requires the Committee to proceed in his absence.
18. Mr Williams submitted that he should be anonymised and that the hearing should be in private.
20. The only part of that sentence that could be relevant is the private life of Mr Williams. The allegation relates to a conviction, which was in a public court and which is public knowledge.
21. Paragraph 12 of the case report stated that the common law general rule should only be departed from to the extent that such a departure is strictly necessary. It is not strictly necessary in this case. The clear default position under Article 6 is that hearings should be in public. It is for Mr Williams to prove both the need for any derogation from those rights and for a need to delegate to the extent claimed. The case records that the right to public hearings is jealously guarded.
22. In this case Mr Williams gives four reasons seeking anonymity and a private hearing.
23. First he alleges that the disciplinary regime of the Board is incompatible with the Rehabilitation of Offenders Act 1974. The Committee does not understand this submission. In any event the conviction is not yet spent.
24. Secondly Mr Williams asserts that public disclosure of the charge is disproportionate to the aim of the ARB disciplinary regime. The Committee comprises two lay members to represent the public, and the Committee as a whole feels that the disclosure of the charge is not disproportionate. On the contrary, since part of the function of the Committee is to maintain and uphold professional standards and the reputation of the profession, it is essential that professional disciplinary hearings are public.
25. Mr Williams asserts that public disclosure interferes with his right to private life under Article 8 of the European Convention on Human Rights. The Committee agrees that the Article 8 right to a private life is engaged under Article 8(1). It considers that interference with those rights is proportionate within Article 8(2).
26. Mr Williams submitted there is no sufficient public interest in conducting proceedings in public, and identifying him, such as to justify the curtailment of his right to respect of his private life. The Committee disagrees in principle, and in the circumstances of this case, which relate to a public conviction of a criminal offence.
27. Accordingly the case will proceed in public, and without anonymity.
28. Mr Williams did not deny the fact of the conviction nor give any indication of why it might not be relevant.
29. The Committee noted that the conviction was of one offence, he being acquitted of the other, and it was four years ago, and did not involve practice as an architect, and the money had been repaid. Mr Williams was a man of good character before the offence and has committed no offence since. He has no previous disciplinary record.
30. The Committee perused the four page report of the Board's solicitor with accompanying documents running to a further 24 pages. The Board called no oral evidence.
31. The Committee read and considered the letters written by Mr Williams to the Board and to its clerk.
32. Mr Williams pleaded not guilty to two allegations. The jury could not agree on one, and the judge directed an acquittal. Mr Williams was convicted of the second.
"You have been convicted unanimously by the jury of one count of dishonest representation for obtaining benefit. You were charged with having obtained the benefit dishonestly on 4th February 2010. The amount of benefit that you obtained over a period of time was £7,926.14.
It is a very sad day, Mr Williams, when a man of hitherto previous good character is losing his good name. I cannot think of a greater punishment than the loss of good character for a professional man. So, bearing in mind your age; your previous good character; the fact that you have repaid by way of a consent order the larger amount in relation to the housing benefit, and bearing in mind that you have not been in any trouble since you were arrested and charged for these matters; bearing in mind also the history of this case, that the allegations go back some four years and appear to have taken two years to come to court I am persuaded by Mr Carrs, just, that I should not send you to prison and should not impose a custodial sentence even if it is a suspended sentence. It seems to me that the appropriate way to deal with you is by the imposition of a community order for a period of twelve months.
34. The work was to be completed by 16 July 2015. The Committee does not know whether that work was completed but assumes that this work has been completed satisfactorily.
35. Mr Miller submitted that an offence of dishonesty was always relevant to the practice of a professional. The Committee had its indicative sanctions guidance to follow, and it was a matter for the Committee as to what sanction to impose.
36. Mr Williams made no formal submissions to the Committee about the matter. The Clerk pointed out to the Committee the matters set out above under the heading of defence. There has been no previous disciplinary finding against Mr Williams.
37. The Committee finds the allegation proved. The conviction is not connected in any way with practice as an architect. However the test is whether the conviction has material relevance to fitness to practise.
38. Benefit fraud is a crime against society (which funds the money stolen). It reflects very badly on the profession that a member of it should be convicted of such an offence. This was not a one off action or an isolated incident. It was a consistent course of dishonesty over a period of time.
39. The primary purpose of sanctions is not to be punitive (though this may be their effect) but to protect members of the public, to maintain the collective reputation of the profession (and the Board as its regulator), and to declare and uphold proper standards of conduct and competence. Sanctions also help ensure that the profession better understands the importance of professional standards.
40. The Committee's Indicative Sanctions Guidance states that in cases involving criminal convictions architects will be referred to the Committee when they have been convicted of a criminal offence that is relevant to their fitness to practise as an architect. The architect cannot argue the facts of the matter that led to the conviction, but can make submissions as to why no further or a more lenient sanction should be made by the Committee than would otherwise be the case.
41. The purpose of a hearing in relation to a conviction is not to punish the architect a second time for the same offence, but to protect the public and to maintain the collective reputation of the profession.
42. 'The reputation of the profession is more important than the fortunes of any individual member' (Bingham L.J inBolton v Law Society ).
43. The Committee noted that it should not take cases involving other professions as other than indicative of an approach to be taken and they are not to be taken as precedent.
44. Mr Williams chose not to attend the hearing today. That does not affect the decision of the Committee save that Mr Williams' absence deprived the Committee of the chance to hear from him.
45. Appearance before this Committee is in itself salutary. The Act does not require the Committee to impose a sanction in every case where a guilty finding is reached, so the Committee may choose to make no disciplinary order. If it decides to impose a sanction, the Committee commences at the lowest sanction, and only if it decides that sanction is not appropriate does it move to the next level of sanction. Having arrived at a sanction that it is minded to impose the Committee then reviews the next sanction above so as to satisfy itself that this would be too severe a sanction before arriving at a final conclusion. If the Committee decides on a fine, it is limited by the Architects Act 1997 to £2500.
46. The Committee also bears in mind that Mr Williams has already been punished for the offence of which he was convicted. However the Judge's sentencing remarks clearly had in mind that there would be a sanction imposed by this Committee and bore that in mind when sentencing. The sanction of this Committee is therefore not a double penalty.
47. In all the particular circumstances of this case the Committee considers that a sanction is required because of the need to declare and uphold professional standards.
49. The aggravating factors are that this was a conviction for dishonesty, a lengthy benefit fraud. It was, as the Committee noted when deciding that the allegation was proved, a crime against society.
50. The plea to the charge was one of not guilty, so that Mr Williams is not able to demonstrate any level of insight prior to the conviction, and that plea undermines subsequent assertions of insight, already somewhat hard to establish given that the self report described it only as a "minor conviction".
51. Mr Williams promised mitigation and a defence but provided none, and so there are no mitigating factors to consider, save those set out in the heading "defence".
52. A benefit fraud conviction requires a disciplinary sanction.
55. This matter is too serious for a reprimand.
Penalty orders are fines of up to level 4 on the standard scale of fines for summary offences, currently set at £2,500. A penalty order may be used in relation to those offences too serious to warrant a reprimand, or where a lack of remorse or understanding is displayed.
57. All these three are applicable (though the financial benefit has been removed by the compensation paid).
59. The Committee decided that a reprimand or penalty order is not sufficient to protect the reputation of the profession. However this was behaviour that in the view of the Committee is fundamentally incompatible with Mr Williams continuing to be an architect.
Any individual erased from the Register is not permitted to use the title 'Architect' in business or practice [nor make any reference to membership or fellowship of RIBA.] An erasure order is publicised for a period of five years after the date of sanction.
61. This was a serious criminal offence of dishonesty. Only barely did Mr Williams escape a custodial sentence, and the Judge's sentencing remarks indicated that he thought erasure would follow. This was a premeditated course of dishonesty, motivated, according to the sentencing Judge, by greed.
62. The only possible sanction in this case is one of erasure, and the Committee so orders. The Committee's recommendation as to a minimum period before an application can be made for readmission to the Register is five years.


text:
from typing import Union

import torch

from monai.metrics.utils import do_metric_reduction, ignore_background
from monai.utils import MetricReduction, Weight, look_up_option

from .metric import CumulativeIterationMetric
from .utils import is_binary_tensor

class GeneralizedDiceScore(CumulativeIterationMetric):
    """Compute the Generalized Dice Score metric between tensors, as the complement of the Generalized Dice Loss defined in:

    Sudre, C. et. al. (2017) Generalised Dice overlap as a deep learning
        loss function for highly unbalanced segmentations. DLMIA 2017.

    The inputs `y_pred` and `y` are expected to be one-hot, binarized channel-first
    or batch-first tensors, i.e., CHW[D] or BCHW[D].

    Example of the typical execution steps of this metric class follows :py:class:`monai.metrics.metric.Cumulative`.

    Args:
        include_background (bool, optional): whether to include the background class (assumed to be in channel 0), in the
            score computation. Defaults to True.
        reduction (str, optional): define mode of reduction to the metrics. Available reduction modes:
            {``"none"``, ``"mean_batch"``, ``"sum_batch"``}. Default to ``"mean_batch"``. If "none", will not do reduction.
        weight_type (Union[Weight, str], optional): {``"square"``, ``"simple"``, ``"uniform"``}. Type of function to transform
            ground truth volume into a weight factor. Defaults to ``"square"``.

    Raises:
        ValueError: when the `weight_type` is not one of {``"none"``, ``"mean"``, ``"sum"``}.
    """

    def __init__(
        self,
        include_background: bool = True,
        reduction: Union[MetricReduction, str] = MetricReduction.MEAN_BATCH,
        weight_type: Union[Weight, str] = Weight.SQUARE,
    ) -> None:
        super().__init__()
        self.include_background = include_background
        reduction_options = [
            "none",
            "mean_batch",
            "sum_batch",
            MetricReduction.NONE,
            MetricReduction.MEAN_BATCH,
            MetricReduction.SUM_BATCH,
        ]
        self.reduction = reduction
        if self.reduction not in reduction_options:
            raise ValueError(f"reduction must be one of {reduction_options}")
        self.weight_type = look_up_option(weight_type, Weight)

    def _compute_tensor(self, y_pred: torch.Tensor, y: torch.Tensor):  # type: ignore
        """Computes the Generalized Dice Score and returns a tensor with its per image values.

        Args:
            y_pred (torch.Tensor): binarized segmentation model output. It must be in one-hot format and in the NCHW[D] format,
                where N is the batch dimension, C is the channel dimension, and the remaining are the spatial dimensions.
            y (torch.Tensor): binarized ground-truth. It must be in one-hot format and have the same shape as `y_pred`.

        Raises:
            ValueError: if `y_pred` or `y` is not a binarized PyTorch tensor, if `y_pred` and `y` have less than
            three dimensions, or `y_pred` and `y` don't have the same shape.
        """
        return compute_generalized_dice(
            y_pred=y_pred, y=y, include_background=self.include_background, weight_type=self.weight_type
        )

    def aggregate(self, reduction: Union[MetricReduction, str, None] = None):
        """
        Execute reduction logic for the output of `compute_generalized_dice`.

        Args:
            reduction (Union[MetricReduction, str, None], optional): define mode of reduction to the metrics.
                Available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``}.
                Defaults to ``"mean"``. If "none", will not do reduction.
        """
        data = self.get_buffer()
        if not isinstance(data, torch.Tensor):
            raise ValueError("The data to aggregate must be a PyTorch Tensor.")

        # Validate reduction argument if specified
        if reduction is not None:
            reduction_options = ["none", "mean", "sum", "mean_batch", "sum_batch"]
            if reduction not in reduction_options:
                raise ValueError(f"reduction must be one of {reduction_options}")

        # Do metric reduction and return
        f, _ = do_metric_reduction(data, reduction or self.reduction)

        return f

def compute_generalized_dice(
    y_pred: torch.Tensor,
    y: torch.Tensor,
    include_background: bool = True,
    weight_type: Union[Weight, str] = Weight.SQUARE,
) -> torch.Tensor:
    """Computes the Generalized Dice Score and returns a tensor with its per image values.

    Args:
        y_pred (torch.Tensor): binarized segmentation model output. It should be binarized, in one-hot format
            and in the NCHW[D] format, where N is the batch dimension, C is the channel dimension, and the
            remaining are the spatial dimensions.
        y (torch.Tensor): binarized ground-truth. It should be binarized, in one-hot format and have the same shape as `y_pred`.
        include_background (bool, optional): whether to skip score computation on the first channel of the
            predicted output. Defaults to True.
        weight_type (Union[Weight, str], optional): {``"square"``, ``"simple"``, ``"uniform"``}. Type of function to
            transform ground truth volume into a weight factor. Defaults to ``"square"``.

    Returns:
        torch.Tensor: per batch and per class Generalized Dice Score, i.e., with the shape [batch_size, num_classes].

    Raises:
        ValueError: if `y_pred` or `y` are not PyTorch tensors, if `y_pred` and `y` have less than three dimensions,
            or `y_pred` and `y` don't have the same shape.
    """
    # Ensure tensors are binarized
    is_binary_tensor(y_pred, "y_pred")
    is_binary_tensor(y, "y")

    # Ensure tensors have at least 3 dimensions and have the same shape
    dims = y_pred.dim()
    if dims < 3:
        raise ValueError(f"y_pred should have at least 3 dimensions (batch, channel, spatial), got {dims}.")
    if y.shape != y_pred.shape:
        raise ValueError(f"y_pred - {y_pred.shape} - and y - {y.shape} - should have the same shapes.")

    # Ignore background, if needed
    if not include_background:
        y_pred, y = ignore_background(y_pred=y_pred, y=y)

    # Reducing only spatial dimensions (not batch nor channels), compute the intersection and non-weighted denominator
    reduce_axis = list(range(2, y_pred.dim()))
    intersection = torch.sum(y * y_pred, dim=reduce_axis)
    y_o = torch.sum(y, dim=reduce_axis)
    y_pred_o = torch.sum(y_pred, dim=reduce_axis)
    denominator = y_o + y_pred_o

    # Set the class weights
    weight_type = look_up_option(weight_type, Weight)
    if weight_type == Weight.SIMPLE:
        w = torch.reciprocal(y_o.float())
    elif weight_type == Weight.SQUARE:
        w = torch.reciprocal(y_o.float() * y_o.float())
    else:
        w = torch.ones_like(y_o.float())

    # Replace infinite values for non-appearing classes by the maximum weight
    for b in w:
        infs = torch.isinf(b)
        b[infs] = 0
        b[infs] = torch.max(b)

    # Compute the weighted numerator and denominator, summing along the class axis
    numer = 2.0 * (intersection * w).sum(dim=1)
    denom = (denominator * w).sum(dim=1)

    # Compute the score
    generalized_dice_score = numer / denom

    # Handle zero deivision. Where denom == 0 and the prediction volume is 0, score is 1.
    # Where denom == 0 but the prediction volume is not 0, score is 0
    y_pred_o = y_pred_o.sum(dim=-1)
    denom_zeros = denom == 0
    generalized_dice_score[denom_zeros] = torch.where(
        (y_pred_o == 0)[denom_zeros], torch.tensor(1.0), torch.tensor(0.0)
    )

    return generalized_dice_score


Welcome to the 16th episode of OzKoç and King Soccer Podcast Show.
Indeed, debates frequently flare up when the topic of discrimination in soccer comes up and rarely is women's football discussed even if it is it tends to be ridiculed. "A lot of female professional footballers feel they get unjust wages, or inadequate facilities, or no share of the spotlight. Its hard for them to feel comfortable or at home with the club that is supposedly backing them." The debate will rage on, but one thing we should all agree to have is the inclusion and good treatment for all players. A team and friendship is something to truly be thankful for.
A time of togetherness, laughter and a time when one can feel relaxed and at home. That sense of belonging is important for anyone at anytime. Whether you're a project manager at an architectural firm, or a footballer trying to break into a new team, feeling included goes a long way when it comes to feeling comfortable. "When someone is about to sign for a club, a lot of deals and accommodations must be made before pen is put to paper," Oz said. "Of course, they have to agree on wages, but a club will also do its best to come up with methods to make the player feel at home, especially if the country is foreign to the newcomer.


A Florida distributor of advanced industrial automation equipment, including SMC pneumatics, reduced the effective rate of credit card processing to under 2%, including all merchant account and gateway fees. While a small part of the overall revenue stream, it was a growing cost center, impacting profit margins.
How did the distributor reduce costs? Two changes were required. First a change in the credit card processing price plan, and second technology to automate qualified interchange rate optimization. Interchange rates include a percentage of the transaction and a per transaction fee, and comprise the bulk of all credit card processing costs. The same card can process at different rates, depending on which rules the merchant complies with.
The best price plan for merchants, commonly available for $1,000,000 in annual processing, is called wholesale interchange plus or interchange pass through. With pass-through pricing, merchants pay all costs, plus a merchant discount, which is identified as a separate line item for billing. Costs and gross profits to the merchant service provider become transparent. Even better is for the merchant account to support level 3 processing, whereby a merchant that sends enhanced level 3 data may qualify for even lower rates on business, corporate and purchasing cards.
A Bank of America representative offered the merchant an additional agreement for a new interchange plus merchant account solely for their largest corporate customer. I recommended the merchant either renegotiate all of their business with my input or go with another vendor. It made no financial sense that the merchant solve the cost concern for only one client and not all of them. To reduce credit card processing fees, first the merchant needed a new interchange plus merchant account for all customers.
Interchange is the largest component of credit card processing fees. There are many rules to achieving the lowest qualified interchange rate. For business to business companies, it's infinitely more difficult to qualify for the lowest rate for any given card type due to the high prevalence of business, corporate and purchasing cards, and their many rules. Because it's virtually impossible for employees to learn all the nuances of those rules, as well as even know what kind of cards their remote customers are presenting, cloud payment technology is the break-through that merchants have needed to achieve lower effective costs while also increasing efficiencies.
Without all three of the rules met, fees can run one percent or more extra vs. when all rules were complied with. The merchant needed software that would help them meet all requirements, yet there are few market choices, including among cloud payment / virtual terminal solutions.
Bank of America offered a reasonably priced desktop software solution that would support level 3 processing. The reason it was presented to use for one customer only, is because all the information needed to be sent with each transaction creates an extra burden for accounts receivable. If the merchant used it for all customers, then they'd have to enter a lot of extra information on every sale to be safe, because users would have no idea whether the card would benefit from level 3 data or not. Additionally, the one customer was on 30 day terms, so at the time the invoices were paid, the other criteria would be met. But that wasn't true for new and other customers who were not on terms. An authorization was obtained for those customers on order, and weeks later, the final amount would often be different. This meant the merchant would not meet all three minimum rules for the other accounts to qualify for the best rates.
I recommended the merchant implement CenPOS, an intelligent rules-based cloud payment technology that mitigates risk of employees making decisions that impacted fees paid. It automatically determines when level 3 data is required for the lowest qualified rate. Additionally, it automatically forces proper settlement rules are complied with, including authorization.
Increased access: Anyone authorized can process transactions via the virtual terminal because it's in the cloud, not desktop software.
PCI Compliance: stored tokens replaced full card data- no employee access to card data. PCI compliant custom credit card authorization forms automatically generated for customer signature.
Operational Efficiencies: Quick and easy to charge repeat customer accounts using stored tokens. One reporting hub to retrieve all payments, including resending receipts to merchants. Custom Level 3 data template(s) significantly reduce burden of adding level 3 data when prompted.
The merchant chose to open a new interchange plus merchant account as well as implement CenPOS. Within 30 days, the merchant streamlined payment processing and reduced card acceptance costs over 50%, as evidenced by comparing before and after merchant statements. Additionally, PCI compliance burden and financial risks were reduced, providing peace of mind for the family business owners.
Above: Example of a new low interchange rate a transaction qualified for vs 3.77% on the old solution.
ARTICLE DISCLAIMER: The details of the third party offer are based on my recollection of verbal statements by the merchant. It's possible not all information was shared with me, or that my recollection is imperfect. Before making any financial decisions for your company, speak with a qualified representative familiar with the nuances of business to business interchange rules and PCI compliance rules.
Did you like this article? Please give it a thumbs up / like it, review or share it.
This entry was posted in CenPOS, rates, virtual terminal and tagged CenPOS, credit card processing, level 3 data, level 3 processing, virtual terminal by Christine Speedy. Bookmark the permalink.