Exemplo n.º 1
0
        private void PrintStats()
        {
            Thread letterThread = new Thread(getLetterFrequency);
            Thread prefixThread = new Thread(getPrefixFrequency);

            letterThread.Start();
            prefixThread.Start();

            letterThread.Join();
            prefixThread.Join();

            Console.WriteLine("Letter Frequency: ");
            foreach (var pair in letterFrequency)
            {
                Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
            }

            Console.WriteLine("Total Capital Letters: {0}", totalCapLetters);

            var keyOfMaxValue = wordFrequency.Aggregate((x, y) =>
                                                        x.Value > y.Value ? x : y).Key;

            Console.WriteLine("Most Common Word: {0}", keyOfMaxValue);
            Console.WriteLine("{0} Frequency: {1}", keyOfMaxValue,
                              wordFrequency[keyOfMaxValue]);

            keyOfMaxValue = twoCharPrefixFrequency.Aggregate((x, y) =>
                                                             x.Value > y.Value ? x : y).Key;
            Console.WriteLine("Most Common Two Letter Prefix: {0}", keyOfMaxValue);
            Console.WriteLine("{0} Frequency: {1}",
                              keyOfMaxValue,
                              twoCharPrefixFrequency[keyOfMaxValue]);
        }
Exemplo n.º 2
0
        /**
         * 参数数组转换为url格式
         * @param map 参数名与参数值的映射表
         * @return URL字符串
         */
        private string ToUrlParams(SortedDictionary <string, object> map)
        {
            string buff = map.Aggregate("", (current, pair) => current + (pair.Key + "=" + pair.Value + "&"));

            buff = buff.Trim('&');
            return(buff);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Use OAuth1.0a auth to do more intensive reads
        /// </summary>
        /// <param name="url">URL to call</param>
        /// <param name="parameters">Params to send</param>
        /// <returns></returns>
        public new async Task <HttpResponseMessage> GetAsync(string url, SortedDictionary <string, string> parameters)
        {
            if (TwitterCredentials == TwitterCredentials.Null || TwitterCredentials.Valid == false)
            {
                throw new ArgumentException("TwitterCredentials must be specified and validated");
            }

            var querystring = parameters.Aggregate("", (current, entry) => current + (entry.Key + "=" + entry.Value + "&"));

            var oauth1aAuthheader = BuildAuthenticatedResult(url, parameters, "GET");
            var fullUrl           = url;

            var handler = new HttpClientHandler();

            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }
            var client = new HttpClient(handler);

            client.DefaultRequestHeaders.Add("Authorization", oauth1aAuthheader.Header);
            client.DefaultRequestHeaders.Add("User-Agent", TwitterApi.UserAgent());

            if (!string.IsNullOrWhiteSpace(querystring))
            {
                fullUrl += "?" + querystring.Substring(0, querystring.Length - 1);
            }

            var download       = client.GetAsync(fullUrl).ToObservable().Timeout(TimeSpan.FromSeconds(waitTimeoutSeconds));
            var clientdownload = await download;

            return(clientdownload);
        }
Exemplo n.º 4
0
        public AnswerModel <int> GetMostFrequentChar(string text)
        {
            string[] tokens = text.Split(' ', '.', ',', '-', '?', '!', '<', '>', '&', '[', ']', '(', ')');
            IDictionary <string, int> words = new SortedDictionary <string, int>(new CaseInsensitiveComparer());

            foreach (string word in tokens)
            {
                if (string.IsNullOrEmpty(word.Trim()))
                {
                    continue;
                }
                int count;
                if (!words.TryGetValue(word, out count))
                {
                    count = 0;
                }
                words[word] = count + 1;
            }

            var keyOfMaxValue = words.Aggregate((x, y) => x.Value > y.Value ? x : y).Key;

            AnswerModel <int> answer = new AnswerModel <int>();

            //answer.Value = words.Values.Max();
            answer.Property = keyOfMaxValue;
            answer.Value    = words[keyOfMaxValue];

            return(answer);
        }
Exemplo n.º 5
0
        private void Draw()
        {
            int signalsCount = signals.Aggregate(0, (accumulator, element) =>
                                                 accumulator + element.Value?.Count ?? 0
                                                 );

            for (int i = 0; i < signalsCount; i++)
            {
                if (views.Count <= i)
                {
                    views.Add(new View(container, i));
                }

                var view = views[i];

                int             searchPos = 0;
                SatelliteSignal signal    = null;
                SatelliteType?  type      = null;
                foreach (var signalType in signals.Keys)
                {
                    var list     = signals[signalType];
                    int topLimit = searchPos + (list?.Count ?? 0);
                    if (i < topLimit && list != null)
                    {
                        signal = list[i - searchPos];
                        type   = signalType;
                        break;
                    }

                    searchPos = topLimit;
                }

                if (signal != null && type != null)
                {
                    string satelliteTypeName;
                    switch (type)
                    {
                    case SatelliteType.GPS:
                    case SatelliteType.Glonass:
                    case SatelliteType.Beidou:
                    case SatelliteType.Galileo:
                        satelliteTypeName = type.ToString();
                        break;

                    default:
                        satelliteTypeName = "Satellite";
                        break;
                    }

                    view.Text     = $"{satelliteTypeName}{signal.prn}";
                    view.Value    = signal.value;
                    view.Visibile = true;
                }
            }

            for (int i = signalsCount; i < views.Count; i++)
            {
                views[i].Visibile = false;
            }
        }
Exemplo n.º 6
0
        private static void Results(SortedDictionary <string, int> keyItems, SortedDictionary <string, int> junkItems)
        {
            string legendary = keyItems.Aggregate((comparison, current) => comparison.Value > current.Value ? comparison : current).Key;

            switch (legendary)
            {
            case "shards":
                Console.WriteLine("Shadowmourne obtained!");
                keyItems[legendary] -= 250;
                PrintRest(keyItems, junkItems);
                break;

            case "fragments":
                Console.WriteLine("Valanyr obtained!");
                keyItems[legendary] -= 250;
                PrintRest(keyItems, junkItems);
                break;

            case "motes":
                Console.WriteLine("Dragonwrath obtained!");
                keyItems[legendary] -= 250;
                PrintRest(keyItems, junkItems);
                break;
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Use OAuth1.0a auth to do more intensive POST
        /// </summary>
        /// <param name="url">URL to call</param>
        /// <param name="parameters">Params to send</param>
        /// <returns></returns>
        public async Task <HttpResponseMessage> PostAsync(string url, SortedDictionary <string, string> parameters)
        {
            if (TwitterCredentials == TwitterCredentials.Null || TwitterCredentials.Valid == false)
            {
                throw new ArgumentException("TwitterCredentials must be specified and validated");
            }

            var oauth1aAuthheader = BuildAuthenticatedResult(url, parameters, "POST");
            var handler           = new HttpClientHandler();

            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }
            var client = new HttpClient(handler);

            client.DefaultRequestHeaders.Add("Authorization", oauth1aAuthheader.Header);
            client.DefaultRequestHeaders.Add("User-Agent", TwitterApi.UserAgent());

            var content = parameters.Aggregate(string.Empty, (current, e) => current + string.Format("{0}={1}&", e.Key, Uri.EscapeDataString(e.Value)));
            var data    = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");

            var download       = client.PostAsync(url, data).ToObservable().Timeout(TimeSpan.FromSeconds(waitTimeoutSeconds));
            var clientdownload = await download;

            return(clientdownload);
        }
        /// <summary>
        /// Use OAuth2 Bearer To do read-only GET query
        /// </summary>
        /// <param name="url">URL to call</param>
        /// <param name="parameters">Params to send</param>
        /// <returns></returns>
        public async Task<HttpResponseMessage> GetAsync(string url, SortedDictionary<string, string> parameters)
        {
            // ensure we have a bearerToken before progressing
            if (clientID != null && clientSecret != null && bearerToken == null)
            {
                await this.StartApplicationOnlyAuth();
            }
            if (bearerToken == null) return null;

            var querystring = parameters.Aggregate("", (current, entry) => current + (entry.Key + "=" + entry.Value + "&"));

            var oauth2 = String.Format("Bearer {0}", bearerToken);
            var fullUrl = url;

            var handler = new HttpClientHandler();
            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }
            var client = new HttpClient(handler);
            client.DefaultRequestHeaders.Add("Authorization", oauth2);
            client.DefaultRequestHeaders.Add("User-Agent", TwitterApi.UserAgent());

            if (!string.IsNullOrWhiteSpace(querystring))
                fullUrl += "?" + querystring.TrimLastChar();

            var download = client.GetAsync(fullUrl).ToObservable().Timeout(TimeSpan.FromSeconds(waitTimeoutSeconds));
            return await download;
       }
        /// <summary>
        /// Use OAuth2 Bearer To do read-only GET query
        /// </summary>
        /// <param name="url">URL to call</param>
        /// <param name="parameters">Params to send</param>
        /// <returns></returns>
        public async Task<HttpResponseMessage> GetAsync(string url, SortedDictionary<string, string> parameters)
        {
            // ensure we have a bearerToken before progressing
            if (clientID != null && clientSecret != null && bearerToken == null)
            {
                await this.StartApplicationOnlyAuth();
            }
            if (bearerToken == null) return null;

            var querystring = parameters.Aggregate("", (current, entry) => current + (entry.Key + "=" + entry.Value + "&"));

            var oauth2 = String.Format("Bearer {0}", bearerToken);
            var fullUrl = url;

            var handler = new HttpClientHandler();
            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }
            var client = new HttpClient(handler);
            client.DefaultRequestHeaders.Add("Authorization", oauth2);
            client.DefaultRequestHeaders.Add("User-Agent", TwitterApi.UserAgent());

            if (!string.IsNullOrWhiteSpace(querystring))
                fullUrl += "?" + querystring.TrimLastChar();

            var download = client.GetAsync(fullUrl).ToObservable().Timeout(TimeSpan.FromSeconds(waitTimeoutSeconds));
            return await download;
       }
Exemplo n.º 10
0
        /// <summary>
        /// Get presign canonical request.
        /// </summary>
        /// <param name="client">Instantiated client object</param>
        /// <param name="request">Instantiated request object</param>
        /// <param name="requestQuery">Additional request query params</param>
        /// <param name="headersToSign"></param>
        /// <returns>Presigned canonical request</returns>
        private string GetPresignCanonicalRequest(IRestClient client, IRestRequest request, string requestQuery, SortedDictionary <string, string> headersToSign)
        {
            LinkedList <string> canonicalStringList = new LinkedList <string>();

            // METHOD
            canonicalStringList.AddLast(request.Method.ToString());

            string path = request.Resource;

            if (!path.StartsWith("/"))
            {
                path = "/" + path;
            }
            canonicalStringList.AddLast(path);
            String query = headersToSign.Aggregate(requestQuery, (pv, cv) => $"{pv}&{utils.UrlEncode(cv.Key)}={utils.UrlEncode(s3utils.TrimAll(cv.Value))}");

            canonicalStringList.AddLast(query);
            if (client.BaseUrl.Port > 0 && (client.BaseUrl.Port != 80 && client.BaseUrl.Port != 443))
            {
                canonicalStringList.AddLast("host:" + client.BaseUrl.Host + ":" + client.BaseUrl.Port);
            }
            else
            {
                canonicalStringList.AddLast("host:" + client.BaseUrl.Host);
            }

            canonicalStringList.AddLast("");
            canonicalStringList.AddLast("host");
            canonicalStringList.AddLast("UNSIGNED-PAYLOAD");

            return(string.Join("\n", canonicalStringList));
        }
        private List <KeyValuePair <int, char> > NormalizeGrayscales(SortedDictionary <int, char> grayscales)
        {
            var max = grayscales.Aggregate(int.MinValue, (memo, pair) => memo < pair.Key ? pair.Key : memo);
            var min = grayscales.Aggregate(int.MaxValue, (memo, pair) => memo > pair.Key ? pair.Key : memo);

            var range = max - min;

            Func <KeyValuePair <int, char>, KeyValuePair <int, char> > normalizePair = (pair) =>
            {
                var newKey = 1 + (pair.Key - min) * 255 / range;
                return(new KeyValuePair <int, char>(newKey, pair.Value));
            };

            var normalizedGrayscales = grayscales.Select(normalizePair).ToList();

            return(normalizedGrayscales);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Получить id состояния, которое нужно включить в AccessDescriptor
        /// </summary>
        /// <returns>id состояния. -1 - код не совпал ни с одним назначением</returns>
        private int GetActivatedStateId()
        {
            // Собираем код
            var code           = _usedHardware.Aggregate(string.Empty, (current, h) => current + (h.Value ? "1" : "0"));
            var activatedState = Connections.FirstOrDefault(accessDescriptorStateAssignment => accessDescriptorStateAssignment.GetAssignedHardware() == code);

            return(activatedState == null ? -1 : activatedState.GetConnector().Id);
        }
Exemplo n.º 13
0
        private XDocument LoadOverrideFile()
        {
            try
            {
                if (_hotsBuild.HasValue)
                {
                    if (_overrideFileNamesByBuild.Count > 0)
                    {
                        // exact build number override file
                        if (_overrideFileNamesByBuild.TryGetValue(_hotsBuild.Value, out string?filePath))
                        {
                            LoadedOverrideFileName = filePath;
                        }
                        else if (_hotsBuild.Value <= _overrideFileNamesByBuild.Keys.Min()) // load lowest
                        {
                            LoadedOverrideFileName = _overrideFileNamesByBuild[_overrideFileNamesByBuild.Keys.Min()];
                        }
                        else if (_hotsBuild.Value >= _overrideFileNamesByBuild.Keys.Max()) // load the default
                        {
                            LoadedOverrideFileName = Path.Combine(DataOverridesDirectoryPath, OverrideFileName);
                        }
                        else // load next lowest
                        {
                            LoadedOverrideFileName = _overrideFileNamesByBuild.Aggregate((x, y) => Math.Abs(x.Key - _hotsBuild.Value) <= Math.Abs(y.Key - _hotsBuild.Value) ? x : y).Value;
                        }

                        return(XDocument.Load(LoadedOverrideFileName));
                    }
                }

                // default load
                if (File.Exists(Path.Combine(DataOverridesDirectoryPath, OverrideFileName)))
                {
                    LoadedOverrideFileName = Path.Combine(DataOverridesDirectoryPath, OverrideFileName);

                    return(XDocument.Load(Path.Combine(DataOverridesDirectoryPath, OverrideFileName)));
                }

                throw new FileNotFoundException();
            }
            catch (FileNotFoundException)
            {
                if (_hotsBuild.HasValue)
                {
                    throw new FileNotFoundException($"File not found: {OverrideFileName} or {Path.GetFileNameWithoutExtension(OverrideFileName)}_{_hotsBuild}.xml at {DataOverridesDirectoryPath}");
                }
                else
                {
                    throw new FileNotFoundException($"File not found: {OverrideFileName} at {DataOverridesDirectoryPath}");
                }
            }
        }
        /// <summary>
        /// Use OAuth2 Bearer Token for POST
        /// </summary>
        /// <param name="url">URL to call</param>
        /// <param name="parameters">Params to send</param>
        /// <param name="forInitialAuth">Is for an initial auth to get bearer token</param>
        /// <returns></returns>
        public async Task <HttpResponseMessage> PostAsync(string url, SortedDictionary <string, string> parameters, bool forInitialAuth = false)
        {
            if (forInitialAuth)
            {
                if (clientID == null && clientSecret == null)
                {
                    return(null);
                }
            }
            else
            {
                if (clientID != null && clientSecret != null && bearerToken == null)
                {
                    await this.StartApplicationOnlyAuth();
                }
                if (bearerToken == null)
                {
                    return(null);
                }
            }

            var querystring = parameters.Aggregate("", (current, entry) => current + (entry.Key + "=" + entry.Value + "&"));

            if (!string.IsNullOrWhiteSpace(querystring))
            {
                querystring = querystring.TrimLastChar();
            }

            var oauth2Bearertoken = forInitialAuth
                ? String.Format("Basic {0}",
                                String.Format("{0}:{1}", clientID.UrlEncode(), clientSecret.UrlEncode()).ToBase64String())
                : String.Format("Bearer {0}", bearerToken);

            var handler = new HttpClientHandler();
            var client  = new HttpClient(handler);

            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }
            client.DefaultRequestHeaders.Add("Authorization", oauth2Bearertoken);
            client.DefaultRequestHeaders.Add("User-Agent", TwitterApi.UserAgent());

            var data = new StringContent(querystring, Encoding.UTF8, "application/x-www-form-urlencoded");

            var download = client.PostAsync(url, data).ToObservable().Timeout(TimeSpan.FromSeconds(waitTimeoutSeconds));

            return(await download);
        }
Exemplo n.º 15
0
        int CalcualteUpperLimit()
        {
            int highestCumAppearance = _inputData.Aggregate((x, y) => x.Value.cumAppearance > y.Value.cumAppearance ? x : y).Value.cumAppearance;
            int M  = 0;
            int B  = 0;
            int Q1 = 0;

            while (highestCumAppearance > Q1)
            {
                M  = Convert.ToInt32(Math.Pow(2, B) - 1);
                Q1 = Convert.ToInt32(M / 4) + 1;
                B++;
            }
            return(M);
        }
Exemplo n.º 16
0
        public Task<HttpResponseMessage> GetAsync(string relativeUrl, SortedDictionary<string, string> parameters)
        {
            var url = _getFullUrl(relativeUrl);
            var querystring = parameters.Aggregate("", (current, entry) => current + (entry.Key + "=" + entry.Value + "&"));
            var oauth = BuildAuthenticatedResult(url, parameters, "GET");
            var fullUrl = url;

            var client = new HttpClient { MaxResponseContentBufferSize = 10 * 1024 * 1024 };
            client.DefaultRequestHeaders.Add("Authorization", oauth.Header);

            if (!string.IsNullOrWhiteSpace(querystring))
                fullUrl += "?" + querystring.Substring(0, querystring.Length - 1);

            return client.GetAsync(fullUrl);
        }
Exemplo n.º 17
0
        public Task<HttpResponseMessage> PostAsync(string relativeUrl, SortedDictionary<string, string> parameters)
        {
            var url = _getFullUrl(relativeUrl);
            var oauth = BuildAuthenticatedResult(url, parameters, "POST");
            var client = new HttpClient();

            client.DefaultRequestHeaders.Add("Authorization", oauth.Header);

            var content = parameters.Aggregate(string.Empty, (current, e) => current + string.Format("{0}={1}&", e.Key, e.Value));
            content.Substring(0, content.Length - 1);

            var data = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");

            return client.PostAsync(url, data);
        }
Exemplo n.º 18
0
        private void GenerateSlopeOfPriceStackAndCummalativeVolumeProfile(Dictionary <string, PriceStack> obj)
        {
            double[] slopeStats = new double[3];
            SortedDictionary <double, double> cummVolumeStats = new SortedDictionary <double, double>();

            List <double> prices = new List <double>();

            foreach (KeyValuePair <string, PriceStack> data in obj)
            {
                //Print(String.Format("{0}  {1}  {2}", data.Value.Time, data.Value.Price, data.Value.Volume));
                prices.Add(data.Value.Price);
            }

            //prices.ToArray();
            int[] xUniformInts = Enumerable.Range(0, prices.Count()).ToArray();

            //Print("Calculate the Slope");
            //GET LIST OF ALL STATISTICAL DAtA FOR THIS CHART.


            cummVolumeStats = GetCummalitivePriceVolumeProfile(obj);


            var maxKey = cummVolumeStats.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
            var maxVolumeInDictionary = cummVolumeStats[maxKey];

            slopeStats = GetSlope(xUniformInts, prices.ToArray());

            Print(string.Format("Slope: {0}  Y-Intercept: {1}  R-Coeffecient: {2}", Math.Round(slopeStats[0], 4), Math.Round(slopeStats[1], 2), Math.Round(slopeStats[2], 4)));

            //Print(cummVolumeStats.Keys.Max());
            foreach (var data in cummVolumeStats)
            {
                string asteriskGuage = "";
                string outputSpacing = "";

                for (int i = 0; i < Math.Round(data.Value / maxVolumeInDictionary * 100, 0); i++)
                {
                    asteriskGuage = asteriskGuage + "|";
                }
                for (int i = 0; i < 110 - Math.Round(data.Value / maxVolumeInDictionary * 100, 0); i++)
                {
                    outputSpacing = outputSpacing + " ";
                }

                Print(string.Format("{0}  {3}  {4} ({2}) {1}", data.Key.ToString("0.00"), data.Value, Math.Round(data.Value / maxVolumeInDictionary * 100, 0), asteriskGuage, outputSpacing));
            }
        }
Exemplo n.º 19
0
        public Task <HttpResponseMessage> PostAsync(string relativeUrl, SortedDictionary <string, string> parameters)
        {
            var url    = _getFullUrl(relativeUrl);
            var oauth  = BuildAuthenticatedResult(url, parameters, "POST");
            var client = new HttpClient();

            client.DefaultRequestHeaders.Add("Authorization", oauth.Header);

            var content = parameters.Aggregate(string.Empty, (current, e) => current + string.Format("{0}={1}&", e.Key, e.Value));

            content.Substring(0, content.Length - 1);

            var data = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");

            return(client.PostAsync(url, data));
        }
Exemplo n.º 20
0
        public HttpRequestMessage CreatePost(string url, SortedDictionary <string, string> parameters)
        {
            var oauth   = BuildAuthenticatedResult(url, parameters, "POST");
            var fullUrl = url;

            var request = new HttpRequestMessage(HttpMethod.Post, fullUrl);

            request.Headers.Add("Authorization", oauth.Header);
            request.Headers.Add("User-Agent", TwitterApi.UserAgent());

            var content = parameters.Aggregate(string.Empty, (current, e) => current + string.Format("{0}={1}&", e.Key, Uri.EscapeDataString(e.Value)));

            request.Content = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");

            return(request);
        }
Exemplo n.º 21
0
        public HttpRequestMessage CreateGet(string relativeUrl, SortedDictionary<string, string> parameters)
        {
            var url = "https://userstream.twitter.com/2/" + relativeUrl;

            var querystring = parameters.Aggregate("", (current, entry) => current + (entry.Key + "=" + entry.Value + "&"));
            var oauth = BuildAuthenticatedResult(url, parameters, "GET");
            var fullUrl = url;

            if (!string.IsNullOrWhiteSpace(querystring))
                fullUrl += "?" + querystring.Substring(0, querystring.Length - 1);

            var request = new HttpRequestMessage(HttpMethod.Get, fullUrl);
            request.Headers.Add("Authorization", oauth.Header);
            request.Headers.Add("User-Agent", "dodo");
            return request;
        }
Exemplo n.º 22
0
        public HttpRequestMessage CreateGet(string url, SortedDictionary <string, string> parameters)
        {
            var querystring = parameters.Aggregate("", (current, entry) => current + (entry.Key + "=" + entry.Value + "&"));
            var oauth       = BuildAuthenticatedResult(url, parameters, "GET");
            var fullUrl     = url;

            if (!string.IsNullOrWhiteSpace(querystring))
            {
                fullUrl += "?" + querystring.Substring(0, querystring.Length - 1);
            }

            var request = new HttpRequestMessage(HttpMethod.Get, fullUrl);

            request.Headers.Add("Authorization", oauth.Header);
            request.Headers.Add("User-Agent", TwitterApi.UserAgent());
            return(request);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Generates the the string of parameters used for making the signature.
        /// </summary>
        /// <param name="queryString">Values representing the query string.</param>
        /// <param name="body">Values representing the POST body.</param>
        public virtual string GenerateParameterString(NameValueCollection queryString, NameValueCollection body)
        {
            // The parameters must be alphabetically sorted
            SortedDictionary <string, string> sorted = new SortedDictionary <string, string>();

            // Add parameters from the query string
            if (queryString != null)
            {
                foreach (string key in queryString)
                {
                    //if (key.StartsWith("oauth_")) continue;
                    sorted.Add(Uri.EscapeDataString(key), Uri.EscapeDataString(queryString[key]));
                }
            }

            // Add parameters from the POST data
            if (body != null)
            {
                foreach (string key in body)
                {
                    //if (key.StartsWith("oauth_")) continue;
                    sorted.Add(Uri.EscapeDataString(key), Uri.EscapeDataString(body[key]));
                }
            }

            // Add OAuth values
            if (!String.IsNullOrEmpty(Callback))
            {
                sorted.Add("oauth_callback", Uri.EscapeDataString(Callback));
            }
            sorted.Add("oauth_consumer_key", Uri.EscapeDataString(ConsumerKey));
            sorted.Add("oauth_nonce", Uri.EscapeDataString(Nonce));
            sorted.Add("oauth_signature_method", "HMAC-SHA1");
            sorted.Add("oauth_timestamp", Uri.EscapeDataString(Timestamp));
            if (!String.IsNullOrEmpty(Token))
            {
                sorted.Add("oauth_token", Uri.EscapeDataString(Token));
            }
            sorted.Add("oauth_version", Uri.EscapeDataString(Version));

            // Merge all parameters
            return(sorted.Aggregate("", (current, pair) => current + ("&" + pair.Key + "=" + pair.Value)).Substring(1));
        }
Exemplo n.º 24
0
        public Task <HttpResponseMessage> GetAsync(string relativeUrl, SortedDictionary <string, string> parameters)
        {
            var url         = _getFullUrl(relativeUrl);
            var querystring = parameters.Aggregate("", (current, entry) => current + (entry.Key + "=" + entry.Value + "&"));
            var oauth       = BuildAuthenticatedResult(url, parameters, "GET");
            var fullUrl     = url;

            var client = new HttpClient {
                MaxResponseContentBufferSize = 10 * 1024 * 1024
            };

            client.DefaultRequestHeaders.Add("Authorization", oauth.Header);

            if (!string.IsNullOrWhiteSpace(querystring))
            {
                fullUrl += "?" + querystring.Substring(0, querystring.Length - 1);
            }

            return(client.GetAsync(fullUrl));
        }
Exemplo n.º 25
0
        /// <summary>
        /// Use OAuth1.0a auth to do more intensive reads
        /// </summary>
        /// <param name="url">URL to call</param>
        /// <param name="parameters">Params to send</param>
        /// <returns></returns>
        public new async Task<HttpResponseMessage> GetAsync(string url, SortedDictionary<string, string> parameters) 
        {
            if (TwitterCredentials == TwitterCredentials.Null || TwitterCredentials.Valid == false)
                throw new ArgumentException("TwitterCredentials must be specified and validated");

            var querystring = parameters.Aggregate("", (current, entry) => current + (entry.Key + "=" + entry.Value + "&"));

            var oauth1aAuthheader = BuildAuthenticatedResult(url, parameters, "GET");
            var fullUrl = url;

            var handler = new HttpClientHandler();
            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }
            var client = new HttpClient(handler);
            client.DefaultRequestHeaders.Add("Authorization", oauth1aAuthheader.Header);
            client.DefaultRequestHeaders.Add("User-Agent", TwitterApi.UserAgent());

            if (!string.IsNullOrWhiteSpace(querystring))
                fullUrl += "?" + querystring.Substring(0, querystring.Length - 1);

            var download = client.GetAsync(fullUrl).ToObservable().Timeout(TimeSpan.FromSeconds(waitTimeoutSeconds));
            var clientdownload = await download;

            return clientdownload;
        }
Exemplo n.º 26
0
                public static void executegathering()
                {
                    int x = 0;

                    if (!aantalkeermeegedaanpersoon.ContainsKey("persoon2"))
                    {
                        aantalkeermeegedaanpersoon.Add("persoon2", 1);
                    }
                    else
                    {
                        aantalkeermeegedaanpersoon["persoon2"] = aantalkeermeegedaanpersoon["persoon2"] + 1;
                    }

                    if (!personenpergroep.Any())
                    {
                        List <List <string> >          temporarylist                = personenpergroep.DeepClone();
                        List <string>                  storenamestocheck            = Cloneablestringlist.DeepClone();
                        List <int>                     groupswhichareeligable       = cloneablelist.DeepClone();
                        List <string>                  hostnumberpersonsinsidegroup = Cloneablestringlist.DeepClone();
                        List <string>                  temporaryhostpergroup        = hostpergroep.DeepClone();
                        List <string>                  clonedkeuzegerechten         = keuzegerechten.DeepClone();
                        List <string>                  clonedkeuzegerechten2        = keuzegerechten2.DeepClone();
                        SortedDictionary <string, int> temporarydictionary          = cloneablestringkeydictionary.DeepClone();

                        x++;
                        personenpergroep.Add(new List <string> {
                            "name1"
                        });
                        maximumlijst.Add(r.Next(2, 9));
                        rondesperpersoon.Add("name2", r.Next(2, 6));
                    }
                    else
                    {
                        List <List <string> >          temporarylist                = personenpergroep.DeepClone();
                        List <string>                  storenamestocheck            = Cloneablestringlist.DeepClone();
                        List <int>                     groupswhichareeligable       = cloneablelist.DeepClone();
                        List <string>                  hostnumberpersonsinsidegroup = Cloneablestringlist.DeepClone();
                        List <string>                  temporaryhostpergroup        = hostpergroep.DeepClone();
                        List <string>                  clonedkeuzegerechten         = keuzegerechten.DeepClone();
                        List <string>                  clonedkeuzegerechten2        = keuzegerechten2.DeepClone();
                        SortedDictionary <string, int> temporarydictionary          = cloneablestringkeydictionary.DeepClone();

                        if (!rondesperpersoon.ContainsKey("name2"))
                        {
                            rondesperpersoon.Add("name2", r.Next(2, 9));
                        }
                        while (x < rondesperpersoon["name2"])
                        {
                            x++;


                            temporaryhostpergroup.Clear();
                            int i = 0;

                            //get index of lists with person + remove person in clone
                            foreach (var index in temporarylist)
                            {
                                if (index.Contains("person2"))
                                {
                                    var indexoflist = temporarylist[i].IndexOf("person2");
                                    temporarylist[i].RemoveAt(indexoflist);
                                    foreach (var item in temporarylist[i])
                                    {
                                        storenamestocheck.Add(item);
                                    }
                                }
                                i++;
                            }
                            //chechk limit is reached of group
                            foreach (int index2 in maximumlijst)
                            {
                                if (maximumlijst[index2] > personenpergroep[index2].Count)
                                {
                                    hostpergroep.Add("null");
                                    //check if persons have met eachother already

                                    if (personenpergroep[index2].Intersect(storenamestocheck).Any())
                                    {
                                    }
                                    else
                                    {
                                        groupswhichareeligable.Add(index2);
                                    }
                                }

                                else
                                {
                                    if (!temporaryhostpergroup.Contains("null"))
                                    {
                                    }
                                    else
                                    {
                                        foreach (var index3 in personenpergroep[index2])
                                        {
                                            hostnumberpersonsinsidegroup.Add(index3);
                                        }


                                        foreach (var index4 in hostnumberpersonsinsidegroup)
                                        {
                                            if (!hostsperpersoon.ContainsKey(index4))
                                            {
                                                hostsperpersoon.Add(index4, 0);
                                                temporarydictionary.Add(index4, 0);
                                            }
                                            else
                                            {
                                                temporarydictionary.Add(index4, hostsperpersoon[index4]);
                                            }
                                        }
                                        if (x == rondesperpersoon["person2"] - 1 && (hostsperpersoon["person2"] < aantalkeermeegedaanpersoon["person2"]))
                                        {
                                            hostpergroep.Add("person2");
                                        }
                                        else
                                        {
                                            var indexhost = temporarydictionary.Aggregate((l, a) => l.Value < a.Value ? l : a).Key;
                                            hostpergroep.Add(indexhost);
                                        }



                                        DateTime today            = DateTime.Today;
                                        int      daysUntilTuesday = (((int)DayOfWeek.Monday - (int)today.DayOfWeek + 7) % 7) + 1;
                                        DateTime nextTuesday      = today.AddDays(daysUntilTuesday);


                                        Document  doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
                                        PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("host.pdf", FileMode.Create));
                                        doc.Open();
                                        // dieetwensen toevoegen!!!!!!!!!
                                        string    storestring1 = "Beste Meneer/Mevrouw @ hierbij bent u gekozen als de gastheer voor de walking dinner op " + nextTuesday.ToString("dd/MM/yyyy") + " om 18:00, @ de gerechten welk u moet voorbereiden bestaan uit het volgende: @ Hoofdgerecht. @" + clonedkeuzegerechten[r.Next(2)] + "@" + clonedkeuzegerechten2[r.Next(2)];
                                        string    addnewlines1 = storestring1.Replace("@", Environment.NewLine);
                                        Paragraph paragraph    = new Paragraph(addnewlines1);
                                        paragraph.IndentationRight = 100;
                                        paragraph.IndentationLeft  = 100;
                                        doc.Add(paragraph);
                                        doc.Close();
                                        var pathpdffile = Path.GetFullPath("host.pdf");

                                        Document  doc2 = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
                                        PdfWriter wri2 = PdfWriter.GetInstance(doc2, new FileStream("bezoeker.pdf", FileMode.Create));
                                        doc2.Open();
                                        // locatie toevoegen!!!!!!!!!
                                        string    storestring2 = "Beste Meneer/Mevrouw @ hierbij bent u gekozen als bezoeker voor de walking dinner op " + nextTuesday.ToString("dd/MM/yyyy") + " om 18:00 op";
                                        string    addnewlines2 = storestring2.Replace("@", Environment.NewLine);
                                        Paragraph paragraph2   = new Paragraph(addnewlines2);
                                        paragraph2.IndentationRight = 100;
                                        paragraph2.IndentationLeft  = 100;
                                        doc2.Add(paragraph2);
                                        doc2.Close();
                                        var pathpdffile2 = Path.GetFullPath("bezoeker.pdf");

                                        using (MailMessage mail = new MailMessage())
                                        {
                                            mail.From = new MailAddress("*****@*****.**");
                                            mail.To.Add("*****@*****.**");
                                            mail.Subject    = "Walking Dinner";
                                            mail.Body       = "Beste Meneer/Mevrouw, in de bijlages bevindt zich de data voor de aankomende Walking Dinner.";
                                            mail.IsBodyHtml = true;
                                            System.Net.Mail.Attachment attachment;
                                            attachment = new System.Net.Mail.Attachment(pathpdffile);
                                            mail.Attachments.Add(attachment);

                                            using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
                                            {
                                                smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "testmail");
                                                smtp.EnableSsl   = true;
                                                smtp.Send(mail);
                                            }
                                        }


                                        using (MailMessage mail2 = new MailMessage())
                                        {
                                            mail2.From = new MailAddress("*****@*****.**");
                                            mail2.To.Add("*****@*****.**");
                                            mail2.Subject    = "Walking Dinner";
                                            mail2.Body       = "Beste Meneer/Mevrouw, in de bijlages bevindt zich de data voor de aankomende Walking Dinner.";
                                            mail2.IsBodyHtml = true;
                                            System.Net.Mail.Attachment attachment;
                                            attachment = new System.Net.Mail.Attachment(pathpdffile2);
                                            mail2.Attachments.Add(attachment);

                                            using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
                                            {
                                                smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "testmail");
                                                smtp.EnableSsl   = true;
                                                smtp.Send(mail2);
                                            }
                                        }
                                    }
                                }
                            }

                            if (!groupswhichareeligable.Any())
                            {
                                personenpergroep.Add(new List <string> {
                                    "name2"
                                });
                                maximumlijst.Add(r.Next(2, 9));
                            }
                            else
                            {
                                personenpergroep[groupswhichareeligable.First()].Add("person2");
                            }
                        }
                    }
                }
        /// <summary>
        /// Update subscription totals
        /// </summary>
        /// <param name="updateSubscriptionParameters">Parameters for the updating subscription</param>
        /// <param name="restoredCart">Shopping cart</param>
        public virtual void UpdateSubscriptionTotals(UpdateSubscriptionParameters updateSubscriptionParameters, IList <ShoppingCartItem> restoredCart)
        {
            var updatedSubscription     = updateSubscriptionParameters.UpdatedSubscription;
            var updatedSubscriptionItem = updateSubscriptionParameters.UpdatedSubscriptionItem;

            //get the customer
            var customer = restoredCart.GetCustomer();

            #region Sub total

            var subTotalExclTax  = decimal.Zero;
            var subTotalInclTax  = decimal.Zero;
            var subTotalTaxRates = new SortedDictionary <decimal, decimal>();

            foreach (var shoppingCartItem in restoredCart)
            {
                var itemSubTotalExclTax = decimal.Zero;
                var itemSubTotalInclTax = decimal.Zero;
                var taxRate             = decimal.Zero;


                //calculate subtotal for the updated subscription item
                if (shoppingCartItem.Id == updatedSubscriptionItem.Id)
                {
                    //update subscription item
                    updatedSubscriptionItem.UnitPriceExclTax      = updateSubscriptionParameters.PriceExclTax;
                    updatedSubscriptionItem.UnitPriceInclTax      = updateSubscriptionParameters.PriceInclTax;
                    updatedSubscriptionItem.DiscountAmountExclTax = updateSubscriptionParameters.DiscountAmountExclTax;
                    updatedSubscriptionItem.DiscountAmountInclTax = updateSubscriptionParameters.DiscountAmountInclTax;
                    updatedSubscriptionItem.PriceExclTax          = itemSubTotalExclTax = updateSubscriptionParameters.SubTotalExclTax;
                    updatedSubscriptionItem.PriceInclTax          = itemSubTotalInclTax = updateSubscriptionParameters.SubTotalInclTax;
                    updatedSubscriptionItem.Quantity = shoppingCartItem.Quantity;

                    taxRate = Math.Round((100 * (itemSubTotalInclTax - itemSubTotalExclTax)) / itemSubTotalExclTax, 3);
                }
                else
                {
                    //get the already calculated subtotal from the subscription item
                    itemSubTotalExclTax = updatedSubscription.SubscriptionItems.FirstOrDefault(item => item.Id == shoppingCartItem.Id).PriceExclTax;
                    itemSubTotalInclTax = updatedSubscription.SubscriptionItems.FirstOrDefault(item => item.Id == shoppingCartItem.Id).PriceInclTax;
                    taxRate             = Math.Round((100 * (itemSubTotalInclTax - itemSubTotalExclTax)) / itemSubTotalExclTax, 3);
                }



                subTotalExclTax += itemSubTotalExclTax;
                subTotalInclTax += itemSubTotalInclTax;

                //tax rates
                var itemTaxValue = itemSubTotalInclTax - itemSubTotalExclTax;
                if (taxRate > decimal.Zero && itemTaxValue > decimal.Zero)
                {
                    if (!subTotalTaxRates.ContainsKey(taxRate))
                    {
                        subTotalTaxRates.Add(taxRate, itemTaxValue);
                    }
                    else
                    {
                        subTotalTaxRates[taxRate] = subTotalTaxRates[taxRate] + itemTaxValue;
                    }
                }
            }

            if (subTotalExclTax < decimal.Zero)
            {
                subTotalExclTax = decimal.Zero;
            }

            if (subTotalInclTax < decimal.Zero)
            {
                subTotalInclTax = decimal.Zero;
            }

            //We calculate discount amount on subscription subtotal excl tax (discount first)
            //calculate discount amount ('Applied to subscription subtotal' discount)


            //add tax for shopping items
            var tempTaxRates = new Dictionary <decimal, decimal>(subTotalTaxRates);
            foreach (var kvp in tempTaxRates)
            {
                if (kvp.Value != decimal.Zero && subTotalExclTax > decimal.Zero)
                {
                    subTotalTaxRates[kvp.Key] = kvp.Value;
                }
            }

            //rounding
            if (_shoppingCartSettings.RoundPricesDuringCalculation)
            {
                subTotalExclTax = RoundingHelper.RoundPrice(subTotalExclTax);
                subTotalInclTax = RoundingHelper.RoundPrice(subTotalInclTax);
            }

            updatedSubscription.SubscriptionSubtotalExclTax = subTotalExclTax;
            updatedSubscription.SubscriptionSubtotalInclTax = subTotalInclTax;


            #endregion



            #region Tax rates

            var taxRates = new SortedDictionary <decimal, decimal>();

            //subscription subtotal taxes
            var subTotalTax = decimal.Zero;
            foreach (var kvp in subTotalTaxRates)
            {
                subTotalTax += kvp.Value;
                if (kvp.Key > decimal.Zero && kvp.Value > decimal.Zero)
                {
                    if (!taxRates.ContainsKey(kvp.Key))
                    {
                        taxRates.Add(kvp.Key, kvp.Value);
                    }
                    else
                    {
                        taxRates[kvp.Key] = taxRates[kvp.Key] + kvp.Value;
                    }
                }
            }



            //payment method additional fee tax
            var paymentMethodAdditionalFeeTax = decimal.Zero;
            if (_taxSettings.PaymentMethodAdditionalFeeIsTaxable)
            {
                paymentMethodAdditionalFeeTax = updatedSubscription.PaymentMethodAdditionalFeeInclTax - updatedSubscription.PaymentMethodAdditionalFeeExclTax;
                if (paymentMethodAdditionalFeeTax < decimal.Zero)
                {
                    paymentMethodAdditionalFeeTax = decimal.Zero;
                }

                if (updatedSubscription.PaymentMethodAdditionalFeeExclTax > decimal.Zero)
                {
                    var paymentTaxRate = Math.Round(100 * paymentMethodAdditionalFeeTax / updatedSubscription.PaymentMethodAdditionalFeeExclTax, 3);
                    if (paymentTaxRate > decimal.Zero && paymentMethodAdditionalFeeTax > decimal.Zero)
                    {
                        if (!taxRates.ContainsKey(paymentTaxRate))
                        {
                            taxRates.Add(paymentTaxRate, paymentMethodAdditionalFeeTax);
                        }
                        else
                        {
                            taxRates[paymentTaxRate] = taxRates[paymentTaxRate] + paymentMethodAdditionalFeeTax;
                        }
                    }
                }
            }

            //add at least one tax rate (0%)
            if (!taxRates.Any())
            {
                taxRates.Add(decimal.Zero, decimal.Zero);
            }

            //summarize taxes
            var taxTotal = subTotalTax + paymentMethodAdditionalFeeTax;
            if (taxTotal < decimal.Zero)
            {
                taxTotal = decimal.Zero;
            }

            //round tax
            if (_shoppingCartSettings.RoundPricesDuringCalculation)
            {
                taxTotal = RoundingHelper.RoundPrice(taxTotal);
            }

            updatedSubscription.SubscriptionTax = taxTotal;
            updatedSubscription.TaxRates        = taxRates.Aggregate(string.Empty, (current, next) =>
                                                                     string.Format("{0}{1}:{2};   ", current, next.Key.ToString(CultureInfo.InvariantCulture), next.Value.ToString(CultureInfo.InvariantCulture)));

            #endregion

            #region Total

            var total = (subTotalExclTax) + updatedSubscription.PaymentMethodAdditionalFeeExclTax + taxTotal;



            //reward points
            var rewardPointsOfSubscription = _rewardPointService.GetRewardPointsHistory(customer.Id, true).FirstOrDefault(history => history.UsedWithSubscription == updatedSubscription);
            if (rewardPointsOfSubscription != null)
            {
                var rewardPoints       = -rewardPointsOfSubscription.Points;
                var rewardPointsAmount = ConvertRewardPointsToAmount(rewardPoints);
                if (total < rewardPointsAmount)
                {
                    rewardPoints       = ConvertAmountToRewardPoints(total);
                    rewardPointsAmount = total;
                }
                if (total > decimal.Zero)
                {
                    total -= rewardPointsAmount;
                }

                //uncomment here for the return unused reward points if new subscription total less redeemed reward points amount
                //if (rewardPoints < -rewardPointsOfSubscription.Points)
                //    _rewardPointService.AddRewardPointsHistoryEntry(customer, -rewardPointsOfSubscription.Points - rewardPoints, _storeContext.CurrentStore.Id, "Return unused reward points");

                if (rewardPointsAmount != rewardPointsOfSubscription.UsedAmount)
                {
                    rewardPointsOfSubscription.UsedAmount = rewardPointsAmount;
                    rewardPointsOfSubscription.Points     = -rewardPoints;
                    _rewardPointService.UpdateRewardPointsHistoryEntry(rewardPointsOfSubscription);
                }
            }

            //rounding
            if (total < decimal.Zero)
            {
                total = decimal.Zero;
            }
            if (_shoppingCartSettings.RoundPricesDuringCalculation)
            {
                total = RoundingHelper.RoundPrice(total);
            }



            #endregion
        }
Exemplo n.º 28
0
        public async Task <int> setForecastData(ForecastData data)
        {
            ForecastEntry[]  entries           = data.Entries;
            List <GraphData> graphDataToday    = new List <GraphData>();
            List <GraphData> graphDataTomorrow = new List <GraphData>();

            this.FiveDays = new List <Status>();
            SortedDictionary <WeatherStatus, int> averageStatusTomorrow = new SortedDictionary <WeatherStatus, int>();

            double maxTemperature       = 0;
            double minTemperature       = 0;
            string currentWeatherStatus = "";
            string currentWeatherIcon   = null;
            double rain           = 0;
            double windSpeed      = 0;
            long   windDegree     = 0;
            double temperature    = 0;
            long   pressure       = 0;
            long   humidity       = 0;
            int    n_entries_days = 0;

            foreach (ForecastEntry entry in entries)
            {
                DateTime current  = DateTime.Today;
                DateTime date     = DateTime.Parse(entry.DateTimeText);
                double   dateDiff = (date.Date - current).TotalDays;

                if (dateDiff == 0 || (dateDiff == 1 && date.Hour == 0))
                {
                    GraphData gr = new GraphData(date, Math.Round(entry.Main.MaxTemperature).ToString(), Math.Round(entry.Main.MinTemperature).ToString(), entry.Weather[0].Status, entry.Weather[0].Icon);
                    await gr.setImage(entry.Weather[0].Icon);

                    graphDataToday.Add(gr);
                }
                else if (dateDiff == 1 || (dateDiff == 2 && date.Hour == 0))
                {
                    temperature    += entry.Main.Temperature;
                    rain           += entry.Rain != null ? entry.Rain.RainVolume : 0;
                    maxTemperature += entry.Main.MaxTemperature;
                    minTemperature += entry.Main.MinTemperature;
                    pressure       += entry.Main.Pressure;
                    humidity       += entry.Main.Humidity;
                    windSpeed      += entry.Wind.Speed;
                    windDegree     += entry.Wind.Degree;
                    n_entries_days += 1;

                    // Saving status for tomorrow to later check what was the most common
                    if (averageStatusTomorrow.ContainsKey(entry.Weather[0]))
                    {
                        averageStatusTomorrow[entry.Weather[0]] = averageStatusTomorrow[entry.Weather[0]] + 1;
                    }
                    else
                    {
                        averageStatusTomorrow.Add(entry.Weather[0], 1);
                    }

                    // saving graph data
                    GraphData gr = new GraphData(date, Math.Round(entry.Main.MaxTemperature).ToString(), Math.Round(entry.Main.MinTemperature).ToString(), entry.Weather[0].Status, entry.Weather[0].Icon);
                    await gr.setImage(entry.Weather[0].Icon);

                    graphDataTomorrow.Add(gr);
                }
                else if ((dateDiff >= 2 || dateDiff <= 6) && date.Hour == 12)
                {
                    Status status = new Status();
                    status.setData(entry);
                    this.FiveDays.Add(status);
                }
            }

            // Averages of the data for tomorrow
            rain           = rain != 0 ? rain / n_entries_days : 0;
            temperature    = temperature / n_entries_days;
            maxTemperature = maxTemperature / n_entries_days;
            minTemperature = minTemperature / n_entries_days;
            pressure       = pressure / n_entries_days;
            humidity       = humidity / n_entries_days;
            windSpeed      = windSpeed / n_entries_days;
            windDegree     = windDegree / n_entries_days;

            // Get the most common status in the forecast for tomorrow
            WeatherStatus statusTomorrow = averageStatusTomorrow.Aggregate((left, right) => left.Value > right.Value ? left : right).Key;

            this.Tomorrow.setData("Tomorrow", statusTomorrow.Status, statusTomorrow.Icon, rain, windSpeed, windDegree, temperature, pressure, humidity, minTemperature, maxTemperature, (DateTime.Now).AddDays(1));
            this.Tomorrow.GraphData = graphDataTomorrow;

            this.Today.GraphData = graphDataToday;

            this.FiveDays.Insert(0, this.Tomorrow);
            this.FiveDays.Insert(0, this.Today);

            return(0);
        }
Exemplo n.º 29
0
        private void Tweet()
        {
            const string Oauth_version          = "1.0";
            const string Oauth_signature_method = "HMAC-SHA1";

            if (this.Message.Length > 140)
            {
                this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Message too long: {0}. Maximum length is 140 characters.", this.Message.Length));
                return;
            }

            // TODO: figure out encoding to support sending apostrophes
            this.Message = this.Message.Replace("'", " ");
            this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Tweeting: {0}", this.Message));
            string   postBody           = "status=" + Uri.EscapeDataString(this.Message);
            string   oauth_consumer_key = this.ConsumerKey;
            string   oauth_nonce        = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            string   oauth_timestamp             = Convert.ToInt64(ts.TotalSeconds).ToString();
            SortedDictionary <string, string> sd = new SortedDictionary <string, string> {
                { "status", Uri.EscapeDataString(this.Message) }, { "oauth_version", Oauth_version }, { "oauth_consumer_key", oauth_consumer_key }, { "oauth_nonce", oauth_nonce }, { "oauth_signature_method", Oauth_signature_method }, { "oauth_timestamp", oauth_timestamp }, { "oauth_token", this.AccessToken }
            };

            string baseString = string.Empty;

            baseString += "POST" + "&";
            baseString += Uri.EscapeDataString(this.TwitterUrl) + "&";
            baseString  = sd.Aggregate(baseString, (current, entry) => current + Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&"));
            baseString  = baseString.Substring(0, baseString.Length - 3);

            string signingKey = Uri.EscapeDataString(this.ConsumerSecret) + "&" + Uri.EscapeDataString(this.AccessTokenSecret);
            string signatureString;

            using (HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey)))
            {
                signatureString = Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(baseString)));
            }

            ServicePointManager.Expect100Continue = false;
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(this.TwitterUrl));

            StringBuilder authorizationHeaderParams = new StringBuilder();

            authorizationHeaderParams.Append("OAuth ");
            authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauth_nonce) + "\",");
            authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(Oauth_signature_method) + "\",");
            authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauth_timestamp) + "\",");
            authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauth_consumer_key) + "\",");
            authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(this.AccessToken) + "\",");
            authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(signatureString) + "\",");
            authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(Oauth_version) + "\"");
            webRequest.Headers.Add("Authorization", authorizationHeaderParams.ToString());
            webRequest.Method      = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            using (Stream stream = webRequest.GetRequestStream())
            {
                byte[] bodyBytes = new ASCIIEncoding().GetBytes(postBody);
                stream.Write(bodyBytes, 0, bodyBytes.Length);
                stream.Flush();
            }

            webRequest.Timeout = 3 * 60 * 1000;
            try
            {
                HttpWebResponse rsp = webRequest.GetResponse() as HttpWebResponse;

                Stream responseStream = rsp.GetResponseStream();
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    string content = reader.ReadToEnd();
                    this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Response: {0}", content));
                }
            }
            catch (Exception e)
            {
                this.Log.LogError(e.ToString());
            }
        }
Exemplo n.º 30
0
 public string EncodeBag()
 {
     return(_inventory.Aggregate("", (current, it) => current +
                                 $"{Convert.ToChar(it.Key)}{Convert.ToChar(it.Value)}"));
 }
        /// <summary>
        /// Use OAuth2 Bearer Token for POST
        /// </summary>
        /// <param name="url">URL to call</param>
        /// <param name="parameters">Params to send</param>
        /// <param name="forInitialAuth">Is for an initial auth to get bearer token</param>
        /// <returns></returns>
        public async Task<HttpResponseMessage> PostAsync(string url, SortedDictionary<string, string> parameters, bool forInitialAuth = false)
        {
            if (forInitialAuth)
            {
                if (clientID == null && clientSecret == null)
                {
                    return null;
                }
            }
            else
            {
                if (clientID != null && clientSecret != null && bearerToken == null)
                {
                    await this.StartApplicationOnlyAuth();
                }
                if (bearerToken == null) return null;
            }

            var querystring = parameters.Aggregate("", (current, entry) => current + (entry.Key + "=" + entry.Value + "&"));
            if (!string.IsNullOrWhiteSpace(querystring))
                querystring = querystring.TrimLastChar();

            var oauth2Bearertoken = forInitialAuth
                ? String.Format("Basic {0}",
                    String.Format("{0}:{1}", clientID.UrlEncode(), clientSecret.UrlEncode()).ToBase64String())
                : String.Format("Bearer {0}", bearerToken);

            var handler = new HttpClientHandler();
            var client = new HttpClient(handler);
            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }
            client.DefaultRequestHeaders.Add("Authorization", oauth2Bearertoken);
            client.DefaultRequestHeaders.Add("User-Agent", TwitterApi.UserAgent());

            var data = new StringContent(querystring, Encoding.UTF8, "application/x-www-form-urlencoded");

            var download = client.PostAsync(url, data).ToObservable().Timeout(TimeSpan.FromSeconds(waitTimeoutSeconds));
            return await download;
        }
        private List<KeyValuePair<int, char>> NormalizeGrayscales(SortedDictionary<int, char> grayscales)
        {
            var max = grayscales.Aggregate(int.MinValue, (memo, pair) => memo < pair.Key ? pair.Key : memo);
            var min = grayscales.Aggregate(int.MaxValue, (memo, pair) => memo > pair.Key ? pair.Key : memo);

            var range = max - min;

            Func<KeyValuePair<int, char>, KeyValuePair<int, char>> normalizePair = (pair) =>
            {
                var newKey = 1 + (pair.Key - min) * 255 / range;
                return new KeyValuePair<int, char>(newKey, pair.Value);
            };

            var normalizedGrayscales = grayscales.Select(normalizePair).ToList();
            return normalizedGrayscales;
        }
Exemplo n.º 33
0
 public double Value(Point point) =>
 _variables.Aggregate(_variables.Count > 0 ? 1.0 : 0.0,
                      (current, entry) => current * Math.Pow(point[entry.Key], entry.Value));
Exemplo n.º 34
0
        public HttpRequestMessage CreatePost(string url, SortedDictionary<string, string> parameters)
        {
            var oauth = BuildAuthenticatedResult(url, parameters, "POST");
            var fullUrl = url;

            var request = new HttpRequestMessage(HttpMethod.Post, fullUrl);
            request.Headers.Add("Authorization", oauth.Header);
            request.Headers.Add("User-Agent", TwitterApi.UserAgent());

            var content = parameters.Aggregate(string.Empty, (current, e) => current + string.Format("{0}={1}&", e.Key, Uri.EscapeDataString(e.Value)));
            request.Content = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");
            
            return request;
        }
Exemplo n.º 35
0
        /// <summary>
        /// Generates the the string of parameters used for making the signature.
        /// </summary>
        /// <param name="queryString">Values representing the query string.</param>
        /// <param name="body">Values representing the POST body.</param>
        public virtual string GenerateParameterString(NameValueCollection queryString, NameValueCollection body) {

            // The parameters must be alphabetically sorted
            SortedDictionary<string, string> sorted = new SortedDictionary<string, string>();

            // Add parameters from the query string
            if (queryString != null) {
                foreach (string key in queryString) {
                    //if (key.StartsWith("oauth_")) continue;
                    sorted.Add(Uri.EscapeDataString(key), Uri.EscapeDataString(queryString[key]));
                }
            }
            
            // Add parameters from the POST data
            if (body != null) {
                foreach (string key in body) {
                    //if (key.StartsWith("oauth_")) continue;
                    sorted.Add(Uri.EscapeDataString(key), Uri.EscapeDataString(body[key]));
                }
            }

            // Add OAuth values
            if (!String.IsNullOrEmpty(Callback)) sorted.Add("oauth_callback", Uri.EscapeDataString(Callback));
            sorted.Add("oauth_consumer_key", Uri.EscapeDataString(ConsumerKey));
            sorted.Add("oauth_nonce", Uri.EscapeDataString(Nonce));
            sorted.Add("oauth_signature_method", "HMAC-SHA1");
            sorted.Add("oauth_timestamp", Uri.EscapeDataString(Timestamp));
            if (!String.IsNullOrEmpty(Token)) sorted.Add("oauth_token", Uri.EscapeDataString(Token));
            sorted.Add("oauth_version", Uri.EscapeDataString(Version));

            // Merge all parameters
            return sorted.Aggregate("", (current, pair) => current + ("&" + pair.Key + "=" + pair.Value)).Substring(1);

        }
Exemplo n.º 36
0
        /// <summary>
        /// Use OAuth1.0a auth to do more intensive POST
        /// </summary>
        /// <param name="url">URL to call</param>
        /// <param name="parameters">Params to send</param>
        /// <returns></returns>
        public async Task<HttpResponseMessage> PostAsync(string url, SortedDictionary<string, string> parameters)
        {
            if (TwitterCredentials == TwitterCredentials.Null || TwitterCredentials.Valid == false)
                throw new ArgumentException("TwitterCredentials must be specified and validated");

            var oauth1aAuthheader = BuildAuthenticatedResult(url, parameters, "POST");
            var handler = new HttpClientHandler();
            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }
            var client = new HttpClient(handler);

            client.DefaultRequestHeaders.Add("Authorization", oauth1aAuthheader.Header);
            client.DefaultRequestHeaders.Add("User-Agent", TwitterApi.UserAgent());

            var content = parameters.Aggregate(string.Empty, (current, e) => current + string.Format("{0}={1}&", e.Key, Uri.EscapeDataString(e.Value)));
            var data = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");

            var download = client.PostAsync(url, data).ToObservable().Timeout(TimeSpan.FromSeconds(waitTimeoutSeconds));
            var clientdownload = await download;

            return clientdownload;
        }
    // TESTING
    private void OnGetToneAnalyze(ToneAnalyzerResponse resp, Dictionary <string, object> customData)
    {
        double anger   = resp.document_tone.tone_categories[0].tones[0].score;
        double disgust = resp.document_tone.tone_categories[0].tones[1].score;
        double fear    = resp.document_tone.tone_categories[0].tones[2].score;
        double joy     = resp.document_tone.tone_categories[0].tones[3].score;
        double sadness = resp.document_tone.tone_categories[0].tones[4].score;


        var tones = new SortedDictionary <string, double> {
            { "anger", anger },
            { "disgust", disgust },
            { "fear", fear },
            { "joy", joy },
            { "sadness", sadness },
        };


        string max_tone = tones.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;


        //Grow that emotion
        if (tones[max_tone] > emotion_threshold && emotional_states[max_tone] < max_emotion_value)
        {
            Log.Debug("Tone Levels ", "1) Growing Max Tone = {0}", max_tone);
            //text_scroll.addline("test", max_tone);
            emotional_states[max_tone] += emotional_growth;
        }
        else
        {
            Log.Debug("Tone Levels ", "1) Max tone below Threshold {0}", emotion_threshold);
        }

        //decay all others
        Log.Debug("Tone Levels ", "2) Dacaying other tones", max_tone);
        List <string> keys = new List <string>(emotional_states.Keys);

        foreach (string e_state in keys)
        {
            if (emotional_states[e_state] > 0)
            {
                emotional_states[e_state] -= emotional_decay;
            }
        }
        Log.Debug("Emotional State Levels", "J:{0} S:{1} F:{2} D:{3} A:{4}", emotional_states["joy"], emotional_states["sadness"], emotional_states["fear"], emotional_states["disgust"], emotional_states["anger"]);

        string max_emotion = emotional_states.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;

        Log.Debug("Tone Levels ", "3) Looking for Prodominant Emotion = {0}", max_emotion);

        Log.Debug("Tone Levels ", "4) checking emotion above idle threshold : {0}", (emotional_states[max_emotion] > idle_threshold));

        string state = (emotional_states[max_emotion] > idle_threshold) ? max_emotion : "idle";

        Log.Debug("Tone Levels ", "5) Updating state to {0} ", state);
        CactusField.text = state;

        // set to default
        Log.Debug("Tone Levels", "6)Updating bars - No Emotion");
        bar1JoyRenderer.transform.localScale    = new Vector3(1F, 1F + (bar_scale * emotional_states["joy"]), 1F);
        bar1JoyRenderer.transform.localPosition = joy_base + new Vector3(0F, (bar_scale * emotional_states["joy"]) / 2, 0F);

        bar2SadnessRenderer.transform.localScale    = new Vector3(1F, 1F + (bar_scale * emotional_states["sadness"]), 1F);
        bar2SadnessRenderer.transform.localPosition = sad_base + new Vector3(0F, (bar_scale * emotional_states["sadness"]) / 2, 0F);


        bar3FearRenderer.transform.localScale    = new Vector3(1F, 1F + (bar_scale * emotional_states["fear"]), 1F);
        bar3FearRenderer.transform.localPosition = fear_base + new Vector3(0F, (bar_scale * emotional_states["fear"]) / 2, 0F);


        bar4DisgustRenderer.transform.localScale    = new Vector3(1F, 1F + (bar_scale * emotional_states["disgust"]), 1F);
        bar4DisgustRenderer.transform.localPosition = disgust_base + new Vector3(0F, (bar_scale * emotional_states["disgust"]) / 2, 0F);


        bar5AngerRenderer.transform.localScale    = new Vector3(1F, 1F + (bar_scale * emotional_states["anger"]), 1F);
        bar5AngerRenderer.transform.localPosition = anger_base + new Vector3(0F, (bar_scale * emotional_states["anger"]) / 2, 0F);



        int state_id = 0;

        switch (state)
        {
        case "idle":
            state_id = 0;
            break;

        case "joy":
            state_id = 1;
            break;

        case "sadness":
            state_id = 2;
            break;

        case "fear":
            state_id = 3;
            break;

        case "disgust":
            state_id = 4;
            break;

        case "anger":
            state_id = 5;
            break;
        }

        //stops trigger loop
        if (state_id != last_state_id)
        {
            Log.Debug("Tone Levels", "7)Trigger Animation via State_ID - {0}", state_id);
            droid_animator.SetInteger("State_ID", state_id);
            last_state_id = state_id;
        }
        else
        {
            Log.Debug("Tone Levels", "7)Leaving Animation, state stable", state_id);
        }


        if (resp.document_tone.tone_categories[1].tones[0].score > emotion_threshold)
        {
        }
        else if (resp.document_tone.tone_categories[1].tones[1].score > emotion_threshold)
        {
        }
        else if (resp.document_tone.tone_categories [1].tones[2].score > emotion_threshold)
        {
        }


        // OTHER TEXT - Formatting for On Screen dump - LATER - pretty this up to use standard DESERIALIZE methods and table
        string RAW = (customData["json"].ToString());          // works but long and cannot read

        //RAW = string.Concat("Tone Response \n", RAW);
        RAW = Regex.Replace(RAW, "tone_categories", " \\\n");
        RAW = Regex.Replace(RAW, "}", "} \\\n");
        RAW = Regex.Replace(RAW, "tone_id", " ");
        RAW = Regex.Replace(RAW, "tone_name", " ");
        RAW = Regex.Replace(RAW, "score", " ");
        RAW = Regex.Replace(RAW, @"[{\\},:]", "");
        RAW = Regex.Replace(RAW, "\"", "");
        //ResultsField.text = RAW;

        _analyzeToneTested = true;
    }
Exemplo n.º 38
0
        private void Tweet()
        {
            string oauth_version = "1.0";
            string oauth_signature_method = "HMAC-SHA1";
            if (this.Message.Length > 140)
            {
                this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Message too long: {0}. Maximum length is 140 characters.", this.Message.Length));
                return;
            }

            // TODO: figure out encoding to support sending apostrophes
            this.Message = this.Message.Replace("'", " ");
            this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Tweeting: {0}", this.Message));
            string postBody = "status=" + Uri.EscapeDataString(this.Message);
            string oauth_consumer_key = this.ConsumerKey;
            string oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            string oauth_timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
            SortedDictionary<string, string> sd = new SortedDictionary<string, string> { { "status", Uri.EscapeDataString(this.Message) }, { "oauth_version", oauth_version }, { "oauth_consumer_key", oauth_consumer_key }, { "oauth_nonce", oauth_nonce }, { "oauth_signature_method", oauth_signature_method }, { "oauth_timestamp", oauth_timestamp }, { "oauth_token", this.AccessToken } };

            string baseString = string.Empty;
            baseString += "POST" + "&";
            baseString += Uri.EscapeDataString(this.TwitterUrl) + "&";
            baseString = sd.Aggregate(baseString, (current, entry) => current + Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&"));
            baseString = baseString.Substring(0, baseString.Length - 3);

            string signingKey = Uri.EscapeDataString(this.ConsumerSecret) + "&" + Uri.EscapeDataString(this.AccessTokenSecret);
            string signatureString;
            using (HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey)))
            {
                signatureString = Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(baseString)));
            }

            ServicePointManager.Expect100Continue = false;
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(this.TwitterUrl));
            
            StringBuilder authorizationHeaderParams = new StringBuilder();
            authorizationHeaderParams.Append("OAuth ");
            authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauth_nonce) + "\",");
            authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauth_signature_method) + "\",");
            authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauth_timestamp) + "\",");
            authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauth_consumer_key) + "\",");
            authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(this.AccessToken) + "\",");
            authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(signatureString) + "\",");
            authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauth_version) + "\"");
            webRequest.Headers.Add("Authorization", authorizationHeaderParams.ToString());
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            using (Stream stream = webRequest.GetRequestStream())
            {
                byte[] bodyBytes = new ASCIIEncoding().GetBytes(postBody);
                stream.Write(bodyBytes, 0, bodyBytes.Length);
                stream.Flush();
            }

            webRequest.Timeout = 3 * 60 * 1000;
            try
            {
                HttpWebResponse rsp = webRequest.GetResponse() as HttpWebResponse;

                Stream responseStream = rsp.GetResponseStream();
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    string content = reader.ReadToEnd();
                    this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Response: {0}", content));
                }
            }
            catch (Exception e)
            {
                this.Log.LogError(e.ToString());
            }
        }
Exemplo n.º 39
0
    private void OnGetToneAnalyze(ToneAnalysis resp, Dictionary <string, object> customData)
    {
        // Example response from Tone Analyzer ( Version  2017-05-25)
        //    { "document_tone":{ "tones":[{"score":1.0,"tone_id":"joy","tone_name":"Joy"}]}}



        double anger   = resp.DocumentTone.ToneCategories[0].Tones[0].Score.Value;
        double disgust = resp.DocumentTone.ToneCategories[0].Tones[1].Score.Value;
        double fear    = resp.DocumentTone.ToneCategories[0].Tones[2].Score.Value;
        double joy     = resp.DocumentTone.ToneCategories[0].Tones[3].Score.Value;
        double sadness = resp.DocumentTone.ToneCategories[0].Tones[4].Score.Value;


        var tones = new SortedDictionary <string, double> {
            { "anger", anger },
            { "disgust", disgust },
            { "fear", fear },
            { "joy", joy },
            { "sadness", sadness },
        };

        // max_tone gets the tone which has the highest value.
        string max_tone = tones.Aggregate((l, right) => l.Value > right.Value ? l : right).Key;

        //if this tone is bigger than the threshold we set, then we'll change the Octopus colour.
        if (tones[max_tone] > emotion_threshold)
        {
            Log.Debug("ToneHandler.OnGetToneAnalyze()", "Growing Max Tone = {0}", max_tone);
            //text_scroll.addline("test", max_tone);
            //          emotional_states[max_tone] += emotional_growth;


            Color color = Color.red;                                            // Default color to be overwritten.
            Tonea2.text          = Tonea1.text;                                 // Move old tone values up the debug log in the Debug Panel.
            TonePercenta2.text   = TonePercenta1.text;
            Tonea1.text          = ResultsField.text;
            TonePercenta1.text   = PercentageField.text;
            ResultsField.text    = max_tone;                 // Set the current value in the Debug Panel
            PercentageField.text = "(" + tones[max_tone] * 100 + "%)";
            int intensity = 3;                               // This is by default, a new emotion we've not seen before
            if (Tonea1.text.CompareTo(ResultsField.text) == 0)
            {
                intensity = 2;                                  // This is the same emotion twice
                if (Tonea2.text.CompareTo(ResultsField.text) == 0)
                {
                    intensity = 1;                                  // This is the same emotion three times
                }
            }

            //  Set the color of the octopus depending on the tone from tone analyzer.
            //  Multiply some of the RGB values to change the color based on intensity value set above.

            switch (max_tone)
            {
            case "joy":
            {
                color = new Color(0.2f * intensity, 0.9f, 0.2f * intensity);
                break;
            }

            case "anger":
            {
                color = new Color(0.9f, 0.2f * intensity, 0.2f * intensity);
                break;
            }

            case "fear":
            {
                color = new Color(0.9f, 0.9f, 0.2f * intensity);
                break;
            }

            case "sadness":
            {
                color = new Color(0.2f * intensity, 0.2f * intensity, 0.2f * intensity);
                break;
            }

            case "disgust":
            {
                color = new Color(0.9f, 0.2f * intensity, 0.9f);
                break;
            }
            }

            // Here we set the color - the Octopus has 3 renderers, one for the body (with 2 materials), and one for each eye - we'll adjust the color of each to the
            // same color here, but of course these could be set to different colors if you wanted just parts of the Octopus to change.
            Log.Debug("ToneHandler.OnGetToneAnalyze()", "Setting color = {0}", color);
            r            = GameObject.Find("body").GetComponent <Renderer>();
            rendEyeRight = GameObject.Find("eye - right").GetComponent <Renderer>();
            rendEyeLeft  = GameObject.Find("eye - left").GetComponent <Renderer>();
            r.materials[0].SetColor("_Color", color);
            r.materials[1].SetColor("_Color", color);
            rendEyeLeft.material.SetColor("_Color", color);
            rendEyeRight.material.SetColor("_Color", color);

            Log.Debug("ToneHandler.OnGetToneAnalyze()", "Growing Max Tone = {0}", max_tone);
        }
        else                // If the tone measured has a lower confidence level, then we'll indicate that we're not confident
        // and not change the color.
        {
            Log.Debug("ToneHandler.OnGetToneAnalyze()", "Max tone below Threshold {0}", emotion_threshold);
            Tonea2.text          = Tonea1.text;
            TonePercenta2.text   = TonePercenta1.text;
            Tonea1.text          = ResultsField.text;
            TonePercenta1.text   = PercentageField.text;
            PercentageField.text = "";
            ResultsField.text    = "Tone not clear";
        }
    }
Exemplo n.º 40
0
        /// <summary>
        /// Update order totals
        /// </summary>
        /// <param name="updateOrderParameters">Parameters for the updating order</param>
        /// <param name="restoredCart">Shopping cart</param>
        public virtual void UpdateOrderTotals(UpdateOrderParameters updateOrderParameters, IList<ShoppingCartItem> restoredCart)
        {
            var updatedOrder = updateOrderParameters.UpdatedOrder;
            var updatedOrderItem = updateOrderParameters.UpdatedOrderItem;

            //get the customer 
            var customer = restoredCart.GetCustomer();

            #region Sub total

            var subTotalExclTax = decimal.Zero;
            var subTotalInclTax = decimal.Zero;
            var subTotalTaxRates = new SortedDictionary<decimal, decimal>();

            foreach (var shoppingCartItem in restoredCart)
            {
                var itemSubTotalExclTax = decimal.Zero;
                var itemSubTotalInclTax = decimal.Zero;
                var taxRate = decimal.Zero;
                var itemDiscounts = new List<Discount>();

                //calculate subtotal for the updated order item
                if (shoppingCartItem.Id == updatedOrderItem.Id)
                {
                    //update order item 
                    updatedOrderItem.UnitPriceExclTax = updateOrderParameters.PriceExclTax;
                    updatedOrderItem.UnitPriceInclTax = updateOrderParameters.PriceInclTax;
                    updatedOrderItem.DiscountAmountExclTax = updateOrderParameters.DiscountAmountExclTax;
                    updatedOrderItem.DiscountAmountInclTax = updateOrderParameters.DiscountAmountInclTax;
                    updatedOrderItem.PriceExclTax = itemSubTotalExclTax = updateOrderParameters.SubTotalExclTax;
                    updatedOrderItem.PriceInclTax = itemSubTotalInclTax = updateOrderParameters.SubTotalInclTax;
                    updatedOrderItem.Quantity = shoppingCartItem.Quantity;

                    taxRate = Math.Round((100 * (itemSubTotalInclTax - itemSubTotalExclTax)) / itemSubTotalExclTax, 3);
                }
                else
                {
                    //get the already calculated subtotal from the order item
                    itemSubTotalExclTax = updatedOrder.OrderItems.FirstOrDefault(item => item.Id == shoppingCartItem.Id).PriceExclTax;
                    itemSubTotalInclTax = updatedOrder.OrderItems.FirstOrDefault(item => item.Id == shoppingCartItem.Id).PriceInclTax;
                    taxRate = Math.Round((100 * (itemSubTotalInclTax - itemSubTotalExclTax)) / itemSubTotalExclTax, 3);
                }

                foreach (var discount in itemDiscounts)
                    if (!updateOrderParameters.AppliedDiscounts.ContainsDiscount(discount))
                        updateOrderParameters.AppliedDiscounts.Add(discount);

                subTotalExclTax += itemSubTotalExclTax;
                subTotalInclTax += itemSubTotalInclTax;

                //tax rates
                var itemTaxValue = itemSubTotalInclTax - itemSubTotalExclTax;
                if (taxRate > decimal.Zero && itemTaxValue > decimal.Zero)
                {
                    if (!subTotalTaxRates.ContainsKey(taxRate))
                        subTotalTaxRates.Add(taxRate, itemTaxValue);
                    else
                        subTotalTaxRates[taxRate] = subTotalTaxRates[taxRate] + itemTaxValue;
                }
            }

            if (subTotalExclTax < decimal.Zero)
                subTotalExclTax = decimal.Zero;

            if (subTotalInclTax < decimal.Zero)
                subTotalInclTax = decimal.Zero;

            //We calculate discount amount on order subtotal excl tax (discount first)
            //calculate discount amount ('Applied to order subtotal' discount)
            List<Discount> subTotalDiscounts;
            var discountAmountExclTax = GetOrderSubtotalDiscount(customer, subTotalExclTax, out subTotalDiscounts);
            if (subTotalExclTax < discountAmountExclTax)
                discountAmountExclTax = subTotalExclTax;
            var discountAmountInclTax = discountAmountExclTax;

            //add tax for shopping items
            var tempTaxRates = new Dictionary<decimal, decimal>(subTotalTaxRates);
            foreach (var kvp in tempTaxRates)
            {
                if (kvp.Value != decimal.Zero && subTotalExclTax > decimal.Zero)
                {
                    var discountTaxValue = kvp.Value * (discountAmountExclTax / subTotalExclTax);
                    discountAmountInclTax += discountTaxValue;
                    subTotalTaxRates[kvp.Key] = kvp.Value - discountTaxValue;
                }
            }

            //rounding
            if (_shoppingCartSettings.RoundPricesDuringCalculation)
            {
                subTotalExclTax = RoundingHelper.RoundPrice(subTotalExclTax);
                subTotalInclTax = RoundingHelper.RoundPrice(subTotalInclTax);
                discountAmountExclTax = RoundingHelper.RoundPrice(discountAmountExclTax);
                discountAmountInclTax = RoundingHelper.RoundPrice(discountAmountInclTax);
            }

            updatedOrder.OrderSubtotalExclTax = subTotalExclTax;
            updatedOrder.OrderSubtotalInclTax = subTotalInclTax;
            updatedOrder.OrderSubTotalDiscountExclTax = discountAmountExclTax;
            updatedOrder.OrderSubTotalDiscountInclTax = discountAmountInclTax;

            foreach (var discount in subTotalDiscounts)
                if (!updateOrderParameters.AppliedDiscounts.ContainsDiscount(discount))
                    updateOrderParameters.AppliedDiscounts.Add(discount);

            #endregion

            #region Shipping

            var shippingTotalExclTax = decimal.Zero;
            var shippingTotalInclTax = decimal.Zero;
            var shippingTaxRate = decimal.Zero;

            if (restoredCart.RequiresShipping())
            {
                if (!IsFreeShipping(restoredCart, _shippingSettings.FreeShippingOverXIncludingTax ? subTotalInclTax : subTotalExclTax))
                {
                    var shippingTotal = decimal.Zero;
                    if (!string.IsNullOrEmpty(updatedOrder.ShippingRateComputationMethodSystemName))
                    {
                        //in the updated order were shipping items
                        if (updatedOrder.PickUpInStore)
                        {
                            //customer chose pickup in store method, try to get chosen pickup point
                            if (_shippingSettings.AllowPickUpInStore)
                            {
                                var pickupPointsResponse = _shippingService.GetPickupPoints(updatedOrder.BillingAddress,
                                    updatedOrder.ShippingRateComputationMethodSystemName, _storeContext.CurrentStore.Id);
                                if (pickupPointsResponse.Success)
                                {
                                    var selectedPickupPoint = pickupPointsResponse.PickupPoints.FirstOrDefault(point => updatedOrder.ShippingMethod.Contains(point.Name));
                                    if (selectedPickupPoint != null)
                                        shippingTotal = selectedPickupPoint.PickupFee;
                                    else
                                        updateOrderParameters.Warnings.Add(string.Format("Shipping method {0} could not be loaded", updatedOrder.ShippingMethod));
                                }
                                else
                                    updateOrderParameters.Warnings.AddRange(pickupPointsResponse.Errors);
                            }
                            else
                                updateOrderParameters.Warnings.Add("Pick up in store is not available");
                        }
                        else
                        {
                            //customer chose shipping to address, try to get chosen shipping option
                            var shippingOptionsResponse = _shippingService.GetShippingOptions(restoredCart,
                                updatedOrder.ShippingAddress, updatedOrder.ShippingRateComputationMethodSystemName, _storeContext.CurrentStore.Id);
                            if (shippingOptionsResponse.Success)
                            {
                                var shippingOption = shippingOptionsResponse.ShippingOptions.FirstOrDefault(option => updatedOrder.ShippingMethod.Contains(option.Name));
                                if (shippingOption != null)
                                    shippingTotal = shippingOption.Rate;
                                else
                                    updateOrderParameters.Warnings.Add(string.Format("Shipping method {0} could not be loaded", updatedOrder.ShippingMethod));
                            }
                            else
                                updateOrderParameters.Warnings.AddRange(shippingOptionsResponse.Errors);
                        }
                    }
                    else
                    {
                        //before updating order was without shipping
                        if (_shippingSettings.AllowPickUpInStore)
                        {
                            //try to get the cheapest pickup point
                            var pickupPointsResponse = _shippingService.GetPickupPoints(updatedOrder.BillingAddress, null, _storeContext.CurrentStore.Id);
                            if (pickupPointsResponse.Success)
                            {
                                updateOrderParameters.PickupPoint = pickupPointsResponse.PickupPoints.OrderBy(point => point.PickupFee).First();
                                shippingTotal = updateOrderParameters.PickupPoint.PickupFee;
                            }
                            else
                                updateOrderParameters.Warnings.AddRange(pickupPointsResponse.Errors);
                        }
                        else
                            updateOrderParameters.Warnings.Add("Pick up in store is not available");

                        if (updateOrderParameters.PickupPoint == null)
                        {
                            //or try to get the cheapest shipping option for the shipping to the customer address 
                            var shippingRateComputationMethods = _shippingService.LoadActiveShippingRateComputationMethods(_storeContext.CurrentStore.Id);
                            if (shippingRateComputationMethods.Any())
                            {
                                var shippingOptionsResponse = _shippingService.GetShippingOptions(restoredCart, customer.ShippingAddress, null, _storeContext.CurrentStore.Id);
                                if (shippingOptionsResponse.Success)
                                {
                                    var shippingOption = shippingOptionsResponse.ShippingOptions.OrderBy(option => option.Rate).First();
                                    updatedOrder.ShippingRateComputationMethodSystemName = shippingOption.ShippingRateComputationMethodSystemName;
                                    updatedOrder.ShippingMethod = shippingOption.Name;
                                    updatedOrder.ShippingAddress = (Address)customer.ShippingAddress.Clone();
                                    shippingTotal = shippingOption.Rate;
                                }
                                else
                                    updateOrderParameters.Warnings.AddRange(shippingOptionsResponse.Errors);
                            }
                            else
                                updateOrderParameters.Warnings.Add("Shipping rate computation method could not be loaded");
                        }
                    }

                    //additional shipping charge
                    shippingTotal += restoredCart.Where(item => item.IsShipEnabled && !item.IsFreeShipping).Sum(item => item.Product.AdditionalShippingCharge);

                    //shipping discounts
                    List<Discount> shippingTotalDiscounts;
                    shippingTotal -= GetShippingDiscount(customer, shippingTotal, out shippingTotalDiscounts);
                    if (shippingTotal < decimal.Zero)
                        shippingTotal = decimal.Zero;

                    shippingTotalExclTax = _taxService.GetShippingPrice(shippingTotal, false, customer);
                    shippingTotalInclTax = _taxService.GetShippingPrice(shippingTotal, true, customer, out shippingTaxRate);

                    //rounding
                    if (_shoppingCartSettings.RoundPricesDuringCalculation)
                    {
                        shippingTotalExclTax = RoundingHelper.RoundPrice(shippingTotalExclTax);
                        shippingTotalInclTax = RoundingHelper.RoundPrice(shippingTotalInclTax);
                    }

                    //change shipping status
                    if (updatedOrder.ShippingStatus == ShippingStatus.ShippingNotRequired || updatedOrder.ShippingStatus == ShippingStatus.NotYetShipped)
                        updatedOrder.ShippingStatus = ShippingStatus.NotYetShipped;
                    else
                        updatedOrder.ShippingStatus = ShippingStatus.PartiallyShipped;

                    foreach (var discount in shippingTotalDiscounts)
                        if (!updateOrderParameters.AppliedDiscounts.ContainsDiscount(discount))
                            updateOrderParameters.AppliedDiscounts.Add(discount);
                }
            }
            else
                updatedOrder.ShippingStatus = ShippingStatus.ShippingNotRequired;

            updatedOrder.OrderShippingExclTax = shippingTotalExclTax;
            updatedOrder.OrderShippingInclTax = shippingTotalInclTax;

            #endregion

            #region Tax rates

            var taxRates = new SortedDictionary<decimal, decimal>();

            //order subtotal taxes
            var subTotalTax = decimal.Zero;
            foreach (var kvp in subTotalTaxRates)
            {
                subTotalTax += kvp.Value;
                if (kvp.Key > decimal.Zero && kvp.Value > decimal.Zero)
                {
                    if (!taxRates.ContainsKey(kvp.Key))
                        taxRates.Add(kvp.Key, kvp.Value);
                    else
                        taxRates[kvp.Key] = taxRates[kvp.Key] + kvp.Value;
                }
            }

            //shipping taxes
            var shippingTax = decimal.Zero;
            if (_taxSettings.ShippingIsTaxable)
            {
                shippingTax = shippingTotalInclTax - shippingTotalExclTax;
                if (shippingTax < decimal.Zero)
                    shippingTax = decimal.Zero;

                if (shippingTaxRate > decimal.Zero && shippingTax > decimal.Zero)
                {
                    if (!taxRates.ContainsKey(shippingTaxRate))
                        taxRates.Add(shippingTaxRate, shippingTax);
                    else
                        taxRates[shippingTaxRate] = taxRates[shippingTaxRate] + shippingTax;
                }
            }

            //payment method additional fee tax
            var paymentMethodAdditionalFeeTax = decimal.Zero;
            if (_taxSettings.PaymentMethodAdditionalFeeIsTaxable)
            {
                paymentMethodAdditionalFeeTax = updatedOrder.PaymentMethodAdditionalFeeInclTax - updatedOrder.PaymentMethodAdditionalFeeExclTax;
                if (paymentMethodAdditionalFeeTax < decimal.Zero)
                    paymentMethodAdditionalFeeTax = decimal.Zero;

                if (updatedOrder.PaymentMethodAdditionalFeeExclTax > decimal.Zero)
                {
                    var paymentTaxRate = Math.Round(100 * paymentMethodAdditionalFeeTax / updatedOrder.PaymentMethodAdditionalFeeExclTax, 3);
                    if (paymentTaxRate > decimal.Zero && paymentMethodAdditionalFeeTax > decimal.Zero)
                    {
                        if (!taxRates.ContainsKey(paymentTaxRate))
                            taxRates.Add(paymentTaxRate, paymentMethodAdditionalFeeTax);
                        else
                            taxRates[paymentTaxRate] = taxRates[paymentTaxRate] + paymentMethodAdditionalFeeTax;
                    }
                }
            }

            //add at least one tax rate (0%)
            if (!taxRates.Any())
                taxRates.Add(decimal.Zero, decimal.Zero);

            //summarize taxes
            var taxTotal = subTotalTax + shippingTax + paymentMethodAdditionalFeeTax;
            if (taxTotal < decimal.Zero)
                taxTotal = decimal.Zero;

            //round tax
            if (_shoppingCartSettings.RoundPricesDuringCalculation)
                taxTotal = RoundingHelper.RoundPrice(taxTotal);

            updatedOrder.OrderTax = taxTotal;
            updatedOrder.TaxRates = taxRates.Aggregate(string.Empty, (current, next) =>
                string.Format("{0}{1}:{2};   ", current, next.Key.ToString(CultureInfo.InvariantCulture), next.Value.ToString(CultureInfo.InvariantCulture)));

            #endregion

            #region Total

            var total = (subTotalExclTax - discountAmountExclTax) + shippingTotalExclTax + updatedOrder.PaymentMethodAdditionalFeeExclTax + taxTotal;

            //get discounts for the order total
            List<Discount> orderAppliedDiscounts;
            var discountAmountTotal = GetOrderTotalDiscount(customer, total, out orderAppliedDiscounts);     
            if (total < discountAmountTotal)
                discountAmountTotal = total;
            total -= discountAmountTotal;

            //applied giftcards
            foreach (var giftCard in _giftCardService.GetAllGiftCards(usedWithOrderId: updatedOrder.Id))
            {
                if (total > decimal.Zero)
                {
                    var remainingAmount = giftCard.GiftCardUsageHistory.Where(history => history.UsedWithOrderId == updatedOrder.Id).Sum(history => history.UsedValue);
                    var amountCanBeUsed = total > remainingAmount ? remainingAmount : total;
                    total -= amountCanBeUsed;
                }
            }

            //reward points
            var rewardPointsOfOrder = _rewardPointService.GetRewardPointsHistory(customer.Id, true).FirstOrDefault(history => history.UsedWithOrder == updatedOrder);
            if (rewardPointsOfOrder != null)
            {
                var rewardPoints = -rewardPointsOfOrder.Points;
                var rewardPointsAmount = ConvertRewardPointsToAmount(rewardPoints);
                if (total < rewardPointsAmount)
                {
                    rewardPoints = ConvertAmountToRewardPoints(total);
                    rewardPointsAmount = total;
                }
                if (total > decimal.Zero)
                    total -= rewardPointsAmount;

                //uncomment here for the return unused reward points if new order total less redeemed reward points amount
                //if (rewardPoints < -rewardPointsOfOrder.Points)
                //    _rewardPointService.AddRewardPointsHistoryEntry(customer, -rewardPointsOfOrder.Points - rewardPoints, _storeContext.CurrentStore.Id, "Return unused reward points");

                if (rewardPointsAmount != rewardPointsOfOrder.UsedAmount)
                {
                    rewardPointsOfOrder.UsedAmount = rewardPointsAmount;
                    rewardPointsOfOrder.Points = -rewardPoints;
                    _rewardPointService.UpdateRewardPointsHistoryEntry(rewardPointsOfOrder);
                }
            }

            //rounding
            if (total < decimal.Zero)
                total = decimal.Zero;
            if (_shoppingCartSettings.RoundPricesDuringCalculation)
                total = RoundingHelper.RoundPrice(total);

            updatedOrder.OrderDiscount = discountAmountTotal;
            updatedOrder.OrderTotal = total;

            foreach (var discount in orderAppliedDiscounts)
                if (!updateOrderParameters.AppliedDiscounts.ContainsDiscount(discount))
                    updateOrderParameters.AppliedDiscounts.Add(discount);

            #endregion
        }
Exemplo n.º 41
0
        public async Task Execute(CancellationToken cancellationToken, IProgress <double> progress)
        {
            var databaseFileName = "/config/data/smart-inbox.db";

            this._logger.Info("Creating Database '{0}'...", databaseFileName);
            var sqLiteConnection   = new SQLiteConnection(new SQLitePlatformGeneric(), databaseFileName);
            var createTableCommand = sqLiteConnection.CreateCommand(
                @"CREATE TABLE IF NOT EXISTS [Movies] (
                            [Id] TEXT NOT NULL PRIMARY KEY,
                            [Name] TEXT NOT NULL,
                            [CommunityRating] FLOAT NULL,
                            [IsPlayed] BIT NOT NULL,
                            [IsDeleted] BIT NOT NULL,
                            [DateCreated] DATE NOT NULL,
                            [DateSynched] DATE NOT NULL
                        )");

            createTableCommand.ExecuteNonQuery();

            try
            {
                var createIndexCommand = sqLiteConnection.CreateCommand("CREATE INDEX \"Id_Idx\" ON \"Movies\" (\"Id\" ASC)");
                createIndexCommand.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                this._logger.Warn("Error creating index: {0}", e.Message);
            }

            var recursiveChildren = this._libraryManager.RootFolder.GetRecursiveChildren();

            if (recursiveChildren.Length == 0)
            {
                this._logger.Warn("UserRootFolder has no recursive children");

                return;
            }

            var baseItem = recursiveChildren[1];
            var query    = new InternalItemsQuery
            {
                MediaTypes = new[]
                {
                    MediaType.Video,
                },
            };

            var items = this._libraryManager.GetItemList(
                query,
                new[]
            {
                baseItem,
            }).OfType <Movie>().ToList();

            this._logger.Info("Computing genres...");
            var regex  = new Regex("(\\s+|-)", RegexOptions.Compiled);
            var genres = new SortedDictionary <string, string>();

            foreach (var currentItem in items)
            {
                foreach (var genre in currentItem.Genres)
                {
                    var trimmedGenre      = genre.Trim();
                    var trimmedGenreLower = trimmedGenre.ToLowerInvariant();
                    if (!genres.ContainsKey(trimmedGenreLower))
                    {
                        var fieldName = "Is" + regex.Replace(trimmedGenre, string.Empty);
                        genres[trimmedGenreLower] = fieldName;
                    }
                }
            }

            this._logger.Info("Computed genres");

            var schemaQueryCommand = sqLiteConnection.CreateCommand("SELECT * FROM [Movies] LIMIT 1");
            var commandResult      = schemaQueryCommand.ExecuteDeferredQuery();
            var columnNames        = commandResult.ColumnNames.ToList();

            this._logger.Info("Updating table '{0}' schema ...", "Movies");

            foreach (var genre in genres)
            {
                var fieldName = genre.Value;
                if (!columnNames.Contains(fieldName, StringComparer.InvariantCultureIgnoreCase))
                {
                    var alterTableCommand = sqLiteConnection.CreateCommand(
                        $@"ALTER TABLE [Movies]
                    ADD [{fieldName}] BIT NOT NULL default 0");
                    try
                    {
                        alterTableCommand.ExecuteNonQuery();
                    }
                    catch (SQLiteException e)
                    {
                        this._logger.ErrorException("Error altering [Movies] table", e);
                    }
                }
            }

            this._logger.Info("Updated table '{0}' schema", "Movies");

            var user = this._userManager.GetUserList(
                new UserQuery
            {
                IsDisabled = false,
            }).FirstOrDefault();


            this._logger.Info("Updating table '{0}'...", "Movies");

            var beginCommand = sqLiteConnection.CreateCommand("BEGIN");

            beginCommand.ExecuteNonQuery();

            var datedSynched = DateTime.Now;

            for (var index = 0; index < items.Count; index++)
            {
                progress.Report(index * 100.0d / (2 * items.Count));

                var currentItem = items[index];
                var key         = string.Empty;
                foreach (var currentItemProviderId in currentItem.ProviderIds.OrderBy(pair => pair.Key))
                {
                    key += currentItemProviderId.Key + "=" + currentItemProviderId.Value + "|";
                }

                key = key.TrimEnd('|');

                if (!string.IsNullOrWhiteSpace(key))
                {
                    if (currentItem.CommunityRating != null)
                    {
                        var genreColumns = string.Empty;
                        var genreValues  = string.Empty;

                        genreColumns = genres.Aggregate(genreColumns, (current, genre) => current + genre.Value + ", ")
                                       .TrimEnd(',', ' ');
                        genreValues = genres.Aggregate(
                            genreValues,
                            (current, genre) =>
                            current + (Array.FindIndex(
                                           currentItem.Genres,
                                           g => g.Trim().ToLowerInvariant() == genre.Key) != -1
                                               ? "1"
                                               : "0") + ", ").TrimEnd(',', ' ');

                        var dateCreated = currentItem.DateCreated.DateTime;
                        if (currentItem.DateCreated < currentItem.DateModified)
                        {
                            dateCreated = currentItem.DateModified.DateTime;
                        }

                        var updateCommandText =
                            $"INSERT OR REPLACE INTO Movies(Id, Name, CommunityRating, IsPlayed, IsDeleted, DateCreated, DateSynched, {genreColumns}) Values(?, ?, ?, ?, ?, ?, ?, {genreValues})";

                        var updateCommand = sqLiteConnection.CreateCommand(
                            updateCommandText,
                            key,
                            currentItem.Name,
                            currentItem.CommunityRating,
                            currentItem.IsPlayed(user),
                            false,
                            dateCreated.ToString("yyyy-MM-dd HH:mm:ss"),
                            datedSynched.ToString("yyyy-MM-dd HH:mm:ss"));

                        updateCommand.ExecuteNonQuery();
                    }
                }
            }

            var endCommand = sqLiteConnection.CreateCommand("END");

            endCommand.ExecuteNonQuery();


            this._logger.Info("Synchronizing deleted items ...", null);
            var updateDeletedCommand = sqLiteConnection.CreateCommand(
                @"UPDATE Movies SET IsDeleted = true WHERE DateSynched <> ?",
                datedSynched.ToString("yyyy-MM-dd HH:mm:ss"));

            updateDeletedCommand.ExecuteNonQuery();

            var smartEmbyUrl = Environment.GetEnvironmentVariable("SMART_EMBY_SERVER_URL");

            this._logger.Info("Uploading File in Smart Emby server '{0}'....", smartEmbyUrl);
            var form        = new MultipartFormDataContent();
            var fileContent = new ByteArrayContent(File.ReadAllBytes(databaseFileName));

            fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
            form.Add(fileContent, "file", Path.GetFileName(databaseFileName));
            var httpClient = new HttpClient();
            var maxEpoch   = Environment.GetEnvironmentVariable("SMART_EMBY_MAX_EPOCHS");

            if (!int.TryParse(maxEpoch, out _))
            {
                maxEpoch = "500";
            }

            var maxEpochWithNoImprovement = Environment.GetEnvironmentVariable("SMART_EMBY_MAX_EPOCHS_WITH_NO_IMPROVEMENT");

            if (!int.TryParse(maxEpochWithNoImprovement, out _))
            {
                maxEpochWithNoImprovement = "20";
            }

            var newMoviesCount = Environment.GetEnvironmentVariable("SMART_EMBY_NEW_MOVIES_COUNT");

            if (!int.TryParse(newMoviesCount, out _))
            {
                newMoviesCount = "50";
            }

            var oldMoviesToTreatAsNew = Environment.GetEnvironmentVariable("SMART_EMBY_OLD_MOVIES_TO_TREAT_AS_NEW");

            if (!int.TryParse(oldMoviesToTreatAsNew, out var oldMoviesToTreatAsNewInt))
            {
                oldMoviesToTreatAsNew = Math.Truncate(oldMoviesToTreatAsNewInt * 0.10f).ToString(CultureInfo.InvariantCulture);
            }

            var uri      = $"{smartEmbyUrl}/api/smartinbox/train?maxEpochs={maxEpoch}&maxEpochsWithNoImprovement={maxEpochWithNoImprovement}&newMoviesCount={newMoviesCount}&oldMoviesToTreatAsNew={oldMoviesToTreatAsNew}";
            var response = await httpClient.PostAsync(uri, form, cancellationToken);

            var trainingId = this._jsonSerializer.DeserializeFromString <Guid>(await response.Content.ReadAsStringAsync());

            var streamWriter = new StreamWriter(File.OpenWrite("/config/plugins/SmartInbox.Emby.tid"));
            await streamWriter.WriteLineAsync(trainingId.ToString());

            await streamWriter.FlushAsync();

            streamWriter.Close();

            this._logger.Info("Saved Training Id '{trainingId}'", trainingId);

            progress.Report(75);
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var recommendationsResponse = await httpClient.GetAsync($"{smartEmbyUrl}/api/smartinbox/recommendations?id=" + trainingId, cancellationToken);

                    recommendationsResponse.EnsureSuccessStatusCode();
                    progress.Report(100);
                    return;
                }
                catch (Exception ex)
                {
                    this._logger.Warn("Recommendations for training '{trainingId}' are not available yet.", ex.Message);
                }
            }
        }
Exemplo n.º 42
0
 private string GetCurrentControlsCode()
 {
     return(_activeButtonsList.Aggregate(string.Empty, (current, bl) => current + (bl.Value ? "1" : "0")));
 }