/// <summary>
 /// Export exchange data to csv and then to optimized bin files
 /// </summary>
 /// <param name="api">Exchange api, null to just convert existing csv files</param>
 /// <param name="symbol">Symbol to export</param>
 /// <param name="basePath">Base path to export to, should not contain symbol, symbol will be appended</param>
 /// <param name="sinceDateTime">Start date to begin export at</param>
 /// <param name="callback">Callback if api is not null to notify of progress</param>
 public static void ExportExchangeTrades(IExchangeAPI api, string symbol, string basePath, DateTime sinceDateTime, System.Action <long> callback = null)
 {
     basePath = Path.Combine(basePath, symbol);
     Directory.CreateDirectory(basePath);
     sinceDateTime = sinceDateTime.ToUniversalTime();
     if (api != null)
     {
         long         count     = 0;
         int          lastYear  = -1;
         int          lastMonth = -1;
         StreamWriter writer    = null;
         foreach (ExchangeTrade trade in api.GetHistoricalTrades(symbol, sinceDateTime))
         {
             if (trade.Timestamp.Year != lastYear || trade.Timestamp.Month != lastMonth)
             {
                 if (writer != null)
                 {
                     writer.Close();
                 }
                 lastYear  = trade.Timestamp.Year;
                 lastMonth = trade.Timestamp.Month;
                 writer    = new StreamWriter(basePath + trade.Timestamp.Year + "-" + trade.Timestamp.Month.ToString("00") + ".csv");
             }
             writer.WriteLine("{0},{1},{2}", CryptoUtility.UnixTimestampFromDateTimeSeconds(trade.Timestamp), trade.Price, trade.Amount);
             if (++count % 100 == 0)
             {
                 callback?.Invoke(count);
             }
         }
         writer.Close();
         callback?.Invoke(count);
     }
     TraderFileReader.ConvertCSVFilesToBinFiles(basePath);
 }
Example #2
0
    public void SetAddCardToSlotListener(System.Action <Card> listener, CardDetail.CanAddCardToSlot condition = null)
    {
        if (listener == null)
        {
            cardDetail.SetAddCardToSlotListener(null);
            onClickCard = OpenCardDetailWithCard;
        }
        else
        {
            cardDetail.SetAddCardToSlotListener((card) =>
            {
                cardDetail.Close();
                Close();
                listener.Invoke(card);
            }, condition);

            onClickCard = (card) =>
            {
                if (condition(card))
                {
                    Close();
                    listener.Invoke(card);
                }
                else
                {
                    OpenCardDetailWithCard(card);
                }
            };
        }
    }
Example #3
0
        public void ProcessJobWithCompletion(EDQueue.EDQueue queue, NSDictionary job, System.Action <int> block)
        {
            NSThread.SleepFor(1);

            try
            {
                var jobStatus = ((NSString)job.ObjectForKey(new NSString("task")))?.ToString();

                switch (jobStatus)
                {
                case "success":
                    block?.Invoke((int)EDQueueResult.Success);
                    break;

                case "fail":
                    block?.Invoke((int)EDQueueResult.Fail);
                    break;

                default:
                    block?.Invoke((int)EDQueueResult.Critical);
                    break;
                }
            } catch {
                block?.Invoke((int)EDQueueResult.Critical);
            }
        }
Example #4
0
    protected SoundComponent LoadAndPlay(string fileName, Vector3 Position, KBusAudio bus = null, float DelayTime = 0f, float Duration = -1f)
    {
        SoundComponent source = GetAudioSource3D(fileName);

        if (source == null)
        {
            return(null);
        }

        if (bus != null)
        {
            if (bus.Add(source) == false)
            {
                if (PushToPool != null)
                {
                    PushToPool.Invoke(source.transform);
                }
                else
                {
                    Destroy(source.transform.gameObject);
                }

                return(null);
            }
            else
            {
                // Please Add All CallbackFunction
                // Do dùng cái Pool nên sợ Add thê nhiều lần
                // if (_Sound.callback == null)
                //      :: Todo
                // Ignore add to Pool of KAudioCompoenent
                source._Sound.callback = () =>
                {
                    bus.Remove(source);

                    if (PushToPool != null)
                    {
                        PushToPool.Invoke(source.transform);
                    }
                    else
                    {
                        Destroy(source.transform.gameObject);
                    }
                };
            }
        }

        source.gameObject.transform.localPosition = Position;

        if (Duration > 0)
        {
            source.Play(DelayTime, Duration);
        }
        else
        {
            source.Play(DelayTime);
        }

        return(source);
    }
Example #5
0
        private void WriteUser(INetUser user, string wishlist, System.Action <INetUser> onSuccess, System.Action <INetError> onError)
        {
            WWWForm form = new WWWForm();

            form.AddField("op", "write_user");
            form.AddField("user_id", user.id);
            form.AddField("user_name", user.name);
            form.AddField("avatar_id", user.avatarId);
            form.AddField("level", user.level);
            form.AddField("wishlist", wishlist);

            MakeRequest(form, (json) => {
                try {
                    Dictionary <string, object> userObj = Json.Deserialize(json) as Dictionary <string, object>;
                    if (userObj == null)
                    {
                        onError?.Invoke(errorFactory.Create(NetErrorCode.json, string.Empty));
                        return;
                    }
                    NetPlayer player = new NetPlayer(userObj, true, resourceService);
                    onSuccess?.Invoke(player);
                } catch (Exception exception) {
                    onError?.Invoke(errorFactory.Create(NetErrorCode.json, string.Empty));
                }
            }, onError);
        }
 private void OnResumeClick()
 {
     _isVisible = false;
     SetVisible(_isVisible);
     _onActivation?.Invoke(_isVisible);
     Time.timeScale = 1f;
 }
Example #7
0
        public virtual void Play(float timeDelay = 0f)
        {
            this._Sound.DelayTime = timeDelay;
            //Debug.LogError(Clip.name);
            if (_Sound.callback == null)
            {
                _Sound.callback += () => {
                    _Sound.source.Stop();
                    //_Sound.source.time = 0;
                    //_Sound.source.timeSamples = 0;
                    _Sound._Count = 0;

                    if (PushToPool != null)
                    {
                        PushToPool.Invoke(this.transform);
                    }
                    else
                    {
                        Destroy(this.gameObject);
                    }
                };
            }

            if (timeDelay == 0f)
            {
                _Sound.Playing = true;
            }
            //_Sound.IsFadeOut = true;
            //_Sound.IsFadeIn = true;
            //Debug.LogError(_Sound.clip.samples);
            if (_Sound.clip != null)
            {
                StartCoroutine(WaitTime((float)_Sound.clip.samples / (float)_Sound.clip.frequency));
            }
        }
Example #8
0
        private void FastRenderMultiThread(Scene scene, System.Action <int, int> progressCallBackAction)
        {
            List <ManualResetEvent> eventList = new List <ManualResetEvent>();

            int total    = m_RenderTarget.width * m_RenderTarget.height;
            int finished = 0;

            for (int j = 0; j < m_RenderTarget.height; j++)
            {
                for (int i = 0; i < m_RenderTarget.width; i++)
                {
                    var job = new FastRenderJob(i, j, scene, this);
                    eventList.Add(job.resetEvent);
                    ThreadPool.QueueUserWorkItem(job.Render);

                    if (eventList.Count >= Environment.ProcessorCount)
                    {
                        WaitRender(eventList);
                        progressCallBackAction?.Invoke(finished, total);
                        finished++;
                    }
                }
            }

            while (eventList.Count > 0)
            {
                WaitRender(eventList);
                progressCallBackAction?.Invoke(finished, total);
                finished++;
            }
        }
Example #9
0
File: App.cs Project: jeffscm/mvcrx
 public void Publish()
 {
     foreach (var s in subscriptions)
     {
         registerCall?.Invoke(s);
     }
 }
        private static void LoadAllAssetsFromAssetBundle <T>(string path, Type type, System.Action <T[]> callback) where T : UnityEngine.Object
        {
            string bundleName = AssetBundlePath.DirectoryToBundleName(path);

            LoadAssetBundle(bundleName, (AssetBundle bundle) =>
            {
                if (bundle != null)
                {
                    AssetBundleRequest request = bundle.LoadAllAssetsAsync(type);
                    request.completed         += (AsyncOperation operation) =>
                    {
                        UnityEngine.Object[] allAssets = request.allAssets;
                        T[] assets = new T[allAssets.Length];
                        for (int i = 0; i < allAssets.Length; i++)
                        {
                            assets[i] = allAssets[i] as T;
                        }
                        callback?.Invoke(assets);
                    };
                }
                else
                {
                    callback?.Invoke(new T[0]);
                }
            });
        }
Example #11
0
        /// <summary>
        /// byte加密读取
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        protected virtual void ByteEncryption_WebRead(string path, System.Action <FileObject> OnCall)
        {
            byte[] data = new byte[1024];
            MainSystem.Instance.ReadWebData(path, (w) =>
            {
                if (w.error == null)
                {
                    string[] strs = w.downloadHandler.text.Split('-');
                    data          = new byte[strs.Length];
                    for (int i = 0; i < strs.Length; i++)
                    {
                        data[i] = Convert.ToByte(strs[i], 16);
                    }
                    Error = true;

                    OnCall?.Invoke(new FileObject {
                        Buffet = data, isError = true
                    });
                }
                else
                {
                    Error = false;
                    OnCall?.Invoke(new FileObject {
                        Buffet = null, isError = false
                    });
                    Debug.Log("文件不存在=path:" + path);
                }
            });
        }
Example #12
0
        /// <summary>
        /// 卸载伙伴身上的所有装备
        /// </summary>
        /// <param name="heroId"></param>
        /// <param name="callback"></param>
        public void RequireUnEquipAll(int heroId, System.Action <bool> callback = null)
        {
            LTPartnerData parData = LTPartnerDataManager.Instance.GetPartnerByHeroId(heroId);

            if (parData == null)
            {
                EB.Debug.LogError("LTPartnerEquipDataManager RequireUnEquipAll heroid is Error, heroid = {0}", heroId);
                callback?.Invoke(false);
                return;
            }

            HeroEquipmentInfo[]      infos  = parData.EquipmentsInfo;
            List <HeroEquipmentInfo> eInfos = new List <HeroEquipmentInfo>();

            for (int i = 0; i < infos.Length; i++)
            {
                if (infos[i].Eid > 0)
                {
                    eInfos.Add(infos[i]);
                }
            }

            if (eInfos.Count == 0)
            {
                callback?.Invoke(true);
                return;
            }

            if (isMaxEquipNumOneKey(eInfos.Count))
            {
                MessageTemplateManager.ShowMessage(eMessageUIType.FloatingText, EB.Localizer.GetString("ID_codefont_in_MailApi_1124"));
                return;
            }

            for (int i = 0; i < eInfos.Count; i++)
            {
                if (i == eInfos.Count - 1)
                {
                    RequireUnEquip(eInfos[i].Eid, heroId, (success) =>
                    {
                        if (!success)
                        {
                            return;
                        }

                        callback?.Invoke(success);
                    }, true);
                }
                else
                {
                    RequireUnEquip(eInfos[i].Eid, heroId, (success) =>
                    {
                        if (!success)
                        {
                            return;
                        }
                    }, false);
                }
            }
        }
        private static void LoadAssetFromAssetBundle <T>(string path, Type type, System.Action <T> callback) where T : UnityEngine.Object
        {
            string bundleName = AssetBundlePath.FileToBundleName(path);

            LoadAssetBundle(bundleName, (AssetBundle bundle) =>
            {
                if (bundle != null)
                {
                    string assetName           = AssetBundlePath.FileToAssetName(path);
                    AssetBundleRequest request = bundle.LoadAssetAsync(assetName, type);
                    request.completed         += (AsyncOperation operation) =>
                    {
                        T asset = request.asset as T;
                        if (asset == null)
                        {
                            AssetBundleLoaderDebug.LogError("Asset loading faild in bundle" + Environment.NewLine +
                                                            "bundle name: " + bundleName + Environment.NewLine +
                                                            "asset name: " + assetName);
                        }
                        callback?.Invoke(asset);
                    };
                }
                else
                {
                    callback?.Invoke(null);
                }
            });
        }
Example #14
0
        private void WritePoints(UserRoomPoints userRoomPoints, System.Action <UserRoomPoints> onSuccess, System.Action <INetError> onError)
        {
            WWWForm form = new WWWForm();

            form.AddField("op", "write_points");
            form.AddField("room_id", userRoomPoints.RoomPoints.RoomId);
            form.AddField("room_mode", userRoomPoints.RoomPoints.RoomMode.ToString());
            form.AddField("user_id", userRoomPoints.User.id);
            form.AddField("user_name", userRoomPoints.User.name);
            form.AddField("avatar_id", userRoomPoints.User.avatarId);
            form.AddField("level", userRoomPoints.User.level);
            form.AddField("points", userRoomPoints.RoomPoints.Points);

            MakeRequest(form, (json) => {
                try {
                    Dictionary <string, object> dict = Json.Deserialize(json) as Dictionary <string, object>;
                    if (dict == null)
                    {
                        onError?.Invoke(errorFactory.Create(NetErrorCode.json, string.Empty));
                        return;
                    }
                    UserRoomPoints returnedPoints = new UserRoomPoints(dict, resourceService);
                    onSuccess?.Invoke(returnedPoints);
                } catch (Exception exception) {
                    onError?.Invoke(errorFactory.Create(NetErrorCode.json, string.Empty));
                }
            }, onError);
        }
Example #15
0
    IEnumerator DoDisconnectDieCr(EditDie editDie, System.Action <EditDie, bool, string> dieDisconnectedCallback)
    {
        var dt = dice.First(p => p == editDie);

        if (dt == null)
        {
            Debug.LogError("Trying to disconnect unknown edit die " + editDie.name);
        }
        else if (dt.die == null)
        {
            Debug.LogError("Trying to disconnect unknown die " + editDie.name);
        }
        else if (dt.die.connectionState != Die.ConnectionState.Ready)
        {
            Debug.LogError("Trying to disconnect die that isn't connected " + editDie.name + ", current state " + dt.die.connectionState);
        }
        else
        {
            bool?res = null;
            DicePool.Instance.DisconnectDie(dt.die, (d, r, s) => res = r);
            yield return(new WaitUntil(() => res.HasValue));

            if (res.Value)
            {
                dieDisconnectedCallback?.Invoke(editDie, true, null);
            }
            else
            {
                dieDisconnectedCallback?.Invoke(editDie, false, "Could not disconnect to Die " + editDie.name + ". Communication Error");
            }
        }
    }
Example #16
0
        private void ReadPoints(INetUser user, INetRoom room, System.Action <NetRoomPlayerRank> onSuccess, System.Action <INetError> onError)
        {
            WWWForm form = new WWWForm();

            form.AddField("op", "read_points");
            form.AddField("room_id", room.RoomId);
            form.AddField("room_mode", room.RoomMode.ToString());
            form.AddField("user_id", user.id);
            form.AddField("user_name", user.name);
            form.AddField("avatar_id", user.avatarId);
            form.AddField("level", user.level);

            MakeRequest(form, json => {
                try {
                    Dictionary <string, object> dict = Json.Deserialize(json) as Dictionary <string, object>;
                    if (dict == null)
                    {
                        onError?.Invoke(errorFactory.Create(NetErrorCode.json, string.Empty));
                        return;
                    }
                    NetRoomPlayerRank rank = new NetRoomPlayerRank(dict, resourceService);
                    onSuccess?.Invoke(rank);
                } catch (Exception exception) {
                    onError?.Invoke(errorFactory.Create(NetErrorCode.json, string.Empty));
                }
            }, onError);
        }
Example #17
0
        public bool     HasChanged()
        {
            if (!this.CacheIndex.HasValue)
            {
                return(false);
            }

            //	read & copy latest bytes
            try
            {
                int Revision = -1;

                if (PixelBytes != null)
                {
                    Revision = ReadPixelBytesFromCache(this.CacheIndex.Value, PixelBytes, PixelBytes.Length);
                    if (Revision < 0)
                    {
                        throw new System.Exception("ReadPixelBytesFromCache returned " + Revision);
                    }
                }
                if (PixelFloats != null)
                {
                    Revision = ReadPixelFloatsFromCache(this.CacheIndex.Value, PixelFloats, PixelFloats.Length);
                    if (Revision < 0)
                    {
                        throw new System.Exception("ReadPixelFloatsFromCache returned " + Revision);
                    }
                }

                var Changed = LastRevision.HasValue ? (LastRevision.Value != Revision) : true;
                if (Changed)
                {
                    if (ByteCallback != null)
                    {
                        ByteCallback.Invoke(PixelBytes, Channels, null);
                    }
                    if (FloatCallback != null)
                    {
                        FloatCallback.Invoke(PixelFloats, Channels, null);
                    }
                }
                LastRevision = Revision;
                return(Changed);
            }
            catch (System.Exception e)
            {
                if (ByteCallback != null)
                {
                    ByteCallback.Invoke(null, 0, e.Message);
                }
                if (FloatCallback != null)
                {
                    FloatCallback.Invoke(null, 0, e.Message);
                }
                return(false);
            }
        }
Example #18
0
        private IEnumerator GetBalanceShipImpl(System.Action <List <ShipModuleData> > onSuccess, System.Action <string> onError)
        {
            UnityWebRequest request = UnityWebRequest.Get(FullUrl(balanceShipUrl));

            request.SetRequestHeader(authKey, AuthHeader);
            UnityWebRequestAsyncOperation operation = request.SendWebRequest();

            yield return(operation);

            if (operation.isDone)
            {
                if (false == operation.webRequest.isHttpError)
                {
                    try {
                        string result = operation.webRequest.downloadHandler.text;
                        string json   = JWT.JsonWebToken.Decode(result, secretKey);
                        //print(json.Colored(ConsoleTextColor.green));
                        JObject parent = JObject.Parse(json);
                        JToken  arr    = parent["response"]["data"];

                        int moduleId = 0;
                        List <ShipModuleData> modules = new List <ShipModuleData>();
                        foreach (JToken token in arr)
                        {
                            int    planetLevel = token.Value <int>(0);
                            double companyCash = token.Value <double>(1);
                            double securities  = token.Value <double>(2);
                            int    coins       = token.Value <int>(3);
                            if (companyCash != 0.0)
                            {
                                modules.Add(new ShipModuleData(moduleId, planetLevel, Currency.CreateCompanyCash(companyCash)));
                            }
                            else if (securities != 0.0)
                            {
                                modules.Add(new ShipModuleData(moduleId, planetLevel, Currency.CreateSecurities(securities)));
                            }
                            else
                            {
                                modules.Add(new ShipModuleData(moduleId, planetLevel, Currency.CreateCoins(coins)));
                            }
                            moduleId++;
                        }
                        onSuccess?.Invoke(modules);
                    } catch (Exception exception) {
                        onError?.Invoke(exception.Message);
                    }
                }
                else
                {
                    onError?.Invoke(operation.webRequest.error);
                }
            }
            else
            {
                onError?.Invoke("operation GetShipBalance not done");
            }
        }
Example #19
0
    public void OnClickYesBtn()
    {
        if (callback != null)
        {
            callback.Invoke(true);
        }

        OnBackPressed(true);
    }
Example #20
0
 public void Init(Levels.FlowerConfiguration config)
 {
     flowerFace.flower = this;
     flowerState.Init(config.isHappy);
     flowerPetals.SetPetals(this, config);
     if (onStateChange != null)
     {
         onStateChange.Invoke(config.isHappy);
     }
 }
        public static void Play(Replay replay)
        {
            IsPlayingBack = true;
            StartStreaming(replay);
            FrameManager.AdjustFramerate = false;

            if (onIsPlayingBack != null)
            {
                onIsPlayingBack.Invoke(IsPlayingBack);
            }
        }
Example #22
0
 public void ObserveState()
 {
     if (PlayerInfo.HasValue)
     {
         if (observe_dieFlag == false && PlayerInfo.Value.IsDead == 1)
         {
             observe_dieFlag = true;
             onDie?.Invoke(Position, PlayerInfo.Value.ColorId);
         }
     }
 }
Example #23
0
        public IEnumerator LoadRes(string _IEName, System.Type type, System.Action <Object> _callBack)
        {
            yield return(null);

            Object _obj = Resources.Load(_IEName, type);

            if (_obj != null)
            {
                if (_callBack != null)
                {
                    _callBack.Invoke(_obj);
                }
            }
            else
            {
                ResourceRequest _req = Resources.LoadAsync(_IEName, type);
                while (!_req.isDone)
                {
                    yield return(null);
                }
                //if(Z-Resource)
                if (_req.asset == null)
                {
                    _req = null;
                    yield return(null);

                    _req = Resources.LoadAsync("Z-Resource/" + _IEName, type);
                    while (!_req.isDone)
                    {
                        yield return(null);
                    }
                }
                if (_req.asset != null)
                {
                    _obj = Object.Instantiate(_req.asset);
                    yield return(null);

                    if (_callBack != null)
                    {
                        _callBack.Invoke(_obj);
                    }
                }
                else
                {
                    if (_callBack != null)
                    {
                        _callBack.Invoke(null);
                    }
                }
            }
            //执行从数组中删除的操作//
            StartCoroutine(ExecIE(_IEName));
        }
Example #24
0
        public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, System.Action <UIBackgroundFetchResult> completionHandler)
        {
            var result = Push.DidReceiveRemoteNotification(userInfo);

            if (result)
            {
                completionHandler?.Invoke(UIBackgroundFetchResult.NewData);
            }
            else
            {
                completionHandler?.Invoke(UIBackgroundFetchResult.NoData);
            }
        }
Example #25
0
        private IEnumerator GetBalanceMechanicImpl(System.Action <List <MechanicData> > onSuccess, System.Action <string> onError)
        {
            UnityWebRequest request = UnityWebRequest.Get(FullUrl(kBalanceMechanicUrl));

            request.SetRequestHeader(authKey, AuthHeader);
            UnityWebRequestAsyncOperation operation = request.SendWebRequest();

            yield return(operation);

            if (operation.isDone)
            {
                if (!operation.webRequest.isHttpError)
                {
                    try {
                        string result = operation.webRequest.downloadHandler.text;
                        string json   = JWT.JsonWebToken.Decode(result, secretKey);
                        //print(json.Colored(ConsoleTextColor.green));
                        JObject parent = JObject.Parse(json);
                        JToken  arr    = parent["response"]["data"];

                        int planetId = 0;
                        List <MechanicData> mechanics = new List <MechanicData>();

                        foreach (JToken token in arr)
                        {
                            int    priceForFirstMechanic = token.Value <int>(0);
                            int    priceIncreasing       = token.Value <int>(1);
                            int    unitCountService      = token.Value <int>(2);
                            float  fatigue = token.Value <float>(3);
                            int    restoredPer10Seconds = token.Value <int>(4);
                            double cashPrice            = token.Value <double>(5);
                            mechanics.Add(new MechanicData(planetId, priceForFirstMechanic, priceIncreasing,
                                                           unitCountService, fatigue, restoredPer10Seconds, cashPrice));
                            planetId++;
                        }
                        onSuccess?.Invoke(mechanics);
                    } catch (System.Exception exception) {
                        onError?.Invoke(exception.Message);
                    }
                }
                else
                {
                    onError?.Invoke(operation.webRequest.error);
                }
            }
            else
            {
                onError?.Invoke("operation GetBalanceMechanic is not done");
            }
        }
Example #26
0
    public static IEnumerator LerpRoutine(float duration, System.Action <float> onEachIteration)
    {
        float timer = 0;

        while (timer < duration)
        {
            yield return(new WaitForEndOfFrame());

            onEachIteration.Invoke(timer / duration);
            timer += Time.deltaTime;
        }

        onEachIteration.Invoke(1);
    }
Example #27
0
        private void Connect(string key, System.Action <bool> onResult = null)
        {
            if (this.net.Connected() == true)
            {
                if (UnityEngine.UI.Windows.Constants.LOGS_ENABLED == true)
                {
                    UnityEngine.Debug.Log("Stat, Is already connected");
                }
                if (onResult != null)
                {
                    onResult.Invoke(true);
                }
            }
            else if (connecting == true)
            {
                if (UnityEngine.UI.Windows.Constants.LOGS_ENABLED == true)
                {
                    UnityEngine.Debug.LogError("Stat, Is already connecting");
                }
            }
            else
            {
                this.connectDT  = System.DateTime.UtcNow;
                this.connecting = true;
                this.net.Connect(host, port, (b) => {
                    var seconds = (System.DateTime.UtcNow - connectDT).TotalSeconds;
                    if (UnityEngine.UI.Windows.Constants.LOGS_ENABLED == true)
                    {
                        UnityEngine.Debug.Log(string.Format("Stat connect to host: {0} r: {1} s: {2}", host, b, seconds));
                    }
                    reconnectDelay = b ? minDelay : System.Math.Min(reconnectDelay * 2, maxDelay);

                    if (b == true)
                    {
                        this.authTO = new AuthTO()
                        {
                            key = key
                        };
                        this.net.SendMsg(AuthTO.version, this.SerializeB(authTO));
                    }

                    this.connecting = false;
                    if (onResult != null)
                    {
                        onResult.Invoke(b);
                    }
                });
                this.net.onRecMsg = this.OnRecMsg;
            }
        }
Example #28
0
        Thread StartListener(Stream transferChannel, System.Action <ulong, byte[]> receiveDataSet)
        {
            var listenThrd = new Thread(() => { // Listener thread
                try {
                    var pkgBuilder = new Dictionary <uint, DataBuilder>();
                    while (true)
                    {
                        foreach (var tpLspS in TpLspHelper.SequenceReader(transferChannel))
                        {
                            if (tpLspS.IsQuantizied)
                            {
                                DataBuilder db = null;
                                if (!pkgBuilder.TryGetValue(tpLspS.QuantId, out db))
                                {
                                    db = new DataBuilder(tpLspS.DataLength);
                                    pkgBuilder.Add(tpLspS.QuantId, db);
                                }

                                db.WriteData(tpLspS.QuantData, tpLspS.QuantShift);

                                if (db.IsComplete())
                                {
                                    var result = db.GetData();

                                    pkgBuilder.Remove(tpLspS.QuantId);
                                    receiveDataSet.Invoke(tpLspS.Rap, result);
                                }
                            }
                            else
                            {
                                var result = tpLspS.QuantData;
                                receiveDataSet.Invoke(tpLspS.Rap, result);
                            }
                        }
                    }
                }
                catch (Exception e) {
                    isTranferDead = true;
                    OnConnectionError(e);
                }
            })
            {
                IsBackground = true, Priority = ThreadPriority.Normal
            };

            listenThrd.Start();

            return(listenThrd);
        }
Example #29
0
        public static string GetHTML(string hackerNewsUrl)
        {
            if (Logger != null)
            {
                Logger.Invoke("Fetching " + hackerNewsUrl);
            }
            var c = new HttpClient();

            c.DefaultRequestHeaders.Add("User-Agent", useragent);
            c.DefaultRequestHeaders.Add("Referer", "https://news.ycombinator.com/");
            var s = c.GetStringAsync(hnurl + hackerNewsUrl).GetAwaiter().GetResult();

            Logger.Invoke("Retrieved " + hackerNewsUrl);
            return(s);
        }
Example #30
0
    /// <summary>
    /// 获取资源
    /// 异步方法
    /// </summary>
    /// <param name="resPath">Resources下的相对目录</param>
    /// <param name="OnGetComplete">返回值为资源</param>
    /// <param name="isFinishUnload">下载完AB后是否马上卸载AB的内存镜像(不销毁从中加载的资源)</param>
    public static void GetResource(string resPath, System.Action <object> OnGetComplete, bool isFinishUnload = false)
    {
        if (!Global.IsUseAB)
        {
            object res = Resources.Load(resPath);
            if (res == null)
            {
                Debug.LogWarning(resPath + " not exist!");
                return;
            }
            OnGetComplete.Invoke(res);
            return;
        }
        resPath = resPath.ToLower();
        if (!_abAssetPathDic.ContainsKey(resPath))
        {
            Debug.LogWarning(resPath + " not exist!");
            return;
        }
        if (_taskDic.ContainsKey(OnGetComplete))
        {
            return;
        }
        if (_assetDic.ContainsKey(resPath))
        {
            OnGetComplete.Invoke(_assetDic[resPath]);
            return;
        }
        string abName = _abAssetPathDic[resPath];

        if (_abDic.ContainsKey(abName))
        {
            AssetBundle ab  = _abDic[abName];
            object      obj = ab.LoadAsset(Path.GetFileNameWithoutExtension(resPath));
            _assetDic.Add(resPath, obj);
            OnGetComplete.Invoke(obj);
        }
        else
        {
            LoadTask task = new LoadTask();
            task.resPath        = resPath;
            task.abName         = abName;
            task.resCallback    = OnGetComplete;
            task.isFinishUnload = isFinishUnload;
            _taskDic.Add(OnGetComplete, task);
            StartLoad(task);
        }
    }