private static SortedDictionary<string, int> GetArtists(XmlNode rootNode)
        {
            var artists = new SortedDictionary<string, int>();

            if (rootNode == null)
            {
                throw new ArgumentNullException("rootNode" + "is empty");
            }

            foreach (var artistName in from XmlNode node in rootNode.ChildNodes
                                       select node["artist"] into xmlElement
                                       where xmlElement != null
                                       select xmlElement.InnerText)
            {
                if (artists.ContainsKey(artistName))
                {
                    artists[artistName]++;
                }
                else
                {
                    artists.Add(artistName, 1);
                }
            }

            return artists;
        }
Esempio n. 2
1
        public static string[] Search(String[] token, String txt, out Byte distance)
        {
            if (txt.Length > 0)
            {
                Byte bestKey = 255;
                SortedDictionary<Byte, List<string>> matches = new SortedDictionary<byte, List<string>>();
                Docking.Tools.ITextMetric tm = new Docking.Tools.Levenshtein(50);
                foreach(string s in token)
                {
                    Byte d = tm.distance(txt, s);
                    if (d <= bestKey) // ignore worse matches as previously found
                    {
                        bestKey = d;
                        List<string> values;
                        if (!matches.TryGetValue(d, out values))
                        {
                            values = new List<string>();
                            matches.Add(d, values);
                        }
                        if (!values.Contains(s))
                            values.Add(s);
                    }
                }

                if (matches.Count > 0)
                {
                    List<string> result = matches[bestKey];
                    distance = bestKey;
                    return result.ToArray();
                }
            }
            distance = 0;
            return null;
        }
        private static void ReadStudentsInfoFromFile(string filePath, SortedDictionary<string, SortedSet<Student>> courses)
        {
            using (StreamReader reader = new StreamReader(filePath))
            {
                string line = reader.ReadLine();
                while (line != string.Empty && line != null)
                {
                    string[] data = line.Split('|');
                    string firstName = data[0].Trim();
                    string lastName = data[1].Trim();
                    string courseName = data[2].Trim();

                    if (courses.ContainsKey(courseName))
                    {
                        courses[courseName].Add(new Student(firstName, lastName));
                    }
                    else
                    {
                        courses[courseName] = new SortedSet<Student>();
                        courses[courseName].Add(new Student(firstName, lastName));
                    }

                    line = reader.ReadLine();
                }
            }
        }
 public SqlCallProcedureInfo(MethodInfo method, ISerializationTypeInfoProvider typeInfoProvider)
 {
     if (method == null) {
         throw new ArgumentNullException("method");
     }
     if (typeInfoProvider == null) {
         throw new ArgumentNullException("typeInfoProvider");
     }
     SqlProcAttribute procedure = GetSqlProcAttribute(method);
     schemaName = procedure.SchemaName;
     name = procedure.Name;
     timeout = procedure.Timeout;
     deserializeReturnNullOnEmptyReader = procedure.DeserializeReturnNullOnEmptyReader;
     deserializeRowLimit = procedure.DeserializeRowLimit;
     deserializeCallConstructor = procedure.DeserializeCallConstructor;
     SortedDictionary<int, SqlCallParameterInfo> sortedParams = new SortedDictionary<int, SqlCallParameterInfo>();
     outArgCount = 0;
     foreach (ParameterInfo parameterInfo in method.GetParameters()) {
         if ((parameterInfo.GetCustomAttributes(typeof(SqlNameTableAttribute), true).Length > 0) || (typeof(XmlNameTable).IsAssignableFrom(parameterInfo.ParameterType))) {
             if (xmlNameTableParameter == null) {
                 xmlNameTableParameter = parameterInfo;
             }
         } else {
             SqlCallParameterInfo sqlParameterInfo = new SqlCallParameterInfo(parameterInfo, typeInfoProvider, ref outArgCount);
             sortedParams.Add(parameterInfo.Position, sqlParameterInfo);
         }
     }
     parameters = sortedParams.Select(p => p.Value).ToArray();
     returnTypeInfo = typeInfoProvider.GetSerializationTypeInfo(method.ReturnType);
     if ((procedure.UseReturnValue != SqlReturnValue.Auto) || (method.ReturnType != typeof(void))) {
         useReturnValue = (procedure.UseReturnValue == SqlReturnValue.ReturnValue) || ((procedure.UseReturnValue == SqlReturnValue.Auto) && (typeInfoProvider.TypeMappingProvider.GetMapping(method.ReturnType).DbType == SqlDbType.Int));
     }
 }
Esempio n. 5
0
        public static SortedDictionary<int, List<string>> Pizzas(params string[] arr)
        {
            SortedDictionary<int, List<string>> dictionary = new SortedDictionary<int, List<string>>();
            foreach(string pizza in arr)
            {
                int counter = 0;
                int index = 0;
                char ch = pizza[index];
                while(char.IsDigit(ch))
                {
                    counter++;
                    index++;
                    ch = pizza[index];
                }

                int group = int.Parse(pizza.Substring(0, counter));
                string name = pizza.Substring(counter);

                if(dictionary.ContainsKey(group))
                {
                    dictionary[group].Add(name);
                }
                else
                {
                    dictionary[group] = new List<string>();
                    dictionary[group].Add(name);
                }
            }

            return dictionary;
        }
Esempio n. 6
0
 public CaseExpr( IPersistentMap sourceSpan, LocalBindingExpr expr, int shift, int mask, int low, int high, Expr defaultExpr,
     SortedDictionary<int, Expr> tests, Dictionary<int, Expr> thens, Keyword switchType, Keyword testType, IPersistentSet skipCheck)
 {
     _sourceSpan = sourceSpan;
     _expr = expr;
     _shift = shift;
     _mask = mask;
     //_low = low;
     //_high = high;
     _defaultExpr = defaultExpr;
     _tests = tests;
     _thens = thens;
     if (switchType != _compactKey && switchType != _sparseKey)
         throw new ArgumentException("Unexpected switch type: " + switchType);
     //_switchType = switchType;
     if (testType != _intKey && testType != _hashEquivKey && testType != _hashIdentityKey)
         throw new ArgumentException("Unexpected test type: " + testType);
     _testType = testType;
     _skipCheck = skipCheck;
     ICollection<Expr> returns = new List<Expr>(thens.Values);
     returns.Add(defaultExpr);
     _returnType = Compiler.MaybeClrType(returns);
     if (RT.count(skipCheck) > 0 && RT.booleanCast(RT.WarnOnReflectionVar.deref()))
     {
         RT.errPrintWriter().WriteLine("Performance warning, {0}:{1} - hash collision of some case test constants; if selected, those entries will be tested sequentially.",
             Compiler.SourcePathVar.deref(),RT.get(sourceSpan,RT.StartLineKey));
     }
 }
 public LRUCacheManager(String savedLocation, String memoryRunLocation)
 {
     StreamReader reader = new StreamReader(savedLocation);
     StorageFileLocation = reader.ReadLine();
     File.Copy(StorageFileLocation, memoryRunLocation, true);
     StorageFileLocation = memoryRunLocation;
     NextPageAddress = Int64.Parse(reader.ReadLine());
     CacheSize = Int32.Parse(reader.ReadLine());
     NumberOfNodes = Int32.Parse(reader.ReadLine());
     StorageReader = new FileStream(
         memoryRunLocation,
         FileMode.OpenOrCreate,
         FileAccess.ReadWrite,
         FileShare.None,
         8,
         FileOptions.WriteThrough | FileOptions.RandomAccess);
     AddressTranslationTable = new SortedDictionary<Address, Int64>();
     PageTranslationTable = new Dictionary<Int64, Page>();
     LeastRecentlyUsed = new SortedList<Int64, Page>();
     DirtyPages = new List<Page>();
     FreePages = new Queue<Int64>();
     Ticks = 0;
     if (!reader.ReadLine().Equals("AddressTranslationTable"))
         throw new Exception();
     String buffer;
     while (!(buffer = reader.ReadLine()).Equals("FreePages"))
         AddressTranslationTable.Add(
             new Address(buffer),
             Int64.Parse(reader.ReadLine()));
     while (!reader.EndOfStream)
         FreePages.Enqueue(Int64.Parse(reader.ReadLine()));
     reader.Close();
 }
Esempio n. 8
0
        public static int Compare(this SortedDictionary<string,string> set1, SortedDictionary<string, string> set2)
        {
            int minCount = set1.Count <= set2.Count ? set1.Count : set2.Count;

            for (int i = 0; i < minCount; i++)
            {

                if (String.Compare(set1.Keys.ElementAt(i), set2.Keys.ElementAt(i)) == 0 )
                {
                    if (String.Compare(set1.Values.ElementAt(i), set2.Values.ElementAt(i)) != 0)
                        return set1.Values.ElementAt(i).CompareTo(set2.Values.ElementAt(i));
                }
                else
                {
                    return set1.Keys.ElementAt(i).CompareTo(set2.Keys.ElementAt(i));
                }
            }

            if (set1.Count == set2.Count)
                return 0;
            else
            {
                if (set1.Count == minCount)
                    return 1;
                else
                    return -1;
            }
        }
Esempio n. 9
0
 public CheatSheet(string path)
 {
     List<string> lines = File.ReadAllLines(path).ToList();
     // strip out comments and blank lines
     lines.RemoveAll(u => u.TrimStart().StartsWith(";") || u == "");
     m_cheat_sheet = ParseCheatSheet(lines);
 }
Esempio n. 10
0
        protected override object GetSolution()
        {
            SortedDictionary<long, long> decomposition = new SortedDictionary<long, long>();
            for (var i = 1; i <= MAX; i++)
            {
                var currentDecomposition = GetDecomposition(i);
                foreach (KeyValuePair<long, long> kvp in currentDecomposition)
                {
                    if (!decomposition.Keys.Contains(kvp.Key))
                    {
                        decomposition.Add(kvp.Key, kvp.Value);
                    }
                    else
                    {
                        var value = decomposition[kvp.Key];
                        if (value < kvp.Value)
                        {
                            decomposition[kvp.Key] = kvp.Value;
                        }
                    }
                }
            }

            double returnValue = 1;
            foreach (KeyValuePair<long, long> kvp in decomposition)
            {
                returnValue *= Math.Pow((double)kvp.Key, (double)kvp.Value);
            }

            return returnValue;
        }
Esempio n. 11
0
        public Form1()
        {
            InitializeComponent();
            Dictionary<String, int> h = new Dictionary<String, int>();
            SortedDictionary<String, int> otherHash = new SortedDictionary<String, int>();
            String badNames = "";

            for (int i = 1; i < leader.Length; i = i + 2)
            {
                String[] temp = leader[i].Split('\t');
                h.Add(temp[0].Trim(), Convert.ToInt32(temp[1].Replace("E", "0").Trim()));
            }

            foreach (String line in picks)
            {
                String[] temp = line.Split('=');
                int score = 0;
                foreach (String name in temp[1].Split(','))
                {
                    if (h.ContainsKey(name))
                        score += h[name.Trim()];
                    else
                        badNames += name + "\n";
                }
                otherHash.Add(temp[0], score);
            }

            foreach (KeyValuePair<String, int> pair in otherHash)
                richTextBox1.Text += pair.Key + ": " + pair.Value.ToString() + "\n";
            richTextBox1.Text += "The following names had bets placed on them but had to score available.\n" + badNames;
        }
        public List<SpreadPeriod> GetData()
        {
            var results = new SortedDictionary<long, SpreadPeriod>();
            this.AddValues(results, this.max, (x, y) => x.max = y);
            this.AddValues(results, this.min, (x, y) => x.min = y);
            this.AddValues(results, this.avg, (x, y) => x.avg = y);

            double lastMax = 0;
            double lastMin = 0;
            double lastAvg = 0;
            foreach (var period in results.Select(pair => pair.Value))
            {
                if (period.max == 0)
                {
                    period.max = lastMax;
                }
                if (period.min == 0)
                {
                    period.min = lastMin;
                }
                if (period.avg == 0)
                {
                    period.avg = lastAvg;
                }
                lastMax = period.max;
                lastMin = period.min;
                lastAvg = period.avg;
            }

            return results.Values.ToList();
        }
Esempio n. 13
0
        private void BindDataSource() {
            var queryTable = new SortedDictionary<string, string>(_repository.QueryProvider.GetQueries());

            lblProductName.Text = _dbName;
            rptMethods.DataSource = queryTable;
            rptMethods.DataBind();
        }
Esempio n. 14
0
        public FindReplaceForm()
        {
            InitializeComponent();

            m_Selection = new ObjectId[0];

            m_PosList = new SortedDictionary<string, List<ObjectId>>();
            m_CountList = new SortedDictionary<string, List<ObjectId>>();
            m_DiameterList = new SortedDictionary<string, List<ObjectId>>();
            m_SpacingList = new SortedDictionary<string, List<ObjectId>>();
            m_NoteList = new SortedDictionary<string, List<ObjectId>>();
            m_MultiplierList = new SortedDictionary<int, List<ObjectId>>();
            m_ShapeList = new SortedDictionary<string, List<ObjectId>>();

            m_PosProperties = new Dictionary<string, SelectedPos>();

            m_FindShape = string.Empty;
            m_ReplaceShape = string.Empty;
            m_FindFields = 0;
            m_ReplaceFields = 0;

            psvFind.BackColor = DWGUtility.ModelBackgroundColor();
            psvReplace.BackColor = DWGUtility.ModelBackgroundColor();

            init = false;
        }
 private static void PrintArtists(SortedDictionary<string, int> artists)
 {
     foreach (var artist in artists)
     {
         Console.WriteLine("Artist name: {0}, Number of albums: {1}", artist.Key, artist.Value);
     }
 }
Esempio n. 16
0
 private static SortedDictionary<string, object> ConvertHashTable(Hashtable ht) {
     var retval = new SortedDictionary<string, object>();
     foreach (DictionaryEntry de in ht) {
         retval.Add(de.Key.ToString(), de.Value);
     }
     return retval;
 }
        public static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(@"..\..\students.txt");
            using (reader)
            {
                SortedDictionary<string, OrderedBag<Student>> students = new SortedDictionary<string, OrderedBag<Student>>();
                for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
                {
                    var input = line.Split('|');
                    if (!students.ContainsKey(input[2].Trim()))
                    {
                        var grouped = new OrderedBag<Student>();
                        grouped.Add(new Student(input[0].Trim(), input[1].Trim()));
                        students.Add(input[2].Trim(), grouped);
                    }
                    else
                    {
                        students[input[2].Trim()].Add(new Student(input[0].Trim(), input[1].Trim()));
                    }
                }

                foreach (var student in students)
                {
                    Console.WriteLine(student);
                }
            }
        }
Esempio n. 18
0
        public void Process(RayCollection rayBuffer)
        {

            var topLevelHits = new SortedDictionary<uint, List<Tuple<Ray, PrimitiveHit>>>();
            rtDevice.TraceBuffer(rayBuffer);
            for (int index = 0; index < rayBuffer.rayHits.Length; index++)
            {
                if (!topLevelHits.ContainsKey(rayBuffer.rayHits[index].PrimitiveId))
                {
                    topLevelHits.Add(rayBuffer.rayHits[index].PrimitiveId, new List<Tuple<Ray, PrimitiveHit>>());
                }
                topLevelHits[rayBuffer.rayHits[index].PrimitiveId].Add(new Tuple<Ray, PrimitiveHit>(rayBuffer.RaysInfo[index], rayBuffer.rayHits[index]));
            }
            //Process Top Level Hits

            foreach (var topLevelHit in topLevelHits)
            {
                var prim = GetMesh(topLevelHit.Key);
                var rays = topLevelHit.Value.Select(item => item.Item1).ToArray();

                var buffer = new RayCollection(rays.Length);

                rtDevice.SetData(prim.BottomLevelBVH);
                rtDevice.TraceBuffer(buffer);
                for (int index = 0; index < buffer.rayHits.Length; index++)
                {
                    rayBuffer.UpdateHit(buffer.RaysInfo[index].Id, ref buffer.rayHits[index]);
                }
            }

        }
Esempio n. 19
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]);
                }
            }
        }
Esempio n. 20
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;
        }
Esempio n. 21
0
        public void TestDistributionCalculation()
        {
            {
                var data = new[] { 0M, 0.1M, 0.6M, 0.8M, 1.1M, 2.2M, 2.4M, };
                var distribution = Stats.CalculateDistribution(data, 0.5M);
                var sample = new SortedDictionary<decimal, int>
                    {
                        { 0, 1 },
                        { 0.5M, 1 },
                        { 1, 2 },
                        { 1.5M, 1 },
                        { 2.5M, 2 }
                    };
                Assert.IsTrue(distribution.Vals.SequenceEqual(sample));
            }

            {
                var data = new[] { 0M, 0.1M, 0.2M, 0.21M, 0.25M };
                var distribution = Stats.CalculateDistribution(data, 0.2M);
                var sample = new SortedDictionary<decimal, int>
                    {
                        { 0, 1 },
                        { 0.2M, 2 },
                        { 0.4M, 2 },
                    };
                Assert.IsTrue(distribution.Vals.SequenceEqual(sample));
            }
        }
Esempio n. 22
0
        /// <summary>
        /// 授权并执行
        /// </summary>
        /// <param name="requrl">请求地址</param>
        /// <param name="secid">签名方式</param>
        /// <param name="partner">合作伙伴ID</param>
        /// <param name="callbackurl">支付成功跳转链接</param>
        /// <param name="format">请求参数格式</param>
        /// <param name="version">版本</param>
        /// <param name="service">服务</param>
        /// <param name="token">返回token</param> 
        /// <param name="input_charset">编码格式</param>
        /// <param name="gatway">网关</param>
        /// <param name="key">MD5校验码</param>
        /// <param name="sign_type">签名类型</param>
        /// <returns>直接跳转</returns>
        public string alipay_Wap_Auth_AuthAndExecute(
            string requrl,
            string secid,
            string partner,
            string callbackurl,
            string format,
            string version,
            string service,
            string token,
            string input_charset,
            string gatway,
            string key,
            string sign_type)
        {
            //临时请求参数数组
            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
            //拼接req_data
            string req_Data = "<auth_and_execute_req><request_token>" + token + "</request_token></auth_and_execute_req>";

            sParaTemp.Add("req_data" , req_Data);
            sParaTemp.Add("service" , service);
            sParaTemp.Add("sec_id" , secid);
            sParaTemp.Add("partner" , partner);
            sParaTemp.Add("format" , format);
            sParaTemp.Add("v" , version);

            //返回拼接后的跳转URL
            return Submit.SendPostRedirect(sParaTemp, gatway, input_charset, key, sign_type);
        }
    private static void Main()
    {
        SortedDictionary<string, List<Student>> courses = new SortedDictionary<string, List<Student>>();
        string studentsFilePath = "../../Resources/students.txt";

        using (StreamReader reader = new StreamReader(studentsFilePath))
        {
            string line;

            while ((line = reader.ReadLine()) != null)
            {
                string[] recordData = line.Split('|');
                string firstName = recordData[0].Trim();
                string lastName = recordData[1].Trim();
                string course = recordData[2].Trim();

                List<Student> students;

                if (!courses.TryGetValue(course, out students))
                {
                    students = new List<Student>();
                    courses.Add(course, students);
                }

                Student student = new Student(firstName, lastName);
                students.Add(student);
            }
        }

        foreach (var pair in courses)
        {
            Console.WriteLine("{0,15}:\n\t\t{1}", pair.Key, string.Join("\n\t\t", pair.Value));
        }
    }
 public static AreaCodeMap ParseAreaCodeMap(Stream stream)
 {
     SortedDictionary<int, String> areaCodeMapTemp = new SortedDictionary<int, String>();
     using (var lines = new StreamReader(stream, Encoding.UTF8))
     {
         String line;
         while ((line = lines.ReadLine()) != null)
         {
             line = line.Trim();
             if (line.Length <= 0 || line[0] == '#')
                 continue;
             var indexOfPipe = line.IndexOf('|');
             if (indexOfPipe == -1)
             {
                 continue;
             }
             String areaCode = line.Substring(0, indexOfPipe);
             String location = line.Substring(indexOfPipe + 1);
             areaCodeMapTemp[int.Parse(areaCode)] = location;
         }
         // Build the corresponding area code map and serialize it to the binary format.
         AreaCodeMap areaCodeMap = new AreaCodeMap();
         areaCodeMap.readAreaCodeMap(areaCodeMapTemp);
         return areaCodeMap;
     }
 }
Esempio n. 25
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));
        }
Esempio n. 26
0
        /// <summary>
        /// 计算参数签名
        /// </summary>
        /// <param name="params">请求参数集,所有参数必须已转换为字符串类型</param>
        /// <param name="secret">签名密钥</param>
        /// <returns>签名</returns>
        public static string GetSignature(IDictionary<string, string> parameters, string secret, string url)
        {
            // 先将参数以其参数名的字典序升序进行排序
            IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
            IEnumerator<KeyValuePair<string, string>> iterator = sortedParams.GetEnumerator();

            // 遍历排序后的字典,将所有参数按"key=value"格式拼接在一起
            StringBuilder basestring = new StringBuilder();
            WebRequest request = WebRequest.Create(url);
            basestring.Append("POST").Append(request.RequestUri.Host).Append(request.RequestUri.AbsolutePath);
            while (iterator.MoveNext())
            {
                string key = iterator.Current.Key;
                string value = iterator.Current.Value;
                if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                {
                    basestring.Append(key).Append("=").Append(value);
                }
            }
            basestring.Append(secret);

            // 使用MD5对待签名串求签
            MD5 md5 = MD5.Create();
            byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(basestring.ToString()));

            // 将MD5输出的二进制结果转换为小写的十六进制
            StringBuilder result = new StringBuilder();
            foreach (byte b in bytes)
            {
                result.Append(b.ToString("x2").ToLower());
            }
            return result.ToString();
        }
Esempio n. 27
0
        static Input()
        {
            availableCommands = new SortedDictionary<string, MBCShellCommandHandler>();
            availableCommandDescriptions = new SortedDictionary<string, string>();

            AddCommand(Show.Config, "show", "config", "Displays the current configuration");
            AddCommand(Show.Controllers, "show", "controllers", "Displays the currently loaded controllers and their usage IDs");

            AddCommand(Create.Match, "create", "match", "[controllerIDs...] Discards the current match (if any) and creates a new match with the specified controllers by ID as shown by \"show controllers\".");
            AddCommand(Create.Config, "create", "config", "[configname] Creates a new configuration with the specified name.");

            AddCommand(Load.Match, "load", "match", "[filename] Loads a match from a file.");
            AddCommand(Load.Config, "load", "config", "[filename] Loads a configuration from a file.");

            AddCommand(Save.Match, "save", "match", "[filename] Saves the current match to a file.");
            AddCommand(Save.Config, "save", "config", "[filename] Saves the configuration to a file.");

            AddCommand(MatchRun.Step, "match", "step", "Steps through the current match.");
            AddCommand(MatchRun.Start, "match", "start", "Plays through a match until it ends.");
            AddCommand(MatchRun.Start, "match", "stop", "Ends the current match.");

            AddCommand(Set.Config, "set", "config", "[key] [value] Sets a configuration key value to the one specified.");

            AddCommand(EventOutput.Enable, "event", "enable", "[\"match\"/\"controller\"/\"round\"] Enables console display of the specified event.");
            AddCommand(EventOutput.Disable, "event", "disable", "[\"match\"/\"controller\"/\"round\"] Disables console display of the specified event.");

            AddCommand(Help.Commands, "help", "Shows this help display.");

            AddCommand(Stop, "exit", "Exits the console application.");
        }
        public static string GenerateAuthString(string httpmethod, string url, SortedDictionary<string, string> parameters, string callback, string oauthToken = "")
        {
            byte[] nonceBuffer = new byte[32];
            random.NextBytes(nonceBuffer);

            string oauth_nonce = Convert.ToBase64String(nonceBuffer);
            string oauth_signature_method = "HMAC-SHA1";
            string oauth_timestamp = UnixTime().ToString();
            string oauth_callback = callback;
            string oauth_version = "1.0";

			if(callback != null)
			{
				parameters.Add("oauth_callback", oauth_callback);
			}
            parameters.Add("oauth_consumer_key", oauth_consumer_key);
            parameters.Add("oauth_nonce", oauth_nonce);
            parameters.Add("oauth_signature_method", oauth_signature_method);
            parameters.Add("oauth_timestamp", oauth_timestamp);
			if(oauthToken != "")
			{
				parameters.Add("oauth_token", oauthToken);
			}
            parameters.Add("oauth_version", oauth_version);

            string parameterString = ParameterString(parameters);

            parameters.Add("oauth_signature", Signature(httpmethod, url, parameterString, oauthToken));
            return "OAuth " + AuthenticationString(parameters);
        }
Esempio n. 29
0
        public string cycle_check(SortedDictionary<char, char> cycle)
        {
            cycle_str = "A";
            cycle_key = 'A';
            cycle_value = cycle['A'];
            cycle_length = "";

            while (cycle.Count != 1)
            {
                if (cycle_str.IndexOf(cycle_value) != -1)
                {
                    cycle.Remove(cycle_key);
                    cycle_key = cycle.ElementAt(0).Key;
                    cycle_value = cycle[cycle_key];
                    cycle_str += " " + cycle_key.ToString();
                }
                else
                {
                    cycle_str += cycle_value.ToString();
                    cycle.Remove(cycle_key);
                    cycle_key = cycle_value;
                    cycle_value = cycle[cycle_key];
                }
            }

            foreach (var el in cycle_str.Split(' '))
                cycle_length += el.Length + " ";

            return cycle_length;
        }
Esempio n. 30
0
        /// <summary>
        /// 构造模拟远程HTTP的GET请求,获取支付宝的返回XML处理结果
        /// </summary>
        /// <param name="sParaTemp">请求参数数组</param>
        /// <param name="gateway">网关地址</param>
        /// <returns>支付宝返回XML处理结果</returns>
        public static XmlDocument SendGetInfo(SortedDictionary<string, string> sParaTemp, string gateway)
        {
            //待请求参数数组字符串
            Encoding code = Encoding.GetEncoding(_input_charset);
            string strRequestData = BuildRequestParaToString(sParaTemp, code);

            //构造请求地址
            string strUrl = gateway + strRequestData;

            //请求远程HTTP
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                //设置HttpWebRequest基本信息
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                myReq.Method = "get";

                //发送POST数据请求服务器
                HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
                Stream myStream = HttpWResp.GetResponseStream();

                //获取服务器返回信息
                XmlTextReader Reader = new XmlTextReader(myStream);
                xmlDoc.Load(Reader);
            }
            catch (Exception exp)
            {
                string strXmlError = "<error>" + exp.Message + "</error>";
                xmlDoc.LoadXml(strXmlError);
            }

            return xmlDoc;
        }
Esempio n. 31
0
        /// <summary>
        /// Get presign canonical request.
        /// </summary>
        /// <param name="client">Instantiated client object</param>
        /// <param name="request">Instantiated request object</param>
        /// <param name="requestQuery">Additional request query params</param>
        /// <param name="headersToSign"></param>
        /// <returns>Presigned canonical request</returns>
        internal string GetPresignCanonicalRequest(IRestClient client, IRestRequest request, string requestQuery, SortedDictionary<string, string> headersToSign)
        {
            var canonicalStringList = new LinkedList<string>();
            // METHOD
            canonicalStringList.AddLast(request.Method.ToString());

            string path = request.Resource;
            if (!path.StartsWith("/"))
            {
                path = $"/{path}";
            }
            canonicalStringList.AddLast(path);
            string query = headersToSign.Aggregate(requestQuery, (pv, cv) => $"{pv}&{utils.UrlEncode(cv.Key)}={utils.UrlEncode(s3utils.TrimAll(cv.Value))}");
            canonicalStringList.AddLast(query);
            if (client.BaseUrl.Port > 0 && (client.BaseUrl.Port != 80 && client.BaseUrl.Port != 443))
            {
                canonicalStringList.AddLast($"host:{client.BaseUrl.Host}:{client.BaseUrl.Port}");
            }
            else
            {
                canonicalStringList.AddLast($"host:{client.BaseUrl.Host}");
            }

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

            return string.Join("\n", canonicalStringList);
        }
Esempio n. 32
0
 public BstPriorityQueue(IComparer <T> comparer = null)
 {
     sd = new SortedDictionary <T, int>(comparer ?? Comparer <T> .Default);
 }
Esempio n. 33
0
        private static bool Menu()
        {
            BuildMenu();
            ConsoleUtil.Lines.WriteQueuedLines(true);

            //string jql2 = string.Format("project in (BAM,POS) AND parentEpic={0}", epicKey);

            //project in (require 1 or more))

            /*
             * 1.  specify 1 or more projects, space delimited
             * 2.  optional
             *   - ANY search terms found in Summary OR Description
             *   - ALL search terms found in Summary OR Description
             *   -
             *
             *
             *
             */

            var resp = Console.ReadKey(true);

            if (resp.Key == ConsoleKey.K)
            {
                ConsoleUtil.WriteLine("Enter Epic Key (e.g. BAM-1234)");
                var epicKey = Console.ReadLine();
                ConsoleUtil.WriteLine(string.Format("Create time metrics for Epic: {0}? (ENTER 'Y' TO CONTINUE OR PRESS ANOTHER KEY TO RETURN TO MENU", epicKey));
                var read = Console.ReadKey(true);
                if (read.Key != ConsoleKey.Y)
                {
                    return(true);
                }

                var dic       = MainClass.GetBusinessHours();
                int startHour = dic["start"];
                int endHour   = dic["end"];

                MainClass.CreateWorkMetricsFile(BuildJQL_EpicChildren(epicKey), startHour, endHour, epicKey);

                ConsoleUtil.WriteLine("");
                ConsoleUtil.WriteLine("Press any key to continue.");
                Console.ReadKey(true);
            }
            else if (resp.Key == ConsoleKey.F)
            {
                string projects           = string.Empty;
                bool   ANDED              = false;
                bool   SUMMARY_ONLY       = false;
                bool   RETURN_ALL_RESULTS = false;;
                string searchTerms        = string.Empty;

                ConsoleUtil.WriteLine("You are required to enter 1 or more project keys.", ConsoleColor.White, ConsoleColor.DarkCyan, false);
                ConsoleUtil.WriteLine("optionally you can enter search terms to finds Epics by Summary (Title) or Description.", ConsoleColor.White, ConsoleColor.DarkCyan, false);
                ConsoleUtil.WriteLine("ENTER 1 OR MORE PROJECT KEYS, SEPARATED BY SPACES (e.g. BAM POS)", ConsoleColor.White, ConsoleColor.DarkCyan, false);
                projects = Console.ReadLine();
                ConsoleUtil.WriteLine("***** Epic Summary (Title) and Description Search *****", ConsoleColor.White, ConsoleColor.DarkCyan, false);
                ConsoleUtil.WriteLine("***** Choose a search option *****", ConsoleColor.White, ConsoleColor.DarkCyan, false);
                ConsoleUtil.WriteLine("1 - Return epics where Summary or Description contain ANY search terms", ConsoleColor.White, ConsoleColor.DarkCyan, false);
                ConsoleUtil.WriteLine("2 - Return epics where Summary or Description contain ALL search terms", ConsoleColor.White, ConsoleColor.DarkCyan, false);
                ConsoleUtil.WriteLine("3 - Return epics where Summary (Title) contains ANY search terms", ConsoleColor.White, ConsoleColor.DarkCyan, false);
                ConsoleUtil.WriteLine("4 - Return epics where Summary (Title) contains ALL search terms", ConsoleColor.White, ConsoleColor.DarkCyan, false);
                ConsoleUtil.WriteLine("5 - View list of all epics for selected project(s).", ConsoleColor.White, ConsoleColor.DarkCyan, false);

                var    searchOption       = Console.ReadKey(true);
                string searchStrategyDesc = string.Empty;

                if (searchOption.KeyChar.ToString() == "1")
                {
                    ConsoleUtil.WriteLine("Search Option 1 selected", ConsoleColor.White, ConsoleColor.DarkYellow, false);
                    searchStrategyDesc = "Enter 1 or more search terms, separated by spaces. Epics that contain ** ANY ** search terms (Summary or Desc fields) will be returned.";
                    ANDED = false;
                }
                else if (searchOption.KeyChar.ToString() == "2")
                {
                    ConsoleUtil.WriteLine("Search Option 2 selected", ConsoleColor.White, ConsoleColor.DarkYellow, false);
                    searchStrategyDesc = "Enter 1 or more search terms, separated by spaces. Epics that contain ** ALL ** search terms (Summary or Desc fields) will be returned.";
                    ANDED = true;
                }
                else if (searchOption.KeyChar.ToString() == "3")
                {
                    ConsoleUtil.WriteLine("Search Option 3 selected", ConsoleColor.White, ConsoleColor.DarkYellow, false);
                    searchStrategyDesc = "Enter 1 or more search terms, separated by spaces. Epics that contain ** ANY ** search terms (Summary field) will be returned.";
                    ANDED        = false;
                    SUMMARY_ONLY = true;
                }
                else if (searchOption.KeyChar.ToString() == "4")
                {
                    ConsoleUtil.WriteLine("Search Option 4 selected", ConsoleColor.White, ConsoleColor.DarkYellow, false);
                    searchStrategyDesc = "Enter 1 or more search terms, separated by spaces. Epics that contain ** ALL ** search terms (Summary field) will be returned.";
                    ANDED        = true;
                    SUMMARY_ONLY = true;
                }
                else if (searchOption.KeyChar.ToString() == "5")
                {
                    ConsoleUtil.WriteLine("Search Option 5 selected", ConsoleColor.White, ConsoleColor.DarkYellow, false);

                    RETURN_ALL_RESULTS = true;
                }



                if (projects == null || projects.Trim().Length == 0)
                {
                    ConsoleUtil.WriteLine("1 Or More Project Keys is required!  Doh!", ConsoleColor.Red, ConsoleColor.White, false);
                    ConsoleUtil.PressAnyKeyToContinue();
                    return(true);
                }
                if (!RETURN_ALL_RESULTS)
                {
                    ConsoleUtil.WriteLine(searchStrategyDesc, ConsoleColor.White, ConsoleColor.DarkCyan, false);
                    searchTerms = Console.ReadLine();

                    if (searchTerms == null || searchTerms.Trim().Length == 0)
                    {
                        ConsoleUtil.WriteLine("You chose to search for epics based on search terms, but failed to enter any search terms.  Doh!", ConsoleColor.Red, ConsoleColor.Yellow, false);
                        ConsoleUtil.PressAnyKeyToContinue();
                        return(true);
                    }
                }
                string epicSearchJQL = BuildJQL_EpicSearch(projects, searchTerms, ANDED, SUMMARY_ONLY, RETURN_ALL_RESULTS);;
                ConsoleUtil.WriteLine(string.Format("AWESOME -- Please be patient while your results are fetched using the following *** JQL: {0}", epicSearchJQL), ConsoleColor.DarkBlue, ConsoleColor.Gray, false);

                var epics = JiraUtil.JiraRepo.GetIssues(epicSearchJQL);
                ConsoleUtil.WriteLine("***** ***** *****", ConsoleColor.White, ConsoleColor.Black, false);
                ConsoleUtil.WriteLine("***** ***** *****", ConsoleColor.White, ConsoleColor.Black, false);
                ConsoleUtil.WriteLine(string.Format("{0} epics were found matching your search criteria", epics.Count), ConsoleColor.White, ConsoleColor.Black, false);
                ConsoleUtil.WriteLine("***** ***** *****", ConsoleColor.White, ConsoleColor.Black, false);
                ConsoleUtil.WriteLine("***** ***** *****", ConsoleColor.White, ConsoleColor.Black, false);
                ConsoleUtil.PressAnyKeyToContinue();

                if (epics.Count == 0)
                {
                    return(true);
                }
                ConsoleUtil.WriteLine("Please wait while the search results are evaluated", ConsoleColor.DarkBlue, ConsoleColor.Gray, false);
                SortedList <JIssue, List <JIssue> > epicsWithChildren = new SortedList <JIssue, List <JIssue> >();

                string[] projArray       = projects.ToUpper().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                string   projSearchItems = projArray.Length == 1 ? projArray[0] : String.Join(",", projArray);

                int epicsEvaluated  = 0;
                int totalEpicsFound = epics.Count;

                foreach (Issue epic in epics)
                {
                    epicsEvaluated += 1;
                    SortedDictionary <string, int> epicIssueBreakdown = new SortedDictionary <string, int>();
                    JIssue jepic = new JIssue(epic);
                    ConsoleUtil.WriteLine(string.Format("Analyzing Epic: {0} ({1}) - {2}", jepic.Key, jepic.StatusName, jepic.Summary), ConsoleColor.DarkBlue, ConsoleColor.Gray, false);

                    string epicIssuesJQL = string.Format("project in({0}) AND parentEpic={1}", projSearchItems, jepic.Key);

                    List <Issue>  epicIssues   = JiraUtil.JiraRepo.GetIssues(epicIssuesJQL);
                    List <JIssue> epicChildren = new List <JIssue>();
                    foreach (Issue epicIssue in epicIssues)
                    {
                        JIssue epicChild = new JIssue(epicIssue);
                        epicChildren.Add(epicChild);
                        if (epicIssueBreakdown.ContainsKey(epicChild.IssueType.ToLower()))
                        {
                            epicIssueBreakdown[epicChild.IssueType.ToLower()] = epicIssueBreakdown[epicChild.IssueType.ToLower()] + 1;
                        }
                        else
                        {
                            epicIssueBreakdown.Add(epicChild.IssueType.ToLower(), 1);
                        }
                    }
                    ConsoleTable table = new ConsoleTable(string.Format("Epic:{0} ({1}/{2} results)", jepic.Key, epicsEvaluated, totalEpicsFound), "ChildType", "Qty");
                    foreach (var kvp in epicIssueBreakdown)
                    {
                        table.AddRow(" ***** ", kvp.Key, kvp.Value);
                    }
                    table.Write();

                    ConsoleUtil.WriteLine(string.Format("Isn't this cool? -- Do you want to generate the Work Time Analytics for this Epic ({0})? (Don't worry, we'll come back here where you left off if you decide to do that!)", jepic.Key), ConsoleColor.DarkBlue, ConsoleColor.Gray, false);
                    ConsoleUtil.WriteLine(string.Format("Press 'Y' to generate the Work Time Analytics file for epic {0}", jepic.Key), ConsoleColor.DarkBlue, ConsoleColor.Gray, false);
                    ConsoleUtil.WriteLine(string.Format("Press 'E' to stop reviewing epic search results", jepic.Key), ConsoleColor.DarkBlue, ConsoleColor.Gray, false);
                    ConsoleUtil.WriteLine(string.Format("Press any other key to continue reviewing epic search results.", jepic.Key), ConsoleColor.DarkBlue, ConsoleColor.Gray, false); var read = Console.ReadKey(true);
                    if (read.Key == ConsoleKey.Y)
                    {
                        MainClass.CreateWorkMetricsFile(epicIssuesJQL, 7, 18, jepic.Key);
                        ConsoleUtil.PressAnyKeyToContinue();
                    }
                    else if (read.Key == ConsoleKey.E)
                    {
                        return(true);
                    }
                }
            }
            else if (resp.Key == ConsoleKey.M)
            {
                return(false);
            }

            return(true);
        }
Esempio n. 34
0
        private void PrioritizeMods()
        {
            Manager.Info("Prioritizing loaded mods...");
            var modGroups = GetGraph(LoadedMods.Values).DepthSort();

            Manager.Debug($"Found {modGroups.Count()} separate groups of mod dependencies.");

            //the key is the index of the group within modGroups
            Dictionary <uint, Priority> groupPrios = new Dictionary <uint, Priority>();

            //Find the highest load priority of each group.
            foreach (var group in modGroups)
            {
                Guid highest = Guid.Empty;
                foreach (var id in group)
                {
                    if (LoadedMods[id].RequestedLoadPriority > LoadedMods[highest].RequestedLoadPriority)
                    {
                        highest = id;
                    }
                }
                groupPrios[(uint)modGroups.IndexOf(group)] = (Priority)LoadedMods[highest].RequestedLoadPriority;
            }

            var  loadPriorities  = new SortedDictionary <uint, ModInfo>();
            uint currentPriority = 0;

            loadPriorities[currentPriority++] = CoreMod;
            Manager.Debug($"CoreMod was assigned load priority {CoreMod.LoadPriority}");

            //Now that we've determined the highest load priority of each group, we're going to ensure that each mod has its
            // individual priority assigned accordingly. This involves looping through each group and sequentially incrementing
            // the load priority of each mod.
            foreach (Priority prio in new Priority().GetValues())
            {
                var mods = groupPrios.Where(x => x.Value == prio);
                foreach (var pair in mods)
                {
                    foreach (var id in modGroups[(int)pair.Key])
                    {
                        if (id == ModInfo.CoreModID)
                        {
                            continue;
                        }
                        var mod = LoadedMods[id];
                        mod.SetLoadPriority(currentPriority++);
                        loadPriorities[mod.LoadPriority] = mod;
                        Manager.Debug($"Mod {mod.ModName} was assigned load priority {mod.LoadPriority}");
                    }
                }
            }
            ModsByLoadPriority = new ReadOnlyDictionary <uint, ModInfo>(loadPriorities);

            var runPriorities = new SortedDictionary <uint, ModInfo>();

            currentPriority = 0;
            //Run priority is a bit simpler.  Simply sort by requested priority, and in the event of conflict, sort alphabetically.
            foreach (Priority prio in new Priority().GetValues().Reverse())
            {
                var mods = LoadedMods.Values.Where(x => (Priority)x.RequestedRunPriority == prio).ToList();
                mods.Sort((x, y) => { return(x.ModName.CompareTo(y.ModName)); });
                foreach (var mod in mods)
                {
                    if (mod.IsCoreMod)
                    {
                        continue;
                    }
                    mod.RunPriority = currentPriority++;
                    runPriorities[mod.LoadPriority] = mod;
                    Manager.Debug($"Mod {mod.ModName} was assigned run priority {mod.RunPriority}");
                }
                //Set the CoreMod to have the highest Normal priority.
                if (prio == Priority.Normal)
                {
                    CoreMod.RunPriority = currentPriority++;
                    runPriorities[CoreMod.RunPriority] = CoreMod;
                    Manager.Debug($"CoreMod was assigned run priority {CoreMod.RunPriority}");
                }
            }
            ModsByRunPriority = new ReadOnlyDictionary <uint, ModInfo>(loadPriorities);
        }
Esempio n. 35
0
        static void Main(string[] args)
        {
            string input = Console.ReadLine();

            Dictionary <string, string> contests = new Dictionary <string, string>();
            SortedDictionary <string, Dictionary <string, int> > users = new SortedDictionary <string, Dictionary <string, int> >();

            while (input != "end of contests")
            {
                string[] contestsData = input.Split(":");

                string nameOfContest = contestsData[0];
                string password      = contestsData[1];

                contests.Add(nameOfContest, password);

                input = Console.ReadLine();
            }

            input = Console.ReadLine();

            while (input != "end of submissions")
            {
                string[] sumbissionsData = input.Split("=>");

                string nameOfContest = sumbissionsData[0];
                string password      = sumbissionsData[1];
                string userName      = sumbissionsData[2];
                int    points        = int.Parse(sumbissionsData[3]);

                bool isContestValid    = contests.ContainsKey(nameOfContest);
                bool isPassWordCorrect = false;

                if (isContestValid && contests.ContainsValue(password))
                {
                    isPassWordCorrect = true;
                }

                if (isContestValid && isPassWordCorrect)
                {
                    if (users.ContainsKey(userName))
                    {
                        if (users[userName].ContainsKey(nameOfContest) && points > users[userName][nameOfContest])
                        {
                            users[userName][nameOfContest] = points;
                        }
                        else if (!users[userName].ContainsKey(nameOfContest))
                        {
                            users[userName].Add(nameOfContest, points);
                        }
                    }
                    else
                    {
                        users.Add(userName, new Dictionary <string, int>());
                        users[userName].Add(nameOfContest, points);
                    }
                }

                input = Console.ReadLine();
            }

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

            foreach (var kvp in users)
            {
                usersTotalPoints[kvp.Key] = kvp.Value.Values.Sum();
            }

            string bestCandidat = String.Empty;
            int    maxPoints    = 0;

            foreach (var kvp in usersTotalPoints)
            {
                if (kvp.Value > maxPoints)
                {
                    maxPoints    = kvp.Value;
                    bestCandidat = kvp.Key;
                }
            }

            Console.WriteLine($"Best candidate is {bestCandidat} with total {maxPoints} points.");
            Console.WriteLine("Ranking:");

            foreach (var kvp in users)
            {
                Console.WriteLine(kvp.Key);

                foreach (var contest in kvp.Value.OrderByDescending(c => c.Value))
                {
                    Console.WriteLine($"#  {contest.Key} -> {contest.Value}");
                }
            }
        }
Esempio n. 36
0
        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);
            }
        }
Esempio n. 37
0
        private void AddAposPath(Rectangle r, bool isNegative, bool isVertical)
        {
            if (r.Width == 0 || r.Height == 0)
            {
                // No need to add this rectangle.
                return;
            }

            // TODO: Use more appropriate data structures.
            var container = isVertical ? _vertical : _horizontal;
            var overlaps  = container.Query(r).ToList();

            List <AposPath> pending = new List <AposPath>();
            SortedDictionary <int, List <Range> > slabs = new SortedDictionary <int, List <Range> >();

            int nextId = 0;

            slabs.Add(CreateRangeKey(r, true, isVertical), new List <Range>()
            {
                CreateRange(nextId, r, true, isNegative, isVertical)
            });
            slabs.Add(CreateRangeKey(r, false, isVertical), new List <Range>()
            {
                CreateRange(nextId++, r, false, isNegative, isVertical)
            });

            foreach (var o in overlaps)
            {
                Rectangle rect   = o.Rect;
                int       keyA   = CreateRangeKey(rect, true, isVertical);
                int       keyB   = CreateRangeKey(rect, false, isVertical);
                Range     rangeA = CreateRange(nextId, rect, true, false, isVertical);
                Range     rangeB = CreateRange(nextId++, rect, false, false, isVertical);
                if (slabs.TryGetValue(keyA, out List <Range>?l1))
                {
                    l1.Add(rangeA);
                }
                else
                {
                    slabs.Add(keyA, new List <Range>()
                    {
                        rangeA
                    });
                }

                if (slabs.TryGetValue(keyB, out List <Range>?l2))
                {
                    l2.Add(rangeB);
                }
                else
                {
                    slabs.Add(keyB, new List <Range>()
                    {
                        rangeB
                    });
                }

                o.Leaf = container.Remove(o.Leaf);
            }

            // Generate overlaps. Preserve active overlaps while going through the slabs.
            List <Range>         existingRanges = new List <Range>();
            List <Range.Overlap> oldOverlaps;
            List <Range.Overlap> newOverlaps = new List <Range.Overlap>();

            foreach (var kvp in slabs)
            {
                oldOverlaps = newOverlaps;
                newOverlaps = new List <Range.Overlap>();

                // Update existing
                foreach (var s in kvp.Value)
                {
                    if (existingRanges.RemoveAll(e => e.Id == s.Id) == 0)
                    {
                        existingRanges.Add(s);
                    }
                }

                existingRanges.Sort((a, b) => {
                    if (a.IsNegative == b.IsNegative)
                    {
                        if (a.IsNegative)
                        {
                            return(a.O.B.CompareTo(b.O.B));
                        }
                        else
                        {
                            return(a.O.A.CompareTo(b.O.A));
                        }
                    }
                    else
                    {
                        if (a.IsNegative)
                        {
                            return(a.O.B.CompareTo(b.O.A) <= 0 ? -1 : 1);
                        }
                        else
                        {
                            return(a.O.A.CompareTo(b.O.B) >= 0 ? 1 : -1);
                        }
                    }
                });

                // Merge existing into new overlaps
                for (int i = 0; i < existingRanges.Count; i++)
                {
                    var range = existingRanges[i];
                    if (range.IsNegative)
                    {
                        int count = newOverlaps.Count;
                        int limit = count;
                        for (int j = count - 1; j >= 0; j--)
                        {
                            var positiveOverlap = newOverlaps[j];
                            if (!range.O.CheapNegativeOverlap(positiveOverlap))
                            {
                                break;
                            }

                            limit = j;
                        }
                        for (int j = limit; j < count; j++)
                        {
                            var positiveOverlap = newOverlaps[j];

                            var o = positiveOverlap.Split(range.O, out bool isRemoved);
                            if (isRemoved)
                            {
                                newOverlaps.RemoveAt(j);
                                --j;
                                --count;
                            }
                            else
                            {
                                if (o != null)
                                {
                                    newOverlaps.Add(o);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (newOverlaps.Count == 0 || !newOverlaps.Last().CheapOverlap(range.O))
                        {
                            newOverlaps.Add(range.O.Copy(kvp.Key));
                        }
                        else
                        {
                            newOverlaps.Last().Merge(range.O);
                        }
                    }
                }

                // Figure out the difference and create rectangles.
                foreach (var oo in oldOverlaps)
                {
                    bool createRect = true;

                    foreach (var no in newOverlaps)
                    {
                        if (oo.ExactMatch(no))
                        {
                            createRect = false;
                            no.C       = oo.C; // Bring C forward
                        }
                    }

                    if (createRect)
                    {
                        var p = new AposPath(OverlapToRect(oo.A, oo.B, oo.C, kvp.Key, isVertical));
                        p.Leaf = container.Add(p.Rect, p);
                    }
                }
            }
        }
Esempio n. 38
0
        private bool CheckIncrementSoldTradesParameters(SortedDictionary <string, string> parameters, out DateTime start_modified, out DateTime end_modified, out string status, out int page_no, out int page_size, ref string result)
        {
            start_modified = DateTime.Now;
            end_modified   = DateTime.Now;
            page_size      = 10;
            page_no        = 1;
            status         = DataHelper.CleanSearchString(parameters["status"]);
            if (!OpenApiHelper.CheckSystemParameters(parameters, this.site.AppKey, out result))
            {
                return(false);
            }
            if (((!string.IsNullOrWhiteSpace(status) && (status != "WAIT_BUYER_PAY")) && ((status != "WAIT_SELLER_SEND_GOODS ") && (status != "WAIT_BUYER_CONFIRM_GOODS"))) && ((status != "TRADE_CLOSED") && (status != "TRADE_FINISHED")))
            {
                result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Trade_Status_is_Invalid, "status");
                return(false);
            }
            if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_size"])) && !int.TryParse(parameters["page_size"].ToString(), out page_size))
            {
                result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Parameters_Format_Error, "page_size");
                return(false);
            }
            if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_size"])) && ((page_size <= 0) || (page_size > 100)))
            {
                result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Page_Size_Too_Long, "page_size");
                return(false);
            }
            if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_no"])) && !int.TryParse(parameters["page_no"].ToString(), out page_no))
            {
                result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Parameters_Format_Error, "page_no");
                return(false);
            }
            if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_no"])) && (page_no <= 0))
            {
                result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Page_Size_Too_Long, "page_no");
                return(false);
            }
            if (string.IsNullOrEmpty(parameters["start_modified"]))
            {
                result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Missing_Required_Arguments, "start_modified");
                return(false);
            }
            if (!OpenApiHelper.IsDate(parameters["start_modified"]))
            {
                result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Invalid_Timestamp, "start_modified");
                return(false);
            }
            DateTime.TryParse(parameters["start_modified"], out start_modified);
            if (start_modified > DateTime.Now)
            {
                result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_Start_Now, "start_modified and currenttime");
                return(false);
            }
            if (string.IsNullOrEmpty(parameters["end_modified"]))
            {
                result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Missing_Required_Arguments, "end_modified");
                return(false);
            }
            if (!OpenApiHelper.IsDate(parameters["end_modified"]))
            {
                result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Invalid_Timestamp, "end_modified");
                return(false);
            }
            DateTime.TryParse(parameters["end_modified"], out end_modified);
            if (start_modified > end_modified)
            {
                result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_Start_End, "start_modified and end_modified");
                return(false);
            }
            TimeSpan span = (TimeSpan)(end_modified - start_modified);

            if (span.TotalDays > 1.0)
            {
                result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_StartModified_AND_EndModified, "start_modified and end_modified");
                return(false);
            }
            if (end_modified > DateTime.Now)
            {
                result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_End_Now, "end_modified and currenttime");
                return(false);
            }
            return(true);
        }
Esempio n. 39
0
 public PCDHeader()
 {
     Fields = new SortedDictionary <int, FieldDescription>();
     Width  = 0;
     Height = 0;
 }
Esempio n. 40
0
 public KeyedPriorityQueue(Func <T, TKey> keySelector, IComparer <TKey> comparer = null)
 {
     this.keySelector = keySelector ?? throw new ArgumentNullException(nameof(keySelector));
     sd = new SortedDictionary <TKey, Queue <T> >(comparer ?? Comparer <TKey> .Default);
 }
Esempio n. 41
0
        } // class TpmStructMemberInfo

        TpmStructMemberInfo[] GetFieldsToMarshal(bool trackTags = false)
        {
            var    t       = GetType();
            string caption = (trackTags ? "Unmarshaling" : "Marshaling") + " " + t.Name;

            if (!t.GetTypeInfo().IsValueType)
            {
                var b = t.GetTypeInfo().BaseType;
                if (b != null && b != typeof(TpmStructureBase) && b != typeof(object))
                {
                    t        = b;
                    caption += " as " + b.Name;
                }
            }
            dbg.Trace(caption);
            dbg.Indent();
            var members = new SortedDictionary <int, TpmStructMemberInfo>();
            Dictionary <string, TpmStructMemberInfo> tags = null;

            //Dictionary<string, TpmStructMemberInfo> untaggedFields = null;
            if (trackTags)
            {
                tags = new Dictionary <string, TpmStructMemberInfo>();
                //untaggedFields = new Dictionary<string, TpmStructMemberInfo>();
            }
            foreach (var bf in new BindingFlags[] { BindingFlags.Public | BindingFlags.NonPublic })
            {
                var candidateMembers = t.GetMembers(BindingFlags.Instance | bf);
                foreach (var mi in candidateMembers)
                {
                    var memberAttrs = mi.CustomAttributes;
                    foreach (var a in memberAttrs)
                    {
                        if (a.AttributeType.Name != "MarshalAsAttribute")
                        {
                            continue;
                        }
                        int idx  = 0;
                        var arg0 = a.ConstructorArguments[0];
                        if (arg0.ArgumentType == typeof(int))
                        {
                            idx = (int)arg0.Value;
                        }
                        else
                        {
                            // The only variant of the marshaling attribute with
                            // a non-int first argument:
                            //     arg0.ArgumentType == typeof(Type))
                            // is used for types only, and never for structure fields.
                            Debug.Assert(false);
                        }

                        members.Add(idx, mi);

                        var tsmi = members[idx];
                        var arg1 = a.ConstructorArguments[1];
                        Debug.Assert(arg1.ArgumentType == typeof(MarshalType));
                        var mt = (MarshalType)arg1.Value;
                        Debug.Assert(mt != MarshalType.ArrayCount && mt != MarshalType.LengthOfStruct);

                        tsmi.WireType = mt;
                        if (mt == MarshalType.VariableLengthArray || mt == MarshalType.SizedStruct)
                        {
                            tsmi.SizeName   = (string)a.ConstructorArguments[2].Value;
                            tsmi.SizeLength = (int)a.ConstructorArguments[3].Value;
                            dbg.Trace("Preproc " + (mt == MarshalType.SizedStruct ? "Struct " : "Array ")
                                      + mi.Name + " with size tag " + tsmi.SizeName + "=" + tsmi.SizeLength);
                        }

                        if (trackTags)
                        {
                            var marshalType = (MarshalType)arg1.Value;
                            switch (marshalType)
                            {
                            case MarshalType.UnionSelector:
                            {
                                tags.Add(mi.Name, tsmi);
                                dbg.Trace("Preproc Selector: " + mi.Name);
                                break;
                            }

                            case MarshalType.Union:
                            {
                                var selector = a.ConstructorArguments[2].Value;
                                dbg.Trace("Preproc Union " + mi.Name + " with selector " + selector);
                                tsmi.Tag = tags[(string)selector];
                                break;
                            }

#if false
                            case MarshalType.ArrayCount:
                            {
                                tags.Add(mi.Name, tsmi);
                                dbg.Trace("Preproc Array Count: " + mi.Name);
                                break;
                            }

                            case MarshalType.VariableLengthArray:
                            {
                                var sizeTag = a.ConstructorArguments[2].Value;
                                dbg.Trace("Preproc Array " + mi.Name + " with size tag " + sizeTag);
                                tsmi.Tag = tags[(string)sizeTag];
                                break;
                            }

                            case MarshalType.LengthOfStruct:
                            {
                                var sizedStruct = (string)a.ConstructorArguments[2].Value;
                                dbg.Trace("Preproc Size Tag " + mi.Name + " for struct " + sizedStruct);
                                if (untaggedFields.ContainsKey(sizedStruct))
                                {
                                    untaggedFields[sizedStruct].Tag = tsmi;
                                }
                                else
                                {
                                    tags.Add(sizedStruct, tsmi);
                                }
                                break;
                            }

                            default:
                            {
                                // Check if this is a sized struct
                                if (tags.ContainsKey(mi.Name))
                                {
                                    tsmi.Tag = tags[mi.Name];
                                    dbg.Trace("Preproc Sized Struct" + mi.Name + " with size tag " + tsmi.Tag.Name);
                                }
                                else
                                {
                                    untaggedFields.Add(mi.Name, tsmi);
                                }
                                break;
                            }
#endif
                            }
                        }
                        break;
                    }
                }
            }
            dbg.Unindent();
            return(members.Values.ToArray());
        }
Esempio n. 42
0
 public void QueueInitialize()
 {
     this.performances = new SortedDictionary <string, SortedSet <Performance> >();
 }
Esempio n. 43
0
 public ReportCommodities(Report report)
     : base(null)
 {
     Report      = report;
     Commodities = new SortedDictionary <Commodity, int>();
 }
Esempio n. 44
0
 public ExchangeRateFromDatesSDMXResponse()
 {
     Values = new SortedDictionary <DateTime, decimal>();
 }
Esempio n. 45
0
 public string AlipayInterface(SortedDictionary <string, string> sParaTemp)
 {
     return("");
 }
Esempio n. 46
0
        public void Streaming(string eventPipeFileName)
        {
            // Initialize
            PrepareTestData();

            string eventPipeFilePath = Path.Combine(UnZippedDataDir, eventPipeFileName);

            Output.WriteLine(string.Format("Processing the file {0}", Path.GetFullPath(eventPipeFilePath)));
            var eventStatistics = new SortedDictionary <string, EventRecord>(StringComparer.Ordinal);

            long curStreamPosition = 0;

            using (MockStreamingOnlyStream s = new MockStreamingOnlyStream(new FileStream(eventPipeFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)))
            {
                using (var traceSource = new EventPipeEventSource(s))
                {
                    Action <TraceEvent> handler = delegate(TraceEvent data)
                    {
                        long newStreamPosition = s.TestOnlyPosition;
                        // Empirically these files have event blocks of no more than 103K bytes each
                        // The streaming code should never need to read ahead beyond the end of the current
                        // block to read the events
                        Assert.InRange(newStreamPosition, curStreamPosition, curStreamPosition + 103_000);
                        curStreamPosition = newStreamPosition;


                        string eventName = data.ProviderName + "/" + data.EventName;

                        // For whatever reason the parse filtering below produces a couple extra events
                        // that TraceLog managed to filter out:
                        //    Microsoft-Windows-DotNETRuntime/Method, 2,
                        //    Microsoft-Windows-DotNETRuntimeRundown/Method, 26103, ...
                        // I haven't had an oportunity to investigate and its probably not a big
                        // deal so just hacking around it for the moment
                        if (eventName == "Microsoft-Windows-DotNETRuntimeRundown/Method" ||
                            eventName == "Microsoft-Windows-DotNETRuntime/Method")
                        {
                            return;
                        }

                        if (eventStatistics.ContainsKey(eventName))
                        {
                            eventStatistics[eventName].TotalCount++;
                        }
                        else
                        {
                            eventStatistics[eventName] = new EventRecord()
                            {
                                TotalCount            = 1,
                                FirstSeriazliedSample = new String(data.ToString().Replace("\n", "\\n").Replace("\r", "\\r").Take(1000).ToArray())
                            };
                        }
                    };

                    // this is somewhat arbitrary looking set of parser event callbacks empirically
                    // produces the same set of events as TraceLog.Events.GetSource().AllEvents so
                    // that the baseline files can be reused from the Basic test
                    var rundown = new ClrRundownTraceEventParser(traceSource);
                    rundown.LoaderAppDomainDCStop    += handler;
                    rundown.LoaderAssemblyDCStop     += handler;
                    rundown.LoaderDomainModuleDCStop += handler;
                    rundown.LoaderModuleDCStop       += handler;
                    rundown.MethodDCStopComplete     += handler;
                    rundown.MethodDCStopInit         += handler;
                    var sampleProfiler = new SampleProfilerTraceEventParser(traceSource);
                    sampleProfiler.All += handler;
                    var privateClr = new ClrPrivateTraceEventParser(traceSource);
                    privateClr.All      += handler;
                    traceSource.Clr.All += handler;
                    traceSource.Clr.MethodILToNativeMap -= handler;
                    traceSource.Dynamic.All             += handler;

                    // Process
                    traceSource.Process();
                }
            }
            // Validate
            ValidateEventStatistics(eventStatistics, eventPipeFileName);
        }
Esempio n. 47
0
        protected void Page_Load(object sender, EventArgs e)
        {
            SortedDictionary <string, string> sPara = GetRequestGet();

            if (sPara.Count > 0)//判断是否有带返回参数
            {
                Notify aliNotify    = new Notify();
                bool   verifyResult = aliNotify.Verify(sPara, Request.QueryString["notify_id"], Request.QueryString["sign"]);

                if (verifyResult)//验证成功
                {
                    //商户订单号
                    string out_trade_no = Request.QueryString["out_trade_no"];
                    //支付宝交易号
                    string trade_no = Request.QueryString["trade_no"];
                    //交易状态
                    string trade_status = Request.QueryString["trade_status"];
                    if (Request.QueryString["trade_status"] == "TRADE_SUCCESS")
                    {
                        string orderType = out_trade_no.Substring(out_trade_no.IndexOf("-") + 1);
                        switch (orderType)
                        {
                        case "1000":
                            OrderMsg("1000", 35, "0.035元/条");
                            break;

                        case "2000":
                            OrderMsg("2000", 70, "0.035元/条");
                            break;

                        case "5000":
                            OrderMsg("5000", 175, "0.035元/条");
                            break;

                        case "10000":
                            OrderMsg("10000", 350, "0.035元/条");
                            break;

                        case "20000":
                            OrderMsg("20000", 700, "0.035元/条");
                            break;

                        case "50000":
                            OrderMsg("50000", 1750, "0.035元/条");
                            break;

                        case "100000":
                            OrderMsg("100000", 3500, "0.035元/条");
                            break;

                        case "200000":
                            OrderMsg("200000", 6800, "0.034元/条");
                            break;

                        default:
                            break;
                        }
                        Response.Redirect("http://crm.new9channel.com/messageSetting.aspx");
                    }
                    else
                    {
                        Response.Write("trade_status=" + Request.QueryString["trade_status"]);
                        //打印页面
                        Response.Write("充值失败,请联系客服<br />");
                    }
                }
                else//验证失败
                {
                    Response.Write("支付失败,请联系客服");
                }
            }
            else
            {
                Response.Write("无返回参数");
            }
        }
Esempio n. 48
0
        protected void Page_Load(object sender, EventArgs e)
        {
            SortedDictionary <string, string> sPara = GetRequestPost();

            if (sPara.Count == 0)
            {
                sPara = GetRequestGet();
            }
            //商户订单号
            string     out_trade_no = RequestTool.RequestString("out_trade_no");
            Lebi_Order order        = B_Lebi_Order.GetModel("Code=lbsql{'" + out_trade_no + "'}");

            if (order == null)
            {
                SystemLog.Add(out_trade_no + "系统错误");
                Response.Write("系统错误");
                Response.End();
                return;
            }
            if (sPara.Count > 0)//判断是否有带返回参数
            {
                Notify aliNotify    = new Notify(order);
                bool   verifyResult = aliNotify.Verify(sPara, RequestTool.RequestString("notify_id"), RequestTool.RequestString("sign"));

                if (verifyResult)//验证成功
                {
                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    //请在这里加上商户的业务逻辑程序代码


                    //——请根据您的业务逻辑来编写程序(以下代码仅作参考)——
                    //获取支付宝的通知返回参数,可参考技术文档中服务器异步通知参数列表

                    //支付宝交易号

                    string trade_no = RequestTool.RequestString("trade_no");

                    //交易状态
                    string trade_status = RequestTool.RequestString("trade_status");


                    if (trade_status == "TRADE_FINISHED")
                    {
                        //判断该笔订单是否在商户网站中已经做过处理
                        //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
                        //如果有做过处理,不执行商户的业务程序

                        //注意:
                        //该种交易状态只在两种情况下出现
                        //1、开通了普通即时到账,买家付款成功后。
                        //2、开通了高级即时到账,从该笔交易成功时间算起,过了签约时的可退款时限(如:三个月以内可退款、一年以内可退款等)后。

                        Order.OnlinePaySuccess("alipayJSDZ", out_trade_no, trade_no);
                        Response.Write("success");  //请不要修改或删除
                    }
                    else if (trade_status == "TRADE_SUCCESS")
                    {
                        //判断该笔订单是否在商户网站中已经做过处理
                        //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
                        //如果有做过处理,不执行商户的业务程序

                        //注意:
                        //该种交易状态只在一种情况下出现——开通了高级即时到账,买家付款成功后。
                        Order.OnlinePaySuccess("alipayJSDZ", out_trade_no, trade_no);
                        Response.Write("success");  //请不要修改或删除
                    }
                    else
                    {
                        Response.Write("fail");
                        SystemLog.Add("单号付款" + trade_no + " | " + trade_status);
                    }
                    //Response.Write("success");
                    //Order.PaySuccess(out_trade_no, trade_no);
                }
                else//验证失败
                {
                    Response.Write("fail");
                    SystemLog.Add(out_trade_no + "验证fail");
                }
            }
            else
            {
                Response.Write("无通知参数");
                SystemLog.Add(out_trade_no + "无通知参数");
            }
        }
Esempio n. 49
0
        private void AddDataToChart(DateTime startDate, DateTime endDate, DirectionType direction,
                                    List <Models.Detector> detectorsByDirection, LaneType laneType, MovementType movementType,
                                    TMCOptions options, TMCInfo tmcInfo)
        {
            var MovementTotals    = new SortedDictionary <DateTime, int>();
            var laneTotals        = new SortedDictionary <string, int>();
            var binSizeMultiplier = 60 / options.SelectedBinSize;
            var totalVolume       = 0;
            var tmcDetectors      = new List <Models.Detector>();

            FindLaneDetectors(tmcDetectors, movementType, detectorsByDirection, laneType);
            var laneCount = tmcDetectors.Count();

            for (var ln = 1; ln < 5; ln++)
            {
                var detector = (from r in tmcDetectors
                                where r.LaneNumber == ln
                                select r).FirstOrDefault();
                if (detector != null)
                {
                    if (laneCount > 0 && detector.MovementTypeID != 4 && detector.MovementTypeID != 5)
                    {
                        var d = new Detector(detector, startDate, endDate,
                                             options.SelectedBinSize);
                        foreach (var volume in d.Volumes.Items)
                        {
                            if (options.ShowDataTable)
                            {
                                var tmcd = new TMCData();
                                tmcd.Direction = detector.Approach.DirectionType.Description;
                                tmcd.LaneType  = detector.LaneType.Description;
                                if (!options.ShowLaneVolumes)
                                {
                                    tmcd.MovementType = tmcd.Direction;
                                }
                                else
                                {
                                    tmcd.MovementType = detector.MovementType.Abbreviation;
                                }
                                //tmcd.DetectorID = detector.DetectorID;
                                tmcd.Timestamp = volume.XAxis; //.AddMinutes(options.SelectedBinSize *-1);
                                tmcd.Count     = volume.YAxis / binSizeMultiplier;
                                tmcInfo.tmcData.Add(tmcd);
                            }
                            if (options.ShowLaneVolumes)
                            {
                                chart.Series["Lane " + ln].Points.AddXY(volume.XAxis, volume.YAxis);
                            }
                            //One of the calculations requires total volume by lane.  This if statment keeps a
                            //running total of that volume and stores it in a dictonary with the lane number.
                            if (laneTotals.ContainsKey("L" + ln))
                            {
                                laneTotals["L" + ln] += volume.YAxis;
                            }
                            else
                            {
                                laneTotals.Add("L" + ln, volume.YAxis);
                            }
                            //we need ot track the total number of cars (volume) for this movement.
                            //this uses a time/int dictionary.  The volume record for a given time is contibuted to by each lane.
                            //Then the movement total can be plotted on the graph
                            if (MovementTotals.ContainsKey(volume.XAxis))
                            {
                                MovementTotals[volume.XAxis] += volume.YAxis;
                            }
                            else
                            {
                                MovementTotals.Add(volume.XAxis, volume.YAxis);
                            }
                        }
                    }
                }
            }

            if (movementType.MovementTypeID == 1)
            {
                var thruTurnLanes = (from r in detectorsByDirection
                                     where r.MovementTypeID == 4 ||
                                     r.MovementTypeID == 5
                                     select r).ToList();
                foreach (var detector in thruTurnLanes)
                {
                    var d = new Detector(detector, startDate, endDate, options.SelectedBinSize);
                    foreach (var volume in d.Volumes.Items)
                    {
                        if (detector.MovementType.Abbreviation == "TL")
                        {
                            {
                                if (options.ShowLaneVolumes)
                                {
                                    if (options.ShowDataTable)
                                    {
                                        var tmcd = new TMCData();
                                        tmcd.Direction = detector.Approach.DirectionType.Description;
                                        tmcd.LaneType  = detector.LaneType.Description;
                                        if (!options.ShowLaneVolumes)
                                        {
                                            tmcd.MovementType = tmcd.Direction;
                                        }
                                        else
                                        {
                                            tmcd.MovementType = detector.MovementType.Abbreviation;
                                        }
                                        //tmcd.DetectorID = detector.DetectorID;
                                        tmcd.Timestamp = volume.XAxis; //.AddMinutes(options.SelectedBinSize * -1);
                                        tmcd.Count     = volume.YAxis / binSizeMultiplier;
                                        tmcInfo.tmcData.Add(tmcd);
                                    }
                                    chart.Series["Thru Left"].Points.AddXY(volume.XAxis, volume.YAxis);
                                }
                            }
                            if (laneTotals.ContainsKey("TL"))
                            {
                                laneTotals["TL"] += volume.YAxis;
                            }
                            else
                            {
                                laneTotals.Add("TL", volume.YAxis);
                            }
                        }
                        if (detector.MovementType.Abbreviation == "TR")
                        {
                            if (options.ShowLaneVolumes)
                            {
                                if (options.ShowDataTable)
                                {
                                    var tmcd = new TMCData();
                                    tmcd.Direction = detector.Approach.DirectionType.Description;
                                    tmcd.LaneType  = detector.LaneType.Description;
                                    if (!options.ShowLaneVolumes)
                                    {
                                        tmcd.MovementType = tmcd.Direction;
                                    }
                                    else
                                    {
                                        tmcd.MovementType = detector.MovementType.Abbreviation;
                                    }
                                    //tmcd.DetectorID = detector.DetectorID;
                                    tmcd.Timestamp = volume.XAxis; //.AddMinutes(options.SelectedBinSize * -1);
                                    tmcd.Count     = volume.YAxis / binSizeMultiplier;
                                    tmcInfo.tmcData.Add(tmcd);
                                }
                                chart.Series["Thru Right"].Points.AddXY(volume.XAxis, volume.YAxis);
                            }
                        }
                        if (laneTotals.ContainsKey("TR"))
                        {
                            laneTotals["TR"] += volume.YAxis;
                        }
                        else
                        {
                            laneTotals.Add("TR", volume.YAxis);
                        }
                        if (MovementTotals.ContainsKey(volume.XAxis))
                        {
                            MovementTotals[volume.XAxis] += volume.YAxis;
                        }
                        else
                        {
                            MovementTotals.Add(volume.XAxis, volume.YAxis);
                        }
                    }
                }
            }
            var binMultiplier = 60 / options.SelectedBinSize;

            //get the total volume for the approach
            foreach (var totals in MovementTotals)
            {
                if (options.ShowTotalVolumes)
                {
                    chart.Series["Total Volume"].Points.AddXY(totals.Key, totals.Value);
                }
                totalVolume += totals.Value;
            }

            var highLaneVolume = 0;

            if (laneTotals.Values.Count > 0)
            {
                highLaneVolume = laneTotals.Values.Max();
            }


            var peakHourValue     = findPeakHour(MovementTotals, binMultiplier);
            var PHV               = peakHourValue.Value;
            var peakHour          = peakHourValue.Key;
            var PeakHourMAXVolume = 0;

            var fluPlaceholder = "";

            if (laneCount > 0 && highLaneVolume > 0)
            {
                var fLU = Convert.ToDouble(totalVolume) /
                          (Convert.ToDouble(laneCount) * Convert.ToDouble(highLaneVolume));
                fluPlaceholder = SetSigFigs(fLU, 2).ToString();
            }
            else
            {
                fluPlaceholder = "Not Available";
            }


            for (var i = 0; i < binMultiplier; i++)
            {
                if (MovementTotals.ContainsKey(peakHour.AddMinutes(i * options.SelectedBinSize)))
                {
                    if (PeakHourMAXVolume < MovementTotals[peakHour.AddMinutes(i * options.SelectedBinSize)])
                    {
                        PeakHourMAXVolume = MovementTotals[peakHour.AddMinutes(i * options.SelectedBinSize)];
                    }
                }
            }

            var PHFPlaceholder = FindPHF(PHV, PeakHourMAXVolume, binMultiplier);


            var peakHourString = peakHour.ToShortTimeString() + " - " + peakHour.AddHours(1).ToShortTimeString();
            var statistics     = new Dictionary <string, string>();

            statistics.Add("Total Volume", (totalVolume / binMultiplier).ToString());
            statistics.Add("Peak Hour", peakHourString);
            statistics.Add("Peak Hour Volume", PHV / binMultiplier + " VPH");
            statistics.Add("PHF", PHFPlaceholder);
            statistics.Add("fLU", fluPlaceholder);
            chart.Titles.Add(ChartTitleFactory.GetStatistics(statistics));
            SetSeriesVisibility(laneCount, options.ShowLaneVolumes);
        }
Esempio n. 50
0
        /// <summary>
        /// 保存题目数据文件到磁盘
        /// </summary>
        /// <param name="problemID">题目ID</param>
        /// <param name="forms">Request.Forms</param>
        /// <param name="httpFiles">Request.Files</param>
        /// <returns>是否保存成功</returns>
        public static IMethodResult AdminSaveProblemData(Int32 problemID, NameValueCollection forms, HttpFileCollectionBase httpFiles)
        {
            if (!AdminManager.HasPermission(PermissionType.ProblemManage))
            {
                throw new NoPermissionException();
            }

            if (problemID < ConfigurationManager.ProblemSetStartID)
            {
                return(MethodResult.InvalidRequest(RequestType.Problem));
            }

            SortedDictionary <String, String> dictData = new SortedDictionary <String, String>();

            if (httpFiles != null)
            {
                for (Int32 i = 0; i < httpFiles.Count; i++)
                {
                    HttpPostedFileBase file = httpFiles[i];

                    if (String.IsNullOrEmpty(file.FileName))
                    {
                        return(MethodResult.FailedAndLog("Filename can not be NULL!"));
                    }

                    FileInfo fi = new FileInfo(file.FileName);
                    if (httpFiles.GetKey(i).IndexOf("in", StringComparison.OrdinalIgnoreCase) == 0 && !".in".Equals(fi.Extension, StringComparison.OrdinalIgnoreCase))
                    {
                        return(MethodResult.FailedAndLog("Filename is INVALID!"));
                    }

                    if (httpFiles.GetKey(i).IndexOf("out", StringComparison.OrdinalIgnoreCase) == 0 && !".out".Equals(fi.Extension, StringComparison.OrdinalIgnoreCase) && !".ans".Equals(fi.Extension, StringComparison.OrdinalIgnoreCase))
                    {
                        return(MethodResult.FailedAndLog("Filename is INVALID!"));
                    }

                    if (file.ContentLength <= 0)
                    {
                        return(MethodResult.FailedAndLog("You can not upload empty file!"));
                    }

                    StreamReader sr = new StreamReader(file.InputStream);
                    dictData.Add(httpFiles.GetKey(i), sr.ReadToEnd());
                }
            }

            if (forms != null)
            {
                for (Int32 i = 0; i < forms.Count; i++)
                {
                    if (forms.GetKey(i).IndexOf("in", StringComparison.OrdinalIgnoreCase) == 0 || forms.GetKey(i).IndexOf("out", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        dictData.Add(forms.GetKey(i), forms[i]);
                    }
                }
            }

            if (dictData.Count == 0)
            {
                return(MethodResult.FailedAndLog("No data was added!"));
            }

            if (dictData.Count % 2 != 0)
            {
                return(MethodResult.FailedAndLog("The count of uploaded data is INVALID!"));
            }

            ProblemDataWriter writer = new ProblemDataWriter();

            foreach (KeyValuePair <String, String> pair in dictData)
            {
                if (pair.Key.IndexOf("in", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    String input  = pair.Value;
                    String output = String.Empty;

                    if (!dictData.TryGetValue(pair.Key.ToLower().Replace("in", "out"), out output))
                    {
                        return(MethodResult.FailedAndLog("The count of uploaded data is INVALID!"));
                    }

                    writer.WriteData(input, output);
                }
            }

            String fileNewName = problemID.ToString() + ".zip";
            String savePath    = Path.Combine(ConfigurationManager.ProblemDataPath, fileNewName);

            Byte[] data = writer.WriteTo();
            File.WriteAllBytes(savePath, data);

            ProblemDataCache.RemoveProblemDataVersionCache(problemID);

            return(MethodResult.SuccessAndLog("Admin create problem data, id = {0}", problemID.ToString()));
        }
Esempio n. 51
0
 public virtual object InternalCall(HttpMethod method, string url, SortedDictionary <string, object> parameters, FileDescription file, Dictionary <string, string> extraHeaders = null)
 {
     throw new Exception("Please call overriden method");
 }
Esempio n. 52
0
 public virtual T CallAndParse <T>(HttpMethod method, string url, SortedDictionary <string, object> parameters, FileDescription file, Dictionary <string, string> extraHeaders = null) where T : BaseResult, new()
 {
     throw new NotImplementedException();
 }
        public string GenerateContributionComment(PerformanceOpinion ptfPerformanceOpinion, SortedDictionary <double, string> contributions)
        {
            var lenght    = contributions.Count;
            var keys      = contributions.Keys;
            var keysArray = new double[keys.Count];

            keys.CopyTo(keysArray, 0);

            var values      = contributions.Values;
            var valuesArray = new string[values.Count];

            values.CopyTo(valuesArray, 0);

            var underlyingPerformanceOpinion = this.GetPerformanceOpinions(keysArray);

            return((string)this.ContribCommentMap[ptfPerformanceOpinion].DynamicInvoke(underlyingPerformanceOpinion, keysArray, lenght, valuesArray));
        }
Esempio n. 54
0
        protected SortedDictionary <string, object> BuildUnsignedUploadParams(string preset, SortedDictionary <string, object> parameters = null)
        {
            if (parameters == null)
            {
                parameters = new SortedDictionary <string, object>();
            }

            parameters.Add("upload_preset", preset);
            parameters.Add("unsigned", true);

            return(parameters);
        }
Esempio n. 55
0
        static void Main(string[] args)
        {
            StreamReader sr = new StreamReader("../../input.txt");

            string line;

            string[] spl;

            int severity = 0;
            SortedDictionary <int, SortedSet <int> > unallowed_remainders = new SortedDictionary <int, SortedSet <int> >();

            line = sr.ReadLine();
            while (line != null)
            {
                if (line.Trim() != "")
                {
                    spl = line.Split(new string[] { " ", ":" }, StringSplitOptions.RemoveEmptyEntries);
                    int depth = Convert.ToInt32(spl[0]), range = Convert.ToInt32(spl[1]);
                    int mod = 2 * (range - 1);

                    if (depth % mod == 0)
                    {
                        severity += depth * range;
                    }

                    if (!unallowed_remainders.ContainsKey(mod))
                    {
                        unallowed_remainders.Add(mod, new SortedSet <int>());
                    }
                    unallowed_remainders[mod].Add((mod - depth % mod) % mod);
                }
                line = sr.ReadLine();
            }
            sr.Close();

            Console.WriteLine("First part: " + severity);

            StreamWriter sw = new StreamWriter("../../output.txt");

            foreach (var s in unallowed_remainders)
            {
                sw.Write(s.Key + ": ");
                foreach (int j in s.Value)
                {
                    sw.Write(j + " ");
                }
                sw.WriteLine();
            }
            sw.Close();

            // searching for the smallest valid delay
            int  i = -1;
            bool valid;

            do
            {
                ++i;
                valid = true;
                foreach (var s in unallowed_remainders)
                {
                    if (s.Value.Contains(i % s.Key))
                    {
                        valid = false;
                        break;
                    }
                }
            }while (!valid);

            Console.WriteLine("Second part: " + i);
        }
Esempio n. 56
0
        public IPacketWriter BuildUpdate()
        {
            byte maskSize = ((int)Fields.MAX + 31) / 32;
            SortedDictionary <int, byte[]> fieldData = new SortedDictionary <int, byte[]>();

            byte[] maskArray = new byte[maskSize * 4];

            Action <Fields, object> SetField = (place, value) => this.SetField((int)place, value, ref fieldData, ref maskArray);

            PacketWriter writer = new PacketWriter(Sandbox.Instance.Opcodes[global::Opcodes.SMSG_UPDATE_OBJECT], "SMSG_UPDATE_OBJECT");

            writer.WriteUInt32(1);         //Number of transactions
            writer.WriteUInt8(0);
            writer.WriteUInt8(2);          //UpdateType
            writer.WriteUInt64(this.Guid);
            writer.WriteUInt8(4);          //ObjectType, 4 = Player

            writer.WriteUInt32(0);         //MovementFlagMask
            writer.WriteUInt32((uint)Environment.TickCount);
            writer.WriteFloat(Location.X); //x
            writer.WriteFloat(Location.Y); //y
            writer.WriteFloat(Location.Z); //z
            writer.WriteFloat(Location.O); //w (o)
            writer.WriteFloat(0);
            writer.WriteFloat(2.5f);       //WalkSpeed
            writer.WriteFloat(7.0f);       //RunSpeed
            writer.WriteFloat(2.5f);       //Backwards WalkSpeed
            writer.WriteFloat(4.7222f);    //SwimSpeed
            writer.WriteFloat(4.7222f);    //Backwards SwimSpeed
            writer.WriteFloat(3.14f);      //TurnSpeed

            writer.WriteUInt32(1);         //Flags, 1 - Player
            writer.WriteUInt32(1);         //AttackCycle
            writer.WriteUInt32(0);         //TimerId
            writer.WriteUInt64(0);         //VictimGuid

            SetField(Fields.OBJECT_FIELD_GUID, this.Guid);
            SetField(Fields.OBJECT_FIELD_TYPE, (uint)0x19);
            SetField(Fields.OBJECT_FIELD_ENTRY, 0);
            SetField(Fields.OBJECT_FIELD_SCALE_X, this.Scale);
            SetField(Fields.OBJECT_FIELD_PADDING, 0);
            SetField(Fields.UNIT_FIELD_TARGET, (ulong)0);
            SetField(Fields.UNIT_FIELD_HEALTH, this.Health);
            SetField(Fields.UNIT_FIELD_POWER2, 0);
            SetField(Fields.UNIT_FIELD_MAXHEALTH, this.Health);
            SetField(Fields.UNIT_FIELD_MAXPOWER2, this.Rage);
            SetField(Fields.UNIT_FIELD_LEVEL, this.Level);
            SetField(Fields.UNIT_FIELD_BYTES_0, BitConverter.ToUInt32(new byte[] { this.Race, this.Class, this.Gender, this.PowerType }, 0));
            SetField(Fields.UNIT_FIELD_STAT0, this.Strength);
            SetField(Fields.UNIT_FIELD_STAT1, this.Agility);
            SetField(Fields.UNIT_FIELD_STAT2, this.Stamina);
            SetField(Fields.UNIT_FIELD_STAT3, this.Intellect);
            SetField(Fields.UNIT_FIELD_STAT4, this.Spirit);
            SetField(Fields.UNIT_FIELD_FLAGS, 0);
            SetField(Fields.UNIT_FIELD_BASE_MANA, this.Mana);
            SetField(Fields.UNIT_FIELD_DISPLAYID, DisplayId);
            SetField(Fields.UNIT_FIELD_MOUNTDISPLAYID, MountDisplayId);
            SetField(Fields.UNIT_FIELD_BYTES_1, BitConverter.ToUInt32(new byte[] { (byte)StandState, 0, 0, 0 }, 0));
            SetField(Fields.PLAYER_SELECTION, (ulong)0);
            SetField(Fields.PLAYER_BYTES, BitConverter.ToUInt32(new byte[] { Skin, Face, HairStyle, HairColor }, 0));
            SetField(Fields.PLAYER_BYTES_2, BitConverter.ToUInt32(new byte[] { 0, FacialHair, 0, RestedState }, 0));
            SetField(Fields.PLAYER_BYTES_3, (uint)this.Gender);
            SetField(Fields.PLAYER_XP, 47);
            SetField(Fields.PLAYER_NEXT_LEVEL_XP, 200);

            SetField(Fields.UNIT_FIELD_ATTACKPOWER, 1);
            SetField(Fields.UNIT_FIELD_ATTACK_POWER_MODS, 0);
            SetField(Fields.UNIT_FIELD_RANGEDATTACKPOWER, 1);
            SetField(Fields.UNIT_FIELD_RANGED_ATTACK_POWER_MODS, 0);

            for (int i = 0; i < 32; i++)
            {
                SetField(Fields.PLAYER_EXPLORED_ZONES_1 + i, 0xFFFFFFFF);
            }

            //FillInPartialObjectData
            writer.WriteUInt8(maskSize); //UpdateMaskBlocks
            writer.WriteBytes(maskArray);
            foreach (var kvp in fieldData)
            {
                writer.WriteBytes(kvp.Value); //Data
            }
            return(writer);
        }
        static void Main(string[] args)
        {
            if (!File.Exists("../../veriler.txt"))
            {
                Console.WriteLine("Dosya Bulunamadı");
                Console.ReadLine();
                return;
            }

            string       dosya_yolu = "../../veriler.txt";
            FileStream   fs         = new FileStream(dosya_yolu, FileMode.Open, FileAccess.Read);
            StreamReader sr         = new StreamReader(fs);

            SortedDictionary <string, SortedDictionary <string, string> > rehber = new SortedDictionary <string, SortedDictionary <string, string> >();

            string yazi = sr.ReadLine();

            while (yazi != null)
            {
                string[] dizi = yazi.Split('|');

                if (!rehber.ContainsKey(dizi[1]))
                {
                    rehber.Add(dizi[1], new SortedDictionary <string, string>());
                    rehber[dizi[1]].Add(dizi[0], dizi[2]);
                }
                else
                {
                    if (rehber[dizi[1]].ContainsKey(dizi[0]))
                    {
                        rehber[dizi[1]][dizi[0]] += "\n\t \t \t   " + dizi[2];
                        //Console.WriteLine("sdf");
                    }
                    else
                    {
                        rehber[dizi[1]].Add(dizi[0], dizi[2]);
                    }
                }

                yazi = sr.ReadLine();
            }

            sr.Close();
            fs.Close();

            foreach (var obje in rehber)
            {
                var objeValue = obje.Value;
                Console.WriteLine(obje.Key + " : ");

                foreach (var bilgiler in obje.Value)
                {
                    string txt = "\t" + bilgiler.Key;
                    for (int i = 0; i < 15 - (bilgiler.Key.Length); i++)
                    {
                        txt += " ";
                    }
                    txt += " - ";
                    //for (int i = 0; i < 20 /*- (bilgiler.Value.Length)*/; i++)
                    //{
                    txt += " ";
                    //}
                    Console.WriteLine(txt + bilgiler.Value);
                }
            }

            Console.ReadLine();
        }
Esempio n. 58
0
 /// <summary>
 /// Concatenates sorted list of signed http headers.
 /// </summary>
 /// <param name="headersToSign">Sorted dictionary of headers to be signed</param>
 /// <returns>All signed headers</returns>
 private string GetSignedHeaders(SortedDictionary<string, string> headersToSign)
 {
     return string.Join(";", headersToSign.Keys);
 }
        private void readBillInfoToUI()
        {
            m_projectNum = m_currentOrderInfo.projectNum;

            this.labelSrcOrderBillNum.Visible = true;
            this.labelBillNumber.Visible = true;
            this.labelSummary.Visible = true;

            this.labelMakeBillStaff.Visible = true;
            this.labelMakeDate.Visible = true;
            this.labelBusinessPeople.Visible = true;
            this.labelReviewBillStaff.Visible = true;
            this.labelReviewDate.Visible = true;

            this.labelSrcOrderBillNum.Text = m_currentOrderInfo.srcBillNumber;
            this.labelBillNumber.Text = m_currentOrderInfo.billNumber;

            FormProjectMaterielTable tmp = FormProject.getInctance().getProjectInfoFromBillNumber(m_currentOrderInfo.srcBillNumber);
            this.labelProjectName.Text = tmp.projectName;
            this.labelProjectNo.Text = tmp.projectNum;
            this.labelMakeNo.Text = tmp.makeNum;
            this.labelDevMode.Text = tmp.deviceMode;

            this.labelSummary.Text = m_currentOrderInfo.changeReason;

            this.labelMakeBillStaff.Text = m_currentOrderInfo.makeOrderStaffName;
            this.labelMakeDate.Text = m_currentOrderInfo.makeOrderDate;
            this.labelBusinessPeople.Text = m_currentOrderInfo.designStaffName;
            this.textBoxBusinessPeople.Text = m_currentOrderInfo.designStaffName;
            this.labelReviewBillStaff.Text = m_currentOrderInfo.orderrReviewName;
            this.labelReviewDate.Text = m_currentOrderInfo.reviewDate;

            // 变更前DataGridView 赋值
            string matetiels = m_currentOrderInfo.materielIDs;
            string[] sArray = matetiels.Split('#');
            int rowNum = 0;
            foreach (string index in sArray)
            {
                if (index.ToString().Length > 0)
                {
                    string[] list = index.Split(',');

                    if (list.Length > 1)
                    {
                        setMatetielInfo(rowNum, list[0], list[1], list[2]);
                    }
                    else
                    {
                        setMatetielInfo(rowNum, list[0], "", "");
                    }

                    rowNum++;
                }
            }

            // 变更后DataGridView 赋值
            SortedDictionary<int, ProjectManagerDetailsTable> purchaseOrderDetails =
                ProjectManagerDetails.getInctance().getPurchaseInfoFromBillNumber(m_billNumber);

            foreach (KeyValuePair<int, ProjectManagerDetailsTable> index in purchaseOrderDetails)
            {
                ProjectManagerDetailsTable record = new ProjectManagerDetailsTable();
                record = index.Value;

                int rowIndex = Convert.ToInt32(record.rowNumber.ToString()) - 1;

                dataGridViewDataListChange.Rows[rowIndex].Cells[(int)DataGridColumnName.MatetielNumber].Value = record.materielID;
                dataGridViewDataListChange.Rows[rowIndex].Cells[(int)DataGridColumnName.Brand].Value = record.materielBrand;
                dataGridViewDataListChange.Rows[rowIndex].Cells[(int)DataGridColumnName.MatetielName].Value = record.materielName;

                dataGridViewDataListChange.Rows[rowIndex].Cells[(int)DataGridColumnName.Model].Value = record.materielModel;
                dataGridViewDataListChange.Rows[rowIndex].Cells[(int)DataGridColumnName.Parameter].Value = record.materielParameter;
                dataGridViewDataListChange.Rows[rowIndex].Cells[(int)DataGridColumnName.Size].Value = record.materielSize;
                dataGridViewDataListChange.Rows[rowIndex].Cells[(int)DataGridColumnName.Unit].Value = record.materielUnit;
                dataGridViewDataListChange.Rows[rowIndex].Cells[(int)DataGridColumnName.Value].Value = record.value;
                dataGridViewDataListChange.Rows[rowIndex].Cells[(int)DataGridColumnName.MakeType].Value = record.makeType;
                dataGridViewDataListChange.Rows[rowIndex].Cells[(int)DataGridColumnName.Note].Value = record.materielNote;


                dataGridViewDataListChange.Rows[rowIndex].Cells[(int)DataGridColumnName.Num].Value = record.no;
                dataGridViewDataListChange.Rows[rowIndex].Cells[(int)DataGridColumnName.Sequence].Value = record.sequence;
                dataGridViewDataListChange.Rows[rowIndex].Cells[(int)DataGridColumnName.UseDate].Value = record.useDate;
                dataGridViewDataListChange.Rows[rowIndex].Cells[(int)DataGridColumnName.DeviceName].Value = record.deviceName;
                dataGridViewDataListChange.Rows[rowIndex].Cells[(int)DataGridColumnName.CL].Value = record.cl;
            }

            // 如果单据已审核,则禁用页面所有控件
            if (m_currentOrderInfo.isReview == "1")
            {
                this.labelReviewBillStaff.Text = m_currentOrderInfo.orderrReviewName;
                this.labelReviewDate.Text = m_currentOrderInfo.reviewDate;
                this.panelIsReview.Visible = true;

                this.save.Enabled = false;
                this.toolStripButtonReview.Enabled = false;
                this.dataGridViewDataListChange.ReadOnly = true;

                this.panelSummary.Visible = false;

                this.textBoxSummary.Visible = false;

                this.panelBusinessPeople.Visible = false;
            }
            else
            {
                this.labelReviewBillStaff.Visible = false;
                this.labelReviewDate.Visible = false;
            }
        }
 public void CreateInvertedIndex(string stem)
 {
     invertedIndex = new SortedDictionary <string, Termin>();
     AddToIndex(stem);
     _stem = stem;
 }