/// <summary>
        /// Generate default configurations for the filter.
        /// </summary>
        /// <returns>Dictionary used to pass configuration though the 
        /// configs parameter of the method ApplyFilter. 
        /// null if there is the filter doesn't use configurations.</returns>
        public override SortedDictionary<string, object> GetDefaultConfigs()
        {
            SortedDictionary<string, object> ret = new SortedDictionary<string, object>();

            // Add configs from Gaussian
            SortedDictionary<string, object> tmp_conf = g.GetDefaultConfigs();
            if (null != tmp_conf)
            {
                foreach (KeyValuePair<string, object> item in tmp_conf)
                {
                    ret.Add(item.Key, item.Value);
                }
            }

            // Add configs from Laplacian of Gauss
            tmp_conf = logauss.GetDefaultConfigs();
            if (null != tmp_conf)
            {
                foreach (KeyValuePair<string, object> item in tmp_conf)
                {
                    if (!ret.ContainsKey(item.Key))
                    {
                        ret.Add(item.Key, item.Value);
                    }
                }
            }

            return ret;
        }
示例#2
0
        public long Solve()
        {
            var primes = new Prime((int)DivisoNumbers);

            var sortedPrimes = new SortedDictionary<long, PrimeDivisors>();
            foreach (var prime in primes.PrimeList)
            {
                sortedPrimes.Add(prime, new PrimeDivisors(prime));
            }

            while (true)
            {
                var minkey = sortedPrimes.Keys.First();
                var maxKey = sortedPrimes.Keys.Last();

                var minValue = sortedPrimes[minkey];

                var newKey = minkey * minkey;
                if (newKey > maxKey)
                {
                    break;
                }
                sortedPrimes.Add(newKey, minValue.UpdatePower());

                sortedPrimes.Remove(minkey);
                sortedPrimes.Remove(maxKey);
            }

            return sortedPrimes.Select(
                primeDivisorse => (long)Math.Pow(primeDivisorse.Value.Prime, primeDivisorse.Value.Power) % Modulo
            ).Aggregate(
                1L, (current, coefficient) => (current * coefficient) % Modulo
            );
        }
示例#3
0
        /// <summary>
        /// Finds the all the types that implement or inherit from the baseType.  
        /// </summary>
        /// <param name="baseType">base type.</param>
        /// <param name="includeBaseType">if set to <c>true</c> the base type will be included in the result</param>
        /// <returns></returns>
        public static SortedDictionary<string, Type> FindTypes( Type baseType, bool includeBaseType )
        {
            SortedDictionary<string, Type> types = new SortedDictionary<string, Type>();

            if ( includeBaseType )
                types.Add( ClassName( baseType ), baseType );

            Assembly executingAssembly = Assembly.GetExecutingAssembly();
            FileInfo executingFile = new FileInfo( executingAssembly.Location );

            Dictionary<string, Assembly> assemblies = new Dictionary<string, Assembly>();
            assemblies.Add( executingAssembly.Location.ToLower(), executingAssembly );

            foreach ( Assembly assembly in AppDomain.CurrentDomain.GetAssemblies() )
                if ( assembly.FullName.StartsWith( "Rock" ) && !assemblies.Keys.Contains( assembly.Location  ) )
                    assemblies.Add( assembly.FullName.ToLower(), assembly );

            foreach ( FileInfo fileInfo in executingFile.Directory.GetFiles( "rock.*.dll" ) )
                if ( !assemblies.Keys.Contains( fileInfo.FullName.ToLower() ) )
                {
                    Assembly fileAssembly = Assembly.LoadFrom( fileInfo.FullName );
                    assemblies.Add( fileInfo.FullName.ToLower(), fileAssembly );
                }

            foreach ( KeyValuePair<string, Assembly> assemblyEntry in assemblies )
                foreach ( KeyValuePair<string, Type> typeEntry in SearchAssembly( assemblyEntry.Value, baseType ) )
                    if (!types.Keys.Contains(typeEntry.Key))
                        types.Add( typeEntry.Key, typeEntry.Value );

            return types;
        }
示例#4
0
 private void chooseBttn_Click(object sender, EventArgs e)
 {
     fileDialog.ShowDialog();
     fileBox.Text = fileDialog.FileName;
     string content = "";
     content = Program.ExtractTextFromPdf(fileDialog.FileName);
     var numtype = new Regex(@"\(\d{4,6}\/2015\)\s+([\d]). mell", RegexOptions.Multiline);
     var eur = new Regex(@"\(\d{4,6}\/2015\)\s+EUR", RegexOptions.Multiline);
     var dict = new SortedDictionary<string, int>();
     dict.Add("total", 0);
     foreach (Match item in numtype.Matches(content))
     {
         string key = item.Groups[1].Value;
         if (!dict.ContainsKey(key)) dict.Add(key, 0);
         dict[key]++;
         dict["total"]++;
     }
     dict.Add("eur", 0);
     foreach (Match item in eur.Matches(content))
     {
         dict["eur"]++;
         dict["total"]++;
     }
     int total = 0;
     foreach (KeyValuePair<string, int> item in dict)
     {
         dataView.Rows.Add(new string[] { item.Key, item.Value.ToString() });
     }
 }
示例#5
0
        private static void TitleFillUp()
        {
            System.IO.StreamReader files = new System.IO.StreamReader(@"../../CodeResources/Files.txt");
            System.IO.StreamReader dependences = new System.IO.StreamReader(@"../../CodeResources/Dependences.txt");

            SortedDictionary<string, Node> independedFolders = new SortedDictionary<string, Node>();
            independedFolders.Add("TASKS_EXPLORER\n", new Node("TASKS_EXPLORER\n"));

            while (!files.EndOfStream) {
                string file = files.ReadLine();
                independedFolders.Add(file, new Node(file));
            }

            while (!dependences.EndOfStream) {
                string inp = dependences.ReadLine();
                inp = Regex.Replace(inp, @"\s+", " ");
                inp = Regex.Replace(inp, @"\\n+", "\n");
                string[] edge = inp.Split(' ');
                independedFolders[edge[0]].children.Add(independedFolders[edge[1]]);
                independedFolders[edge[0]].children[independedFolders[edge[0]].children.Count - 1].number = independedFolders[edge[0]].children.Count - 1;
                independedFolders[edge[0]].children[independedFolders[edge[0]].children.Count - 1].parent = independedFolders[edge[0]];
            }

            folders = independedFolders["TASKS_EXPLORER\n"];

            files.Close();
            dependences.Close();
        }
示例#6
0
		public List<License> GetLast10Licenses()
		{
			var newLics = (from l in _licensesRepository.GetAllLicenses()
										 where l.UpdatedOn == null
										 orderby l.CreatedOn descending
										 select l).ToList();


			var updatedLics = (from l in _licensesRepository.GetAllLicenses()
												 where l.UpdatedOn != null
												 orderby l.UpdatedOn descending
												 select l).ToList();

			SortedDictionary<DateTime, License> sortedLics = new SortedDictionary<DateTime, License>();

			foreach (var lic in newLics)
			{
				sortedLics.Add(lic.CreatedOn, lic);
			}

			foreach (var lic in updatedLics)
			{
				sortedLics.Add(lic.UpdatedOn.Value, lic);
			}

			return sortedLics.Take(8).Select(x => x.Value).ToList();
		}
示例#7
0
        public SortedDictionary<string, string> GetRequestParameters()
        {
            int i = 0;
            SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
            try
            {
                NameValueCollection coll;
                //Load Form variables into NameValueCollection variable.
                coll = request.QueryString;

                // Get names of all forms into a string array.
                String[] requestItem = coll.AllKeys;

                for (i = 0; i < requestItem.Length; i++)
                {
                    sArray.Add(requestItem[i], request[requestItem[i]]);
                }

                string[] formKeys = request.Form.AllKeys;
                if (formKeys != null)
                {
                    for (int j = 0; j < formKeys.Length; j++)
                    {
                        sArray.Add(formKeys[j], request[formKeys[j]]);
                    }
                }
            }
            catch(Exception ex)
            {
                logger.Error(ex);
            }

            return sArray;
        }
示例#8
0
        protected AbstractClassifier(/*IDictionary<string,object> prms=null*/)
        {
            Prms = new SortedDictionary<string, object>();
            //foreach (var p in prms.Keys)
            //    Prms.Add(p, prms[p]);

            string trp = ConfigReader.Read("TrainPath");
            if (trp != null) TrainPath = trp;
            Prms.Add("TrainPath", TrainPath);

            string tsp = ConfigReader.Read("TestPath");
            if (tsp != null) TestPath = tsp;
            Prms.Add("TestPath", TestPath);

            string tn = ConfigReader.Read("TargetName");
            if (tn != null) TargetName = tn;
            Prms.Add("TargetName", TargetName);

            string inm = ConfigReader.Read("IdName");
            if (inm != null) IdName = inm;
            Prms.Add("IdName", IdName);

            string isp = ConfigReader.Read("IsParallel");
            if (isp != null) IsParallel = bool.Parse(isp);
            Prms.Add("IsParallel", IsParallel);
        }
示例#9
0
        private static void KwayMerge(IEnumerable<string> chunkFilePaths, string resultFilePath)
        {
            var chunkReaders = chunkFilePaths
                .Select(path => new StreamReader(path))
                .Where(chunkReader => !chunkReader.EndOfStream)
                .ToList();

            var sortedDict = new SortedDictionary<string, TextReader>();
            chunkReaders.ForEach(chunkReader => sortedDict.Add(chunkReader.ReadLine(), chunkReader));

            using (var resultWriter = new StreamWriter(resultFilePath, false))
                while (sortedDict.Any())
                {
                    var line = sortedDict.Keys.First();
                    var chunkReader = sortedDict[line];
                    sortedDict.Remove(line);

                    resultWriter.WriteLine(line);

                    var nextLine = chunkReader.ReadLine();
                    if (nextLine != null)
                    {
                        sortedDict.Add(nextLine, chunkReader);
                    }
                    else
                    {
                        chunkReader.Dispose();
                    }
                }
        }
示例#10
0
        //Build double array trie-tree from text file
        //strTextFileName: raw text file name used to build DA trie-tree
        //  text file format: key \t value
        //  key as string type
        //  value as non-netgive integer
        //strDAFileName: double array trie-tree binary file name built from strTextFileName
        private static void Build(string strTextFileName, string strDAFileName)
        {
            StreamReader sr = new StreamReader(strTextFileName);
            //Load raw data from text file and sort them as ordinal
            SortedDictionary<string, int> sdict = new SortedDictionary<string, int>(StringComparer.Ordinal);
            Console.WriteLine("Loading key value pairs from raw text file and sort them...");
            while (sr.EndOfStream == false)
            {
                string strLine = sr.ReadLine();
                if (strLine.Length == 0)
                {
                    continue;
                }

                string[] items = strLine.Split('\t');
                sdict.Add(items[0], int.Parse(items[1]));
            }

            //test case for SearchAsKeyPrefix and SearchByPrefix
            sdict.Add("TestSearchPrefix_case0", 1234567);
            sdict.Add("TestSearchPrefix_case01", 2345678);
            sdict.Add("TestSearchPrefix_case012", 3456789);

            DoubleArrayTrieBuilder dab = new DoubleArrayTrieBuilder(4);
            Console.WriteLine("Begin to build double array trie-tree...");
            dab.build(sdict);
            dab.save(strDAFileName);
            Console.WriteLine("Done!");
        }
        private static void Main()
        {
            string readLine = Console.ReadLine();
            SortedDictionary<char, int> countsOfChars = new SortedDictionary<char, int>();
            int count = 1;

            for (int i = 0; i < readLine.Length; i++)
            {
                if (countsOfChars.ContainsKey(readLine[i]))
                {
                    int value = countsOfChars[readLine[i]];
                    countsOfChars.Remove(readLine[i]);
                    countsOfChars.Add(readLine[i], count + value);
                }
                else
                {
                    countsOfChars.Add(readLine[i], count);
                }
            }

            foreach (KeyValuePair<char, int> p in countsOfChars)
            {
                Console.WriteLine("{0}: {1} time/s", p.Key, p.Value);
            }
        }
示例#12
0
        protected virtual SortedDictionary<decimal, decimal> ParseTaxRates(string taxRatesStr)
        {
            var taxRatesDictionary = new SortedDictionary<decimal, decimal>();
            if (String.IsNullOrEmpty(taxRatesStr))
                return taxRatesDictionary;

            string[] lines = taxRatesStr.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string line in lines)
            {
                if (String.IsNullOrEmpty(line.Trim()))
                    continue;

                string[] taxes = line.Split(new [] { ':' });
                if (taxes.Length == 2)
                {
                    try
                    {
                        decimal taxRate = decimal.Parse(taxes[0].Trim(), CultureInfo.InvariantCulture);
                        decimal taxValue = decimal.Parse(taxes[1].Trim(), CultureInfo.InvariantCulture);
                        taxRatesDictionary.Add(taxRate, taxValue);
                    }
                    catch (Exception exc)
                    {
                        Debug.WriteLine(exc.ToString());
                    }
                }
            }

            //add at least one tax rate (0%)
            if (taxRatesDictionary.Count == 0)
                taxRatesDictionary.Add(decimal.Zero, decimal.Zero);

            return taxRatesDictionary;
        }
示例#13
0
        public MainGame(Game1 theGame)
            : base("background", 1.0f)
        {
            LABELWIDTH = SEC1WIDTH / 2 - MARGIN;
            CARDWIDTH = (Game1.WIDTH - 8 * (MARGIN * 2) - 30) / MAXHANDSIZE;
            CARDHEIGHT = (int) (CARDWIDTH * 1.612);
            LABELLENGTH = (SEC1WIDTH - MARGIN) / 5;
            RESOURCELENGTH = (SEC1WIDTH - 3 * MARGIN) * 4 / 5;
            player = null;
            wonder = null;
            lastPlayed = new Dictionary<string, Visual>();
            hand = new SortedDictionary<string, Visual>();
            leftButton = new Button(new Vector2(Game1.WIDTH - 27, 200 + CARDHEIGHT / 2 - 7), 15, 15, "", "Font1", "left");
            leftButton.z = 1;
            hand.Add("paperleft", new Visual(new Vector2(Game1.WIDTH - 27, 190), 30, CARDHEIGHT + 30, "paperleft"));
            hand.Add("leftButton", leftButton.setBorder(false));

            close = new Button(new Vector2(Game1.WIDTH - Game1.WIDTH / 9, Game1.HEIGHT * 5/ 8), 75, 40, "Close", "Font1");

            lastPlayed.Add("bg", new Visual(new Vector2(Game1.WIDTH / 3, Game1.HEIGHT / 6), Game1.WIDTH * 2 / 3, Game1.HEIGHT * 2 / 3, "bg"));
            lastPlayed.Add("close", close);

            seatVisuals = new Dictionary<int, Dictionary<string, Visual>>();
            baseVisuals = new Dictionary<String, Visual>();
            baseVisuals.Add("Label1", new Visual(new Vector2(MARGIN, MARGIN), LABELWIDTH, LABELHEIGHT, "Players", "Font1", null, Color.Gray, "grayback"));
            baseVisuals.Add("Label2", new Visual(new Vector2(MARGIN + LABELWIDTH, MARGIN), LABELWIDTH, LABELHEIGHT, "icons"));
            baseVisuals.Add("Divider1", new Visual(new Vector2(SEC1WIDTH - 1, 0), DIVIDERWIDTH, Game1.HEIGHT, "line", Color.Silver));
            baseVisuals.Add("Divider2", new Visual(new Vector2(0, SEC1HEIGHT - 1), Game1.WIDTH, DIVIDERWIDTH, "line", Color.Silver));
            baseVisuals.Add("Age", new Visual(new Vector2(Game1.WIDTH - MARGIN - 75, MARGIN), 75, 75, "age1"));
            baseVisuals.Add("discard", new Visual(new Vector2(Game1.WIDTH - MARGIN - 60, MARGIN * 3 + 120), 60, 60, "0", "Font1", null, Color.White, "deck"));
            baseVisuals["discard"].setLeftMargin(15);
            baseVisuals["discard"].setTopMargin(9);
        }
 public void TestNumbersOrWords()
 {
     IDictionary<Int64, String> euroCities = new SortedDictionary<Int64, String>();
     euroCities.Add(2, "Oslo");
     euroCities.Add(4, "Helsinki");
     euroCities.Add(8, "Lisbon");
     euroCities.Add(16, "Dubrovnik");
     FizzBuzz fizzbuzz = new FizzBuzz(300, euroCities);
     IEnumerable<String> results = from fb in fizzbuzz select fb;
     long index = 1;
     foreach (String r in results)
     {
         try
         {
             // odds should be a number
             Int64 i64 = Convert.ToInt64(r);
             Assert.AreNotEqual(0, index % 2);
         }
         catch (FormatException)
         {
             // evens will be a city and throw an exception based on number conversion
             Assert.AreEqual(0, index % 2);
         }
         finally
         {
             index++;
         }
     }
 }
示例#15
0
        public static bool FollowAccount(string AccessToken,string AccessTokenSecret ,string Screen_name, string user_id) 
        {
            bool IsFollowed = false;
            oAuthTwitter oauth = new oAuthTwitter();

            oauth.AccessToken = AccessToken;
            oauth.AccessTokenSecret = AccessTokenSecret;
            oauth.ConsumerKey = ConfigurationManager.AppSettings["consumerKey"];
            oauth.ConsumerKeySecret = ConfigurationManager.AppSettings["consumerSecret"];
            string RequestUrl = "https://api.twitter.com/1.1/friendships/create.json";
            SortedDictionary<string, string> strdic = new SortedDictionary<string, string>();
            if (!string.IsNullOrEmpty(Screen_name)) 
            {
                strdic.Add("screen_name", Screen_name);
            }
            else if (!string.IsNullOrEmpty(user_id))
            {
                strdic.Add("user_id", user_id);
            }
            else 
            {
                return false;
            }
            strdic.Add("follow", "true");
            string response = oauth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic);
            if (!string.IsNullOrEmpty(response)) 
            {
                IsFollowed = true;
            }
            return IsFollowed;
        }
示例#16
0
		/// <summary>
		/// Returns an immutable case-insensitive map from canonical names to
		/// <code>Charset</code>
		/// instances.
		/// If multiple charsets have the same canonical name, it is unspecified which is returned in
		/// the map. This method may be slow. If you know which charset you're looking for, use
		/// <see cref="forName(string)">forName(string)</see>
		/// .
		/// </summary>
		/// <returns>
		/// an immutable case-insensitive map from canonical names to
		/// <code>Charset</code>
		/// instances
		/// </returns>
		public static SortedDictionary<string, Charset> availableCharsets ()
		{
			SortedDictionary<string, Charset> charsets = new SortedDictionary<string, Charset> ();
			charsets.Add (utf8.Name, utf8);
			charsets.Add (ascii.Name, ascii);
			return charsets;
		}
        private string GenerateAuthHeader(OAuthState oAuthState, HttpRequestMessage request)
        {
            SortedDictionary<string, string> sortedDictionary = new SortedDictionary<string, string>();
            sortedDictionary.Add(Constants.OAuthNonce, OAuthUtil.PercentEncode(oAuthState.Nonce));
            sortedDictionary.Add(Constants.OAuthSignatureMethod, OAuthUtil.PercentEncode(oAuthState.SignatureMethod));
            sortedDictionary.Add(Constants.OAuthTimestamp, OAuthUtil.PercentEncode(oAuthState.Timestamp));
            sortedDictionary.Add(Constants.OAuthConsumerKey, OAuthUtil.PercentEncode(oAuthState.Credential.ConsumerKey));
            sortedDictionary.Add(Constants.OAuthVersion, OAuthUtil.PercentEncode(oAuthState.Version));

            if (!string.IsNullOrEmpty(_oAuthState.Credential.Token))
                sortedDictionary.Add(Constants.OAuthToken, OAuthUtil.PercentEncode(oAuthState.Credential.Token));

            //don't encode it here again.
            //we already did that and this auth header field doesn't require it to be encoded twice
            if (!string.IsNullOrEmpty(_oAuthState.Credential.CallbackUrl))
                sortedDictionary.Add(Constants.OAuthCallback, oAuthState.Credential.CallbackUrl);

            StringBuilder strBuilder = new StringBuilder();
            var valueFormat = "{0}=\"{1}\",";

            sortedDictionary.ForEach(x => {
                strBuilder.AppendFormat(valueFormat, x.Key, x.Value);
            });

            //oAuth parameters has to be sorted before sending, but signature has to be at the end of the authorization request
            //http://stackoverflow.com/questions/5591240/acquire-twitter-request-token-failed
            strBuilder.AppendFormat(valueFormat, Constants.OAuthSignature, OAuthUtil.PercentEncode(GenerateSignature(oAuthState, request)));

            return strBuilder.ToString().TrimEnd(',');
        }
示例#18
0
        // Use the standard root node to get a list of locales available.
        public static SortedDictionary<string, string> GetLocales()
        {
            SortedDictionary<string, string> locales = new SortedDictionary<string, string>();
            getContentRequest request = new getContentRequest();
            ContentService proxy = new ContentService();
            getContentResponse response;

            request.contentIdentifier = rootContentItem.contentId;
            request.locale = "en-US"; // Now required otherwise an exception.

            try
            {
                response = proxy.GetContent(request);
            }
            catch
            {
                locales.Add("English (United States)", "en-us");
                return locales;
            }

            foreach (availableVersionAndLocale av in response.availableVersionsAndLocales)
            {
                // Use the DisplayName as the key instead of the locale because
                // that's how we want the collection sorted.
                string displayName = new CultureInfo(av.locale).DisplayName;

                if (locales.ContainsKey(displayName) == false)
                    locales.Add(displayName, av.locale.ToLower());

            }

            return locales;
        }
示例#19
0
        public ActionResult AlipayUrl()
        {
            var shop = YunShop.Web.CommonMethod.GetSeoInfo();
            string partners = "";
            string return_url = "";
            try
            {
                partners = shop.FirstOrDefault(e => e.Key == "alipaykey").Value;
                if (string.IsNullOrWhiteSpace(shop.FirstOrDefault(e => e.Key == "alipayvalue").Value))
                {
                    return Json(false);
                }
                return_url = shop.FirstOrDefault(e => e.Key == "alipayurl").Value;
            }
            catch
            {
                return Json(false);
            }
            string target_service = "user.auth.quick.login";
            //必填
            //必填,页面跳转同步通知页面路径
            //需http://格式的完整路径,不允许加?id=123这类自定义参数

            //把请求参数打包成数组
            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
            sParaTemp.Add("partner", partners);
            sParaTemp.Add("_input_charset", Config.Input_charset.ToLower());
            sParaTemp.Add("service", "alipay.auth.authorize");
            sParaTemp.Add("target_service", target_service);
            sParaTemp.Add("return_url", return_url);
            //建立请求
            return Json(Submit.BuildRequestUrl(sParaTemp, shop.FirstOrDefault(e => e.Key == "alipayvalue").Value));
        }
示例#20
0
        private static void Main()
        {
            Queue<string> grad = new Queue<string>();
            SortedDictionary<string, string> venueAndEvent = new SortedDictionary<string, string>();

            while (true)
            {
                string[] readLineComand = Console.ReadLine().Split(';').ToArray();
                if (readLineComand[0] == "END")
                {
                    for (int i = 0; i < grad.Count; i++)
                    {
                        Console.WriteLine(grad.Peek());
                        foreach (KeyValuePair<string, string> p in venueAndEvent)
                        {
                            Console.WriteLine("->{0}: {1}", p.Key, p.Value);
                        }
                    }
                    return;
                }

                if (venueAndEvent.ContainsKey(readLineComand[1]))
                {
                    string value = venueAndEvent[readLineComand[1]];
                    venueAndEvent.Remove(readLineComand[1]);
                    venueAndEvent.Add(readLineComand[1], value + value);
                }
                else if (true)
                {
                    grad.Enqueue(readLineComand[0]);
                    venueAndEvent.Add(readLineComand[1], readLineComand[2]);
                }
            }
        }
示例#21
0
        public static void Init()
        {
            entries = new SortedDictionary<string, Stream>();
            string[] archives = Directory.GetFiles(Directory.GetCurrentDirectory(),"*.big",SearchOption.AllDirectories);

            foreach (var archive in archives)
            {
                var content = Loaders.BigArchive.GetEntries(archive);
                foreach (var c in content)
                {
                    if (!entries.ContainsKey(c.Key))
                        entries.Add(c.Key, c.Value);
                }
            }

            string[] files = Directory.GetFiles(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories);
            foreach (var f in files)
            {
                if (Path.GetExtension(f)!=".big")
                {
                    var relPath = f.Replace(Directory.GetCurrentDirectory(), "").TrimStart('\\');
                    if (!entries.ContainsKey(relPath))
                        entries.Add(relPath, null);
                }
            }
        }
示例#22
0
    protected void BtnAlipay_Click(object sender, EventArgs e)
    {
        ////////////////////////////////////////////请求参数////////////////////////////////////////////

        //服务器异步通知页面路径
        string notify_url = "http://www.xxx.com/alipay.trade.direct.forcard.pay-CSHARP-UTF-8/notify_url.aspx";
        //需http://格式的完整路径,不允许加?id=123这类自定义参数
        //页面跳转同步通知页面路径
        string return_url = "http://www.xxx.com/alipay.trade.direct.forcard.pay-CSHARP-UTF-8/return_url.aspx";
        //需http://格式的完整路径,不允许加?id=123这类自定义参数
        //商户订单号
        string out_trade_no = WIDout_trade_no.Text.Trim();
        //必填
        //订单名称
        string subject = WIDsubject.Text.Trim();
        //可填
        //默认网银
        string default_bank = WIDdefault_bank.Text.Trim();
        //必填,如果要使用外卡支付功能,本参数需赋值为“12.5 银行列表”中的值
        //公用业务扩展参数
        string extend_param = WIDextend_param.Text.Trim();
        //必填,用于商户的特定业务信息的传递
        //卖家支付宝账号
        string seller_logon_id = WIDseller_logon_id.Text.Trim();
        //必填
        //付款金额
        string total_fee = WIDtotal_fee.Text.Trim();
        //必填
        //订单描述
        string body = WIDbody.Text.Trim();
        //商品展示地址
        string show_url = WIDshow_url.Text.Trim();
        //币种
        string currency = WIDcurrency.Text.Trim();
        //必填,default_bank为boc-visa或boc-master时,支持USD,为boc-jcb时,不支持currency参数,即默认支持RMB

        ////////////////////////////////////////////////////////////////////////////////////////////////

        //把请求参数打包成数组
        SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
        sParaTemp.Add("partner", Config.Partner);
        sParaTemp.Add("_input_charset", Config.Input_charset.ToLower());
        sParaTemp.Add("service", "alipay.trade.direct.forcard.pay");
        sParaTemp.Add("notify_url", notify_url);
        sParaTemp.Add("return_url", return_url);
        sParaTemp.Add("out_trade_no", out_trade_no);
        sParaTemp.Add("subject", subject);
        sParaTemp.Add("default_bank", default_bank);
        sParaTemp.Add("extend_param", extend_param);
        sParaTemp.Add("seller_logon_id", seller_logon_id);
        sParaTemp.Add("total_fee", total_fee);
        sParaTemp.Add("body", body);
        sParaTemp.Add("show_url", show_url);
        sParaTemp.Add("currency", currency);

        //建立请求
        string sHtmlText = Submit.BuildRequest(sParaTemp, "get", "确认");
        Response.Write(sHtmlText);
    }
示例#23
0
 public SortedDictionary<string, string> GetRequestParam(string qrcode)
 {
     SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
     sParaTemp.Add("content", qrcode);
     sParaTemp.Add("guard", Config.termId);
     sParaTemp.Add("app", Config.App);
     return sParaTemp;
 }
示例#24
0
        protected String BtnAlipay_Click(string Subject, string Body, string Price)
        {
            ////////////////////////////////////////////请求参数////////////////////////////////////////////

                //必填参数//

                string out_trade_no = DateTimeOffset.Now.ToString("yyyyMMddHHmmss");  //请与贵网站订单系统中的唯一订单号匹配
                string subject = Subject;//Request.Form["TxtSubject"];                    //订单名称,显示在支付宝收银台里的“商品名称”里,显示在支付宝的交易管理的“商品名称”的列表里。
                string body = Body;//Request.Form["TxtBody"];                          //订单描述、订单详细、订单备注,显示在支付宝收银台里的“商品描述”里
                string price = Price;// Request.Form["TxtTotal_fee"];    		        //订单总金额,显示在支付宝收银台里的“商品单价”里

                string logistics_fee = "0.00";                  				//物流费用,即运费。
                string logistics_type = "EXPRESS";				                //物流类型,三个值可选:EXPRESS(快递)、POST(平邮)、EMS(EMS)
                string logistics_payment = "SELLER_PAY";            			//物流支付方式,两个值可选:SELLER_PAY(卖家承担运费)、BUYER_PAY(买家承担运费)

                string quantity = "1";              							//商品数量,建议默认为1,不改变值,把一次交易看成是一次下订单而非购买一件商品。

                //选填参数//

                //买家收货信息(推荐作为必填)
                //该功能作用在于买家已经在商户网站的下单流程中填过一次收货信息,而不需要买家在支付宝的付款流程中再次填写收货信息。
                //若要使用该功能,请至少保证receive_name、receive_address有值
                //收货信息格式请严格按照姓名、地址、邮编、电话、手机的格式填写
                string receive_name = "收货人姓名";			                    //收货人姓名,如:张三
                string receive_address = "收货人地址";			                //收货人地址,如:XX省XXX市XXX区XXX路XXX小区XXX栋XXX单元XXX号
                string receive_zip = "123456";                  			    //收货人邮编,如:123456
                string receive_phone = "0571-81234567";                		    //收货人电话号码,如:0571-81234567
                string receive_mobile = "13312341234";               		    //收货人手机号码,如:13312341234

                //网站商品的展示地址,不允许加?id=123这类自定义参数
                string show_url = "http://www.xxx.com/myorder.aspx";

                ////////////////////////////////////////////////////////////////////////////////////////////////

                //把请求参数打包成数组
                SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
                sParaTemp.Add("body", body);
                sParaTemp.Add("logistics_fee", logistics_fee);
                sParaTemp.Add("logistics_payment", logistics_payment);
                sParaTemp.Add("logistics_type", logistics_type);
                sParaTemp.Add("out_trade_no", out_trade_no);
                sParaTemp.Add("payment_type", "1");
                sParaTemp.Add("price", price);
                sParaTemp.Add("quantity", quantity);
                sParaTemp.Add("receive_address", receive_address);
                sParaTemp.Add("receive_mobile", receive_mobile);
                sParaTemp.Add("receive_name", receive_name);
                sParaTemp.Add("receive_phone", receive_phone);
                sParaTemp.Add("receive_zip", receive_zip);
                sParaTemp.Add("show_url", show_url);
                sParaTemp.Add("subject", subject);

                //构造担保交易接口表单提交HTML数据,无需修改
                Service ali = new Service();
                string sHtmlText = ali.Create_partner_trade_by_buyer(sParaTemp);
                //Response.Write(sHtmlText);
                return sHtmlText;
        }
        /// <summary>
        /// Generate default configurations for the filter.
        /// </summary>
        /// <returns>Dictionary used to pass configuration though the 
        /// configs parameter of the method ApplyFilter. 
        /// null if there is the filter doesn't use configurations.</returns>
        public override SortedDictionary<string, object> GetDefaultConfigs()
        {
            SortedDictionary<string, object> ret = new SortedDictionary<string, object>();

            ret.Add("Var", new Rangeable(0.5, 0, 255, 0.5));
            ret.Add("Mean", new Rangeable(10, 0, 255, 0.5));

            return ret;
        }
示例#26
0
 public string GetMentions(int count)
 {
     string resourceUrl = string.Format("http://api.twitter.com/1/statuses/mentions.json");
     var requestParameters = new SortedDictionary();
     requestParameters.Add("count", count.ToString());
     requestParameters.Add("include_entities", "true");
     var response = GetResponse(resourceUrl, Method.GET, requestParameters);
     return response;
 }
示例#27
0
 public string GetTweets(string screenName, int count)
 {
     string resourceUrl = string.Format("https://api.twitter.com/1.1/statuses/user_timeline.json");
     var requestParameters = new SortedDictionary();
     requestParameters.Add("count", count.ToString());
     requestParameters.Add("screen_name", screenName);
     var response = GetResponse(resourceUrl, Method.GET, requestParameters);
     return response;
 }
示例#28
0
 public string PostStatusUpdate(string status, double latitude, double longitude)
 {
     const string resourceUrl = "http://api.twitter.com/1/statuses/update.json";
     var requestParameters = new SortedDictionary();
     requestParameters.Add("status", status);
     requestParameters.Add("lat", latitude.ToString());
     requestParameters.Add("long", longitude.ToString());
     return GetResponse(resourceUrl, Method.POST, requestParameters);
 }
示例#29
0
        /// <summary>
        /// 支付异常消息
        /// </summary>
        /// <param name="error">错误信息</param>
        /// <returns>SortedDictionary<string, object></returns>
        public static SortedDictionary<string, object> ErrorInfo(string error)
        {
            var resultPrams = new SortedDictionary<string, object>();

            resultPrams.Add("return_code", "FAIL");
            resultPrams.Add("return_msg", error);

            return resultPrams;
        }
示例#30
0
        public void TestNeedGreedSorting()
        {
            var rolls = new SortedDictionary<LootRollEntry, int>();

            rolls.Add(new LootRollEntry(20, LootRollType.Greed), 20);
            rolls.Add(new LootRollEntry(10, LootRollType.Greed), 10);

            Assert.AreEqual(10, rolls.First().Value);
        }
示例#31
0
        private void AddObject(ObjectType obj)
        {
            RateType rate = RateObject(obj);

            _cachedRelevantObjects?.Add(obj, rate);
            _cachedSortedObjects?.Add(rate, obj);
            CurrentlyChangingRowCount(() => objectList.RowCount += 1);
            foreach (DataGridViewColumn column in objectList.Columns)
            {
                objectList.InvalidateColumn(column.Index);
            }
        }
示例#32
0
        private async Task <HttpResponseMessage> ExecuteRequestAsync(string url, HttpMethod httpMethod, RequestToken accessToken = null, Dictionary <string, string> extraOAuthPairs = null, Dictionary <string, string> queryParameters = null, Dictionary <string, string> formData = null)
        {
            var authorizationParts = new SortedDictionary <string, string>(extraOAuthPairs ?? new Dictionary <string, string>())
            {
                { "oauth_consumer_key", Options.ConsumerKey },
                { "oauth_nonce", Guid.NewGuid().ToString("N") },
                { "oauth_signature_method", "HMAC-SHA1" },
                { "oauth_timestamp", GenerateTimeStamp() },
                { "oauth_version", "1.0" }
            };

            if (accessToken != null)
            {
                authorizationParts.Add("oauth_token", accessToken.Token);
            }

            var signatureParts = new SortedDictionary <string, string>(authorizationParts);

            if (queryParameters != null)
            {
                foreach (var queryParameter in queryParameters)
                {
                    signatureParts.Add(queryParameter.Key, queryParameter.Value);
                }
            }
            if (formData != null)
            {
                foreach (var formItem in formData)
                {
                    signatureParts.Add(formItem.Key, formItem.Value);
                }
            }

            var parameterBuilder = new StringBuilder();

            foreach (var signaturePart in signatureParts)
            {
                parameterBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", Uri.EscapeDataString(signaturePart.Key), Uri.EscapeDataString(signaturePart.Value));
            }
            parameterBuilder.Length--;
            var parameterString = parameterBuilder.ToString();

            var canonicalizedRequestBuilder = new StringBuilder();

            canonicalizedRequestBuilder.Append(httpMethod.Method);
            canonicalizedRequestBuilder.Append("&");
            canonicalizedRequestBuilder.Append(Uri.EscapeDataString(url));
            canonicalizedRequestBuilder.Append("&");
            canonicalizedRequestBuilder.Append(Uri.EscapeDataString(parameterString));

            var signature = ComputeSignature(Options.ConsumerSecret, accessToken?.TokenSecret, canonicalizedRequestBuilder.ToString());

            authorizationParts.Add("oauth_signature", signature);

            var queryString = "";

            if (queryParameters != null)
            {
                var queryStringBuilder = new StringBuilder("?");
                foreach (var queryParam in queryParameters)
                {
                    queryStringBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", queryParam.Key, queryParam.Value);
                }
                queryStringBuilder.Length--;
                queryString = queryStringBuilder.ToString();
            }

            var authorizationHeaderBuilder = new StringBuilder();

            authorizationHeaderBuilder.Append("OAuth ");
            foreach (var authorizationPart in authorizationParts)
            {
                authorizationHeaderBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}=\"{1}\",", authorizationPart.Key, Uri.EscapeDataString(authorizationPart.Value));
            }
            authorizationHeaderBuilder.Length--;

            var request = new HttpRequestMessage(httpMethod, url + queryString);

            request.Headers.Add("Authorization", authorizationHeaderBuilder.ToString());

            if (formData != null)
            {
                request.Content = new FormUrlEncodedContent(formData);
            }

            return(await Backchannel.SendAsync(request, Context.RequestAborted));
        }
示例#33
0
        public SortedDictionary <string, string> GetParameters()
        {
            var parameters = new SortedDictionary <string, string>();

            /* Protection code transformations */

            if (this.FunctionOutlining == FunctionOutlining.Enabled)
            {
                parameters.Add("function_outlining", GetEnumStringValue(this.FunctionOutlining));
            }

            if (this.FunctionReorder == FunctionReorder.Enabled)
            {
                parameters.Add("function_reorder", GetEnumStringValue(this.FunctionReorder));
            }

            if (this.DotNotationElimination == DotNotationElimination.Enabled)
            {
                parameters.Add("dot_notation_elimination", GetEnumStringValue(this.DotNotationElimination));
            }

            if (this.DeadCode == DeadCode.Enabled)
            {
                parameters.Add("dead_code", GetEnumStringValue(this.DeadCode));
            }

            if (this.LiteralHooking != LiteralHooking.Disabled)
            {
                if (this.LiteralHooking == LiteralHooking.Enabled ||
                    this.LiteralHookingPredicates == null)
                {
                    parameters.Add("literal_hooking", GetEnumStringValue(this.LiteralHooking));
                }
                else
                {
                    var predicatesExpression = string.Format(GetEnumStringValue(this.LiteralHooking),
                                                             this.LiteralHookingPredicates.Value.Min,
                                                             this.LiteralHookingPredicates.Value.Max,
                                                             this.LiteralHookingPredicates.Value.Percent);

                    parameters.Add("literal_hooking", predicatesExpression);
                }
            }

            /* Optimization code transformations */

            if (this.RenameLocal == RenameLocal.Enabled)
            {
                parameters.Add("rename_local", GetEnumStringValue(this.RenameLocal));
            }

            if (this.RenameAll == RenameAll.Enabled)
            {
                parameters.Add("rename_all", GetEnumStringValue(this.RenameAll));
            }

            if (this.WhitespaceRemoval == WhitespaceRemoval.Enabled)
            {
                parameters.Add("whitespace", GetEnumStringValue(this.WhitespaceRemoval));
            }

            if (this.DuplicateLiterals == DuplicateLiterals.Enabled)
            {
                parameters.Add("duplicate_literals", GetEnumStringValue(this.DuplicateLiterals));
            }

            if (this.ConstantFolding == ConstantFolding.Enabled)
            {
                parameters.Add("constant_folding", GetEnumStringValue(this.ConstantFolding));
            }

            if (this.DeadCodeElimination == DeadCodeElimination.Enabled)
            {
                parameters.Add("dead_code_elimination", GetEnumStringValue(this.DeadCodeElimination));
            }

            if (this.DictionaryCompression == DictionaryCompression.Enabled)
            {
                parameters.Add("dictionary_compression", GetEnumStringValue(this.DictionaryCompression));
            }

            /* Other code transformations */
            if (!string.IsNullOrEmpty(this.NamePrefix))
            {
                parameters.Add("name_prefix", this.NamePrefix);
            }

            if (this.IgnoreFiles.Count > 0)
            {
                parameters.Add("ignore_files", String.Join(";", this.IgnoreFiles.ToArray()));
            }

            if (this.ExceptionsList.Count > 0)
            {
                parameters.Add("exceptions_list", String.Join(";", this.ExceptionsList.ToArray()));
            }

            if (this.AssertsElimination.Count > 0)
            {
                parameters.Add("asserts_elimination", String.Join(";", this.AssertsElimination.ToArray()));
            }

            if (this.DebuggingCodeElimination.Count > 0)
            {
                parameters.Add("debugging_code_elimination", String.Join(";", this.DebuggingCodeElimination.ToArray()));
            }

            return(parameters);
        }
示例#34
0
    //Este método es llamado cada vez que se pulsa enter en el inputField y recibe de parámetro la palabra introducida.
    public void OnFieldEnter(string word)
    {
        string log = "";

        if (diccionary.ContainsKey(word.ToLower()))
        //Si la palabra se encuentra en el diccionario la añadimos al diccionario de respondidos
        {
            int value = -1;
            diccionary.TryGetValue(word.ToLower(), out value);
            answered.Add(word, value);
            log = "\t✔ Ha respondido correctamente con: " + word;
            Debug.Log("Acertaste");
            feedbackResponse.gameObject.SetActive(true);
            feedbackResponse.text = "Has respondido " + word;


            // Tracking
            Dictionary <String, bool> simpleVarDictionary = new Dictionary <string, bool>();
            foreach (KeyValuePair <string, int> attachStat in simpleDictionary)
            {
                int simpleValue = -1;
                simpleDictionary.TryGetValue(attachStat.Key, out simpleValue);
                if (simpleValue == value)
                {
                    simpleVarDictionary.Add(attachStat.Key, true);
                }
                else
                {
                    simpleVarDictionary.Add(attachStat.Key, false);
                }

                // Mappings por si hacen falta en el analysis
                String varKey   = "mappings_" + attachStat.Key;
                String varValue = " ";
                foreach (KeyValuePair <string, int> dicKeyValues in diccionary)
                {
                    if (dicKeyValues.Value == attachStat.Value)
                    {
                        varValue += dicKeyValues.Key + ",";
                    }
                }
                if (varValue.EndsWith(","))
                {
                    varValue = varValue.Substring(0, varValue.Length - 1);
                }
                if (varKey != null && varValue != null)
                {
                    Tracker.T.setVar(varKey, varValue);
                }
            }
            if (simpleVarDictionary != null)
            {
                Tracker.T.setVar("targets", simpleVarDictionary);
            }

            foreach (KeyValuePair <string, int> attachStat in diccionary)
            {
                if (attachStat.Key != null)
                {
                    Tracker.T.setVar(attachStat.Key, attachStat.Value);
                }
            }
            // No hubo cambio de objeto
            Tracker.T.setVar("object-changed", 0);
            // Respuesta correcta
            Tracker.T.setVar("correct", 1);
            Tracker.T.setSuccess(true);
            Tracker.T.Alternative.Selected(level, word);
        }
        else if (word != "")
        {
            mistakes++;
            Debug.Log("Fallaste");
            if (answered.ContainsKey(word.ToLower()))
            {
                log = "\t✘ Ha respondido una palabra repetida: " + word;
            }
            else
            {
                log = "\t✘ Ha respondido con error: " + word;
            }
            feedbackResponse.gameObject.SetActive(true);
            feedbackResponse.text = "Has respondido " + word;

            // Tracking
            Dictionary <String, bool> simpleVarDictionary = new Dictionary <string, bool>();
            foreach (KeyValuePair <string, int> attachStat in simpleDictionary)
            {
                simpleVarDictionary.Add(attachStat.Key, false);

                // Mappings por si hacen falta en el analysis
                String varKey   = "mappings_" + attachStat.Key;
                String varValue = " ";
                foreach (KeyValuePair <string, int> dicKeyValues in diccionary)
                {
                    if (dicKeyValues.Value == attachStat.Value)
                    {
                        varValue += dicKeyValues.Key + ",";
                    }
                }
                if (varValue.EndsWith(","))
                {
                    varValue = varValue.Substring(0, varValue.Length - 1);
                }
                if (varKey != null && varValue != null)
                {
                    Tracker.T.setVar(varKey, varValue);
                }
            }
            if (simpleVarDictionary != null)
            {
                Tracker.T.setVar("targets", simpleVarDictionary);
            }

            foreach (KeyValuePair <string, int> attachStat in diccionary)
            {
                if (attachStat.Key != null)
                {
                    Tracker.T.setVar(attachStat.Key, attachStat.Value);
                }
            }
            // No hubo cambio de objeto
            Tracker.T.setVar("object-changed", 0);
            // Respuesta incorrecta
            Tracker.T.setVar("correct", 0);
            Tracker.T.setSuccess(false);
            Tracker.T.Alternative.Selected(level, word);
        }
        else
        {
            log = "\tHa cambiado de objeto";

            // Tracking object changed without answer
            Dictionary <String, bool> simpleVarDictionary = new Dictionary <string, bool>();
            foreach (KeyValuePair <string, int> attachStat in simpleDictionary)
            {
                simpleVarDictionary.Add(attachStat.Key, false);

                // Mappings por si hacen falta en el analysis
                String varKey   = "mappings_" + attachStat.Key;
                String varValue = " ";
                foreach (KeyValuePair <string, int> dicKeyValues in diccionary)
                {
                    if (dicKeyValues.Value == attachStat.Value)
                    {
                        varValue += dicKeyValues.Key + ",";
                    }
                }
                if (varValue.EndsWith(","))
                {
                    varValue = varValue.Substring(0, varValue.Length - 1);
                }
                if (varKey != null && varValue != null)
                {
                    Tracker.T.setVar(varKey, varValue);
                }
            }
            if (simpleVarDictionary != null)
            {
                Tracker.T.setVar("targets", simpleVarDictionary);
            }

            foreach (KeyValuePair <string, int> attachStat in diccionary)
            {
                if (attachStat.Key != null)
                {
                    Tracker.T.setVar(attachStat.Key, attachStat.Value);
                }
            }
            // Hubo cambio de objeto
            Tracker.T.setVar("object-changed", 1);
            // Respuesta desconocida
            Tracker.T.setVar("correct", -1);
            Tracker.T.setSuccess(false);
            Tracker.T.Alternative.Selected(level, "empty");
        }
        log += "\n";

        Byte[] info = new UTF8Encoding(true).GetBytes(log);
        fs.Write(info, 0, info.Length);

        diccionary.Clear();                                                    //Limpiamod el diccionario.
        simpleDictionary.Clear();
        textBx.gameObject.SetActive(false);
        attempts++;

        if (hayCont)
        {
            cont.text = "Has respondido " + attempts.ToString() + " objetos.\nTe quedan " + (totalAttempts - attempts).ToString();
        }
        if (hayLista)
        {
            listaText.text += "\n- " + word;
        }

        textBx.Select();
        textBx.text = "";

        // Progreso del nivel actual
        float progress = (float)attempts / (float)totalAttempts;

        Tracker.T.Completable.Progressed(level, CompletableTracker.Completable.Level, progress);
    }
    private void UpdateTriangles()//根据倍数重新计算三角面片
    {
        var mesh     = GetComponent <SkinnedMeshRenderer>().sharedMesh;
        var vertices = mesh.vertices;

        if (triangleMultiNum == 1)//1倍直接把原来存好的三角形给它
        {
            MeshACopyToMeshB(oldMesh, mesh);
            return;
        }

        var verticesList = new List <Vector3>();
        var normalsList  = new List <Vector3>();
        var uvList       = new List <Vector2>();
        int triangleNum  = (int)(oldMesh.triangles.Length * triangleMultiNum);

        triangleNum += 3 - triangleNum % 3;
        Debug.Log("triangleNum: " + triangleNum);
        //var triangles = new int[triangleNum];
        var trianglesList = new List <int>();

        foreach (var item in oldMesh.vertices)
        {
            verticesList.Add(item);
        }

        foreach (var item in oldMesh.normals)
        {
            normalsList.Add(item);
        }

        foreach (var item in oldMesh.uv)
        {
            uvList.Add(item);
        }


        var sd = new SortedDictionary <Cost, int[]>(new CostComparer());
        int id = 0;//新加入sd的cost的id

        for (int i = 0; i < oldMesh.triangles.Length; i += 3)
        {
            int[] outTriangle;
            int[] triangle = new int[] { oldMesh.triangles[i], oldMesh.triangles[i + 1], oldMesh.triangles[i + 2] };
            float len      = DivideTriangle(triangle, out outTriangle, verticesList);
            sd.Add(new Cost(len, ++id), triangle);
        }

        while (sd.Count * 3 < triangleNum)
        {
            var e = sd.GetEnumerator();
            e.MoveNext();
            var   ec       = e.Current;
            int[] triangle = ec.Value; //取最长边最长的三角形进行划分
            sd.Remove(ec.Key);         //从sd中删掉该三角形
            int[] outTriangle;
            DivideTriangle(triangle, out outTriangle, verticesList);
            int tot = verticesList.Count;                                                        //新加的点的index
            verticesList.Add((verticesList[outTriangle[0]] + verticesList[outTriangle[1]]) / 2); //加入最长边中点
            var normal = new Vector3(0, 0, 0);
            var uv     = new Vector2(0, 0);
            foreach (var i in triangle)
            {
                if (haveNormals)
                {
                    normal += normalsList[i];
                }
                if (haveUv)
                {
                    uv += uvList[i];
                }
            }
            normal /= triangle.Length;
            uv     /= triangle.Length;
            if (haveNormals)
            {
                normalsList.Add(normal);
            }
            if (haveUv)
            {
                uvList.Add(uv);
            }
            var t1 = new int[] { outTriangle[0], tot, outTriangle[2] };
            var t2 = new int[] { outTriangle[1], outTriangle[2], tot };

            var len = DivideTriangle(t1, out outTriangle, verticesList);
            sd.Add(new Cost(len, ++id), t1);
            len = DivideTriangle(t2, out outTriangle, verticesList);
            sd.Add(new Cost(len, ++id), t2);
        }

        int cc         = 0;
        var enumerator = sd.GetEnumerator();

        for (int i = 0; enumerator.MoveNext(); i++)
        {
            //Debug.Log("length: "+enumerator.Current.Key.cost);
            int[] triangle = enumerator.Current.Value;
            for (int j = 0; j < 3; j++)
            {
                //triangles[i * 3 + j] = triangle[j];
                trianglesList.Add(triangle[j]);
                cc++;
            }
        }
        mesh.Clear();
        mesh.vertices = verticesList.ToArray();
        if (haveNormals)
        {
            mesh.normals = normalsList.ToArray();
        }
        if (haveUv)
        {
            mesh.uv = uvList.ToArray();
        }
        mesh.triangles = trianglesList.ToArray();
        panelStatusController.UpdateTextTriangleNum();
    }
示例#36
0
    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            contNoAnswer++;
            //Se comprueba si en el punto del mouse al hacer click hay colisión con algún objeto. Se devuelven todos los objetos en result.
            Collider2D[] result = Physics2D.OverlapPointAll(Camera.main.ScreenToWorldPoint(Input.mousePosition));

            int i = result.Length;
            if (i > 0)
            {
                contNoAnswer = 0;
                simpleDictionary.Clear();
                diccionary.Clear();
                textBx.gameObject.SetActive(true);
                textBx.Select();
                textBx.ActivateInputField();
            }
            string log = "Se ha pinchado en: ";
            while (i > 0)
            {
                i--;
                int id;
                log += result[i].name + " ";
                Debug.Log("manpinchao " + result[i].name);
                string[] aux = result[i].GetComponent <Objeto>().dameDic(out id);       //El método dameDic devuelve una vector de palabras y un identificador que nos servirá para comprobar si se había respondido ya esa palabra.

                simpleDictionary.Add(result[i].name, id);
                if (!answered.ContainsValue(id))                                        //Si no se había respondido ya añadimos las palabras de cada objeto al diccionario.
                {
                    for (int w = 0; w < aux.Length; w++)
                    {
                        diccionary.Add(aux[w], id);
                    }
                }
            }
            log += "\n";
            Byte[] info = new UTF8Encoding(true).GetBytes(log);
            if (result.Length > 0)
            {
                fs.Write(info, 0, info.Length);
            }
        }

        if (contNoAnswer == 2)
        {
            noAnswer.gameObject.SetActive(true);
            contNoAnswer = 0;
        }

        if (attempts == totalAttempts)
        {
            gameS.fileConfig = false;
            finalPanel.SetActive(true);
            points.text = (attempts - mistakes).ToString() + "/" + totalAttempts;

            // Completed the 15 Objects level
            bool  failed = (float)mistakes > ((float)totalAttempts / 2.0f);
            float score  = 1.0f - ((float)mistakes / (float)totalAttempts);
            Tracker.T.Completable.Completed(level, CompletableTracker.Completable.Level, !failed, score);
        }
    }
示例#37
0
        private async Task <RequestToken> ObtainRequestTokenAsync(string callBackUri, AuthenticationProperties properties)
        {
            Logger.ObtainRequestToken();

            var nonce = Guid.NewGuid().ToString("N");

            var authorizationParts = new SortedDictionary <string, string>
            {
                { "oauth_callback", callBackUri },
                { "oauth_consumer_key", Options.ConsumerKey },
                { "oauth_nonce", nonce },
                { "oauth_signature_method", "HMAC-SHA1" },
                { "oauth_timestamp", GenerateTimeStamp() },
                { "oauth_version", "1.0" }
            };

            var parameterBuilder = new StringBuilder();

            foreach (var authorizationKey in authorizationParts)
            {
                parameterBuilder.AppendFormat("{0}={1}&", UrlEncoder.Encode(authorizationKey.Key), UrlEncoder.Encode(authorizationKey.Value));
            }
            parameterBuilder.Length--;
            var parameterString = parameterBuilder.ToString();

            var canonicalizedRequestBuilder = new StringBuilder();

            canonicalizedRequestBuilder.Append(HttpMethod.Post.Method);
            canonicalizedRequestBuilder.Append("&");
            canonicalizedRequestBuilder.Append(UrlEncoder.Encode(RequestTokenEndpoint));
            canonicalizedRequestBuilder.Append("&");
            canonicalizedRequestBuilder.Append(UrlEncoder.Encode(parameterString));

            var signature = ComputeSignature(Options.ConsumerSecret, null, canonicalizedRequestBuilder.ToString());

            authorizationParts.Add("oauth_signature", signature);

            var authorizationHeaderBuilder = new StringBuilder();

            authorizationHeaderBuilder.Append("OAuth ");
            foreach (var authorizationPart in authorizationParts)
            {
                authorizationHeaderBuilder.AppendFormat(
                    "{0}=\"{1}\", ", authorizationPart.Key, UrlEncoder.Encode(authorizationPart.Value));
            }
            authorizationHeaderBuilder.Length = authorizationHeaderBuilder.Length - 2;

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

            request.Headers.Add("Authorization", authorizationHeaderBuilder.ToString());

            var response = await _httpClient.SendAsync(request, Context.RequestAborted);

            response.EnsureSuccessStatusCode();
            var responseText = await response.Content.ReadAsStringAsync();

            var responseParameters = new FormCollection(new FormReader(responseText).ReadForm());

            if (!string.Equals(responseParameters["oauth_callback_confirmed"], "true", StringComparison.Ordinal))
            {
                throw new Exception("Twitter oauth_callback_confirmed is not true.");
            }

            return(new RequestToken {
                Token = Uri.UnescapeDataString(responseParameters["oauth_token"]), TokenSecret = Uri.UnescapeDataString(responseParameters["oauth_token_secret"]), CallbackConfirmed = true, Properties = properties
            });
        }
示例#38
0
        static void Main()
        {
            var menu           = new Dictionary <string, decimal>();
            int productsInMenu = int.Parse(Console.ReadLine());

            for (int i = 0; i < productsInMenu; i++)
            {
                var productsInput = Console.ReadLine().Split('-');

                var product      = productsInput.First();
                var productPrice = productsInput
                                   .Skip(1)
                                   .Select(decimal.Parse);

                if (!menu.ContainsKey(product))
                {
                    menu.Add(product, 0.0M);
                }
                menu[product] = productPrice.First();
            }

            SortedDictionary <string, Customer> customerDataBase = new SortedDictionary <string, Customer>();

            var input     = Console.ReadLine();
            var totalBill = 0.0M;

            while (input != "end of clients")
            {
                var inputLine = input.Split('-', ',');
                var name      = inputLine.First();
                var product   = inputLine[1];
                var qty       = inputLine.Skip(2).Take(1).Select(int.Parse).First();

                Dictionary <string, int> shopList = new Dictionary <string, int>();

                if (menu.ContainsKey(product))
                {
                    var bill = qty * menu[product];

                    Customer customer = new Customer()
                    {
                        Name     = name,
                        ShopList = shopList,
                        Bill     = bill
                    };

                    if (!customerDataBase.ContainsKey(name))
                    {
                        shopList.Add(product, qty);
                        customerDataBase.Add(name, customer);
                    }

                    else if (customerDataBase[name].ShopList.ContainsKey(product))
                    {
                        customerDataBase[name].ShopList[product] += qty;
                        customerDataBase[name].Bill += bill;
                    }

                    else
                    {
                        customerDataBase[name].ShopList.Add(product, qty);
                        customerDataBase[name].Bill += bill;
                    }
                    totalBill += bill;
                }

                input = Console.ReadLine();
            }

            foreach (var client in customerDataBase)
            {
                Console.WriteLine(client.Key);

                foreach (var item in client.Value.ShopList)
                {
                    Console.WriteLine($"-- {item.Key} - {item.Value} ");
                }

                Console.WriteLine($"Bill: {client.Value.Bill:f2}");
            }

            Console.WriteLine($"Total bill: {totalBill:f2}");
        }
示例#39
0
    public int Book(int start, int end)
    {
        var newinvs = new Dictionary <Interval, int>();
        //Console.WriteLine("start = " + start + " end = " + end);
        var  remove     = new List <Interval>();
        int  max        = 0;
        bool overlap    = false;
        bool cnt        = false;
        int  startagain = -1;

        foreach (var inv in intervals)
        {
            if (cnt)
            {
                if (inv.Key.start > end) // no more overlap
                {
                    if (startagain != end)
                    {
                        var nv = new Interval(startagain, end);
                        newinvs.Add(nv, 1);
                        //Console.WriteLine("c1: Created [" + startagain + "," + end + ") " + inv.Value);
                    }
                    cnt = false;
                    break;
                }
                else if (inv.Key.start == end) // no more overlap
                {
                    cnt = false;
                    break;
                }
                else
                {
                    if (startagain != inv.Key.start)
                    {
                        var nv = new Interval(startagain, inv.Key.start);
                        newinvs.Add(nv, 1);
                        //Console.WriteLine("c2: Created [" + startagain + "," + inv.Key.start + ") " + inv.Value);
                    }
                    start = inv.Key.start;
                }
                cnt = false;
            }
            else
            {
                if (inv.Key.end <= start)
                {
                    continue;
                }

                if (inv.Key.start >= end)
                {
                    continue;
                }
            }

            overlap = true;
            int os = -1;
            remove.Add(inv.Key);
            //Console.WriteLine("Removing [" + inv.Key.start + "," + inv.Key.end + ")");
            if (inv.Key.start - start > 0)
            {
                //new
                var nv = new Interval(start, inv.Key.start);
                newinvs.Add(nv, 1);
                //Console.WriteLine("0. Created [" + start + "," + inv.Key.start + ") = " + 1);
                os = inv.Key.start;
            }
            else if (start - inv.Key.start > 0)
            {
                var nv = new Interval(inv.Key.start, start);
                newinvs.Add(nv, inv.Value);
                //Console.WriteLine("0.5. Created [" + inv.Key.start + "," + start + ") = " + inv.Value);
                os = start;
            }
            else
            {
                os = start;
            }

            int oe = inv.Key.end < end ? inv.Key.end : end;
            //new
            if (os < oe)
            {
                var nv1 = new Interval(os, oe);
                newinvs.Add(nv1, inv.Value + 1);
                //Console.WriteLine("1. Created [" + os + "," + oe + ") = " + (inv.Value + 1));
            }

            if (oe < inv.Key.end)
            {
                var nv2 = new Interval(oe, inv.Key.end);
                newinvs.Add(nv2, inv.Value);
                //Console.WriteLine("2. Created [" + oe + "," + inv.Key.end + ")= " + inv.Value);
                //cnt = false;
            }
            else
            {
                cnt        = true;
                startagain = inv.Key.end;
                //Console.WriteLine("startagain = " + startagain);
            }
        }
        if (cnt)
        {
            var nv2 = new Interval(startagain, end);
            newinvs.Add(nv2, 1);
            //Console.WriteLine("4. Created [" + startagain + "," + end + ")= " + 1);
        }

        foreach (var n in remove)
        {
            intervals.Remove(n);
        }
        foreach (var n in newinvs)
        {
            //Console.WriteLine("Trying Adding [" + n.Key.start + "," + n.Key.end + ")" + n.Value);
            intervals.Add(n.Key, n.Value);
            if (max < n.Value)
            {
                max = n.Value;
            }
        }

        if (!overlap)
        {
            intervals.Add(new Interval(start, end), 1);
            //Console.WriteLine("Adding [" + start + "," + end + ") = " + 1);
            if (max < 1)
            {
                max = 1;
            }
        }
        foreach (var n in intervals)
        {
            if (n.Value > max)
            {
                //Console.WriteLine("Updating max = " + n.Value + " [" + n.Key.start + "," + n.Key.end + ")");
                max = n.Value;
            }
        }

        return(max);
    }
示例#40
0
        static void Main(string[] args)
        {
            var materialsName = new Dictionary <string, string>();

            materialsName.Add("shards", "Shadowmourne");
            materialsName.Add("fragments", "Valanyr");
            materialsName.Add("motes", "Dragonwrath");

            var arr = Console.ReadLine().ToLower().Split().ToArray();

            var junkMateriales = new SortedDictionary <string, int>();
            var keyMateriales  = new Dictionary <string, int>();

            keyMateriales.Add("shards", 0);
            keyMateriales.Add("fragments", 0);
            keyMateriales.Add("motes", 0);

            while (true)
            {
                var currentMaterials = arr.Where((x, i) => i % 2 == 1).ToArray();
                var quantity         = arr.Where((x, i) => i % 2 == 0).Select(int.Parse).ToArray();

                bool hasObtained = false;

                for (int i = 0; i < currentMaterials.Length; i++)
                {
                    string currentMaterial = currentMaterials[i];

                    if (materialsName.Keys.Contains(currentMaterial))
                    {
                        keyMateriales[currentMaterial] += quantity[i];

                        if (keyMateriales.Values.Any(x => x >= 250))
                        {
                            hasObtained = true;
                            break;
                        }
                    }
                    else
                    {
                        if (!junkMateriales.ContainsKey(currentMaterial))
                        {
                            junkMateriales.Add(currentMaterial, 0);
                        }

                        junkMateriales[currentMaterial] += quantity[i];
                    }
                }

                if (hasObtained)
                {
                    break;
                }

                arr = Console.ReadLine().ToLower().Split().ToArray();
            }

            var obtainedElementName = keyMateriales
                                      .Where(x => x.Value >= 250)
                                      .First()
                                      .Key;

            keyMateriales[obtainedElementName] -= 250;

            keyMateriales = keyMateriales
                            .OrderByDescending(x => x.Value)
                            .ThenBy(x => x.Key)
                            .ToDictionary(x => x.Key, x => x.Value);

            Console.WriteLine($"{materialsName[obtainedElementName]} obtained!");

            var result = keyMateriales.Concat(junkMateriales).ToDictionary(x => x.Key, x => x.Value);

            foreach (var material in result)
            {
                Console.WriteLine($"{material.Key}: {material.Value}");
            }
        }
示例#41
0
文件: Course.cs 项目: dswetlik/CS390
 /// <summary>
 /// Adds Student to enrolled students dictionary and removes a seat.
 /// </summary>
 /// <param name="student">Student to be added to enrolled students.</param>
 public void EnrollStudent(Student student)
 {
     enrolledStudents.Add(student.GetUserName(), student);
     numSeats--;
 }
        /// <summary>
        /// Ensures that all the paths in the lookupPaths member are absolute
        /// file system paths.
        /// </summary>
        private void ResolveCurrentDirectoryInLookupPaths()
        {
            var indexesToRemove  = new SortedDictionary <int, int>();
            int removalListCount = 0;

            string fileSystemProviderName = _context.ProviderNames.FileSystem;

            SessionStateInternal sessionState = _context.EngineSessionState;

            // Only use the directory if it gets resolved by the FileSystemProvider
            bool isCurrentDriveValid =
                sessionState.CurrentDrive != null &&
                sessionState.CurrentDrive.Provider.NameEquals(fileSystemProviderName) &&
                sessionState.IsProviderLoaded(fileSystemProviderName);

            string environmentCurrentDirectory = Directory.GetCurrentDirectory();

            LocationGlobber pathResolver = _context.LocationGlobber;

            // Loop through the relative paths and resolve them

            foreach (int index in _lookupPaths.IndexOfRelativePath())
            {
                string resolvedDirectory = null;
                string resolvedPath      = null;

                CommandDiscovery.discoveryTracer.WriteLine(
                    "Lookup directory \"{0}\" appears to be a relative path. Attempting resolution...",
                    _lookupPaths[index]);

                if (isCurrentDriveValid)
                {
                    try
                    {
                        ProviderInfo provider;
                        resolvedPath =
                            pathResolver.GetProviderPath(
                                _lookupPaths[index],
                                out provider);
                    }
                    catch (ProviderInvocationException providerInvocationException)
                    {
                        CommandDiscovery.discoveryTracer.WriteLine(
                            "The relative path '{0}', could not be resolved because the provider threw an exception: '{1}'",
                            _lookupPaths[index],
                            providerInvocationException.Message);
                    }
                    catch (InvalidOperationException)
                    {
                        CommandDiscovery.discoveryTracer.WriteLine(
                            "The relative path '{0}', could not resolve a home directory for the provider",
                            _lookupPaths[index]);
                    }

                    // Note, if the directory resolves to multiple paths, only the first is used.

                    if (!string.IsNullOrEmpty(resolvedPath))
                    {
                        CommandDiscovery.discoveryTracer.TraceError(
                            "The relative path resolved to: {0}",
                            resolvedPath);

                        resolvedDirectory = resolvedPath;
                    }
                    else
                    {
                        CommandDiscovery.discoveryTracer.WriteLine(
                            "The relative path was not a file system path. {0}",
                            _lookupPaths[index]);
                    }
                }
                else
                {
                    CommandDiscovery.discoveryTracer.TraceWarning(
                        "The current drive is not set, using the process current directory: {0}",
                        environmentCurrentDirectory);

                    resolvedDirectory = environmentCurrentDirectory;
                }

                // If we successfully resolved the path, make sure it is unique. Remove
                // any duplicates found after the first occurrence of the path.

                if (resolvedDirectory != null)
                {
                    int existingIndex = _lookupPaths.IndexOf(resolvedDirectory);

                    if (existingIndex != -1)
                    {
                        if (existingIndex > index)
                        {
                            // The relative path index is less than the explicit path,
                            // so remove the explicit path.

                            indexesToRemove.Add(removalListCount++, existingIndex);
                            _lookupPaths[index] = resolvedDirectory;
                        }
                        else
                        {
                            // The explicit path index is less than the relative path
                            // index, so remove the relative path.

                            indexesToRemove.Add(removalListCount++, index);
                        }
                    }
                    else
                    {
                        // Change the relative path to the resolved path.

                        _lookupPaths[index] = resolvedDirectory;
                    }
                }
                else
                {
                    // The directory couldn't be resolved so remove it from the
                    // lookup paths.

                    indexesToRemove.Add(removalListCount++, index);
                }
            }

            // Now remove all the duplicates starting from the back of the collection.
            // As each element is removed, elements that follow are moved up to occupy
            // the emptied index.

            for (int removeIndex = indexesToRemove.Count; removeIndex > 0; --removeIndex)
            {
                int indexToRemove = indexesToRemove[removeIndex - 1];
                _lookupPaths.RemoveAt(indexToRemove);
            }
        }
示例#43
0
        // https://dev.twitter.com/rest/reference/get/account/verify_credentials
        private async Task <JObject> RetrieveUserDetailsAsync(AccessToken accessToken, ClaimsIdentity identity)
        {
            Logger.RetrieveUserDetails();

            var nonce = Guid.NewGuid().ToString("N");

            var authorizationParts = new SortedDictionary <string, string>
            {
                { "oauth_consumer_key", Options.ConsumerKey },
                { "oauth_nonce", nonce },
                { "oauth_signature_method", "HMAC-SHA1" },
                { "oauth_timestamp", GenerateTimeStamp() },
                { "oauth_token", accessToken.Token },
                { "oauth_version", "1.0" }
            };

            var parameterBuilder = new StringBuilder();

            foreach (var authorizationKey in authorizationParts)
            {
                parameterBuilder.AppendFormat("{0}={1}&", UrlEncoder.Encode(authorizationKey.Key), UrlEncoder.Encode(authorizationKey.Value));
            }
            parameterBuilder.Length--;
            var parameterString = parameterBuilder.ToString();

            var resource_url   = "https://api.twitter.com/1.1/account/verify_credentials.json";
            var resource_query = "include_email=true";
            var canonicalizedRequestBuilder = new StringBuilder();

            canonicalizedRequestBuilder.Append(HttpMethod.Get.Method);
            canonicalizedRequestBuilder.Append("&");
            canonicalizedRequestBuilder.Append(UrlEncoder.Encode(resource_url));
            canonicalizedRequestBuilder.Append("&");
            canonicalizedRequestBuilder.Append(UrlEncoder.Encode(resource_query));
            canonicalizedRequestBuilder.Append("%26");
            canonicalizedRequestBuilder.Append(UrlEncoder.Encode(parameterString));

            var signature = ComputeSignature(Options.ConsumerSecret, accessToken.TokenSecret, canonicalizedRequestBuilder.ToString());

            authorizationParts.Add("oauth_signature", signature);

            var authorizationHeaderBuilder = new StringBuilder();

            authorizationHeaderBuilder.Append("OAuth ");
            foreach (var authorizationPart in authorizationParts)
            {
                authorizationHeaderBuilder.AppendFormat(
                    "{0}=\"{1}\", ", authorizationPart.Key, UrlEncoder.Encode(authorizationPart.Value));
            }
            authorizationHeaderBuilder.Length = authorizationHeaderBuilder.Length - 2;

            var request = new HttpRequestMessage(HttpMethod.Get, resource_url + "?include_email=true");

            request.Headers.Add("Authorization", authorizationHeaderBuilder.ToString());

            var response = await _httpClient.SendAsync(request, Context.RequestAborted);

            if (!response.IsSuccessStatusCode)
            {
                Logger.LogError("Email request failed with a status code of " + response.StatusCode);
                response.EnsureSuccessStatusCode(); // throw
            }
            var responseText = await response.Content.ReadAsStringAsync();

            var result = JObject.Parse(responseText);

            var email = result.Value <string>("email");

            if (!string.IsNullOrEmpty(email))
            {
                identity.AddClaim(new Claim(ClaimTypes.Email, email, ClaimValueTypes.Email, Options.ClaimsIssuer));
            }

            return(result);
        }
示例#44
0
        private async Task <AccessToken> ObtainAccessTokenAsync(RequestToken token, string verifier)
        {
            // https://dev.twitter.com/docs/api/1/post/oauth/access_token

            Logger.ObtainAccessToken();

            var nonce = Guid.NewGuid().ToString("N");

            var authorizationParts = new SortedDictionary <string, string>
            {
                { "oauth_consumer_key", Options.ConsumerKey },
                { "oauth_nonce", nonce },
                { "oauth_signature_method", "HMAC-SHA1" },
                { "oauth_token", token.Token },
                { "oauth_timestamp", GenerateTimeStamp() },
                { "oauth_verifier", verifier },
                { "oauth_version", "1.0" },
            };

            var parameterBuilder = new StringBuilder();

            foreach (var authorizationKey in authorizationParts)
            {
                parameterBuilder.AppendFormat("{0}={1}&", UrlEncoder.Encode(authorizationKey.Key), UrlEncoder.Encode(authorizationKey.Value));
            }
            parameterBuilder.Length--;
            var parameterString = parameterBuilder.ToString();

            var canonicalizedRequestBuilder = new StringBuilder();

            canonicalizedRequestBuilder.Append(HttpMethod.Post.Method);
            canonicalizedRequestBuilder.Append("&");
            canonicalizedRequestBuilder.Append(UrlEncoder.Encode(AccessTokenEndpoint));
            canonicalizedRequestBuilder.Append("&");
            canonicalizedRequestBuilder.Append(UrlEncoder.Encode(parameterString));

            var signature = ComputeSignature(Options.ConsumerSecret, token.TokenSecret, canonicalizedRequestBuilder.ToString());

            authorizationParts.Add("oauth_signature", signature);
            authorizationParts.Remove("oauth_verifier");

            var authorizationHeaderBuilder = new StringBuilder();

            authorizationHeaderBuilder.Append("OAuth ");
            foreach (var authorizationPart in authorizationParts)
            {
                authorizationHeaderBuilder.AppendFormat(
                    "{0}=\"{1}\", ", authorizationPart.Key, UrlEncoder.Encode(authorizationPart.Value));
            }
            authorizationHeaderBuilder.Length = authorizationHeaderBuilder.Length - 2;

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

            request.Headers.Add("Authorization", authorizationHeaderBuilder.ToString());

            var formPairs = new Dictionary <string, string>()
            {
                { "oauth_verifier", verifier },
            };

            request.Content = new FormUrlEncodedContent(formPairs);

            var response = await _httpClient.SendAsync(request, Context.RequestAborted);

            if (!response.IsSuccessStatusCode)
            {
                Logger.LogError("AccessToken request failed with a status code of " + response.StatusCode);
                response.EnsureSuccessStatusCode(); // throw
            }

            var responseText = await response.Content.ReadAsStringAsync();

            var responseParameters = new FormCollection(new FormReader(responseText).ReadForm());

            return(new AccessToken
            {
                Token = Uri.UnescapeDataString(responseParameters["oauth_token"]),
                TokenSecret = Uri.UnescapeDataString(responseParameters["oauth_token_secret"]),
                UserId = Uri.UnescapeDataString(responseParameters["user_id"]),
                ScreenName = Uri.UnescapeDataString(responseParameters["screen_name"])
            });
        }
        private static void LoadXml()
        {
            if (!Utils.FileExists(filePath))
            {
                UpdateXml();
            }
            XmlDocument xmlDoc = new XmlDocument();

            try
            {
                xmlDoc.Load(filePath);
            }
            catch (XmlException e)
            {
                Log.Error(string.Format("[SERVERTOOLS] Failed loading {0}: {1}", file, e.Message));
                return;
            }
            XmlNode _XmlNode = xmlDoc.DocumentElement;

            foreach (XmlNode childNode in _XmlNode.ChildNodes)
            {
                if (childNode.Name == "Commands")
                {
                    Dict.Clear();
                    foreach (XmlNode subChild in childNode.ChildNodes)
                    {
                        if (subChild.NodeType == XmlNodeType.Comment)
                        {
                            continue;
                        }
                        if (subChild.NodeType != XmlNodeType.Element)
                        {
                            Log.Warning(string.Format("[SERVERTOOLS] Unexpected XML node found in 'Commands' section: {0}", subChild.OuterXml));
                            continue;
                        }
                        XmlElement _line = (XmlElement)subChild;
                        if (!_line.HasAttribute("Command"))
                        {
                            Log.Warning(string.Format("[SERVERTOOLS] Ignoring Commands entry because of missing a Command attribute: {0}", subChild.OuterXml));
                            continue;
                        }
                        if (!_line.HasAttribute("Response"))
                        {
                            Log.Warning(string.Format("[SERVERTOOLS] Ignoring Commands entry because of missing a Response attribute: {0}", subChild.OuterXml));
                            continue;
                        }
                        int _delay = 0;
                        if (_line.HasAttribute("DelayBetweenUses"))
                        {
                            if (!int.TryParse(_line.GetAttribute("DelayBetweenUses"), out _delay))
                            {
                                Log.Out(string.Format("[SERVERTOOLS] Using default value of 0 for DelayBetweenUses for command entry {1} because of invalid (non-numeric) value: {0}", subChild.OuterXml, _line.GetAttribute("Command")));
                            }
                        }
                        string _command = _line.GetAttribute("Command");
                        _command = _command.ToLower();
                        if (!Dict.ContainsKey(_command))
                        {
                            string[] _response = new string[] { _line.GetAttribute("Response"), _delay.ToString() };
                            Dict.Add(_command, _response);
                        }
                    }
                }
            }
        }
示例#46
0
 public void Add(uint id, T model)
 {
     history.Add(id, model);
     DeleteOldModels();
 }
示例#47
0
        /// <summary>
        /// Export effect data
        /// </summary>
        /// <returns></returns>
        public byte[] Export(Data.NodeRoot rootNode, float magnification = 1.0f, ExporterVersion exporterVersion = ExporterVersion.Latest)
        {
            List <byte[]> data = new List <byte[]>();

            // ヘッダ
            data.Add(Encoding.UTF8.GetBytes("SKFE"));

            // Version
            data.Add(BitConverter.GetBytes((int)exporterVersion));

            // reset texture names
            UsedTextures = new HashSet <string>();

            UsedNormalTextures = new HashSet <string>();

            UsedDistortionTextures = new HashSet <string>();

            Sounds = new HashSet <string>();

            Models = new HashSet <string>();

            Materials = new HashSet <string>();

            Curves = new HashSet <string>();

            ProceduralModels = new List <ProceduralModelParameter>();

            Action <Data.NodeBase> get_textures = null;

            get_textures = (node) =>
            {
                if (node is Data.Node)
                {
                    var _node = node as Data.Node;

                    if (IsRenderedNode(_node))
                    {
                        if (_node.RendererCommonValues.Material.Value == Data.RendererCommonValues.MaterialType.Default)
                        {
                            var relative_path = _node.RendererCommonValues.ColorTexture.RelativePath;
                            if (relative_path != string.Empty)
                            {
                                if (!UsedTextures.Contains(relative_path))
                                {
                                    UsedTextures.Add(relative_path);
                                }
                            }
                            if (exporterVersion >= ExporterVersion.Ver16Alpha1)
                            {
                                var alpha_relative_path = _node.AdvancedRendererCommonValuesValues.AlphaTextureParam.Texture.RelativePath;
                                if (_node.AdvancedRendererCommonValuesValues.AlphaTextureParam.Enabled && alpha_relative_path != string.Empty)
                                {
                                    if (!UsedTextures.Contains(alpha_relative_path))
                                    {
                                        UsedTextures.Add(alpha_relative_path);
                                    }
                                }

                                var uvDistortion_relative_path = _node.AdvancedRendererCommonValuesValues.UVDistortionTextureParam.Texture.RelativePath;
                                if (_node.AdvancedRendererCommonValuesValues.UVDistortionTextureParam.Enabled && uvDistortion_relative_path != string.Empty)
                                {
                                    if (!UsedTextures.Contains(uvDistortion_relative_path))
                                    {
                                        UsedTextures.Add(uvDistortion_relative_path);
                                    }
                                }

                                var blend_relative_path = _node.AdvancedRendererCommonValuesValues.BlendTextureParams.BlendTextureParam.Texture.RelativePath;
                                if (_node.AdvancedRendererCommonValuesValues.BlendTextureParams.Enabled && blend_relative_path != string.Empty)
                                {
                                    if (!UsedTextures.Contains(blend_relative_path))
                                    {
                                        UsedTextures.Add(blend_relative_path);
                                    }

                                    var blend_alpha_relative_path = _node.AdvancedRendererCommonValuesValues.BlendTextureParams.BlendAlphaTextureParam.Texture.RelativePath;
                                    if (_node.AdvancedRendererCommonValuesValues.BlendTextureParams.EnableBlendAlphaTexture &&
                                        blend_alpha_relative_path != string.Empty)
                                    {
                                        if (!UsedTextures.Contains(blend_alpha_relative_path))
                                        {
                                            UsedTextures.Add(blend_alpha_relative_path);
                                        }
                                    }

                                    var blend_uv_distortion_relative_path = _node.AdvancedRendererCommonValuesValues.BlendTextureParams.BlendUVDistortionTextureParam.Texture.RelativePath;
                                    if (_node.AdvancedRendererCommonValuesValues.BlendTextureParams.EnableBlendUVDistortionTexture &&
                                        blend_uv_distortion_relative_path != string.Empty)
                                    {
                                        if (!UsedTextures.Contains(blend_uv_distortion_relative_path))
                                        {
                                            UsedTextures.Add(blend_uv_distortion_relative_path);
                                        }
                                    }
                                }
                            }
                        }
                        if (_node.RendererCommonValues.Material.Value == Data.RendererCommonValues.MaterialType.BackDistortion)
                        {
                            var relative_path = _node.RendererCommonValues.ColorTexture.RelativePath;
                            if (relative_path != string.Empty)
                            {
                                if (!UsedDistortionTextures.Contains(relative_path))
                                {
                                    UsedDistortionTextures.Add(relative_path);
                                }
                            }

                            if (exporterVersion >= ExporterVersion.Ver16Alpha1)
                            {
                                var alpha_relative_path = _node.AdvancedRendererCommonValuesValues.AlphaTextureParam.Texture.RelativePath;
                                if (_node.AdvancedRendererCommonValuesValues.AlphaTextureParam.Enabled && alpha_relative_path != string.Empty)
                                {
                                    if (!UsedDistortionTextures.Contains(alpha_relative_path))
                                    {
                                        UsedDistortionTextures.Add(alpha_relative_path);
                                    }
                                }

                                var uvDistortion_relative_path = _node.AdvancedRendererCommonValuesValues.UVDistortionTextureParam.Texture.RelativePath;
                                if (_node.AdvancedRendererCommonValuesValues.UVDistortionTextureParam.Enabled && uvDistortion_relative_path != string.Empty)
                                {
                                    if (!UsedDistortionTextures.Contains(uvDistortion_relative_path))
                                    {
                                        UsedDistortionTextures.Add(uvDistortion_relative_path);
                                    }
                                }

                                var blend_relative_path = _node.AdvancedRendererCommonValuesValues.BlendTextureParams.BlendTextureParam.Texture.RelativePath;
                                if (_node.AdvancedRendererCommonValuesValues.BlendTextureParams.Enabled && blend_relative_path != string.Empty)
                                {
                                    if (!UsedDistortionTextures.Contains(blend_relative_path))
                                    {
                                        UsedDistortionTextures.Add(blend_relative_path);
                                    }

                                    var blend_alpha_relative_path = _node.AdvancedRendererCommonValuesValues.BlendTextureParams.BlendAlphaTextureParam.Texture.RelativePath;
                                    if (_node.AdvancedRendererCommonValuesValues.BlendTextureParams.EnableBlendAlphaTexture &&
                                        blend_alpha_relative_path != string.Empty)
                                    {
                                        if (!UsedDistortionTextures.Contains(blend_alpha_relative_path))
                                        {
                                            UsedDistortionTextures.Add(blend_alpha_relative_path);
                                        }
                                    }

                                    var blend_uv_distortion_relative_path = _node.AdvancedRendererCommonValuesValues.BlendTextureParams.BlendUVDistortionTextureParam.Texture.RelativePath;
                                    if (_node.AdvancedRendererCommonValuesValues.BlendTextureParams.EnableBlendUVDistortionTexture &&
                                        blend_uv_distortion_relative_path != string.Empty)
                                    {
                                        if (!UsedDistortionTextures.Contains(blend_uv_distortion_relative_path))
                                        {
                                            UsedDistortionTextures.Add(blend_uv_distortion_relative_path);
                                        }
                                    }
                                }
                            }
                        }
                        if (_node.RendererCommonValues.Material.Value == Data.RendererCommonValues.MaterialType.Lighting)
                        {
                            var path1 = _node.RendererCommonValues.ColorTexture.RelativePath;
                            if (path1 != string.Empty)
                            {
                                if (!UsedTextures.Contains(path1))
                                {
                                    UsedTextures.Add(path1);
                                }
                            }

                            var path2 = _node.RendererCommonValues.NormalTexture.RelativePath;
                            if (path2 != string.Empty)
                            {
                                if (!UsedNormalTextures.Contains(path2))
                                {
                                    UsedNormalTextures.Add(path2);
                                }
                            }

                            if (exporterVersion >= ExporterVersion.Ver16Alpha1)
                            {
                                // alpha texture
                                var path3 = _node.AdvancedRendererCommonValuesValues.AlphaTextureParam.Texture.RelativePath;
                                if (_node.AdvancedRendererCommonValuesValues.AlphaTextureParam.Enabled && path3 != string.Empty)
                                {
                                    if (!UsedTextures.Contains(path3))
                                    {
                                        UsedTextures.Add(path3);
                                    }
                                }

                                // uv distortion texture
                                var path4 = _node.AdvancedRendererCommonValuesValues.UVDistortionTextureParam.Texture.RelativePath;
                                if (_node.AdvancedRendererCommonValuesValues.UVDistortionTextureParam.Enabled && path4 != string.Empty)
                                {
                                    if (!UsedTextures.Contains(path4))
                                    {
                                        UsedTextures.Add(path4);
                                    }
                                }

                                // blend texture
                                var path5 = _node.AdvancedRendererCommonValuesValues.BlendTextureParams.BlendTextureParam.Texture.RelativePath;
                                if (_node.AdvancedRendererCommonValuesValues.BlendTextureParams.Enabled && path5 != string.Empty)
                                {
                                    if (!UsedTextures.Contains(path5))
                                    {
                                        UsedTextures.Add(path5);
                                    }

                                    var path6 = _node.AdvancedRendererCommonValuesValues.BlendTextureParams.BlendAlphaTextureParam.Texture.RelativePath;
                                    if (_node.AdvancedRendererCommonValuesValues.BlendTextureParams.EnableBlendAlphaTexture &&
                                        path6 != string.Empty)
                                    {
                                        if (!UsedTextures.Contains(path6))
                                        {
                                            UsedTextures.Add(path6);
                                        }
                                    }

                                    var path7 = _node.AdvancedRendererCommonValuesValues.BlendTextureParams.BlendUVDistortionTextureParam.Texture.RelativePath;
                                    if (_node.AdvancedRendererCommonValuesValues.BlendTextureParams.EnableBlendUVDistortionTexture &&
                                        path7 != string.Empty)
                                    {
                                        if (!UsedTextures.Contains(path7))
                                        {
                                            UsedTextures.Add(path7);
                                        }
                                    }
                                }
                            }
                        }
                        else if (_node.RendererCommonValues.Material.Value == Data.RendererCommonValues.MaterialType.File)
                        {
                            var materialInfo = Core.ResourceCache.LoadMaterialInformation(_node.RendererCommonValues.MaterialFile.Path.AbsolutePath);
                            if (materialInfo == null)
                            {
                                materialInfo = new MaterialInformation();
                            }

                            var textures = _node.RendererCommonValues.MaterialFile.GetTextures(materialInfo).Where(_ => _.Item1 != null);

                            foreach (var texture in textures)
                            {
                                var relative_path = (texture.Item1.Value as Data.Value.PathForImage).RelativePath;
                                if (relative_path != string.Empty)
                                {
                                    if (texture.Item2.Type == TextureType.Value)
                                    {
                                        if (!UsedNormalTextures.Contains(relative_path))
                                        {
                                            UsedNormalTextures.Add(relative_path);
                                        }
                                    }
                                    else
                                    {
                                        if (!UsedTextures.Contains(relative_path))
                                        {
                                            UsedTextures.Add(relative_path);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                for (int i = 0; i < node.Children.Count; i++)
                {
                    get_textures(node.Children[i]);
                }
            };

            get_textures(rootNode);


            var texture_and_index = new SortedDictionary <string, int>();
            {
                int index = 0;
                foreach (var texture in UsedTextures.ToList().OrderBy(_ => _))
                {
                    texture_and_index.Add(texture, index);
                    index++;
                }
            }

            var normalTexture_and_index = new SortedDictionary <string, int>();
            {
                int index = 0;
                foreach (var texture in UsedNormalTextures.ToList().OrderBy(_ => _))
                {
                    normalTexture_and_index.Add(texture, index);
                    index++;
                }
            }

            var distortionTexture_and_index = new SortedDictionary <string, int>();
            {
                int index = 0;
                foreach (var texture in UsedDistortionTextures.ToList().OrderBy(_ => _))
                {
                    distortionTexture_and_index.Add(texture, index);
                    index++;
                }
            }

            Action <Data.NodeBase> get_waves = null;

            get_waves = (node) =>
            {
                if (node is Data.Node)
                {
                    var _node = node as Data.Node;

                    if (IsRenderedNode(_node))
                    {
                        if (_node.SoundValues.Type.GetValue() == Data.SoundValues.ParamaterType.None)
                        {
                        }
                        else if (_node.SoundValues.Type.GetValue() == Data.SoundValues.ParamaterType.Use)
                        {
                            var relative_path = _node.SoundValues.Sound.Wave.RelativePath;
                            if (relative_path != string.Empty)
                            {
                                if (!Sounds.Contains(relative_path))
                                {
                                    Sounds.Add(relative_path);
                                }
                            }
                        }
                    }
                }

                for (int i = 0; i < node.Children.Count; i++)
                {
                    get_waves(node.Children[i]);
                }
            };

            get_waves(rootNode);

            var wave_and_index = new SortedDictionary <string, int>();
            {
                int index = 0;
                foreach (var wave in Sounds.ToList().OrderBy(_ => _))
                {
                    wave_and_index.Add(wave, index);
                    index++;
                }
            }

            Action <Data.NodeBase> get_models = null;

            get_models = (node) =>
            {
                if (node is Data.Node)
                {
                    var _node = node as Data.Node;

                    if (IsRenderedNode(_node) && _node.DrawingValues.Type.Value == Data.RendererValues.ParamaterType.Model)
                    {
                        var relative_path = _node.DrawingValues.Model.Model.RelativePath;

                        if (!string.IsNullOrEmpty(relative_path))
                        {
                            relative_path = Utils.GetModelPath(_node.DrawingValues.Model.Model);

                            if (relative_path != string.Empty)
                            {
                                if (!Models.Contains(relative_path))
                                {
                                    Models.Add(relative_path);
                                }
                            }
                        }
                    }

                    if (_node.GenerationLocationValues.Type.Value == Data.GenerationLocationValues.ParameterType.Model)
                    {
                        var relative_path = _node.GenerationLocationValues.Model.Model.RelativePath;

                        if (!string.IsNullOrEmpty(relative_path))
                        {
                            relative_path = Utils.GetModelPath(_node.GenerationLocationValues.Model.Model);

                            if (relative_path != string.Empty)
                            {
                                if (!Models.Contains(relative_path))
                                {
                                    Models.Add(relative_path);
                                }
                            }
                        }
                    }
                }

                for (int i = 0; i < node.Children.Count; i++)
                {
                    get_models(node.Children[i]);
                }
            };

            get_models(rootNode);

            var model_and_index = new SortedDictionary <string, int>();
            {
                int index = 0;
                foreach (var model in Models.ToList().OrderBy(_ => _))
                {
                    model_and_index.Add(model, index);
                    index++;
                }
            }

            Action <Data.NodeBase> get_materials = null;

            get_materials = (node) =>
            {
                if (node is Data.Node)
                {
                    var _node = node as Data.Node;

                    if (IsRenderedNode(_node) && _node.RendererCommonValues.Material.Value == Data.RendererCommonValues.MaterialType.File)
                    {
                        var relative_path = _node.RendererCommonValues.MaterialFile.Path.RelativePath;
                        if (relative_path != string.Empty)
                        {
                            if (!Materials.Contains(relative_path))
                            {
                                Materials.Add(relative_path);
                            }
                        }
                    }
                }

                for (int i = 0; i < node.Children.Count; i++)
                {
                    get_materials(node.Children[i]);
                }
            };

            get_materials(rootNode);

            var material_and_index = new SortedDictionary <string, int>();
            {
                int index = 0;
                foreach (var wave in Materials.ToList().OrderBy(_ => _))
                {
                    material_and_index.Add(wave, index);
                    index++;
                }
            }

            var curve_and_index = new SortedDictionary <string, int>();

            Action <Data.NodeBase> get_curves = null;

            get_curves = (node) =>
            {
                if (node is Data.Node)
                {
                    var _node = node as Data.Node;

                    if (_node.LocationValues.Type == Data.LocationValues.ParamaterType.NurbsCurve)
                    {
                        var relative_path = _node.LocationValues.NurbsCurve.FilePath.RelativePath;
                        if (!string.IsNullOrEmpty(relative_path))
                        {
                            if (string.IsNullOrEmpty(System.IO.Path.GetDirectoryName(relative_path)))
                            {
                                relative_path = System.IO.Path.GetFileNameWithoutExtension(relative_path) + ".efkcurve";
                            }
                            else
                            {
                                relative_path = System.IO.Path.ChangeExtension(relative_path, ".efkcurve");
                            }

                            if (relative_path != string.Empty)
                            {
                                if (!Curves.Contains(relative_path))
                                {
                                    Curves.Add(relative_path);
                                }
                            }
                        }
                    }
                }

                for (int i = 0; i < node.Children.Count; i++)
                {
                    get_curves(node.Children[i]);
                }
            };

            get_curves(Core.Root);

            if (exporterVersion >= ExporterVersion.Ver16Alpha1)
            {
                int index = 0;
                foreach (var curve in Curves.ToList().OrderBy(_ => _))
                {
                    curve_and_index.Add(curve, index);
                    index++;
                }
            }

            // Procedural meshes

            Action <Data.NodeBase> get_procedural_models = null;

            get_procedural_models = (node) =>
            {
                if (node is Data.Node)
                {
                    var _node = node as Data.Node;

                    if (IsRenderedNode(_node) && _node.DrawingValues.Type.Value == Data.RendererValues.ParamaterType.Model && _node.DrawingValues.Model.ModelReference.Value == ModelReferenceType.ProceduralModel)
                    {
                        var param = _node.DrawingValues.Model.Reference.Value;

                        if (param != null && !ProceduralModels.Contains(param))
                        {
                            ProceduralModels.Add(param);
                        }
                    }

                    if (_node.GenerationLocationValues.Type.Value == Data.GenerationLocationValues.ParameterType.Model && _node.GenerationLocationValues.Model.ModelReference.Value == ModelReferenceType.ProceduralModel)
                    {
                        var param = _node.GenerationLocationValues.Model.Reference.Value;

                        if (param != null && !ProceduralModels.Contains(param))
                        {
                            ProceduralModels.Add(param);
                        }
                    }
                }

                for (int i = 0; i < node.Children.Count; i++)
                {
                    get_procedural_models(node.Children[i]);
                }
            };

            get_procedural_models(rootNode);

            var procedural_mesh_and_index = new Dictionary <ProceduralModelParameter, int>();
            {
                int index = 0;
                foreach (var mesh in ProceduralModels)
                {
                    procedural_mesh_and_index.Add(mesh, index);
                    index++;
                }
            }


            // get all nodes
            var nodes = new List <Data.Node>();

            Action <Data.NodeBase> get_nodes = null;

            get_nodes = (node) =>
            {
                if (node is Data.Node)
                {
                    var _node = node as Data.Node;
                    nodes.Add(_node);
                }

                var children = node.Children.Internal.Where(_ => IsRenderedNodeGroup(_)).ToList();

                for (int i = 0; i < children.Count; i++)
                {
                    get_nodes(children[i]);
                }
            };

            get_nodes(rootNode);

            var snode2ind = nodes.
                            Select((v, i) => Tuple35.Create(v, i)).
                            OrderBy(_ => _.Item1.DepthValues.DrawingPriority.Value * 255 + _.Item2).
                            Select((v, i) => Tuple35.Create(v.Item1, i)).ToList();

            // ファイルにテクスチャ一覧出力
            data.Add(BitConverter.GetBytes(texture_and_index.Count));
            foreach (var texture in texture_and_index)
            {
                var path = Encoding.Unicode.GetBytes(texture.Key);
                data.Add(((path.Count() + 2) / 2).GetBytes());
                data.Add(path);
                data.Add(new byte[] { 0, 0 });
            }

            data.Add(BitConverter.GetBytes(normalTexture_and_index.Count));
            foreach (var texture in normalTexture_and_index)
            {
                var path = Encoding.Unicode.GetBytes(texture.Key);
                data.Add(((path.Count() + 2) / 2).GetBytes());
                data.Add(path);
                data.Add(new byte[] { 0, 0 });
            }

            data.Add(BitConverter.GetBytes(distortionTexture_and_index.Count));
            foreach (var texture in distortionTexture_and_index)
            {
                var path = Encoding.Unicode.GetBytes(texture.Key);
                data.Add(((path.Count() + 2) / 2).GetBytes());
                data.Add(path);
                data.Add(new byte[] { 0, 0 });
            }

            // ファイルにウェーブ一覧出力
            data.Add(BitConverter.GetBytes(wave_and_index.Count));
            foreach (var wave in wave_and_index)
            {
                var path = Encoding.Unicode.GetBytes(wave.Key);
                data.Add(((path.Count() + 2) / 2).GetBytes());
                data.Add(path);
                data.Add(new byte[] { 0, 0 });
            }

            // ファイルにモデル一覧出力
            data.Add(BitConverter.GetBytes(model_and_index.Count));
            foreach (var model in model_and_index)
            {
                var path = Encoding.Unicode.GetBytes(model.Key);
                data.Add(((path.Count() + 2) / 2).GetBytes());
                data.Add(path);
                data.Add(new byte[] { 0, 0 });
            }

            // export materials to a file
            data.Add(BitConverter.GetBytes(material_and_index.Count));
            foreach (var material in material_and_index)
            {
                var path = Encoding.Unicode.GetBytes(material.Key);
                data.Add(((path.Count() + 2) / 2).GetBytes());
                data.Add(path);
                data.Add(new byte[] { 0, 0 });
            }

            if (exporterVersion >= ExporterVersion.Ver16Alpha1)
            {
                // export curves to a file
                data.Add(BitConverter.GetBytes(curve_and_index.Count));
                foreach (var curve in curve_and_index)
                {
                    var path = Encoding.Unicode.GetBytes(curve.Key);
                    data.Add(((path.Count() + 2) / 2).GetBytes());
                    data.Add(path);
                    data.Add(new byte[] { 0, 0 });
                }

                // export procedural meshes
                data.Add(BitConverter.GetBytes(ProceduralModels.Count));
                foreach (var param in ProceduralModels)
                {
                    var type = (int)param.Type.Value;
                    data.Add(type.GetBytes());

                    if (param.Type.Value == ProceduralModelType.Mesh)
                    {
                        data.Add(param.Mesh.AngleBeginEnd.X.Value.GetBytes());
                        data.Add(param.Mesh.AngleBeginEnd.Y.Value.GetBytes());
                        data.Add((byte[])param.Mesh.Divisions);
                        data.Add(param.Mesh.Rotate.Value.GetBytes());
                    }
                    else
                    {
                        data.Add(((int)param.Ribbon.CrossSection.Value).GetBytes());
                        data.Add(param.Ribbon.Rotate.Value.GetBytes());
                        data.Add(param.Ribbon.Vertices.Value.GetBytes());
                        data.Add((byte[])param.Ribbon.RibbonScales);
                        data.Add((byte[])param.Ribbon.RibbonAngles);
                        data.Add((byte[])param.Ribbon.RibbonNoises);
                        data.Add(param.Ribbon.Count.Value.GetBytes());
                    }

                    var primitiveType = (int)param.Shape.PrimitiveType.Value;

                    data.Add(primitiveType.GetBytes());

                    if (param.Shape.PrimitiveType.Value == ProceduralModelPrimitiveType.Sphere)
                    {
                        data.Add(param.Shape.Radius.Value.GetBytes());
                        data.Add(param.Shape.DepthMin.Value.GetBytes());
                        data.Add(param.Shape.DepthMax.Value.GetBytes());
                    }
                    else if (param.Shape.PrimitiveType.Value == ProceduralModelPrimitiveType.Cone)
                    {
                        data.Add(param.Shape.Radius.Value.GetBytes());
                        data.Add(param.Shape.Depth.Value.GetBytes());
                    }
                    else if (param.Shape.PrimitiveType.Value == ProceduralModelPrimitiveType.Cylinder)
                    {
                        data.Add(param.Shape.Radius.Value.GetBytes());
                        data.Add(param.Shape.Radius2.Value.GetBytes());
                        data.Add(param.Shape.Depth.Value.GetBytes());
                    }
                    else if (param.Shape.PrimitiveType.Value == ProceduralModelPrimitiveType.Spline4)
                    {
                        data.Add((byte[])param.Shape.Point1);
                        data.Add((byte[])param.Shape.Point2);
                        data.Add((byte[])param.Shape.Point3);
                        data.Add((byte[])param.Shape.Point4);
                    }

                    var axisType = (int)param.Shape.AxisType.Value;
                    data.Add(axisType.GetBytes());

                    data.Add((byte[])param.ShapeNoise.TiltNoiseFrequency);
                    data.Add((byte[])param.ShapeNoise.TiltNoiseOffset);
                    data.Add((byte[])param.ShapeNoise.TiltNoisePower);
                    data.Add((byte[])param.ShapeNoise.WaveNoiseFrequency);
                    data.Add((byte[])param.ShapeNoise.WaveNoiseOffset);
                    data.Add((byte[])param.ShapeNoise.WaveNoisePower);
                    data.Add((byte[])param.ShapeNoise.CurlNoiseFrequency);
                    data.Add((byte[])param.ShapeNoise.CurlNoiseOffset);
                    data.Add((byte[])param.ShapeNoise.CurlNoisePower);

                    data.Add((byte[])param.VertexColor.ColorUpperLeft);
                    data.Add((byte[])param.VertexColor.ColorUpperCenter);
                    data.Add((byte[])param.VertexColor.ColorUpperRight);

                    data.Add((byte[])param.VertexColor.ColorMiddleLeft);
                    data.Add((byte[])param.VertexColor.ColorMiddleCenter);
                    data.Add((byte[])param.VertexColor.ColorMiddleRight);

                    data.Add((byte[])param.VertexColor.ColorLowerLeft);
                    data.Add((byte[])param.VertexColor.ColorLowerCenter);
                    data.Add((byte[])param.VertexColor.ColorLowerRight);

                    data.Add((byte[])param.VertexColor.ColorCenterPosition);
                    data.Add((byte[])param.VertexColor.ColorCenterArea);

                    data.Add((byte[])param.VertexColorNoise.NoiseFrequency);
                    data.Add((byte[])param.VertexColorNoise.NoiseOffset);
                    data.Add((byte[])param.VertexColorNoise.NoisePower);

                    data.Add((byte[])param.UV.UVPosition);
                    data.Add((byte[])param.UV.UVSize);
                }
            }

            // export dynamic parameters
            data.Add(BitConverter.GetBytes(Core.Dynamic.Inputs.Values.Count));
            foreach (var value in Core.Dynamic.Inputs.Values)
            {
                float value_ = value.Input.Value;
                data.Add(BitConverter.GetBytes(value_));
            }

            data.Add(BitConverter.GetBytes(Core.Dynamic.Equations.Values.Count));

            var compiler = new InternalScript.Compiler();

            foreach (var value in Core.Dynamic.Equations.Values)
            {
                var cx = compiler.Compile(value.Code.Value);

                var cs = new[] { cx };

                foreach (var c in cs)
                {
                    if (c.Bytecode != null)
                    {
                        data.Add(BitConverter.GetBytes((int)c.Bytecode.Length));
                        data.Add(c.Bytecode);
                    }
                    else
                    {
                        data.Add(BitConverter.GetBytes((int)0));
                    }
                }
            }

            // Export the number of nodes
            data.Add(BitConverter.GetBytes(snode2ind.Count));

            var renderPriorityThreshold = snode2ind.Where(_ => _.Item1.DepthValues.DrawingPriority.Value < 0).Count();

            data.Add(BitConverter.GetBytes(renderPriorityThreshold));

            // Export magnification
            data.Add(BitConverter.GetBytes(magnification));

            // Export default seed
            int randomSeed = Core.Global.RandomSeed.Value;

            data.Add(BitConverter.GetBytes(randomSeed));

            // カリングを出力
            data.Add(BitConverter.GetBytes((int)Core.Culling.Type.Value));

            if (Core.Culling.Type.Value == Data.EffectCullingValues.ParamaterType.Sphere)
            {
                data.Add(BitConverter.GetBytes(Core.Culling.Sphere.Radius));
                data.Add(BitConverter.GetBytes(Core.Culling.Sphere.Location.X));
                data.Add(BitConverter.GetBytes(Core.Culling.Sphere.Location.Y));
                data.Add(BitConverter.GetBytes(Core.Culling.Sphere.Location.Z));
            }

            // ノード情報出力
            Action <Data.NodeRoot> outout_rootnode = null;
            Action <Data.Node>     outout_node     = null;

            // Identifier to use when referring to a node from the editor.
            int nextEditorNodeId = 1;

            outout_rootnode = (n) =>
            {
                n.EditorNodeId = nextEditorNodeId;
                nextEditorNodeId++;

                data.Add(((int)NodeType.Root).GetBytes());

                var children = n.Children.Internal.Where(_ => IsRenderedNodeGroup(_)).ToList();

                data.Add(children.Count.GetBytes());
                for (int i = 0; i < children.Count; i++)
                {
                    outout_node(children[i]);
                }
            };


            outout_node = (n) =>
            {
                n.EditorNodeId = nextEditorNodeId;
                nextEditorNodeId++;

                List <byte[]> node_data = new List <byte[]>();

                var isRenderParamExported = n.IsRendered.GetValue();

                for (int i = 0; i < n.Children.Count; i++)
                {
                    var nc = n.Children[i];
                    var v  = nc.RendererCommonValues.ColorInheritType.GetValue();
                    if (v == Data.ParentEffectType.Already || v == Data.ParentEffectType.WhenCreating)
                    {
                        isRenderParamExported = true;
                        break;
                    }
                }

                if (!isRenderParamExported)
                {
                    data.Add(((int)NodeType.None).GetBytes());
                }
                else if (n.DrawingValues.Type.Value == Data.RendererValues.ParamaterType.None)
                {
                    data.Add(((int)NodeType.None).GetBytes());
                }
                else if (n.DrawingValues.Type.Value == Data.RendererValues.ParamaterType.Sprite)
                {
                    data.Add(((int)NodeType.Sprite).GetBytes());
                }
                else if (n.DrawingValues.Type.Value == Data.RendererValues.ParamaterType.Ribbon)
                {
                    data.Add(((int)NodeType.Ribbon).GetBytes());
                }
                else if (n.DrawingValues.Type.Value == Data.RendererValues.ParamaterType.Ring)
                {
                    data.Add(((int)NodeType.Ring).GetBytes());
                }
                else if (n.DrawingValues.Type.Value == Data.RendererValues.ParamaterType.Model)
                {
                    data.Add(((int)NodeType.Model).GetBytes());
                }
                else if (n.DrawingValues.Type.Value == Data.RendererValues.ParamaterType.Track)
                {
                    data.Add(((int)NodeType.Track).GetBytes());
                }
                else
                {
                    throw new Exception();
                }

                // Whether to draw the node.
                if (n.IsRendered)
                {
                    int v = 1;
                    node_data.Add(BitConverter.GetBytes(v));
                }
                else
                {
                    int v = 0;
                    node_data.Add(BitConverter.GetBytes(v));
                }

                // render order
                {
                    var s = snode2ind.FirstOrDefault(_ => _.Item1 == n);
                    if (s.Item1 != null)
                    {
                        node_data.Add(BitConverter.GetBytes(s.Item2));
                    }
                    else
                    {
                        node_data.Add(BitConverter.GetBytes(-1));
                    }
                }

                node_data.Add(CommonValues.GetBytes(n.CommonValues));
                node_data.Add(LocationValues.GetBytes(n.LocationValues, n.CommonValues.ScaleEffectType, curve_and_index, exporterVersion));

                node_data.Add(LocationAbsValues.GetBytes(n.LocationAbsValues, n.CommonValues.ScaleEffectType, exporterVersion));
                node_data.Add(RotationValues.GetBytes(n.RotationValues, exporterVersion));
                node_data.Add(ScaleValues.GetBytes(n.ScalingValues, n.CommonValues.ScaleEffectType, exporterVersion));
                node_data.Add(GenerationLocationValues.GetBytes(n.GenerationLocationValues, n.CommonValues.ScaleEffectType, model_and_index, procedural_mesh_and_index, exporterVersion));

                // Export depth
                node_data.Add(n.DepthValues.DepthOffset.Value.GetBytes());
                node_data.Add(BitConverter.GetBytes(n.DepthValues.IsScaleChangedDependingOnDepthOffset.Value ? 1 : 0));
                node_data.Add(BitConverter.GetBytes(n.DepthValues.IsDepthOffsetChangedDependingOnParticleScale.Value ? 1 : 0));

                node_data.Add(((float)n.DepthValues.SuppressionOfScalingByDepth.Value).GetBytes());

                if (n.DepthValues.DepthClipping.Infinite)
                {
                    node_data.Add((float.MaxValue).GetBytes());
                }
                else
                {
                    node_data.Add(((float)n.DepthValues.DepthClipping.Value.Value).GetBytes());
                }

                node_data.Add(((int)n.DepthValues.ZSort.Value).GetBytes());
                node_data.Add(n.DepthValues.DrawingPriority.Value.GetBytes());

                float compatibility = 1.0f;
                node_data.Add(compatibility.GetBytes());

#if DEBUG
                {
                    var old  = RendererCommonValues_Old.GetBytes(n.RendererCommonValues, n.AdvancedRendererCommonValuesValues, texture_and_index, normalTexture_and_index, distortionTexture_and_index, material_and_index, exporterVersion);
                    var @new = RendererCommonValues.GetBytes(n.RendererCommonValues, n.AdvancedRendererCommonValuesValues, texture_and_index, normalTexture_and_index, distortionTexture_and_index, material_and_index, exporterVersion);
                    if (!old.SequenceEqual(@new))
                    {
                        throw new Exception("RendererCommonValues.GetBytes returned unexpected data.");
                    }

                    node_data.Add(@new);
                }
#else
                node_data.Add(RendererCommonValues.GetBytes(n.RendererCommonValues, n.AdvancedRendererCommonValuesValues, texture_and_index, normalTexture_and_index, distortionTexture_and_index, material_and_index, exporterVersion));
#endif

                if (isRenderParamExported)
                {
                    node_data.Add(RendererValues.GetBytes(n.DrawingValues, texture_and_index, normalTexture_and_index, model_and_index, procedural_mesh_and_index, exporterVersion));
                }
                else
                {
                    node_data.Add(RendererValues.GetBytes(null, texture_and_index, normalTexture_and_index, model_and_index, procedural_mesh_and_index, exporterVersion));
                }

                data.Add(node_data.ToArray().ToArray());

                data.Add(SoundValues.GetBytes(n.SoundValues, wave_and_index));

                var children = n.Children.Internal.Where(_ => IsRenderedNodeGroup(_)).ToList();

                data.Add(children.Count.GetBytes());
                for (int i = 0; i < children.Count; i++)
                {
                    outout_node(children[i]);
                }
            };

            outout_rootnode(rootNode);

            return(data.ToArray().ToArray());
        }
示例#48
0
        internal void WriteToStream(Stream stream, YamlMappingNode?rootNode = null)
        {
            string ToSequenceKey(string itemTypeName)
            {
                return(itemTypeName + "s");
            }

            string?GetItemUid(YamlNode item)
            {
                if (item is YamlMappingNode map)
                {
                    YamlNode name;
                    if (map.Children.TryGetValue(new YamlScalarNode(Utils.UidKey), out name))
                    {
                        if (name is YamlScalarNode nameValue)
                        {
                            return(nameValue.Value);
                        }
                    }
                }
                return("");
            }

            rootNode ??= new YamlMappingNode();
            rootNode.AddStringMapping(Utils.UidKey, this.uid);
            rootNode.AddStringMapping(Utils.NameKey, this.name);
            if (!string.IsNullOrEmpty(this.summary))
            {
                rootNode.AddStringMapping(Utils.SummaryKey, this.summary);
            }

            var itemTypeNodes = new Dictionary <string, SortedDictionary <string, YamlNode> >();

            // Collect existing items
            foreach (var itemType in new[] { Utils.FunctionKind, Utils.OperationKind, Utils.UdtKind })
            {
                var seqKey   = ToSequenceKey(itemType);
                var thisList = new SortedDictionary <string, YamlNode>();
                itemTypeNodes[seqKey] = thisList;

                if (rootNode.Children.TryGetValue(seqKey, out var typeNode))
                {
                    var typeRoot = typeNode as YamlSequenceNode;
                    // We can safely assert here, since we know that the type
                    // node is always a mapping node. That said, it's better to
                    // be explicit and throw an exception instead if the cast
                    // fails.
                    if (typeRoot == null)
                    {
                        throw new Exception($"Expected {itemType} to be a mapping node, was actually a {typeNode.GetType()}.");
                    }
                    foreach (var item in typeRoot)
                    {
                        var uid = GetItemUid(item);
                        if (uid != null)
                        {
                            thisList.Add(uid, item);
                        }
                    }
                }
            }

            // Now add our new items, overwriting if they already exist
            foreach (var item in this.items)
            {
                var typeKey = ToSequenceKey(item.ItemType);
                if (itemTypeNodes.TryGetValue(typeKey, out var typeList))
                {
                    if (typeList.ContainsKey(item.Uid))
                    {
                        // TODO: Emit a warning log / diagnostic. What is the accepted way to do that here?
                        // $"Documentation for {item.Uid} already exists in this folder and will be overwritten.
                        // It's recommended to compile docs to a new folder to avoid deleted files lingering."
                    }

                    typeList[item.Uid] = item.ToNamespaceItem();
                }
            }

            // Now set the merged list back onto the root node
            foreach (var kvp in itemTypeNodes)
            {
                if (kvp.Value.Values.Count > 0)
                {
                    var sortedItems = new YamlSequenceNode(kvp.Value.Values);
                    rootNode.Children[new YamlScalarNode(kvp.Key)] = sortedItems;
                }
            }

            var doc        = new YamlDocument(rootNode);
            var yamlStream = new YamlStream(doc);

            using var output = new StreamWriter(stream);
            output.WriteLine("### " + Utils.QsNamespaceYamlMime + Utils.AutogenerationWarning);
            yamlStream.Save(output, false);
        }
示例#49
0
        static void InitEntities()
        {
            // Build the hash table of HTML entity references.  This list comes
            // from the HTML 4.01 W3C recommendation.
            entities = new SortedDictionary <string, char>(StringComparer.Ordinal);

            entities.Add("nbsp", '\u00A0');
            entities.Add("iexcl", '\u00A1');
            entities.Add("cent", '\u00A2');
            entities.Add("pound", '\u00A3');
            entities.Add("curren", '\u00A4');
            entities.Add("yen", '\u00A5');
            entities.Add("brvbar", '\u00A6');
            entities.Add("sect", '\u00A7');
            entities.Add("uml", '\u00A8');
            entities.Add("copy", '\u00A9');
            entities.Add("ordf", '\u00AA');
            entities.Add("laquo", '\u00AB');
            entities.Add("not", '\u00AC');
            entities.Add("shy", '\u00AD');
            entities.Add("reg", '\u00AE');
            entities.Add("macr", '\u00AF');
            entities.Add("deg", '\u00B0');
            entities.Add("plusmn", '\u00B1');
            entities.Add("sup2", '\u00B2');
            entities.Add("sup3", '\u00B3');
            entities.Add("acute", '\u00B4');
            entities.Add("micro", '\u00B5');
            entities.Add("para", '\u00B6');
            entities.Add("middot", '\u00B7');
            entities.Add("cedil", '\u00B8');
            entities.Add("sup1", '\u00B9');
            entities.Add("ordm", '\u00BA');
            entities.Add("raquo", '\u00BB');
            entities.Add("frac14", '\u00BC');
            entities.Add("frac12", '\u00BD');
            entities.Add("frac34", '\u00BE');
            entities.Add("iquest", '\u00BF');
            entities.Add("Agrave", '\u00C0');
            entities.Add("Aacute", '\u00C1');
            entities.Add("Acirc", '\u00C2');
            entities.Add("Atilde", '\u00C3');
            entities.Add("Auml", '\u00C4');
            entities.Add("Aring", '\u00C5');
            entities.Add("AElig", '\u00C6');
            entities.Add("Ccedil", '\u00C7');
            entities.Add("Egrave", '\u00C8');
            entities.Add("Eacute", '\u00C9');
            entities.Add("Ecirc", '\u00CA');
            entities.Add("Euml", '\u00CB');
            entities.Add("Igrave", '\u00CC');
            entities.Add("Iacute", '\u00CD');
            entities.Add("Icirc", '\u00CE');
            entities.Add("Iuml", '\u00CF');
            entities.Add("ETH", '\u00D0');
            entities.Add("Ntilde", '\u00D1');
            entities.Add("Ograve", '\u00D2');
            entities.Add("Oacute", '\u00D3');
            entities.Add("Ocirc", '\u00D4');
            entities.Add("Otilde", '\u00D5');
            entities.Add("Ouml", '\u00D6');
            entities.Add("times", '\u00D7');
            entities.Add("Oslash", '\u00D8');
            entities.Add("Ugrave", '\u00D9');
            entities.Add("Uacute", '\u00DA');
            entities.Add("Ucirc", '\u00DB');
            entities.Add("Uuml", '\u00DC');
            entities.Add("Yacute", '\u00DD');
            entities.Add("THORN", '\u00DE');
            entities.Add("szlig", '\u00DF');
            entities.Add("agrave", '\u00E0');
            entities.Add("aacute", '\u00E1');
            entities.Add("acirc", '\u00E2');
            entities.Add("atilde", '\u00E3');
            entities.Add("auml", '\u00E4');
            entities.Add("aring", '\u00E5');
            entities.Add("aelig", '\u00E6');
            entities.Add("ccedil", '\u00E7');
            entities.Add("egrave", '\u00E8');
            entities.Add("eacute", '\u00E9');
            entities.Add("ecirc", '\u00EA');
            entities.Add("euml", '\u00EB');
            entities.Add("igrave", '\u00EC');
            entities.Add("iacute", '\u00ED');
            entities.Add("icirc", '\u00EE');
            entities.Add("iuml", '\u00EF');
            entities.Add("eth", '\u00F0');
            entities.Add("ntilde", '\u00F1');
            entities.Add("ograve", '\u00F2');
            entities.Add("oacute", '\u00F3');
            entities.Add("ocirc", '\u00F4');
            entities.Add("otilde", '\u00F5');
            entities.Add("ouml", '\u00F6');
            entities.Add("divide", '\u00F7');
            entities.Add("oslash", '\u00F8');
            entities.Add("ugrave", '\u00F9');
            entities.Add("uacute", '\u00FA');
            entities.Add("ucirc", '\u00FB');
            entities.Add("uuml", '\u00FC');
            entities.Add("yacute", '\u00FD');
            entities.Add("thorn", '\u00FE');
            entities.Add("yuml", '\u00FF');
            entities.Add("fnof", '\u0192');
            entities.Add("Alpha", '\u0391');
            entities.Add("Beta", '\u0392');
            entities.Add("Gamma", '\u0393');
            entities.Add("Delta", '\u0394');
            entities.Add("Epsilon", '\u0395');
            entities.Add("Zeta", '\u0396');
            entities.Add("Eta", '\u0397');
            entities.Add("Theta", '\u0398');
            entities.Add("Iota", '\u0399');
            entities.Add("Kappa", '\u039A');
            entities.Add("Lambda", '\u039B');
            entities.Add("Mu", '\u039C');
            entities.Add("Nu", '\u039D');
            entities.Add("Xi", '\u039E');
            entities.Add("Omicron", '\u039F');
            entities.Add("Pi", '\u03A0');
            entities.Add("Rho", '\u03A1');
            entities.Add("Sigma", '\u03A3');
            entities.Add("Tau", '\u03A4');
            entities.Add("Upsilon", '\u03A5');
            entities.Add("Phi", '\u03A6');
            entities.Add("Chi", '\u03A7');
            entities.Add("Psi", '\u03A8');
            entities.Add("Omega", '\u03A9');
            entities.Add("alpha", '\u03B1');
            entities.Add("beta", '\u03B2');
            entities.Add("gamma", '\u03B3');
            entities.Add("delta", '\u03B4');
            entities.Add("epsilon", '\u03B5');
            entities.Add("zeta", '\u03B6');
            entities.Add("eta", '\u03B7');
            entities.Add("theta", '\u03B8');
            entities.Add("iota", '\u03B9');
            entities.Add("kappa", '\u03BA');
            entities.Add("lambda", '\u03BB');
            entities.Add("mu", '\u03BC');
            entities.Add("nu", '\u03BD');
            entities.Add("xi", '\u03BE');
            entities.Add("omicron", '\u03BF');
            entities.Add("pi", '\u03C0');
            entities.Add("rho", '\u03C1');
            entities.Add("sigmaf", '\u03C2');
            entities.Add("sigma", '\u03C3');
            entities.Add("tau", '\u03C4');
            entities.Add("upsilon", '\u03C5');
            entities.Add("phi", '\u03C6');
            entities.Add("chi", '\u03C7');
            entities.Add("psi", '\u03C8');
            entities.Add("omega", '\u03C9');
            entities.Add("thetasym", '\u03D1');
            entities.Add("upsih", '\u03D2');
            entities.Add("piv", '\u03D6');
            entities.Add("bull", '\u2022');
            entities.Add("hellip", '\u2026');
            entities.Add("prime", '\u2032');
            entities.Add("Prime", '\u2033');
            entities.Add("oline", '\u203E');
            entities.Add("frasl", '\u2044');
            entities.Add("weierp", '\u2118');
            entities.Add("image", '\u2111');
            entities.Add("real", '\u211C');
            entities.Add("trade", '\u2122');
            entities.Add("alefsym", '\u2135');
            entities.Add("larr", '\u2190');
            entities.Add("uarr", '\u2191');
            entities.Add("rarr", '\u2192');
            entities.Add("darr", '\u2193');
            entities.Add("harr", '\u2194');
            entities.Add("crarr", '\u21B5');
            entities.Add("lArr", '\u21D0');
            entities.Add("uArr", '\u21D1');
            entities.Add("rArr", '\u21D2');
            entities.Add("dArr", '\u21D3');
            entities.Add("hArr", '\u21D4');
            entities.Add("forall", '\u2200');
            entities.Add("part", '\u2202');
            entities.Add("exist", '\u2203');
            entities.Add("empty", '\u2205');
            entities.Add("nabla", '\u2207');
            entities.Add("isin", '\u2208');
            entities.Add("notin", '\u2209');
            entities.Add("ni", '\u220B');
            entities.Add("prod", '\u220F');
            entities.Add("sum", '\u2211');
            entities.Add("minus", '\u2212');
            entities.Add("lowast", '\u2217');
            entities.Add("radic", '\u221A');
            entities.Add("prop", '\u221D');
            entities.Add("infin", '\u221E');
            entities.Add("ang", '\u2220');
            entities.Add("and", '\u2227');
            entities.Add("or", '\u2228');
            entities.Add("cap", '\u2229');
            entities.Add("cup", '\u222A');
            entities.Add("int", '\u222B');
            entities.Add("there4", '\u2234');
            entities.Add("sim", '\u223C');
            entities.Add("cong", '\u2245');
            entities.Add("asymp", '\u2248');
            entities.Add("ne", '\u2260');
            entities.Add("equiv", '\u2261');
            entities.Add("le", '\u2264');
            entities.Add("ge", '\u2265');
            entities.Add("sub", '\u2282');
            entities.Add("sup", '\u2283');
            entities.Add("nsub", '\u2284');
            entities.Add("sube", '\u2286');
            entities.Add("supe", '\u2287');
            entities.Add("oplus", '\u2295');
            entities.Add("otimes", '\u2297');
            entities.Add("perp", '\u22A5');
            entities.Add("sdot", '\u22C5');
            entities.Add("lceil", '\u2308');
            entities.Add("rceil", '\u2309');
            entities.Add("lfloor", '\u230A');
            entities.Add("rfloor", '\u230B');
            entities.Add("lang", '\u2329');
            entities.Add("rang", '\u232A');
            entities.Add("loz", '\u25CA');
            entities.Add("spades", '\u2660');
            entities.Add("clubs", '\u2663');
            entities.Add("hearts", '\u2665');
            entities.Add("diams", '\u2666');
            entities.Add("quot", '\u0022');
            entities.Add("amp", '\u0026');
            entities.Add("lt", '\u003C');
            entities.Add("gt", '\u003E');
            entities.Add("OElig", '\u0152');
            entities.Add("oelig", '\u0153');
            entities.Add("Scaron", '\u0160');
            entities.Add("scaron", '\u0161');
            entities.Add("Yuml", '\u0178');
            entities.Add("circ", '\u02C6');
            entities.Add("tilde", '\u02DC');
            entities.Add("ensp", '\u2002');
            entities.Add("emsp", '\u2003');
            entities.Add("thinsp", '\u2009');
            entities.Add("zwnj", '\u200C');
            entities.Add("zwj", '\u200D');
            entities.Add("lrm", '\u200E');
            entities.Add("rlm", '\u200F');
            entities.Add("ndash", '\u2013');
            entities.Add("mdash", '\u2014');
            entities.Add("lsquo", '\u2018');
            entities.Add("rsquo", '\u2019');
            entities.Add("sbquo", '\u201A');
            entities.Add("ldquo", '\u201C');
            entities.Add("rdquo", '\u201D');
            entities.Add("bdquo", '\u201E');
            entities.Add("dagger", '\u2020');
            entities.Add("Dagger", '\u2021');
            entities.Add("permil", '\u2030');
            entities.Add("lsaquo", '\u2039');
            entities.Add("rsaquo", '\u203A');
            entities.Add("euro", '\u20AC');
        }
示例#50
0
        public void GenerateImports()
        {
            _imports.Clear();
            Dictionary <uint, ImportData> tempImports = new Dictionary <uint, ImportData>();

            foreach (ModuleSectionNode s in _sections)
            {
                foreach (ImportData e in tempImports.Values)
                {
                    e._newSection = true;
                    e._lastOffset = 0;
                }

                uint           offset = 0;
                List <RELLink> links;

                //Iterate through each command in the section
                var commands = s._manager.GetCommands();
                foreach (var r in commands)
                {
                    RelCommand command = r.Value;
                    int        index   = r.Key;

                    ImportData impData;
                    uint       moduleID = command._moduleID;

                    //Check if an import has been created for the target module.
                    if (_imports.ContainsKey(moduleID))
                    {
                        //An import already exists, so we'll add to it.
                        links   = _imports[moduleID];
                        impData = tempImports[moduleID];
                    }
                    else
                    {
                        //An import does not exist, so it must be made.
                        _imports.Add(moduleID, links = new List <RELLink>());

                        //Create new temporary import data
                        tempImports.Add(moduleID, impData = new ImportData()
                        {
                            _newSection = true, _lastOffset = 0
                        });
                    }

                    //This is true when a new section is being evaluated.
                    if (impData._newSection)
                    {
                        links.Add(new RELLink()
                        {
                            _type = RELLinkType.Section, _section = (byte)s.Index
                        });
                        impData._newSection = false;
                    }

                    //Get the offset of the command within the section.
                    offset = (uint)index * 4 + (command.IsHalf ? 2u : 0);

                    //Get the offset to this address relative to the last written link offset.
                    uint diff = offset - impData._lastOffset;

                    //If the difference is greater than ushort allows,
                    //add increment links until the difference works
                    while (diff > 0xFFFF)
                    {
                        impData._lastOffset += 0xFFFF;
                        diff = offset - impData._lastOffset;

                        links.Add(new RELLink()
                        {
                            _type = RELLinkType.IncrementOffset, _section = 0, _value = 0, _prevOffset = 0xFFFF
                        });
                    }

                    //Gather the link information
                    byte        targetSection = (byte)command._targetSectionId;
                    RELLinkType type          = (RELLinkType)command._command;
                    uint        val           = command._addend;

                    //Write command link
                    links.Add(new RELLink()
                    {
                        _type = type, _section = targetSection, _value = val, _prevOffset = (ushort)diff
                    });

                    //Don't bother adding the difference,
                    //just set the exact offset as the last offset
                    impData._lastOffset = offset;
                }
            }

            foreach (List <RELLink> cmds in _imports.Values)
            {
                cmds.Add(new RELLink()
                {
                    _type = RELLinkType.End
                });
            }
        }
示例#51
0
        public static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());

            string type   = string.Empty;
            string name   = string.Empty;
            double health = 0;
            double damage = 0;
            double armor  = 0;

            var types = new Dictionary <string, SortedDictionary <string, List <double> > >();
            var names = new SortedDictionary <string, List <double> >();
            var list  = new List <double>();

            for (int i = 0; i < n; i++)
            {
                //Reset
                type   = string.Empty;
                name   = string.Empty;
                health = 0;
                damage = 0;
                armor  = 0;
                list   = new List <double>();
                names  = new SortedDictionary <string, List <double> >();
                //Record characteristics
                var entry = Console.ReadLine().Split(' ').ToList();
                type = entry[0];
                name = entry[1];
                try
                {
                    damage = Convert.ToInt32(entry[2]);
                }
                catch (Exception)
                {
                    damage = 45;
                }
                try
                {
                    health = Convert.ToInt32(entry[3]);
                }
                catch (Exception)
                {
                    health = 250;
                }
                try
                {
                    armor = Convert.ToInt32(entry[4]);
                }
                catch (Exception)
                {
                    armor = 10;
                }
                list.Add(damage);
                list.Add(health);
                list.Add(armor);
                if (!types.ContainsKey(type))
                {
                    names[name] = list;
                    types[type] = names;
                }
                else
                {
                    names = types[type];
                    if (!names.ContainsKey(name))
                    {
                        names.Add(name, list);
                        types[type] = names;
                    }
                    else
                    {
                        names[name] = list;
                        types[type] = names;
                    }
                }
            }
            //Printing out
            foreach (var color in types)
            {
                double avrgDmg    = color.Value.Select(x => x.Value[0]).Average();
                double avrgHealth = color.Value.Select(x => x.Value[1]).Average();
                double avrgArm    = color.Value.Select(x => x.Value[2]).Average();
                Console.WriteLine($"{color.Key}::({avrgDmg:f2}/{avrgHealth:f2}/{avrgArm:f2})");
                foreach (var drag in color.Value)
                {
                    Console.WriteLine($"-{drag.Key} -> damage: {drag.Value[0]}, health: {drag.Value[1]}, armor: {drag.Value[2]}");
                }
            }
        }
示例#52
0
 static FilterFunctions()
 {
     All.Add("username", new UserNameFilterFunction());
     All.Add("userid", new UserIdFilterFunction());
     All.Add("external", new ExternalFilterFunction());
     All.Add("beginswith", new TextMatchingFilterFunction("{0}%"));
     All.Add("doesnotbeginwith", new NegativeTextMatchingFilterFunction("{0}%"));
     All.Add("contains", new TextMatchingFilterFunction("%{0}%"));
     All.Add("doesnotcontain", new NegativeTextMatchingFilterFunction("%{0}%"));
     All.Add("endswith", new TextMatchingFilterFunction("%{0}"));
     All.Add("doesnotendwith", new NegativeTextMatchingFilterFunction("%{0}"));
     All.Add("between", new BetweenFilterFunction());
     All.Add("in", new InFilterFunction());
     All.Add("notin", new NotInFilterFunction());
     All.Add("month1", new DateRangeFilterFunction(1));
     All.Add("month2", new DateRangeFilterFunction(2));
     All.Add("month3", new DateRangeFilterFunction(3));
     All.Add("month4", new DateRangeFilterFunction(4));
     All.Add("month5", new DateRangeFilterFunction(5));
     All.Add("month6", new DateRangeFilterFunction(6));
     All.Add("month7", new DateRangeFilterFunction(7));
     All.Add("month8", new DateRangeFilterFunction(8));
     All.Add("month9", new DateRangeFilterFunction(9));
     All.Add("month10", new DateRangeFilterFunction(10));
     All.Add("month11", new DateRangeFilterFunction(11));
     All.Add("month12", new DateRangeFilterFunction(12));
     All.Add("thismonth", new ThisMonthFilterFunction(0));
     All.Add("nextmonth", new ThisMonthFilterFunction(1));
     All.Add("lastmonth", new ThisMonthFilterFunction(-1));
     All.Add("quarter1", new QuarterFilterFunction(1));
     All.Add("quarter2", new QuarterFilterFunction(2));
     All.Add("quarter3", new QuarterFilterFunction(3));
     All.Add("quarter4", new QuarterFilterFunction(4));
     All.Add("thisquarter", new ThisQuarterFilterFunction(0));
     All.Add("lastquarter", new ThisQuarterFilterFunction(-1));
     All.Add("nextquarter", new ThisQuarterFilterFunction(1));
     All.Add("thisyear", new ThisYearFilterFunction(0));
     All.Add("lastyear", new ThisYearFilterFunction(-1));
     All.Add("nextyear", new ThisYearFilterFunction(1));
     All.Add("yeartodate", new YearToDateFilterFunction());
     All.Add("thisweek", new ThisWeekFilterFunction(0));
     All.Add("lastweek", new ThisWeekFilterFunction(-1));
     All.Add("nextweek", new ThisWeekFilterFunction(1));
     All.Add("today", new TodayFilterFunction(0));
     All.Add("yesterday", new TodayFilterFunction(-1));
     All.Add("tomorrow", new TodayFilterFunction(1));
     All.Add("past", new PastFilterFunction());
     All.Add("future", new FutureFilterFunction());
     All.Add("true", new TrueFilterFunction());
     All.Add("false", new FalseFilterFunction());
     All.Add("isempty", new IsEmptyFilterFunction());
     All.Add("isnotempty", new IsNotEmptyFilterFunction());
 }
示例#53
0
    //考虑网格合并,把使用一个材质的子网格,合并到一起
    int ReadEach(string[] line, int start, int idx)
    {
        //int end = start;
        int left   = 0;
        int matidx = -1;

        for (int i = start; i < line.Length; i++)
        {
            string[] lineobj = line[i].Split(new char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);
            lineobj[0] = lineobj[0].Trim(new char[] { '\t' });
            if (lineobj[0].StartsWith("#"))
            {
                continue;
            }
            else
            if (lineobj[0] == "Static" && lineobj[1] == "Skin" && lineobj.Length == 3)
            {
                Skin = lineobj[2];
            }
            else if (lineobj[0] == "{")
            {
                left++;
            }
            else if (lineobj[0] == "}")
            {
                left--;
                if (left == 0)
                {
                    return(i + 1);
                }
            }
            else if (lineobj[0] == "Materials:")
            {
                materials = new MaterialUnit[int.Parse(lineobj[1])];
            }
            else if (lineobj[0] == "Material")
            {
                matidx++;
                materials[matidx] = new MaterialUnit();
                //mat[matidx] = new Material(Shader.Find("Unlit/Texture"));
            }
            else if (lineobj[0] == "Texture")
            {
                string text = lineobj[1];
                int    dot  = text.LastIndexOf(".");
                if (dot != -1)
                {
                    text = text.Substring(0, dot);
                }
                materials[matidx].Texture = text;
            }
            else if (lineobj[0] == "ColorKey")
            {
                materials[matidx].ColorKey = new Color(float.Parse(lineobj[1]), float.Parse(lineobj[2]), float.Parse(lineobj[3]), float.Parse(lineobj[4]));
            }
            else if (lineobj[0] == "Ambient")
            {
                materials[matidx].Ambient = new Color(float.Parse(lineobj[1]), float.Parse(lineobj[2]), float.Parse(lineobj[3]));
            }
            else if (lineobj[0] == "Diffuse")
            {
                materials[matidx].Diffuse = new Color(float.Parse(lineobj[1]), float.Parse(lineobj[2]), float.Parse(lineobj[3]));
            }
            else if (lineobj[0] == "Specular")
            {
                materials[matidx].ColorKey = new Color(float.Parse(lineobj[1]), float.Parse(lineobj[2]), float.Parse(lineobj[3]));
            }
            else if (lineobj[0] == "Emissive")
            {
                materials[matidx].ColorKey = new Color(float.Parse(lineobj[1]), float.Parse(lineobj[2]), float.Parse(lineobj[3]));
            }
            else if (lineobj[0] == "Opacity")
            {
                materials[matidx].Opacity = float.Parse(lineobj[1]);
            }
            else if (lineobj[0] == "Option")
            {
                materials[matidx].Option = lineobj[1];
            }
            else if (lineobj[0] == "TwoSide")
            {
                materials[matidx].TwoSide = (lineobj[1].ToUpper() == "TRUE");
            }
            else if (lineobj[0] == "Vertices:")
            {
                mesh      = new Mesh();
                mesh.name = Skin;
                int                count          = int.Parse(lineobj[1]);
                List <byte>        bonesPerVertex = new List <byte>();
                List <BoneWeight1> boneWeight     = new List <BoneWeight1>();
                List <Vector3>     vec            = new List <Vector3>();
                List <Vector2>     uv             = new List <Vector2>();
                for (int s = i + 1; s < i + 1 + count; s++)
                {
                    string   line2   = line[s];
                    string[] subline = line2.Split(new char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);
                    if (subline.Length == 1)
                    {
                        subline = subline[0].Split(new char[] { '\t' }, System.StringSplitOptions.RemoveEmptyEntries);
                    }
                    //顶点权重非固定
                    if (subline[0] == "v")
                    {
                        Vector3 v = new Vector3();
                        v.x = float.Parse(subline[1]);
                        v.z = float.Parse(subline[2]);
                        v.y = float.Parse(subline[3]);
                        //右手坐标系,换左手坐标系

                        Vector2 uvv = new Vector2();
                        uvv.x = float.Parse(subline[5]);
                        uvv.y = float.Parse(subline[6]);
                        List <BoneWeight1> boneW = new List <BoneWeight1>();
                        int boneCtrlNum          = int.Parse(subline[8]);
                        for (int z = 9; z < 9 + 2 * boneCtrlNum; z += 2)
                        {
                            int         b = (int)float.Parse(subline[z]);
                            float       w = float.Parse(subline[z + 1]);
                            BoneWeight1 e = new BoneWeight1();
                            e.boneIndex = b;
                            e.weight    = w;
                            boneW.Add(e);
                        }
                        //重新按权重设置各自的比例
                        //float weightTotal = 0.0f;
                        //for (int k = 0; k < boneW.Count; k++)
                        //    weightTotal += boneW[k].Weight;
                        //weight.boneIndex0 = boneW.Count >= 1 ? boneW[0].BoneIndex : 0;
                        //weight.weight0 = boneW.Count >= 1 ? boneW[0].Weight / weightTotal : 0;
                        //weight.boneIndex1 = boneW.Count >= 2 ? boneW[1].BoneIndex : 0;
                        //weight.weight1 = boneW.Count >= 2 ? boneW[1].Weight / weightTotal : 0;
                        //weight.boneIndex2 = boneW.Count >= 3 ? boneW[2].BoneIndex : 0;
                        //weight.weight2 = boneW.Count >= 3 ? boneW[2].Weight / weightTotal : 0;
                        //weight.boneIndex3 = boneW.Count >= 4 ? boneW[3].BoneIndex : 0;
                        //weight.weight3 = boneW.Count >= 4 ? boneW[3].Weight / weightTotal : 0;
                        //boneWeight.Add(weight);
                        bonesPerVertex.Add((byte)boneW.Count);
                        boneWeight.AddRange(boneW);
                        vec.Add(v);
                        uv.Add(uvv);
                    }
                }
                mesh.SetVertices(vec);
                mesh.uv = uv.ToArray();
                var bonesPerVertexArray = new NativeArray <byte>(bonesPerVertex.ToArray(), Allocator.Temp);
                var weightsArray        = new NativeArray <BoneWeight1>(boneWeight.ToArray(), Allocator.Temp);
                mesh.SetBoneWeights(bonesPerVertexArray, weightsArray);
                i += count;
            }
            else if (lineobj[0] == "Triangles:")
            {
                int triNum = int.Parse(lineobj[1]);
                SortedDictionary <int, SortedDictionary <int, int[]> > indic = new SortedDictionary <int, SortedDictionary <int, int[]> >();
                for (int s = i + 1; s < i + 1 + triNum; s++)
                {
                    string   line2   = line[s];
                    int      o       = 0;
                    int      p       = 0;
                    int      q       = 0;
                    int      matIdx2 = 0;
                    string[] subline = line2.Split(new char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);
                    if (subline.Length == 1)
                    {
                        subline = subline[0].Split(new char[] { '\t' }, System.StringSplitOptions.RemoveEmptyEntries);
                    }
                    if (subline[0] == "f")
                    {
                        matIdx2 = int.Parse(subline[2]);
                        o       = int.Parse(subline[3]);
                        p       = int.Parse(subline[4]);
                        q       = int.Parse(subline[5]);
                        int[] ind = new int[3] {
                            o, q, p
                        };                                 //反转yz
                        if (indic.ContainsKey(matIdx2))
                        {
                            indic[matIdx2].Add(s - i - 1, ind);
                        }
                        else
                        {
                            SortedDictionary <int, int[]> va = new SortedDictionary <int, int[]>();
                            va.Add(s - i - 1, ind);
                            indic.Add(matIdx2, va);
                        }
                    }
                }
                i += triNum;
                mesh.subMeshCount = materials.Length;
                for (int mm = 0; mm < materials.Length; mm++)
                {
                    if (indic.ContainsKey(mm))
                    {
                        int   cnt  = indic[mm].Count;
                        int[] va   = new int[cnt * 3];
                        int   next = 0;
                        foreach (var each in indic[mm])
                        {
                            va[next++] = each.Value[0];
                            va[next++] = each.Value[1];
                            va[next++] = each.Value[2];
                        }

                        mesh.SetIndices(va, MeshTopology.Triangles, mm);
                        mesh.SetTriangles(va, mm);
                    }
                }
            }
            else
            {
                Debug.LogError(lineobj[0]);
            }
        }
        return(line.Length - 1);
    }
示例#54
0
 public void Add(string name, int init)
 {
     initiative.Add(init, name);
 }
示例#55
0
    public static void Main(string[] args)
    {
        // SortedSet (like c++ set) (Balanced Binary Search Tree)
        Console.WriteLine("Sorted Set Demo");
        // default
        SortedSet <int> sortedSet = new SortedSet <int>();

        // with initial IEnumerable type
        // int[] a = new int[] {6,0,3,10,-1};
        // SortedSet<int> sortedSet = new SortedSet<int>(a);

        // with custom comparer
        // SortedSet<int> sortedSet = new SortedSet<int>(new CustomComparer());

        // with initial IEnumerable type and custom comparer
        // SortedSet<int> sortedSet = new SortedSet<int>(a,new CustomComparer());

        // Add: O(lg n)
        sortedSet.Add(6);
        sortedSet.Add(0);
        sortedSet.Add(3);
        sortedSet.Add(10);
        sortedSet.Add(-1);

        // contains O(lg n)
        Console.WriteLine($"sortedSet contains 3? {sortedSet.Contains(3)}");
        Console.WriteLine($"sortedSet contains 2? {sortedSet.Contains(2)}");

        // Remove: O(lg n)
        sortedSet.Remove(3);

        foreach (int num in sortedSet)
        {
            Console.Write(num + " ");
        }
        Console.WriteLine();

        Console.WriteLine($"Count {sortedSet.Count}");
        // ** Min Max in O(1) time (This allows us to use this like Priority Queue)
        Console.WriteLine($"Min {sortedSet.Min}");
        Console.WriteLine($"Max {sortedSet.Max}");

        // Supports Some Set Operation. See doc for details

        // Sorted Dictionary (like c++ map) (Balanced Binary Search Tree)
        // Sorted on key
        Console.WriteLine("Sorted Dictionary Demo");
        SortedDictionary <int, string> map = new SortedDictionary <int, string>();

        // also supports constructor
        // SortedDictionary<TKey,TValue>(IComparer<TKey>)
        // SortedDictionary<TKey,TValue>(IDictionary<TKey,TValue>)
        // SortedDictionary<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>)

        // Add: O(lg n)
        map.Add(3, "D");
        map.Add(0, "A");
        map.Add(4, "E");
        map.Add(2, "C");
        map.Add(1, "B");

        // Remove: O(lg n)
        map.Remove(3);

        // access by key: O(lg n)
        Console.WriteLine($"access by key map[{0}] = {map[0]}");

        // contains O(lg n)
        Console.WriteLine($"map contains key 3? {map.ContainsKey(3)}");
        Console.WriteLine($"map contains key 2? {map.ContainsKey(2)}");

        // Loop through all
        foreach (KeyValuePair <int, string> keyValue in map)
        {
            Console.WriteLine($"{keyValue.Key} -> {keyValue.Value}");
        }
    }
示例#56
0
    void SamplePoints()
    {
        Vector3 start = referencePoint.lastLocalPos;

        //lck = new object();
        //thread_num = SystemInfo.processorCount;

        //thread_num = 1;
        //thread_num = (thread_num > 2) ? 2 : thread_num;

        tmin = (float)solver.EvaluateExpression(t_min);
        tmin = (tmin > 0) ? 0 : tmin;
        tmax = (float)solver.EvaluateExpression(t_max);
        tmax = (tmax < 0) ? 0 : tmax;

        currLocalPos = referencePoint.lastLocalPos;
        currExpX     = vectorField.expressionX;
        currExpY     = vectorField.expressionY;
        currExpZ     = vectorField.expressionZ;

        int lastCount = positions.Count;

        positions.Clear();

        solver = new AK.ExpressionSolver();

        solver.SetGlobalVariable("x", referencePoint.lastLocalPos.x);
        solver.SetGlobalVariable("y", referencePoint.lastLocalPos.y);
        solver.SetGlobalVariable("z", referencePoint.lastLocalPos.z);
        expX = solver.SymbolicateExpression(vectorField.es.expressions[ExpressionSet.ExpOptions.X].expression);
        expY = solver.SymbolicateExpression(vectorField.es.expressions[ExpressionSet.ExpOptions.Y].expression);
        expZ = solver.SymbolicateExpression(vectorField.es.expressions[ExpressionSet.ExpOptions.Z].expression);
        varX = solver.GetGlobalVariable("x");
        varY = solver.GetGlobalVariable("y");
        varZ = solver.GetGlobalVariable("z");

        //solvers = new AK.ExpressionSolver[thread_num];
        //expXs = new AK.Expression[thread_num];
        //expYs = new AK.Expression[thread_num];
        //expZs = new AK.Expression[thread_num];
        //for(int i = 0; i < thread_num; i++)
        //{
        //    solvers[i] = new AK.ExpressionSolver();
        //    solvers[i].SetGlobalVariable("x", 0);
        //    solvers[i].SetGlobalVariable("y", 0);
        //    solvers[i].SetGlobalVariable("z", 0);
        //    expXs[i] = solvers[i].SymbolicateExpression(vectorField.es.expressions[ExpressionSet.ExpOptions.X].expression);
        //    expYs[i] = solvers[i].SymbolicateExpression(vectorField.es.expressions[ExpressionSet.ExpOptions.Y].expression);
        //    expZs[i] = solvers[i].SymbolicateExpression(vectorField.es.expressions[ExpressionSet.ExpOptions.Z].expression);
        //}
        //Thread[] threads = new Thread[thread_num];
        float positiveCount = tmax / time_step;

        positiveCount = (positiveCount > 50000) ? 50000 : positiveCount;
        float negativeCount = -tmin / time_step;

        negativeCount = (negativeCount > 50000) ? 50000 : negativeCount;
        //Vector3[] startPts = new Vector3[thread_num];
        //startPts[0] = referencePoint.lastLocalPos;
        //for(int i = 1; i < thread_num; i++)
        //{
        //    startPts[i] = RK4(startPts[i - 1], time_step);
        //}
        //for(int i = 0; i < thread_num; i++)
        //{
        //    int index = i;
        //    threads[i] = new Thread(() => ThreadedSampling(index, startPts[index], time_step * thread_num, positiveCount / thread_num,
        //        negativeCount / thread_num));
        //    threads[i].Start();
        //}
        ////for (int i = 0; i < 5; i++)
        ////{
        ////    yield return null;
        ////}
        //for (int i = 0; i < thread_num; i++)
        //{
        //    threads[i].Join();
        //}

        Vector3 curr = start;

        for (int i = 0; i < positiveCount; i++)
        {
            curr = RK4(curr, time_step);
            positions.Add(i + 1, curr);
        }
        curr = start;
        for (int i = 0; i < negativeCount; i++)
        {
            curr = RK4(curr, -time_step);
            positions.Add(-i, curr);
        }

        if (positions.Count != lastCount)
        {
            InitializeParticleSystem();
        }

        //RenderParticles();

        currHighlight   = 0;
        thread_finished = true;
    }
        /// <summary>
        /// Looks for any action methods in 'assemblyToSearch' that have the RouteAttribute defined, 
        /// adding the routes to the parameter 'routes' collection.
        /// </summary>
        /// <param name="routes">The output is appended to this collection</param>
        /// <param name="assemblyToSearch">An assembly containing Controllers with public methods decorated with the RouteAttribute</param>
        public static void MapDecoratedRoutes(RouteCollection routes, Assembly assemblyToSearch)
        {
            IEnumerable<MethodInfo> decoratedMethods = from t in assemblyToSearch.GetTypes()
                                                       where t.IsSubclassOf(typeof (Controller))
                                                       from m in t.GetMethods()
                                                       where m.IsDefined(typeof (StackRouteAttribute), false)
                                                       select m;

            Debug.WriteLine(string.Format("MapDecoratedRoutes - found {0} methods decorated with RouteAttribute",
                                          decoratedMethods.Count()));

            var methodsToRegister = new SortedDictionary<StackRouteAttribute, MethodInfo>();
                // sort urls alphabetically via RouteAttribute's IComparable implementation

            // first, collect all the methods decorated with our RouteAttribute
            foreach (MethodInfo method in decoratedMethods)
            {
                foreach (object attr in method.GetCustomAttributes(typeof (StackRouteAttribute), false))
                {
                    var ra = (StackRouteAttribute) attr;
                    if (!methodsToRegister.Any(p => p.Key.Url.Equals(ra.Url)))
                        methodsToRegister.Add(ra, method);
                    else
                        Debug.WriteLine("MapDecoratedRoutes - found duplicate url -> " + ra.Url);
                }
            }

            // now register the unique urls to the Controller.Method that they were decorated upon
            foreach (var pair in methodsToRegister)
            {
                StackRouteAttribute attr = pair.Key;
                MethodInfo method = pair.Value;
                string action = method.Name;

                Type controllerType = method.ReflectedType;
                string controllerName = controllerType.Name.Replace("Controller", "");
                string controllerNamespace = controllerType.FullName.Replace("." + controllerType.Name, "");

                Debug.WriteLine(string.Format("MapDecoratedRoutes - mapping url '{0}' to {1}.{2}.{3}", attr.Url,
                                              controllerNamespace, controllerName, action));

                var route = new Route(attr.Url, new MvcRouteHandler());
                route.Defaults = new RouteValueDictionary(new {controller = controllerName, action});

                // optional parameters are specified like: "users/filter/{filter?}"
                if (attr.OptionalParameters != null)
                {
                    foreach (string optional in attr.OptionalParameters)
                        route.Defaults.Add(optional, "");
                }

                // constraints are specified like: @"users/{id:\d+}" or "users/{id:INT}"
                if (attr.Constraints != null)
                {
                    route.Constraints = new RouteValueDictionary();

                    foreach (var constraint in attr.Constraints)
                        route.Constraints.Add(constraint.Key, constraint.Value);
                }

                // fully-qualify route to its controller method by adding the namespace; allows multiple assemblies to share controller names/routes
                // e.g. StackOverflow.Controllers.HomeController, StackOverflow.Api.Controllers.HomeController
                route.DataTokens = new RouteValueDictionary(new {namespaces = new[] {controllerNamespace}});

                routes.Add(attr.Name, route);
            }
        }
        public void AddProperties(PropertyOwner owner)
        {
            BGImage.Position = new Point(1590, 100);
            BGImage.Initialize();



            AddPanelProperties();

            if (owner != PropertyOwner.SLIDER && owner != PropertyOwner.TOGGLE)
            {
                _textProperties = new TextProperty(this);
                _textProperties.AddProperties(owner);
                foreach (var item in _textProperties.Properties)
                {
                    _properties.Add(item.Key, item.Value);
                }
            }

            if (owner != PropertyOwner.LABEL)
            {
                _surfaceProperties = new SurfaceProperty(this);
                _surfaceProperties.AddProperties(owner);
                foreach (var item in _surfaceProperties.Properties)
                {
                    _properties.Add(item.Key, item.Value);
                }
            }

            if (owner == PropertyOwner.COMBOBOX)
            {
                _advancedProperties = new AdvancedProperty(this);
                _advancedProperties.AddProperties(owner);
                foreach (var item in _advancedProperties.Properties)
                {
                    _properties.Add(item.Key, item.Value);
                }
            }
            _generalProperties = new GeneralProperty(this);
            _generalProperties.AddProperties(owner);

            foreach (var item in _generalProperties.Properties)
            {
                _properties.Add(item.Key, item.Value);
            }

            _search.FieldWidth      = 320;
            _search.SampleText      = "Search for an item here...";
            _search.StickSampleText = true;

            _search.TextColor = Color.White;

            AddEvents();
        }
示例#59
0
        public override void SendRequest(VWPayOrderEntity tradeEntity)
        {
            this.out_trade_no = tradeEntity.PayOrderCode.ToString();
            this.subject      = "易店心订单号:" + tradeEntity.SysOrderCode.ToString();
            this.price        = "0.01";// tradeEntity.NeedPayPrice.ToString();

            string paymethod = "bankPay";
            string sign      = "";
            SortedDictionary <string, string> sParaTemp = new SortedDictionary <string, string>();

            sParaTemp.Add("service", alipayConfig.service);
            sParaTemp.Add("partner", alipayConfig.partner);
            sParaTemp.Add("seller_id", alipayConfig.seller_id);
            sParaTemp.Add("_input_charset", alipayConfig.input_charset.ToLower());
            sParaTemp.Add("payment_type", alipayConfig.payment_type);
            sParaTemp.Add("notify_url", alipayConfig.notify_url);
            sParaTemp.Add("return_url", alipayConfig.return_url);
            sParaTemp.Add("anti_phishing_key", alipayConfig.anti_phishing_key);
            sParaTemp.Add("exter_invoke_ip", alipayConfig.exter_invoke_ip);
            sParaTemp.Add("out_trade_no", out_trade_no);
            sParaTemp.Add("subject", subject);
            sParaTemp.Add("total_fee", price);
            sParaTemp.Add("body", body);
            Dictionary <string, string> sPara = new Dictionary <string, string>();
            //签名结果
            string mysign = "";

            //过滤签名参数数组
            sPara = alipayCore.FilterPara(sParaTemp);
            //获得签名结果
            mysign = BuildRequestMysign(sPara);
            sPara.Add("sign", mysign);
            sPara.Add("sign_type", sign_type);

            StringBuilder builder = new StringBuilder();

            foreach (KeyValuePair <string, string> temp in sPara)
            {
                builder.Append(this.CreateField(temp.Key, temp.Value));
            }
            this.SubmitPaymentForm(this.CreateForm(builder.ToString(), this.gateway + "_input_charset=" + alipayConfig.input_charset.ToLower()));
        }
示例#60
0
        public async override Task RunAsync(CancellationTokenSource cts, DateTime testStartAt)
        {
            bool   firstMessageWhileOffline = true;
            var    priorityAndSequence      = new SortedDictionary <int, List <long> >();
            long   messageIdCounter         = 1;
            string trcUrl = Settings.Current.TestResultCoordinatorUrl.Expect <ArgumentException>(() => throw new ArgumentException("Expected TestResultCoordinator URL"));

            await this.SetIsFinishedDirectMethodAsync();

            while (!cts.IsCancellationRequested &&
                   (Settings.Current.TestDuration == TimeSpan.Zero || DateTime.UtcNow - testStartAt < Settings.Current.TestDuration))
            {
                try
                {
                    int rand          = this.rng.Next(this.Priorities.Count);
                    int priority      = this.Priorities[rand];
                    int ttlForMessage = this.Ttls[rand];

                    await this.SendEventAsync(messageIdCounter, "pri" + priority);

                    this.Logger.LogInformation($"Sent message {messageIdCounter} with pri {priority} and ttl {ttlForMessage}");

                    // We need to set the first message because of the way priority queue logic works
                    // When edgeHub cannot send a message, it will retry on that message until it sends, regardless
                    // of priority and TTL. So even though it may not be highest priority or may be expired (or both),
                    // this message will still be the first to send when the receiver comes online.
                    if (firstMessageWhileOffline)
                    {
                        firstMessageWhileOffline = false;
                    }
                    else if (ttlForMessage <= 0 || ttlForMessage > this.TtlThresholdSecs)
                    {
                        priority = (priority < 0) ? 2000000000 : priority;

                        if (!priorityAndSequence.TryGetValue(priority, out List <long> sequenceNums))
                        {
                            priorityAndSequence.Add(priority, new List <long> {
                                messageIdCounter
                            });
                        }
                        else
                        {
                            sequenceNums.Add(messageIdCounter);
                        }
                    }

                    if (messageIdCounter % 1000 == 0)
                    {
                        this.Logger.LogInformation($"Sent {messageIdCounter} messages.");
                    }

                    messageIdCounter++;
                    await Task.Delay(Settings.Current.MessageFrequency);
                }
                catch (Exception ex)
                {
                    this.Logger.LogError(ex, $"[SendEventAsync] Sequence number {messageIdCounter}, BatchId: {this.BatchId};");
                }
            }

            this.Logger.LogInformation($"Sending finished. Now sending expected results to {Settings.Current.TestResultCoordinatorUrl}");

            // Sort priority by sequence number
            List <long> expectedSequenceNumberList = priorityAndSequence
                                                     .SelectMany(t => t.Value)
                                                     .ToList();

            // Need to add 1 for the first sequence number, since it is a special case that we omitted in the expectedSequenceNumberList.
            this.resultsSent = expectedSequenceNumberList.Count + 1;

            // See explanation above why we need to send sequence number 1 as the first expected value.
            await this.ReportResult(1);

            foreach (int sequenceNumber in expectedSequenceNumberList)
            {
                // Report sending message successfully to Test Result Coordinator
                this.Logger.LogInformation($"Sending sequence number {sequenceNumber} to TRC");
                await this.ReportResult(sequenceNumber);
            }

            this.isFinished = true;
        }