Esempio n. 1
0
        public BitmapSource GetBitmap(SymbolID symbolID, Color color, bool dark)
        {
            Dictionary<Color, CacheData> map;
            CacheData data;

            if (color == Colors.Black)
            {
                data = m_blackBitmapList[(int)symbolID];

                if (data == null)
                {
                    data = new CacheData();
                    m_blackBitmapList[(int)symbolID] = data;
                }
            }
            else
            {
                if (!m_bitmapMap.TryGetValue(symbolID, out map))
                {
                    map = new Dictionary<Color, CacheData>();
                    m_bitmapMap[symbolID] = map;
                }

                if (!map.TryGetValue(color, out data))
                {
                    data = new CacheData();
                    map[color] = data;
                }
            }

            if (!dark)
            {
                if (data.Bitmap == null)
                {
                    BitmapSource bmp = CreateSymbolBitmap(symbolID, color, dark);
                    data.Bitmap = bmp;
                }

                return data.Bitmap;
            }
            else
            {
                if (data.BitmapDark == null)
                {
                    BitmapSource bmp = CreateSymbolBitmap(symbolID, color, dark);
                    data.BitmapDark = bmp;
                }

                return data.BitmapDark;
            }
        }
Esempio n. 2
0
 public static void LoadCacheData(ulong id, long timeStamp, bool createPlayer)
 {
     if (GameCache.dataID == id && GameCache.dataTimeStamp == timeStamp && GameCache.Data != null)
     {
         return;
     }
     GameCache.dataID = id;
     GameCache.dataTimeStamp = timeStamp;
     if (createPlayer)
     {
         GameCache.Data = new CacheData();
         GameCache.SaveCacheData();
     }
     else
     {
         FileStream fileStream = null;
         try
         {
             string path = string.Format("{0}/p_{1}_{2}.data", Application.persistentDataPath, GameCache.dataID, GameCache.dataTimeStamp);
             if (File.Exists(path))
             {
                 fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
                 if (fileStream != null)
                 {
                     GameCache.Data = (Serializer.NonGeneric.Deserialize(typeof(CacheData), fileStream) as CacheData);
                     GameCache.TryClearConfigurableActivityDatas();
                 }
             }
         }
         catch (Exception ex)
         {
             global::Debug.LogWarning(new object[]
             {
                 "Load Player Cache failed, Exception:" + ex.Message
             });
         }
         if (fileStream != null)
         {
             fileStream.Close();
         }
         if (GameCache.Data == null)
         {
             GameCache.Data = new CacheData();
         }
     }
 }
Esempio n. 3
0
        //
        // GET: /Stocks/
        public ActionResult Index()
        {
            string u = Request.ServerVariables["HTTP_USER_AGENT"];
            Regex b = new Regex(@"android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|symbian|treo|up\\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            Regex v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|e\\-|e\\/|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\\-|2|g)|yas\\-|your|zeto|zte\\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);

			CacheData cacheData = new CacheData();
			cacheData.Cache();
			
			if ((b.IsMatch(u) || v.IsMatch(u.Substring(0, 4))))
            {
                return RedirectToAction("Mobile", "Stocks", null);
            }
            else
            {				
                return View();
            }
        }
Esempio n. 4
0
        /// <summary>
        /// 移除缓存,提供给服务控制器调用
        /// </summary>
        /// <param name="cacheName"></param>
        /// <param name="key"></param>
        public static void RemoveCache(string cacheName, string key)
        {
            lock (_localCache)
            {
                if (_localCache.Contains(cacheName))
                {
                    CacheObject co = _localCache.GetData(cacheName) as CacheObject;
                    if (co.cacheValue.FindIndex(x => x.key == key) > -1)
                    {
                        CacheData cd = co.cacheValue.Find(x => x.key == key);
                        cd.deleteflag = true;//缓存移除
                        cd.timestamp  = DateTimeToTimestamp(DateTime.Now);
                        co.identify   = DateTimeToTimestamp(DateTime.Now);

                        PublishServiceManage.SendNotify("DistributedCache");//订阅服务发送通知
                    }
                }
            }
        }
Esempio n. 5
0
        public void Execute(Message message)
        {
            if (CacheData.Operators
                .SingleOrDefault(x => x.TelegramUserId == message.From.Id &&
                                 x.Level >= Models.Operator.Levels.Basic) == null &&
                !Utils.ChatTools.IsUserAdmin(message.Chat.Id, message.From.Id))
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp        = DateTime.UtcNow,
                    Chat             = message.Chat,
                    ReplyToMessageId = message.MessageId,
                    Text             = CacheData.GetTranslation("en", "error_not_auth_command")
                });
                return;
            }

            string[] hasMessage = message.Text.Split(" ");
            if (hasMessage.Length == 2)
            {
                if (hasMessage[1] == "close")
                {
                    ToggleGate(message, false);
                }
                else if (hasMessage[1] == "open")
                {
                    ToggleGate(message, true);
                }
                else
                {
                    MessageQueueManager.EnqueueMessage(
                        new Models.ChatMessage()
                    {
                        Timestamp        = DateTime.UtcNow,
                        Chat             = message.Chat,
                        ReplyToMessageId = message.MessageId,
                        Text             = CacheData.GetTranslation("en", "error_gate_command_argument")
                    });
                }
                return;
            }
        }
Esempio n. 6
0
        public static async Task <bool> Parse(CallbackQuery callbackQuery)
        {
            string command = callbackQuery.Data.Split(" ")[0].Remove(0, 1);

            if (!Commands.CommandsList.TryGetValue(command.ToUpper(), out ICommand parsedCommand))
            {
#if DEBUG
                await Manager.BotClient.SendTextMessageAsync(
                    chatId : callbackQuery.Message.Chat.Id,
                    text : CacheData.GetTranslation("en", "error_invalid_command")
                    );
#endif
                return(false);
            }

            await Task.Run(() => parsedCommand.Execute(callbackQuery));

            return(true);
        }
        /// <summary>
        /// 确定交易码
        /// </summary>
        private void OnClickTrandeConfindBtn()
        {
            Dispatch(AreaCode.AUDIO, AudioEvent.PLAY_CLICK_AUDIO, "ClickVoice");

            string confirmPass = InputTradeCode.text;

            if (confirmPass.IsNullOrEmpty())
            {
                //TODO提示
            }
            else if (CacheData.Instance().CommerceState == 1)
            {
                Dispatch(AreaCode.NET, ReqEventType.permission_commerce, confirmPass);
            }
            else if (CacheData.Instance().CommerceState == 2)
            {
                Dispatch(AreaCode.NET, ReqEventType.confirmPass, confirmPass);
            }
        }
Esempio n. 8
0
        public void Execute(Message message)
        {
            if (CacheData.Operators
                .SingleOrDefault(x => x.TelegramUserId == message.From.Id &&
                                 x.Level == Models.Operator.Levels.Super) == null)
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp        = DateTime.UtcNow,
                    Chat             = message.Chat,
                    ReplyToMessageId = message.MessageId,
                    Text             = CacheData.GetTranslation("en", "error_not_auth_command")
                });
                Manager.BotClient.SendTextMessageAsync(
                    chatId: CacheData.ControlChatId,
                    parseMode: ParseMode.Markdown,
                    text: String.Format(
                        "*[Report]*\n" +
                        "⚠️ Non operator tried to use /reloadtranslations\n" +
                        "\n*Chat:* {0}" +
                        "\n*ChatId:* {1}" +
                        "\n*UserId:* {2}" +
                        "\n\n*hash_code:* #UB{3}-{4}",
                        message.Chat.Title,
                        message.Chat.Id,
                        message.From.Id,
                        message.Chat.Id.ToString().Replace("-", ""),
                        Guid.NewGuid())
                    );
                return;
            }

            Program.InitializeTranslations();
            MessageQueueManager.EnqueueMessage(
                new Models.ChatMessage()
            {
                Timestamp        = DateTime.UtcNow,
                Chat             = message.Chat,
                ReplyToMessageId = message.MessageId,
                Text             = CacheData.GetTranslation("en", "done", true)
            });
        }
        public void ChangeBlock(int chunkX, int chunkZ, int blockX, int blockY, int blockZ, Block newBlock)
        {
            HelperMethods.FixCoordinates(ref chunkX, ref chunkZ, ref blockX, ref blockY, ref blockZ);

            lock (CacheLock)
            {
                if (!IsReady(chunkX, chunkZ))
                {
                    throw new ArgumentException("Can't modify a chunk we haven't generated!");
                }

                CacheData dat = this[chunkX, chunkZ];

                dat.Chunk[blockX, blockY, blockZ] = newBlock;
                dat.Chunk.RecalculateVisualGeometry();

                SaveChunk(chunkX, chunkZ);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Get stock summary by symbol name.
        /// </summary>
        /// <param name="symbol">symbol name</param>
        /// <returns></returns>
        public static StockSummary GetStock(string symbol)
        {
            StockSummary stock = null;

            try
            {
                stock = GetStockFromBarchart(symbol);
            }
            catch
            {
                try
                {
                    CacheData cacheData = new CacheData();
                    stock = cacheData.GetCachedStock(symbol);
                }
                catch { }
            }
            return(stock);
        }
Esempio n. 11
0
        public CacheData getCachedSession(string session_id, string agent_id)
        {
            CacheData ret = null;

            lock (m_authed_sessions)
            {
                if (m_authed_sessions.ContainsKey(session_id))
                {
                    CacheData cached_session = m_authed_sessions[session_id];
                    if (!cached_session.isExpired && cached_session.AgentID == agent_id)
                    {
                        ret = m_authed_sessions[session_id];
                        // auto renew
                        m_authed_sessions[session_id].Renew();
                    }
                }
            }
            return(ret);
        }
Esempio n. 12
0
        public void AddOrUpdate(KeyType key, DataType data)
        {
            CacheData cacheData;

            if (_cache.TryGetValue(key, out cacheData) == false)
            {
                if (_cache.Count == _maxItem)
                {
                    long    min             = long.MaxValue;
                    KeyType keyOfMinHitItem = default(KeyType);
                    foreach (var item in _cache)
                    {
                        //if (item.Value.HitCount < min)
                        //{
                        //    min = item.Value.HitCount;
                        //    keyOfMinHitItem = item.Key;
                        //}
                        if (item.Value.LastAccessTime < min)
                        {
                            min             = item.Value.LastAccessTime;
                            keyOfMinHitItem = item.Key;
                        }
                    }
                    _cache.Remove(keyOfMinHitItem);
                }
                cacheData = new CacheData()
                {
                    Data                 = data,
                    HitCount             = 0,
                    LastAccessTime       = System.DateTime.Now.Ticks,
                    DataAsProtoBufStream = new System.IO.MemoryStream()
                };
                ProtoBuf.Serializer.Serialize(cacheData.DataAsProtoBufStream, data);
                _cache.Add(key, cacheData);
            }
            else
            {
                cacheData.Data           = data;
                cacheData.LastAccessTime = System.DateTime.Now.Ticks;
                ProtoBuf.Serializer.Serialize(cacheData.DataAsProtoBufStream, data);
            }
        }
Esempio n. 13
0
        public void Execute(CallbackQuery callbackQuery)
        {
            Message message = callbackQuery.Message;

            if (CacheData.Operators
                .SingleOrDefault(x => x.TelegramUserId == callbackQuery.From.Id &&
                                 x.Level >= Models.Operator.Levels.Basic) == null &&
                !Utils.ChatTools.IsUserAdmin(message.Chat.Id, callbackQuery.From.Id))
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp        = DateTime.UtcNow,
                    Chat             = message.Chat,
                    ReplyToMessageId = message.MessageId,
                    Text             = CacheData.GetTranslation("en", "error_not_auth_command")
                });
                return;
            }

            string[] parameters = callbackQuery.Data.Split(" ");
            switch (parameters[1])
            {
            case "prevPage":
            case "nextPage":
                SendKeyboard(message, parameters[3], Convert.ToInt32(parameters[2]));
                break;

            case "open":
                SetOpenTime(message, parameters[2]);
                break;

            case "close":
                SetCloseTime(message, parameters[2]);
                break;

            case "cancel":
                Manager.BotClient.DeleteMessageAsync(callbackQuery.Message.Chat.Id,
                                                     callbackQuery.Message.MessageId);
                break;
            }
        }
Esempio n. 14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var idUf = 0;
                int.TryParse(ufQuery.ToString(), out idUf);

                try
                {
                    // Se todos os parâmetros forem os padrões da página incial será trazido o dado cacheado
                    if (Dashboard.defaultStartDate == StartDate &&
                        Dashboard.defaultEndDate == EndDate &&
                        idUf == Dashboard.defaultUf)
                    {
                        var cacheData = new CacheData("ucGraficoIndiceSatisfacaoGeral", 24);
                        if (cacheData.HasValidCacheData())
                        {
                            indiceSatisfacao = cacheData.GetCacheData();
                        }
                        else
                        {
                            indiceSatisfacao = ObterIndiceSatisfacao(StartDate, EndDate, idUf);
                            // Queremos que expire na virada de dia e não dure exatamente 24 horas
                            cacheData.SetCacheData(indiceSatisfacao, typeof(DTOIndiceSatisfacao), DateTime.Today.AddDays(1));
                        }
                    }
                    else
                    {
                        indiceSatisfacao = ObterIndiceSatisfacao(StartDate, EndDate, idUf);
                    }
                }
                catch (Exception ex)
                {
                    pnlGrafico.Visible = false;
                    pnlAviso.Visible   = true;

                    ltrAvisoErro.Text = ex.Message + "<br/>" + (ex.InnerException != null
                                            ? ex.InnerException.Message
                                            : "");
                }
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Register an object to be called later by this module.
        /// </summary>
        /// <param name="object">The desired object.</param>
        /// <param name="expires">Time in seconds that the url will expire.</param>
        /// <param name="forceDownload">If true, the client browser will download the file instead of trying to show up.</param>
        /// <param name="fileName">Sets the file name shown by client browser.</param>
        /// <returns>A string with the uri to complete this request.</returns>
        /// <remarks>The object must implement the <see cref="Tenor.Web.IResponseObject">IResponseObject</see> interface.</remarks>
        public static string RegisterObjectForRequest(object @object, int expires, bool forceDownload, string fileName)
        {
            CheckHttpModule();
            HttpContext context = HttpContext.Current;

            if (context == null)
            {
                throw new InvalidContextException();
            }

            if (@object as IResponseObject == null)
            {
                throw (new InvalidCastException("This instance must implement \'" + typeof(IResponseObject).FullName + "\' interface."));
            }

            object messagesLock = new object();

            lock (messagesLock)
            {
                string sControlName = System.Guid.NewGuid().ToString();
                /*Page.Application(HttpModule.IdPrefix & sControlName) = [Object]*/
                CacheData dados = new CacheData();
                dados.Object        = @object;
                dados.Expires       = expires;
                dados.FileName      = fileName;
                dados.ForceDownload = forceDownload;

                context.Cache.Insert(Tenor.Configuration.TenorModuleSection.IdPrefix + sControlName, dados, null, DateTime.UtcNow.AddMinutes(2), System.Web.Caching.Cache.NoSlidingExpiration);

                string uri = Tenor.Configuration.Tenor.Current.TenorModule.HandlerFileName + "?id=" + sControlName;

                if (context.Request.ApplicationPath.EndsWith("/"))
                {
                    uri = context.Request.ApplicationPath + uri;
                }
                else
                {
                    uri = context.Request.ApplicationPath + "/" + uri;
                }
                return(uri);
            }
        }
Esempio n. 16
0
        public void Execute(Message message)
        {
            if (!Utils.BotTools.IsUserOperator(message.From.Id) &&
                !Utils.ChatTools.IsUserAdmin(message.Chat.Id, message.From.Id))
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp        = DateTime.UtcNow,
                    Chat             = message.Chat,
                    ReplyToMessageId = message.MessageId,
                    Text             = CacheData.GetTranslation("en", "error_not_auth_command")
                });
                return;
            }

            string command = message.Text.Split(" ")[0].Remove(0, 1);

            if (command.Contains("@"))
            {
                if (!String.Equals(command.Split("@")[1],
                                   Manager.Username, StringComparison.CurrentCultureIgnoreCase))
                {
                    return;
                }
                command = command.Split("@")[0];
            }
            message.Text = message.Text.Remove(0, command.Length + 2);

            string messageHeader = CacheData.GetTranslation("en", "command_announce_header");
            string parsedMessage = messageHeader + "\n" + message.Text;

            MessageQueueManager.EnqueueMessage(
                new Models.ChatMessage()
            {
                Timestamp      = DateTime.UtcNow,
                Chat           = message.Chat,
                ParseMode      = ParseMode.Html,
                Text           = parsedMessage,
                PostSentAction = Models.ChatMessage.PostSentActions.Pin
            });
        }
 /// <summary>
 /// 设置交易密码 ,修改交易密码响应
 /// </summary>
 /// <param name="value"></param>
 private void expwshopRespon(string value)
 {
     // promptMsg.Change(value, Color.white);
     promptMsg.Change(LanguageService.Instance.GetStringByKey(value, String.Empty), Color.white);
     if (value == "200")
     {
         if (CacheData.Instance().isHasTradePassword)
         {
             promptMsg.Change(LanguageService.Instance.GetStringByKey("修改成功", String.Empty), Color.white);
             Dispatch(AreaCode.UI, UIEvent.CHANGETRADE_ACTIVE, false);
         }
         else
         {
             promptMsg.Change(LanguageService.Instance.GetStringByKey("set", String.Empty), Color.white);
             CacheData.Instance().isHasTradePassword = true;
             Dispatch(AreaCode.UI, UIEvent.SETTRANSACT_ACTIVE, false);
         }
     }
     Dispatch(AreaCode.UI, UIEvent.HINT_ACTIVE, promptMsg);
 }
Esempio n. 18
0
        public void Execute(Message message)
        {
            if (CacheData.Operators
                .SingleOrDefault(x => x.TelegramUserId == message.From.Id &&
                                 x.Level >= Models.Operator.Levels.Basic) == null &&
                !Utils.ChatTools.IsUserAdmin(message.Chat.Id, message.From.Id))
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp        = DateTime.UtcNow,
                    Chat             = message.Chat,
                    ReplyToMessageId = message.MessageId,
                    Text             = CacheData.GetTranslation("en", "error_not_auth_command")
                });
                return;
            }

            SendKeyboard(message, "open");
        }
        public void Create_new_serialized_data_for_test()
        {
            var response = new HttpResponseMessage
            {
                Headers      = { Age = TimeSpan.FromSeconds(5), ETag = new EntityTagHeaderValue("\"unit-test\""), Location = new Uri("http://unittest") },
                StatusCode   = HttpStatusCode.OK,
                ReasonPhrase = "unit-test-reason-phrase",
                Version      = new Version(1, 1)
            };
            var headers        = response.Headers.Where(h => h.Value != null && h.Value.Any()).ToDictionary(h => h.Key, h => h.Value);
            var contentHeaders = new Dictionary <string, IEnumerable <string> >
            {
                { "Content-Type", new[] { "application/json" } }
            };

            var expectedData      = new CacheData(new byte[] { 1, 2, 3, 4, 5 }, response, headers, contentHeaders);
            var newserializedData = expectedData.Serialize();
            var base64Bytes       = Convert.ToBase64String(newserializedData);
            //System.Console.WriteLine(base64Bytes);
        }
Esempio n. 20
0
        public ICollection <CacheDataView> CalculateChartParallel(ParamViewModel paramModel)
        {
            if (paramModel == null)
            {
                throw new ArgumentNullException("param");
            }

            //TODO: add automapper
            Param param = new Param
            {
                CoefficientA = paramModel.CoefficientA,
                CoefficientB = paramModel.CoefficientB,
                CoefficientC = paramModel.CoefficientC,
                Step         = paramModel.Step,
                RangeFrom    = paramModel.RangeFrom,
                RangeTo      = paramModel.RangeTo
            };

            int elementsCount = (int)((param.RangeTo - param.RangeFrom) / param.Step) + 1;

            var elements = new CacheData[elementsCount];

            Parallel.For(0, elementsCount, i => {
                var x       = param.RangeFrom + param.Step * i;
                var y       = CalculatePointY(param.CoefficientA, param.CoefficientB, param.CoefficientC, x);
                elements[i] = new CacheData {
                    PointX = x, PointY = y
                };
            });

            using (var paramRepository = Factory.GetParamRepository())
            {
                param.Points = elements;
                paramRepository.AddOrUpdate(param);
                paramRepository.SaveChanges();
            }

            return(elements.Select(cd => new CacheDataView {
                x = cd.PointX, y = cd.PointY
            })?.ToList());
        }
Esempio n. 21
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ViewState["externosDash"] = 1;

                var idUf = 0;
                int.TryParse(ufQuery.ToString(), out idUf);

                IList <DTOConcluintesEspacoOcupacional> lista;

                // Se todos os parâmetros forem os padrões da página incial será trazido o dado cacheado
                if (Dashboard.defaultStartDate == StartDate &&
                    Dashboard.defaultEndDate == EndDate &&
                    idUf == Dashboard.defaultUf)
                {
                    var cacheData = new CacheData("ucGraficoConcluintesEspacoOcupacionalEmpregados", 24);
                    if (cacheData.HasValidCacheData())
                    {
                        lista = cacheData.GetCacheData();
                    }
                    else
                    {
                        lista =
                            new RelatorioConcluintesEspacoOcupacional().ObterConcluintesEmpregados(StartDate, EndDate,
                                                                                                   idUf);
                        // Queremos que expire na virada de dia e não dure exatamente 24 horas
                        cacheData.SetCacheData(lista, typeof(IList <DTOConcluintesEspacoOcupacional>), DateTime.Today.AddDays(1));
                    }
                }
                else
                {
                    lista = new RelatorioConcluintesEspacoOcupacional().ObterConcluintesEmpregados(StartDate, EndDate,
                                                                                                   idUf);
                }

                Titulos = ObterTitulos(lista);
                Valores = ObterValores(lista);
                Legenda = ObterLegenda(lista);
            }
        }
Esempio n. 22
0
        public void SetData(string key, object data, bool withApply = false)
        {
            if (!data.GetType().IsSerializable)
            {
                throw new ArgumentException("Argument object is not Serializable");
            }

            if (cacheDict.ContainsKey(key))
            {
                cacheDict[key].ChangeData(data);
            }
            else
            {
                cacheDict[key] = new CacheData(data);
            }

            if (withApply)
            {
                this.Apply(key);
            }
        }
Esempio n. 23
0
        public static AuthResult ValidateToken(string token)
        {
            AuthResult result = new AuthResult()
            {
                ErrorMsg = "Token不存在或已过期"
            };
            CacheObject co = DistributedCacheManage.GetLocalCache("tokenList");

            if (co != null)
            {
                CacheData cd = co.cacheValue.Find(x => x.key == token && x.deleteflag == false);
                if (cd != null)
                {
                    result.token    = token;
                    result.User     = JsonConvert.DeserializeObject <UserInfo>(cd.value);
                    result.ErrorMsg = string.Empty;
                }
            }

            return(result);
        }
Esempio n. 24
0
        /// <summary>
        /// Get stock history by symbol name and the date range.
        /// </summary>
        /// <param name="Symbol"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="interval"></param>
        /// <returns></returns>
        public static List <StockSummary> GetStockHistory(string Symbol, DateTime startDate, DateTime endDate, string interval)
        {
            List <StockSummary> lst = new List <StockSummary>();

            try
            {
                lst = GetStockHistoryFromQuandl(Symbol, startDate, endDate, interval);
            }
            catch {
                try {
                    CacheData           cacheData = new CacheData();
                    List <StockDetails> details   = cacheData.GetCachedStockHistory(Symbol, startDate, endDate);
                    foreach (StockDetails s in details)
                    {
                        lst.Add(s);
                    }
                }
                catch { }
            }
            return(lst);
        }
Esempio n. 25
0
 public float CalculateV(IZone origin, IZone destination, Time time)
 {
     if ( ( lastIteration != this.Root.CurrentIteration ) | ( time != CacheTime ) )
     {
         RebuildCache( time );
     }
     var data = this.Cache[origin.ZoneNumber, destination.ZoneNumber];
     if ( data == null )
     {
         int alternatives = 0;
         float averageTotalWaitTime = 0f;
         float averageParkingCost = 0f;
         IZone[] childrenZone = new IZone[this.MaxAccessStations];
         // make sure we clip the number of possible stations
         float[] childrenV = new float[this.MaxAccessStations];
         for ( int i = 0; i < this.MaxAccessStations; i++ )
         {
             childrenV[i] = float.MinValue;
             childrenZone[i] = null;
         }
         var lookAt = this.ClosestStations[origin.ZoneNumber];
         for ( int childIndex = 0; childIndex < lookAt.Length; childIndex++ )
         {
             var index = lookAt[childIndex];
             // once we hit an invalid child index we are done
             if ( index < 0 ) break;
             var child = this.Children[index];
             if ( child.Feasible( origin, destination, time ) )
             {
                 var localV = child.CalculateV( origin, destination, time );
                 if ( localV < MinAccessStationLogsumValue ) continue;
                 if ( !float.IsNaN( localV ) )
                 {
                     int minChild = 0;
                     // find the option with the lowest value
                     for ( int i = 1; i < childrenV.Length; i++ )
                     {
                         if ( childrenV[i] < childrenV[minChild] )
                         {
                             minChild = i;
                         }
                     }
                     // replace the least utility with this new station
                     if ( childrenV[minChild] < localV )
                     {
                         childrenV[minChild] = localV;
                         childrenZone[minChild] = child.InterchangeZone;
                     }
                     alternatives++;
                 }
             }
         }
         if ( alternatives > 0 )
         {
             float logsum = 0f;
             // If there are more than 1 alternatives, then we need to actually compute the logsum
             if ( alternatives > 1 )
             {
                 for ( int i = 0; ( i < alternatives ) & ( i < childrenV.Length ); i++ )
                 {
                     averageTotalWaitTime += this.Second.WaitTime( childrenZone[i], destination, time ).ToMinutes();
                     averageParkingCost += childrenZone[i].ParkingCost;
                     logsum += ( childrenV[i] = (float)Math.Exp( childrenV[i] ) );
                 }
                 logsum = (float)Math.Log( logsum );
             }
             else
             {
                 // If there is only one alternative, log of exp is just the same value, so don't bother with all of the additional math
                 averageTotalWaitTime = this.Second.WaitTime( childrenZone[0], destination, time ).ToMinutes();
                 averageParkingCost = childrenZone[0].ParkingCost;
                 logsum = childrenV[0];
                 childrenV[0] = (float)Math.Exp( childrenV[0] );
             }
             data = new CacheData()
             {
                 Feasible = true,
                 AccessUtil = childrenV,
                 AccessZone = childrenZone,
                 Logsum = logsum,
                 AverageParking = averageParkingCost,
                 AverageWait = averageTotalWaitTime,
                 AccessStations = alternatives
             };
         }
         else
         {
             data = new CacheData()
             {
                 Feasible = false,
                 Logsum = float.NaN
             };
         }
         this.Cache[origin.ZoneNumber, destination.ZoneNumber] = data;
     }
     if ( float.IsNaN( data.Logsum ) )
     {
         return float.NaN;
     }
     return this.CalculateCombinedV( origin, destination, time )
         + ( this.Correlation * data.Logsum )
         + ( ( this.WaitTimeAverageFactor * data.AverageWait
         + this.ParkingCostAverageFactor * data.AverageParking ) / data.AccessStations );
 }
Esempio n. 26
0
        public float CalculateV(IZone origin, IZone destination, Time time)
        {
            if ( ( lastIteration != this.Root.CurrentIteration ) | ( time != CacheTime ) )
            {
                RebuildCache( time );
            }
            var data = this.Cache[origin.ZoneNumber, destination.ZoneNumber];
            if ( data == null )
            {
                int alternatives = 0;
                // make sure we clip the number of possible stations
                float[] childrenV = new float[this.MaxAccessStations];
                float[] childrenDistance = new float[this.MaxAccessStations];
                for ( int i = 0; i < this.MaxAccessStations; i++ )
                {
                    childrenV[i] = float.MinValue;
                    childrenDistance[i] = float.MaxValue;
                }
                var children = Children;
                for ( int childIndex = 0; childIndex < children.Count; childIndex++ )
                {
                    var child = children[childIndex];
                    if ( child.Feasible( origin, destination, time ) )
                    {
                        var localV = child.CalculateV( origin, destination, time );
                        if ( !float.IsNaN( localV ) )
                        {
                            //get the distance for this access station

                            int minChild = 0;
                            // find the option with the lowest value
                            for ( int i = 1; i < childrenV.Length; i++ )
                            {
                                if ( childrenV[i] < childrenV[minChild] )
                                {
                                    minChild = i;
                                }
                            }
                            // replace the least utility with this new station
                            if ( childrenV[minChild] < localV )
                            {
                                childrenV[minChild] = localV;
                            }
                            alternatives++;
                        }
                    }
                }
                if ( alternatives > 0 )
                {
                    double logsum = 0f;
                    for ( int i = 0; ( i < alternatives ) & ( i < childrenV.Length ); i++ )
                    {
                        logsum += Math.Exp( childrenV[i] );
                    }
                    logsum = Math.Log( logsum );
                    if ( logsum >= MinAccessStationLogsumValue )
                    {
                        data = new CacheData()
                        {
                            Feasible = true,
                            Logsum = (float)logsum
                        };
                    }
                    else
                    {
                        data = new CacheData()
                        {
                            Feasible = false,
                            Logsum = float.NaN
                        };
                    }
                }
                else
                {
                    data = new CacheData()
                    {
                        Feasible = false,
                        Logsum = float.NaN
                    };
                }
                this.Cache[origin.ZoneNumber, destination.ZoneNumber] = data;
            }
            if ( float.IsNaN( data.Logsum ) )
            {
                return data.Logsum;
            }
            return ( this.Correlation * data.Logsum ) + this.CalculateCombinedV( origin, destination, time );
        }
Esempio n. 27
0
 public void ClearCache(CacheData data)
 {
     throw new NotImplementedException();
 }
 public void Add(string session_id, string agent_id)
 {
     CacheData data = new CacheData(session_id, agent_id);
     lock (m_authed_sessions)
     {
         if (m_authed_sessions.ContainsKey(session_id))
         {
             m_authed_sessions[session_id] = data;
         }
         else
         {
             m_authed_sessions.Add(session_id, data);
         }
     }
 }
Esempio n. 29
0
File: Stock.cs Progetto: tforsberg/z
		/// <summary>
		/// Get stock summary by symbol name.
		/// </summary>
		/// <param name="symbol">symbol name</param>
		/// <returns></returns>
		public static StockSummary GetStock(string symbol)
		{
			StockSummary stock = null ;
			try
			{
				stock = GetStockFromYahoo(symbol);
			}
			catch
			{
				try
				{
					CacheData cacheData = new CacheData();
					stock = cacheData.GetCachedStock(symbol);
				}
				catch { }
			}
			return stock;
		}
Esempio n. 30
0
File: Stock.cs Progetto: tforsberg/z
		/// <summary>
		/// Get stock list by a list of symbol 
		/// </summary>
		/// <param name="Symbols">symbol list (separator ',')</param>
		/// <returns></returns>
		public static List<StockSummary> GetStocks(string Symbols) {
			List<StockSummary> stocks = null;
			try {
				stocks = GetStocksFromYahoo(Symbols);
			}
			catch {
				CacheData cacheData = new CacheData();
				stocks = cacheData.GetCachedStocks();
			}
			return stocks;
		}
Esempio n. 31
0
File: Stock.cs Progetto: tforsberg/z
		/// <summary>
		/// Get stock history by symbol name and the date range. 
		/// </summary>
		/// <param name="Symbol"></param>
		/// <param name="startDate"></param>
		/// <param name="endDate"></param>
		/// <param name="interval"></param>
		/// <returns></returns>
		public static List<StockSummary> GetStockHistory(string Symbol, DateTime startDate, DateTime endDate, string interval) {
			List<StockSummary> lst = new List<StockSummary>();
			try
			{
				lst = GetStockHistoryFromYahoo(Symbol, startDate, endDate, interval);
			}
			catch {
				try {
					CacheData cacheData = new CacheData();
					List<StockDetails> details = cacheData.GetCachedStockHistory(Symbol, startDate, endDate);
					foreach (StockDetails s in details) 
					{
						lst.Add(s);
					}
				}
				catch { }
			}
			return lst;
		}
Esempio n. 32
0
        /// <summary>
        /// Attempts to save the specified chunk for later.  If the chunk was fully
        /// loaded, it saves it and returns true.  If the chunk was NOT fully loaded,
        /// it just returns false (does not attempt to "save it later.")
        /// </summary>
        /// <param name="chunkX"></param>
        /// <param name="chunkZ"></param>
        /// <returns></returns>
        public bool SaveChunk(int chunkX, int chunkZ)
        {
            lock (CacheLock)
            {
                if (HasSavedChunk(chunkX, chunkZ))
                {
                    return true;
                }
                else if (IsReady(chunkX, chunkZ))
                {
                    CacheData dat = this[chunkX, chunkZ];

                    CacheData blankData = new CacheData();
                    blankData.CleanAndValidate();

                    this[chunkX, chunkZ] = blankData;

                    savedChunkData[new ChunkCoordinate(chunkX, chunkZ)] = dat;

                    if (this[chunkX, chunkZ] != dat)
                        throw new ArgumentException();

                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
Esempio n. 33
0
 /// <summary>
 /// Clears the cache.
 /// </summary>
 /// <param name="data">The part of the cache to clear.</param>
 public void ClearCache(CacheData data)
 {
     switch(data) {
         case CacheData.Pages:
             Content.InvalidateAllPages();
             break;
         case CacheData.MetaFiles:
             Content.ClearPseudoCache();
             break;
         default:
             throw new ArgumentException("Invalid CacheData");
     }
 }
Esempio n. 34
0
        /// <summary>
        /// Adds or updates data for a FieldPath list in the cache.  If it already exists, it will query the data again.
        /// </summary>
        /// <param name="path"></param>
        public virtual void UpdateCache(dbqf.Criterion.IFieldPath path)
        {
            // if item exists in cache, clear and update
            // if item does not exist in cache, add it
            CacheData result;
            if (_listCache.ContainsKey(path))
                result = _listCache[path];
            else
            {
                result = new CacheData() { Data = new BindingList<object>() };
                _listCache.Add(path, result);

                // return if the field has a pre-defined list of items
                if (path.Last.List.Count > 0)
                {
                    result.Data.Add(string.Empty);
                    foreach (var x in path.Last.List)
                        result.Data.Add(x);
                    return;
                }
            }

            var gen = ResultFactory.CreateSqlListGenerator(Configuration).Path(path);
            if (Regex.IsMatch(path.Last.List.Source, @"^select.*[`'\[\s]id", RegexOptions.IgnoreCase))
                gen.IdColumn("ID")
                    .ValueColumn("Value");

            // ensure we'll be able to generate a command
            try { gen.Validate(); }
            catch { return; }

            // kill any existing worker
            if (result.CurrentWorker != null)
                result.CurrentWorker.CancelAsync();

            var bgw = new BackgroundWorker();
            bgw.WorkerSupportsCancellation = true;
            bgw.DoWork += (s2, e2) =>
            {
                result.CurrentWorker = bgw;
                try
                {
                    e2.Result = ResultFactory.CreateSqlResults(Connection).GetList(gen);
                }
                catch (Exception te)
                {
                    e2.Result = te;
                }
            };
            bgw.RunWorkerCompleted += (s2, e2) =>
            {
                if (e2.Cancelled)
                    return;

                if (e2.Result is Exception)
                {
                    // what do we do?
                }
                else
                {
                    var list = result.Data;
                    list.RaiseListChangedEvents = false;
                    list.Clear();
                    list.Add(string.Empty);
                    foreach (var i in (IList<object>)e2.Result)
                        list.Add(i);
                    list.RaiseListChangedEvents = true;
                    list.ResetBindings();
                }

                if (bgw == result.CurrentWorker)
                    result.CurrentWorker = null;
            };
            bgw.RunWorkerAsync();
        }
Esempio n. 35
0
        private void LoadStartingData()
        {
            cache = new CacheData[Width, Height];

            for (int x = 0; x < Width; x++)
            {
                for (int z = 0; z < Height; z++)
                {
                    cache[x, z] = new CacheData();
                }
            }
        }
Esempio n. 36
0
        public float CalculateV(IZone origin, IZone destination, Time time)
        {
            if ( ( lastIteration != this.Root.CurrentIteration ) | ( time != CacheTime ) )
            {
                RebuildCache( time );
            }
            var data = this.Cache[origin.ZoneNumber, destination.ZoneNumber];
            if ( data == null )
            {
                var zones = this.Root.ZoneSystem.ZoneArray;
                var toCheck = this.ClosestAccessStationsToOrigins[zones.GetFlatIndex( origin.ZoneNumber )];
                int alternatives = 0;
                float averageTotalWaitTime = 0f;
                float averageTotalWalkTime = 0f;
                float averageTravelTime = 0f;
                float averageLineHull = 0f;
                // make sure we clip the number of possible stations
                float[] childrenEToV = new float[4];
                IZone[] childrenAccessZone = new IZone[4];
                IZone[] childrenEgressZone = new IZone[4];
                int unions = 0;

                for ( int computeChild = 0; computeChild < 4; computeChild++ )
                {
                    childrenEToV[computeChild] = float.MinValue;
                    var child = this.Children[toCheck[computeChild]];
                    if ( child.Feasible( origin, destination, time ) )
                    {
                        var localV = child.CalculateV( origin, destination, time );
                        if ( !float.IsNaN( localV ) )
                        {
                            if ( localV < MinAccessStationLogsumValue ) continue;
                            var egressZone = child.EgressChoiceCache[destination.ZoneNumber].EgressZone;
                            if ( egressZone.ZoneNumber == this.UnionStationZoneNumber )
                            {
                                unions++;
                            }
                            else if ( origin.RegionNumber == 1 )
                            {
                                // if we are in toronto
                                var flatAcessZone = zones.GetFlatIndex( child.InterchangeZone.ZoneNumber );
                                var flatEgressZone = zones.GetFlatIndex( egressZone.ZoneNumber );
                                // if the to stations are next to eachother just continue on
                                if ( Math.Abs( flatAcessZone - flatEgressZone ) <= 1 )
                                {
                                    continue;
                                }
                            }
                            // replace the least utility with this new station
                            if ( childrenEToV[alternatives] < localV )
                            {
                                childrenEToV[alternatives] = localV;
                                childrenAccessZone[alternatives] = child.InterchangeZone;
                                childrenEgressZone[alternatives] = egressZone;
                                alternatives++;
                                // now add up the averages
                                var lineHull = this.Second.InVehicleTravelTime( child.InterchangeZone, egressZone, time ).ToMinutes();
                                averageLineHull += lineHull;
                                // 5 minutes added for the initial GO wait time
                                averageTotalWaitTime += this.Third.WaitTime( egressZone, destination, time ).ToMinutes() + 5f;
                                averageTotalWalkTime += this.Third.WalkTime( egressZone, destination, time ).ToMinutes();
                                // average travel time does not include walk or wait times
                                averageTravelTime += this.Third.InVehicleTravelTime( egressZone, destination, time ).ToMinutes() + lineHull;
                            }
                        }
                    }
                }
                if ( alternatives > 0 )
                {
                    double logsum = 0f;
                    // if there is only 1 alternative there is no reason to do the log, just solve it here
                    if ( alternatives == 1 )
                    {
                        // do the sum here to avoid doing a log
                        logsum = childrenEToV[0];
                        // we still need this exponentiated for doing our station split
                        childrenEToV[0] = (float)Math.Exp( childrenEToV[0] );
                    }
                    else
                    {
                        for ( int i = 0; i < alternatives; i++ )
                        {
                            var temp = Math.Exp( childrenEToV[i] );
                            childrenEToV[i] = (float)temp;
                            logsum += temp;
                        }
                        logsum = Math.Log( logsum );
                    }
                    data = new CacheData()
                    {
                        Feasible = true,
                        AccessUtil = childrenEToV,
                        AccessZone = childrenAccessZone,
                        EgressZone = childrenEgressZone,
                        Logsum = (float)logsum,
                        AccessStations = alternatives,
                        Unions = unions,
                        AverageLineHull = averageLineHull,
                        AverageTravelTime = averageTravelTime,
                        AverageWaitTime = averageTotalWaitTime,
                        AverageWalkTime = averageTotalWalkTime
                    };
                }
                else
                {
                    data = new CacheData()
                    {
                        Feasible = false,
                        Logsum = float.NaN
                    };
                }

                this.Cache[origin.ZoneNumber, destination.ZoneNumber] = data;
            }
            // if we have nothing, return nothing
            if ( float.IsNaN( data.Logsum ) )
            {
                return float.NaN;
            }
            // otherwise return our utility
            var v = this.CalculateCombinedV( origin, destination, time ) + ( this.Correlation * data.Logsum )
                            + ( ( ( this.Union * data.Unions )
                            + ( data.AverageWaitTime * this.WaitTimeAverageFactor )
                            + ( data.AverageLineHull * this.LineHullAverageFactor )
                            + ( data.AverageWalkTime * this.WalkTimeAverageFactor )
                            + ( data.AverageTravelTime * this.TravelTimeAverageFactor ) ) / data.AccessStations );
            return v;
        }