public static SortedList<int, Tuple<Vector3D, Quaternion>> ParseData(string data)
        {
            SortedList<int, Tuple<Vector3D, Quaternion>> blocks = new SortedList<int, Tuple<Vector3D, Quaternion>>();

            if (data.Length == 0)
            {
                //This is empty, so just leave it empty
                return blocks;
            }

            //Aion's using a shitload of different separators :(
            //Individual block position entries are separated by backslashes
            string[] entries = data.Split('\\');

            //And then inside those entries, data is separated by slashes
            foreach(string entry in entries)
            {
                string[] pieces = entry.Split('/');
                if (pieces.Length != 3)
                {
                    //Invalid thingy, what do?
                    throw new FormatException("Improper format for animation data, expected 3 elements found " + pieces.Length + ". Make sure there's at most three backslashes (\\) in it!");
                }
                //And then it's pretty simple: <ID>, position, rotation
                int id = int.Parse(pieces[0].Trim('<', '>'));
                Vector3D position = Utilities.VectorFromN8String(pieces[1]);
                Quaternion rotation = Utilities.RotationFromN8String(pieces[2]);

                blocks.Add(id, Tuple.Create(position, rotation));
            }

            //And keep it ordered by block ID for later

            return blocks;
        }
 public StandardLimitOrderBook()
 {
     Bids = new SortedList<double, Queue<Order>>();
     Asks = new SortedList<double, Queue<Order>>();
     StopAsks = new SortedList<double, Queue<Order>>();
     StopBids = new SortedList<double, Queue<Order>>();
 }
 public AudioClipInfo(AudioType type, string resourcename, string systemname, float initvolume, int maxSEcount = 16 )
 {
     ResourceName = resourcename;
     if (type == AudioType.SE)
     {
         ResourcePath = SEPath + resourcename;
     }
     else if (type == AudioType.BGM) {
         ResourcePath = BGMPath + resourcename;
     }
     SystemName = systemname;
     MaxSECount = maxSEcount;
     PlayingList = new List<SEInfo>(maxSEcount);
     StockList = new SortedList<int, SEInfo>(maxSEcount);
     InitVolume = initvolume;
     AttenuateRate = calcAttenuateRate();
     //Debug.Log("Att: " + AttenuateRate);
     for (int i = 0; i < MaxSECount; i++) {
         //Debug.LogFormat("InitVol:{0}",InitVolume);
         SEInfo seinfo = new SEInfo(i, 0f, InitVolume * Mathf.Pow(AttenuateRate, i));
         //SEInfo seinfo = new SEInfo(i, 0f, InitVolume);
         StockList.Add(seinfo.Index, seinfo);
         //Debug.Log("Vol: " + seinfo.Volume);
     }
     Loop = null;
 }
 public List<double> getBeforeAndAfterKeys(SortedList<double, double> aSortedList, double pseudoKey)
 {
     double before = 0;
     double after = 0;
     this.getBeforeAndAfterKeys(aSortedList, pseudoKey, ref before, ref after);
     return new List<double>{before, after};
 }
示例#5
0
 public Updater(FileTransfer fileTransfer)
 {
     this.fileTransfer = fileTransfer;
     filesToDelete = new SortedList<string, string>();
     filesToDownload = new SortedList<string,TransferFile>();
     updaterConfig = new UpdaterConfig();
 }
示例#6
0
        public void Filter(string queryText)
        {
            SortedList<int, List<AutoSuggestModel.OptionValue>> l_sortedOption = new SortedList<int, List<AutoSuggestModel.OptionValue>>();
            foreach (AutoSuggestModel.OptionValue l_item in mOptionValueDB)
            {
                string l_target = l_item.CodeName + l_item.Description;
                string l_upperTarget = l_target.ToUpper();
                string l_upperSource = queryText.ToUpper();
                int l_index = l_upperTarget.IndexOf(l_upperSource);
                if (l_index >= 0)
                {
                    int l_sortedIndex = l_sortedOption.IndexOfKey(l_index);
                    if (l_sortedIndex == -1)
                    {
                        l_sortedOption[l_index] = new List<AutoSuggestModel.OptionValue>();
                    }
                    l_sortedOption[l_index].Add(l_item);
                }
            }

            mOptionValueList = new List<AutoSuggestModel.OptionValue>();
            foreach (KeyValuePair<int, List<AutoSuggestModel.OptionValue>> l_items in l_sortedOption)
            {
                foreach (AutoSuggestModel.OptionValue l_item in l_items.Value)
                {
                    mOptionValueList.Add(l_item);
                }
            }
        }
示例#7
0
 protected void rptTeams_ItemDataBound(object sender, RepeaterItemEventArgs e)
 {
     DropDownList drpStanding = (DropDownList)e.Item.FindControl("drpStanding");
     int year = cf.getMaxYear();
     SortedList teams = new SortedList();
     int cnt = 0;
     if (Session["user"] != null)
     {
         user u = (user)Session["user"];
         teams = u.get_teams();
         rptTeams.DataSource = null;
     }
     if (teams == null)
     {
         teams = cf.getTeams(year);
     }
     cnt = teams.Count;
     for (int i = 0; i < cnt; i++)
     {
         int s = i + 1;
         drpStanding.Items.Add(new ListItem(s.ToString(), s.ToString()));
     }
     try
     {
         drpStanding.SelectedIndex = e.Item.ItemIndex;
     }
     catch (Exception ex)
     {
         cf.logError(ex);
     }
 }
示例#8
0
 public string getAvsCode(SortedList<String, String[]> fileDetails, Track video, SortedList<String, String> EncOpts)
   {
       ExtApplication filter;
       switch (EncOpts["denoise"])
       {
           case "1":
               filter = ToolsManager.Instance.getTool("UnDot");
               if (!filter.isInstalled())
                   filter.download();
               return "UnDot()\r\n";
           case "2":
               filter = ToolsManager.Instance.getTool("FluxSmooth");
               if (!filter.isInstalled())
                   filter.download();
               return "FluxSmoothST()\r\n";
           case "3":
               filter = ToolsManager.Instance.getTool("HQDN3D");
               if (!filter.isInstalled())
                   filter.download();
               return "HQDN3D()\r\n";
           case "4":
               filter = ToolsManager.Instance.getTool("UnDot");
               if (!filter.isInstalled())
                   filter.download();
               filter = ToolsManager.Instance.getTool("Deen");
               if (!filter.isInstalled())
                   filter.download();
               return "UnDot.Deen()\r\n";
           default:
               return "";
       }
   }
示例#9
0
        //read XML file for patent info
        public static SortedList<int, Patent> GetPatents()
        {
            XmlDocument doc = new XmlDocument();

            //if file doesn't exist, create it
            if (!File.Exists("Patents.xml"))
                doc.Save("Patents.xml");

            SortedList<int, Patent> patents = new SortedList<int, Patent>();

            XmlReaderSettings readerSettings = new XmlReaderSettings();
            readerSettings.IgnoreWhitespace = true;
            readerSettings.IgnoreComments = true;

            XmlReader readXml = null;

            try
            {
                readXml = XmlReader.Create(path, readerSettings);

                if (readXml.ReadToDescendant("Patent")) //read to first Patent node
                {
                    do
                    {
                        Patent patent = new Patent();
                        patent.Number = Convert.ToInt32(readXml["Number"]);
                        readXml.ReadStartElement("Patent");
                        patent.AppNumber = readXml.ReadElementContentAsString();
                        patent.Description = readXml.ReadElementContentAsString();
                        patent.FilingDate = DateTime.Parse(readXml.ReadElementContentAsString());
                        patent.Inventor = readXml.ReadElementContentAsString();
                        patent.Inventor2 = readXml.ReadElementContentAsString();

                        int key = patent.Number; //assign key to value

                        patents.Add(key, patent); //add key-value pair to list
                    }
                    while (readXml.ReadToNextSibling("Patent"));
                }
            }
            catch (XmlException ex)
            {
                MessageBox.Show(ex.Message, "Xml Error");
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.Message, "IO Exception");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception Occurred");
            }
            finally
            {
                if (readXml != null)
                    readXml.Close();
            }

            return patents;
        }
示例#10
0
    public static void SetCountriesName(string language)
    {
        Debug.Log("countries....." +  language);
        TextAsset textAsset = (TextAsset) Resources.Load("countries");
        var xml = new XmlDocument ();
        xml.LoadXml (textAsset.text);

        Countries = new Hashtable();
        AppCountries = new SortedList();

        try{
            var element = xml.DocumentElement[language];
            if (element != null) {
                var elemEnum = element.GetEnumerator();
                while (elemEnum.MoveNext()) {
                    var xmlItem = (XmlElement)elemEnum.Current;
                    Countries.Add(xmlItem.GetAttribute("name"), xmlItem.InnerText);
                    AppCountries.Add(xmlItem.GetAttribute("name"), xmlItem.InnerText);
                }
            } else {
                Debug.LogError("The specified language does not exist: " + language);
            }

        }
        catch (Exception ex)
        {
            Debug.Log("Language:SetCountryName()" + ex.ToString());
        }
    }
示例#11
0
文件: MainForm.cs 项目: r3c/menora
        public MainForm(string configPath, bool minimize)
        {
            Config config;
            string message;

            this.InitializeComponent();

            this.toolStripMenuItemName.Text += Assembly.GetExecutingAssembly().GetName().Version.ToString(2);
            this.Icon = Resources.AppIcon;

            this.rules = new Dictionary<string, Rule>();
            this.configPath = configPath;
            this.minimize = minimize;
            this.points = new SortedList<int, Point>();

            if (!File.Exists(configPath))
                config = new Config();
            else if (!Config.TryParse(File.ReadAllText(configPath), out config, out message))
            {
                this.toolStripStatusLabel.Text = string.Format(CultureInfo.InvariantCulture, "Configuration error: {0}", message);

                config = new Config();
            }

            this.ConfigSet(config);
            this.ModeConfigRadioCheckedChanged(this, new EventArgs());
        }
示例#12
0
        public static string GetReadableTimespan(TimeSpan ts)
        {
            // formats and its cutoffs based on totalseconds
            var cutoff = new SortedList<long, string>
            {
                {60, "{3:S}" },
                {60*60, "{2:M}, {3:S}"},
                {24*60*60, "{1:H}, {2:M}"},
                {Int64.MaxValue , "{0:D}, {1:H}"}
            };

            // find nearest best match
            var find = cutoff.Keys.ToList()
                          .BinarySearch((long)ts.TotalSeconds);
            // negative values indicate a nearest match
            var near = find < 0 ? Math.Abs(find) - 1 : find;
            // use custom formatter to get the string
            return String.Format(
                new HMSFormatter(),
                cutoff[cutoff.Keys[near]],
                ts.Days,
                ts.Hours,
                ts.Minutes,
                ts.Seconds);
        }
    public bool ContainsNearbyAlmostDuplicate(int[] nums, int k, int t)
    {

        if (k <= 0 || t < 0) return false;
        var index = new SortedList<int, object>();
        for (int i = 0; i < nums.Length; ++i)
        {
            if (index.ContainsKey(nums[i]))
            {
                return true;
            }
            index.Add(nums[i], null);
            var j = index.IndexOfKey(nums[i]);
            if (j > 0 && (long)nums[i] - index.Keys[j - 1] <= t)
            {
                return true;
            }
            if (j < index.Count - 1 && (long)index.Keys[j + 1] - nums[i] <= t)
            {
                return true;
            }
            if (index.Count > k)
            {
                index.Remove(nums[i - k]);
            }
        }
        return false;
    }
        public override void Run(string[] _params)
        {
            try {
                EnumGamePrefs enumGamePrefs = EnumGamePrefs.Last;

                if (_params.Length > 0) {
                    try {
                        enumGamePrefs = (EnumGamePrefs)((int)Enum.Parse (typeof(EnumGamePrefs), _params [0]));
                    } catch (Exception e) {
                        Log.Out ("Error in GetGamePrefs.Run: " + e);
                    }
                }

                if (enumGamePrefs == EnumGamePrefs.Last) {
                    SortedList<string, string> sortedList = new SortedList<string, string> ();
                    foreach (EnumGamePrefs gp in Enum.GetValues(typeof(EnumGamePrefs))) {
                        if ((_params.Length == 0) || (gp.ToString ().ToLower ().Contains (_params [0].ToLower ()))) {
                            if (prefAccessAllowed (gp)) {
                                sortedList.Add (gp.ToString (), string.Format ("{0} = {1}", gp.ToString (), GamePrefs.GetObject (gp)));
                            }
                        }
                    }
                    foreach (string s in sortedList.Keys) {
                        m_Console.SendResult (sortedList [s]);
                    }
                } else {
                    if (prefAccessAllowed (enumGamePrefs))
                        m_Console.SendResult (string.Format ("{0} = {1}", enumGamePrefs, GamePrefs.GetObject (enumGamePrefs)));
                    else
                        m_Console.SendResult ("Je ne peux communiquer cette information.");
                }
            } catch (Exception e) {
                Log.Out ("Error in GetGamePrefs.Run: " + e);
            }
        }
        public List<Measure> CalculateAverage()
        {
            //return empty MeasureList if no measures where added
            if ((_inputList == null) || (_inputList.Count == 0))
            {
                return new List<Measure>();
            }

            //Get the average measures for all logminutes
            SortedList<DateTime, MeasureMinute> calcList = new SortedList<DateTime, MeasureMinute>();
            foreach (var measure in _inputList)
            {
                var currentMeasureTime = Utils.GetWith0Second(measure.DateTime);
                if (!calcList.ContainsKey(currentMeasureTime))
                {
                    calcList.Add(currentMeasureTime, new MeasureMinute(currentMeasureTime));
                }

                calcList[currentMeasureTime].AddMeasure(measure);
            }
            List<Measure> result = new List<Measure>();
            foreach (var logMinute in calcList.Values)
            {
                result.AddRange(logMinute.CalculateAverage());
            }

            return result;
        }
示例#16
0
        internal override void Read(bool newCollection)
        {
            //_131119_113717 SortedList with the default comparer is OK, unlike Distinct. Watch/test cases like 1 and 1.0, @{x=1} and @{x=1.0}, etc.
            _data = new SortedList<BsonValue, BsonDocument>();

            if (newCollection || FilePath == null || !File.Exists(FilePath))
                return;

            int index = -1;
            foreach (BsonDocument doc in ReadDocumentsAs(typeof(BsonDocument), FilePath, FileFormat))
            {
                ++index;
                BsonValue id;
                if (!doc.TryGetValue(MyValue.Id, out id))
                    throw new InvalidDataException(string.Format(null, "The document (index {0}) has no _id.", index));

                try
                {
                    _data.Add(id, doc);
                }
                catch (System.ArgumentException)
                {
                    throw new InvalidDataException(string.Format(null, @"The document (index {0}) has duplicate _id ""{1}"".", index, id));
                }
            }
        }
示例#17
0
 public GetPeersTask(DhtEngine engine, NodeId infohash)
 {
     this.engine = engine;
     this.infoHash = infohash;
     this.closestNodes = new SortedList<NodeId, NodeId>(Bucket.MaxCapacity);
     this.queriedNodes = new SortedList<NodeId, Node>(Bucket.MaxCapacity * 2);
 }
        public ComplexCollection(int sectorCount)
        {
            this.sectorCount = sectorCount;

            sectors = new SortedList<int, List<Complex>>[sectorCount];
            Clear();
        }
示例#19
0
        private TestSource( string testDataPath )
        {
            string[] filesPaths = Directory.GetFiles( testDataPath, "*.xml" );

              this.sourceData = new SortedList<string, XDocument>( );

              foreach ( string filePath in filesPaths )
              {
            string fileName = Path.GetFileNameWithoutExtension( filePath );
            if ( fileName == null || fileName.StartsWith( "_" ) )
              continue;

            XDocument doc = XDocument.Load( filePath );
            this.sourceData.Add( fileName, doc );

            //DateTime[] timestamps =
            //  (
            //    from msg in doc.Root
            //      .Elements( "feedMessageResponse" )
            //      .Elements( "messages" )
            //      .Elements( "message" )
            //    select SpotFeedRequest.ParsePosixTime( ( double ) msg.Element( "unixTime" ) )
            //  ).ToArray( );
              }

              string emptyFeedFilePath = Path.Combine( testDataPath, "_empty.xml" );
              this.emptySource = XDocument.Load( emptyFeedFilePath );
        }
示例#20
0
 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();
 }
    private void LoadData()
    {
        // Create sorted list for drop down values
        var items = new SortedList<string, string>()
        {
            { GetString("smartsearch.indextype." + TreeNode.OBJECT_TYPE), TreeNode.OBJECT_TYPE },
            { GetString("smartsearch.indextype." + UserInfo.OBJECT_TYPE), UserInfo.OBJECT_TYPE },
            { GetString("smartsearch.indextype." + CustomTableInfo.OBJECT_TYPE_CUSTOMTABLE), CustomTableInfo.OBJECT_TYPE_CUSTOMTABLE },
            { GetString("smartsearch.indextype." + SearchHelper.CUSTOM_SEARCH_INDEX), SearchHelper.CUSTOM_SEARCH_INDEX },
            { GetString("smartsearch.indextype." + SearchHelper.DOCUMENTS_CRAWLER_INDEX), SearchHelper.DOCUMENTS_CRAWLER_INDEX },
            { GetString("smartsearch.indextype." + SearchHelper.GENERALINDEX), SearchHelper.GENERALINDEX },
        };

        // Allow forum only if forums module is available
        if ((ModuleManager.IsModuleLoaded(ModuleName.FORUMS)))
        {
            items.Add(GetString("smartsearch.indextype." + PredefinedObjectType.FORUM), PredefinedObjectType.FORUM);
        }

        // Allow on-line forms only if the module is available
        if ((ModuleManager.IsModuleLoaded(ModuleName.BIZFORM)))
        {
            items.Add(GetString("smartsearch.indextype." + SearchHelper.ONLINEFORMINDEX), SearchHelper.ONLINEFORMINDEX);
        }

        // Data bind DDL
        drpIndexType.DataSource = items;
        drpIndexType.DataValueField = "value";
        drpIndexType.DataTextField = "key";
        drpIndexType.DataBind();

        // Pre-select documents
        drpIndexType.SelectedValue = TreeNode.OBJECT_TYPE;
    }
示例#22
0
 public DcmDataset(long streamPosition, uint lengthInStream, DicomTransferSyntax transferSyntax)
 {
     _streamPosition = streamPosition;
     _streamLength = lengthInStream;
     _transferSyntax = transferSyntax;
     _items = new SortedList<DicomTag, DcmItem>(new DicomTagComparer());
 }
示例#23
0
 //This is the function that is used to put buffered data on the database
 public bool flushToDatabase()
 {
     //Set to correct database
     mysql.switchDatabase("crex_forwardmetric");
     Console.WriteLine("Flushing To Forward Metric...");
     Console.WriteLine("0%");
     string returnval = "";
     //Go through all the data and add it efficiently
     for(int i = 0; i < data.Count;i++)
     {
         returnval+=mysql.issueCommand("create table if not exists `"+data.Keys[i]+"` (wordStrings char(50), wordCounts integer unsigned, primary key (wordStrings));");
         if(data.Values[i].Count==0) continue;
         string command = "insert into `"+data.Keys[i]+"` (wordStrings,wordCounts) values ";
         for(int j = 0; j < data.Values[i].Count;j++)
             command+="('"+data.Values[i][j]+"',1),";
         command = command.Remove(command.Length-1);
         command+=" on duplicate key update wordCounts=wordCounts+1;";
         returnval+=mysql.issueCommand(command);
         Console.SetCursorPosition(0, Console.CursorTop - 1);
         Console.WriteLine((int)((double)((double)i/(double)data.Count)*100.00)+"%");
     }
     Console.SetCursorPosition(0, Console.CursorTop - 1);
     Console.WriteLine("100%");
     Console.WriteLine("Done Flushing to Forward Metric...");
     //Reset data
     data = new SortedList<string, List<string>>();
     if(returnval!="") return false;
     return true;
 }
示例#24
0
        private SortedList<int, IAction> GetExternalActions(IPolicyChannel channel)
        {
            SortedList<int, IAction> externalActions = new SortedList<int, IAction>();

            IRoutingTable routing = channel.Routing;

            if (routing == null)
                return externalActions;

            Guid unprivDestinationId = routing.DefaultDestination.Identifier;
            Guid unprivSourceId = routing.DefaultSource.Identifier;

            IRoutingMatrixCell routingMatrixCell = routing[unprivSourceId, unprivDestinationId];
            if (routingMatrixCell == null)
                return externalActions;

            IActionMatrixCell actionMatrixCell = channel.Actions[unprivSourceId, unprivDestinationId];

            if (actionMatrixCell == null)
                return externalActions;

            foreach (IActionConditionGroup actionCondtionGroup in actionMatrixCell.ActionConditionGroups)
            {
                foreach (IAction action in actionCondtionGroup.ActionGroup.Actions)
                {
                    externalActions.Add(action.Precedence, action);
                }
            }
            return externalActions;
        }
示例#25
0
 public ForwardMetric()
 {
     //Star SQL Connection and set data to null
     data = new SortedList<string, List<string>>();
     mysql = new SQLInterface();
     mysql.connect(Program.mysqlusername, Program.mysqlpass, Program.mysqldatabase, Program.mysqlservername);
 }
示例#26
0
        public StopSpider(IPAddress providerDNS, IPAddress censorRedirect, string provider, string country, string reporter)
        {
            // initiate spiderlist

            this.providerDNS = providerDNS;
            this.censorRedirect = censorRedirect;
            this.provider = provider;
            this.country = country;
            this.reporter = reporter;
            this.openDnsResolver = new Resolver(Resolver.DefaultDnsServers[0]);

            // add an initial list in randomized order, this will also prevent adding already known urls!
            SortedList<int, string> rlist = new SortedList<int, string>();
            TextReader inputurls = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("shortlist.txt"));
            string url; Random r = new Random();
            while ((url = inputurls.ReadLine()) != null)
            {
                rlist.Add(r.Next(), url);
            }

            foreach (string uri in rlist.Values)
            {
                spiderlist.Add(new SpiderInfo(uri, 0));
                spidercheck.Add(uri, true);
            }
        }
示例#27
0
        public TabStandards(string standardsFile)
        {
            FilePath = standardsFile;
            StandardsList = new SortedList<long, NZQAStandard>();
            LatestVersions = new SortedList<int, int>();

            bool firstLine = true;
            int lineNumber = 1;
            foreach (var line in File.ReadAllLines(standardsFile))
            {
                if (firstLine)
                {
                    firstLine = false;
                    if (!line.Contains(DELIMETER)) continue;
                }

                var std = ParseLine(line, lineNumber++);
                var stdNo = std.StandardNumber;
                var verNo = std.Version;

                StandardsList[ToKey(stdNo, verNo)] = std;
                if (( !LatestVersions.ContainsKey(stdNo)) || LatestVersions[stdNo] < verNo)
                {
                    LatestVersions[stdNo] = verNo;
                    if (std.IsInternal) StandardsList[ToKey(stdNo, MAX_VERSION)] = std;
                }
            }
        }
示例#28
0
 public static void CovertChatLogsToDialogue(ref SortedList<DateTime, List<ChatWord>> chatLogs, ref SortedList<DateTime, List<ChatDialogue>> chatDialogues, int timeSpan = 60)
 {
     DateTime currentDate = DateTime.Today;
     DateTime currentDateTime = DateTime.Today;
     foreach (var dialogue in chatLogs)
     {
         if (currentDateTime.Equals(DateTime.Today) || (dialogue.Value.First().timeStamp - currentDateTime).TotalMinutes > timeSpan)
         {
             chatDialogues.Add(dialogue.Key, new List<ChatDialogue>());
             currentDate = dialogue.Key;
         }
         foreach (var log in dialogue.Value)
         {
             if (currentDateTime.Equals(DateTime.Today) || (log.timeStamp - currentDateTime).TotalMinutes > timeSpan)
             {
                 if (!currentDate.Date.Equals(log.timeStamp.Date))
                 {
                     chatDialogues.Add(dialogue.Key, new List<ChatDialogue>());
                     currentDate = dialogue.Key;
                 }
                 chatDialogues[currentDate].Add(new ChatDialogue(log.timeStamp));
             }
             chatDialogues[currentDate].Last().chatWords.Add(log);
             currentDateTime = log.timeStamp;
         }
     }
 }
    /// <summary>
    /// Resets all boxes.
    /// </summary>
    public void ResetControls()
    {
        txtCodeName.Text = null;
        txtDisplayName.Text = null;

        //Fill drop down list
        DataHelper.FillWithEnum<AnalyzerTypeEnum>(drpAnalyzer, "srch.index.", SearchIndexInfoProvider.AnalyzerEnumToString, true);

        drpAnalyzer.SelectedValue = SearchIndexInfoProvider.AnalyzerEnumToString(AnalyzerTypeEnum.StandardAnalyzer);
        chkAddIndexToCurrentSite.Checked = true;

        // Create sorted list for drop down values
        SortedList sortedList = new SortedList();

        sortedList.Add(GetString("srch.index.doctype"), PredefinedObjectType.DOCUMENT);
        // Allow forum only if module is available
        if ((ModuleEntry.IsModuleRegistered(ModuleEntry.FORUMS) && ModuleEntry.IsModuleLoaded(ModuleEntry.FORUMS)))
        {
            sortedList.Add(GetString("srch.index.forumtype"), PredefinedObjectType.FORUM);
        }
        sortedList.Add(GetString("srch.index.usertype"), PredefinedObjectType.USER);
        sortedList.Add(GetString("srch.index.customtabletype"), SettingsObjectType.CUSTOMTABLE);
        sortedList.Add(GetString("srch.index.customsearch"), SearchHelper.CUSTOM_SEARCH_INDEX);
        sortedList.Add(GetString("srch.index.doctypecrawler"), SearchHelper.DOCUMENTS_CRAWLER_INDEX);
        sortedList.Add(GetString("srch.index.general"), SearchHelper.GENERALINDEX);

        drpType.DataValueField = "value";
        drpType.DataTextField = "key";
        drpType.DataSource = sortedList;
        drpType.DataBind();

        // Pre-select documents index
        drpType.SelectedValue = PredefinedObjectType.DOCUMENT;
    }
        // assumes identifier is valid
        protected virtual void AddIdentifier(string identifier)
        {
            if (names == null)
                names = new SortedList<string, string>(StringComparer.OrdinalIgnoreCase);

            names.Add(identifier, identifier);
        }
 static void OtherMethods2(SortedList <string, string> list)
 {
 }
示例#32
0
        public void TestGetValuesBasic()
        {
            SortedList  sl        = null;
            ICollection ic        = null;
            IEnumerator ie        = null;
            int         iNumItems = 100;

            // Get an ICollection to Values and make sure there is correct number of them
            sl = new SortedList();

            // add elements to SortedList
            for (int i = 0; i < iNumItems; i++)
            {
                sl.Add(i, i);
            }

            ic = sl.Values;
            Assert.Equal(ic.Count, iNumItems);


            // Get an ICollection to Values and make sure enumerator throws without MoveNext
            Assert.Throws <InvalidOperationException>(() =>
            {
                sl = new SortedList();

                // add elements to SortedList
                for (int i = 0; i < iNumItems; i++)
                {
                    sl.Add(i, i);
                }

                ic = sl.Values;
                ie = (IEnumerator)ic.GetEnumerator();
                object garbageobj = ie.Current;          // should throw exception
            }
                                                      );

            // Get an ICollection to Values and make sure we can enumerate through the collection
            {
                sl = new SortedList();

                // add elements to SortedList
                for (int i = 0; i < iNumItems; i++)
                {
                    sl.Add(i, i);
                }

                ic = sl.Values;

                ie = (IEnumerator)ic.GetEnumerator();

                int iCounter = 0; // keeps track of how many objects there are in enumeration
                while (ie.MoveNext())
                {
                    object o = ie.Current;

                    Assert.NotNull(o);


                    Assert.True(o.Equals(iCounter), "Error, element should not be " + o.ToString() + " but it should be " + iCounter.ToString());
                    iCounter++;
                }

                Assert.Equal(iCounter, iNumItems);
            }

            Assert.Throws <InvalidOperationException>(() =>
            {
                sl = new SortedList();

                // add elements to SortedList
                for (int i = 0; i < iNumItems; i++)
                {
                    sl.Add(i, i);
                }

                ic = sl.Values;
                ie = (IEnumerator)ic.GetEnumerator();

                // make change to underlying collection
                sl.Add(iNumItems, iNumItems);

                ie.MoveNext();
            }
                                                      );


            // Get ICollection to Values make sure that CopyTo throws with incorrect arguments 1
            Assert.Throws <ArgumentNullException>(() =>
            {
                sl = new SortedList();

                // add elements to SortedList
                for (int i = 0; i < iNumItems; i++)
                {
                    sl.Add(i, i);
                }

                ic = sl.Values;

                ic.CopyTo(null, 0);
            }
                                                  );

            // Get ICollection to Values make sure that CopyTo throws with incorrect arguments 2
            Assert.Throws <ArgumentException>(() =>
            {
                sl = new SortedList();

                // add elements to SortedList
                for (int i = 0; i < iNumItems; i++)
                {
                    sl.Add(i, i);
                }

                ic = sl.Values;

                object[] obj = new object[iNumItems];
                // incorrect reference into array
                ic.CopyTo(obj, iNumItems);
            }
                                              );
        }
示例#33
0
 /// <summary>
 /// Creates a new ThreadSafeSortedList object.
 /// </summary>
 public ThreadSafeSortedList()
 {
     _items = new SortedList <TK, TV>();
     _lock  = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
 }
示例#34
0
        /// <summary>
        /// Attempts to refresh broken thumbnails across all visualization sets in the project.
        /// </summary>
        /// <param name="project">Project reference.</param>
        public static void RefreshAllThumbnails(DisasmProject project)
        {
            ScriptSupport iapp = null;
            Dictionary <string, IPlugin> plugins = null;

            SortedList <int, VisualizationSet> visSets = project.VisualizationSets;

            foreach (KeyValuePair <int, VisualizationSet> kvp in visSets)
            {
                VisualizationSet visSet = kvp.Value;
                foreach (Visualization vis in visSet)
                {
                    if (vis.HasImage)
                    {
                        continue;
                    }
                    //Debug.WriteLine("Vis needs refresh: " + vis.Tag);

                    if (vis is VisBitmapAnimation)
                    {
                        continue;
                    }

                    if (iapp == null)
                    {
                        // Prep the plugins on first need.
                        iapp = new ScriptSupport();
                        project.PrepareScripts(iapp);
                    }
                    iapp.MsgTag = vis.Tag;

                    if (plugins == null)
                    {
                        plugins = project.GetActivePlugins();
                    }
                    IPlugin_Visualizer vplug = FindPluginByVisGenIdent(plugins,
                                                                       vis.VisGenIdent, out VisDescr visDescr);
                    if (vplug == null)
                    {
                        Debug.WriteLine("Unable to refresh " + vis.Tag + ": plugin not found");
                        continue;
                    }

                    IVisualization2d                    vis2d   = null;
                    IVisualizationWireframe             visWire = null;
                    ReadOnlyDictionary <string, object> parms   =
                        new ReadOnlyDictionary <string, object>(vis.VisGenParams);
                    try {
                        if (visDescr.VisualizationType == VisDescr.VisType.Bitmap)
                        {
                            vis2d = vplug.Generate2d(visDescr, parms);
                            if (vis2d == null)
                            {
                                Debug.WriteLine("Vis2d generator returned null");
                            }
                        }
                        else if (visDescr.VisualizationType == VisDescr.VisType.Wireframe)
                        {
                            IPlugin_Visualizer_v2 plugin2 = (IPlugin_Visualizer_v2)vplug;
                            visWire = plugin2.GenerateWireframe(visDescr, parms);
                            if (visWire == null)
                            {
                                Debug.WriteLine("VisWire generator returned null");
                            }
                        }
                        else
                        {
                            Debug.Assert(false);
                        }
                    } catch (Exception ex) {
                        Debug.WriteLine("Vis generation failed: " + ex);
                    }
                    if (vis2d != null)
                    {
                        //Debug.WriteLine(" Rendered thumbnail: " + vis.Tag);
                        vis.SetThumbnail(vis2d);
                    }
                    else if (visWire != null)
                    {
                        vis.SetThumbnail(visWire, parms);
                    }
                }
            }

            if (iapp != null)
            {
                project.UnprepareScripts();
            }

            // Now that we've generated images for the Visualizations, update any
            // VisBitmapAnimation thumbnails that may have been affected.
            foreach (KeyValuePair <int, VisualizationSet> kvp in visSets)
            {
                VisualizationSet visSet = kvp.Value;
                foreach (Visualization vis in visSet)
                {
                    if (!(vis is VisBitmapAnimation))
                    {
                        continue;
                    }
                    VisBitmapAnimation visAnim = (VisBitmapAnimation)vis;
                    visAnim.GenerateImage(visSets);
                }
            }
        }
示例#35
0
        public void GenerateDotNetFrameworkProject(string projectName, string title, bool open)
        {
            if (title.Length == 0)
            {
                title = projectName;
            }
            title       = title.Trim();
            projectName = projectName.Trim().Replace(" ", "");

            string visualStudioFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Visual Studio");
            string templateFolder     = Path.Combine(visualStudioFolder, "Template");
            string projectFolder      = Path.Combine(visualStudioFolder, projectName);
            string imagesFolder1      = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images");
            string imagesFolder2      = Path.Combine(projectFolder, "Images");

            try
            {
                if (Directory.Exists(projectFolder))
                {
                    Directory.Delete(projectFolder, true);
                }
                Directory.CreateDirectory(projectFolder);
                Directory.CreateDirectory(imagesFolder2);

                // Generate AssemblyInfo.cs from the template:
                string path = Path.Combine(templateFolder, "AssemblyInfo.cs");
                string text = File.ReadAllText(path).Replace("__PROJECT_NAME__", projectName);
                path = Path.Combine(projectFolder, "Properties");
                Directory.CreateDirectory(path);
                path = Path.Combine(path, "AssemblyInfo.cs");
                File.WriteAllText(path, text);

                // Copy fixed source files from the template:
                Copy(@"Visual Studio\Template\App.config");
                Copy(@"Visual Studio\Template\Styles.xaml");

                // Copy project files from the template, specifying the project name:
                CopyProjectFile("App.xaml");
                CopyProjectFile("App.xaml.cs");
                CopyProjectFile("MainWindow.xaml.cs");

                // Generate xaml for all controls in Z-order:
                var sortedChildren = new SortedList <int, IHmiControl>(gridCanvas.Children.Count);
                foreach (object child in gridCanvas.Children)
                {
                    if (child is IHmiControl control)
                    {
                        sortedChildren[Panel.GetZIndex(control.fe)] = control;
                    }
                }
                var sb = new StringBuilder();
                foreach (IHmiControl child in sortedChildren.Values)
                {
                    sb.AppendLine(child.ToXaml(2, true));
                }

                // Generate MainWindow.xaml, specifying the project name and window title:
                path = Path.Combine(templateFolder, "MainWindow.xaml");
                text = File.ReadAllText(path).Replace("__PROJECT_NAME__", projectName).Replace("__WINDOW_TITLE__", title).Replace("__CONTROLS__", sb.ToString().Trim());
                path = Path.Combine(projectFolder, "MainWindow.xaml");
                File.WriteAllText(path, text);

                // Copy Images and add as project resources:
                var sbImageResources = new StringBuilder();
                foreach (var file in Directory.GetFiles(imagesFolder1))
                {
                    string name = Path.GetFileName(file);
                    File.Copy(file, Path.Combine(imagesFolder2, name));
                    sbImageResources.AppendFormat("    <Resource Include=\"Images\\{0}\" />\r\n", name);
                }

                // Generate VS project file from the template:
                string csprojPath = string.Format(@"{0}\{1}.csproj", projectFolder, projectName);
                path = Path.Combine(templateFolder, "Template.csproj");
                text = File.ReadAllText(path).Replace("__PROJECT_NAME__", projectName);
                text = text.Replace("__PROJECT_GUID__", Guid.NewGuid().ToString().ToUpper());
                text = text.Replace("__ITEMGROUP_RESOURCES__", sbImageResources.ToString().Trim());
                File.WriteAllText(csprojPath, text);

                // Open the new project:
                if (open)
                {
                    System.Diagnostics.Process.Start(csprojPath);  // open project in Visual Studio
                }
                else
                {
                    System.Diagnostics.Process.Start(projectFolder); // open project directory in File Explorer
                }
            }
            catch (Exception exc)
            {
                string message = (exc.InnerException != null) ? exc.InnerException.Message : exc.Message;
                MessageBox.Show("Project generation failed: " + message);
            }

            void Copy(string file, string folder = "")
            {
                file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file);
                if (File.Exists(file))
                {
                    folder = Path.Combine(projectFolder, folder);
                    if (!folder.Equals(projectFolder, StringComparison.InvariantCultureIgnoreCase))
                    {
                        Directory.CreateDirectory(folder);
                    }
                    File.Copy(file, Path.Combine(folder, Path.GetFileName(file)));
                }
            }

            void CopyProjectFile(string filename)
            {
                // Copy filename from the template, specifying the project name:
                string path = Path.Combine(templateFolder, filename);
                string text = File.ReadAllText(path).Replace("__PROJECT_NAME__", projectName);

                path = Path.Combine(projectFolder, filename);
                File.WriteAllText(path, text);
            }
        }
        private void FindDuplicateImages()
        {
            try
            {
                bool foundDuplicate = false;

                /* SortedList sorts by key rather than value. */
                SortedList <float, string> HSBValues = new SortedList <float, string>();

                for (int i = 0; i < files.Length; i++)
                {
                    string tempString = GetFileNameFromPath(files[i]);

                    try
                    {
                        using (Bitmap temp = new Bitmap(files[i]))
                        {
                            float tempFloat = GetAverageBrightness(temp);

                            if (tempFloat > 0f && tempFloat < 1f)
                            {
                                HSBValues.Add(tempFloat, tempString);
                            }
                            else
                            {
                                mainTextBox.Text += "Error with getting" + files[i] + " brightness. Ouside range.\n";
                            }
                        }
                    }
                    catch (Exception)
                    {
                        mainTextBox.Text += "Skipping " + tempString + ". Error creating bitmap from file.\n";
                    }
                }

                int maxNumComparisons = (HSBValues.Count < 5) ? HSBValues.Count - 1 : 5;

                float similarity     = -1f;
                int   numComparisons = 0;
                for (int i = 0; i <= HSBValues.Count - 1; i++)
                {
                    //mainTextBox.Text += HSBValues.Values[i] + " - " + HSBValues.Keys[i] + "\n";

                    numComparisons = (maxNumComparisons + i >= HSBValues.Count) ? HSBValues.Count - i - 1 : maxNumComparisons;

                    for (int j = 1; j <= numComparisons; j++)
                    {
                        if (IsSameImage(HSBValues.Keys[i], HSBValues.Keys[i + j], out similarity))
                        {
                            foundDuplicate    = true;
                            mainTextBox.Text += "> Potential match found (" + similarity * 100f + "): " + HSBValues.Values[i] + " and " + HSBValues.Values[i + j] + "\n";

                            if (!File.Exists(duplicatesFolder + "\\" + HSBValues.Values[i]))
                            {
                                File.Copy(targetFolder + "\\" + HSBValues.Values[i], duplicatesFolder + "\\" + HSBValues.Values[i]);
                            }
                            if (!File.Exists(duplicatesFolder + "\\" + HSBValues.Values[i + j]))
                            {
                                File.Copy(targetFolder + "\\" + HSBValues.Values[i + j], duplicatesFolder + "\\" + HSBValues.Values[i + j]);
                            }
                        }
                    }
                }

                if (!foundDuplicate)
                {
                    mainTextBox.Text += "> No duplicates found (" + similarityThreshold * 100f + "% confidence)\n";
                    Directory.Delete(duplicatesFolder);
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("FindDuplicateImages exception: " + ex.Message);
            }
        }
        public virtual IEnumerable <IMatch> TextMatches(string text)
        {
            var tags = GetTags(text);

            // return to speed-up
            if (tags.Count == 0)
            {
                return(new List <IMatch>());
            }

            var sortedList = new SortedList <int, ITagMatch>();

            foreach (var tag in tags)
            {
                sortedList.Add(tag.Index, tag);
            }

            sortedList = DeleteOverlapping(sortedList);

            var matchedPairs = new List <Tuple <ITagMatch, ITagMatch> >();
            var startsStack  = new Stack <ITagMatch>();

            foreach (var tag in sortedList.Select(pair => pair.Value))
            {
                if (tag is IStartOrEndTagMatch)
                {
                    var startOrEndTag = tag as IStartOrEndTagMatch;

                    if (startOrEndTag.IsStart)
                    {
                        var start = startOrEndTag as IStartTagMatch;
                        if (start.HasEnding)
                        {
                            startsStack.Push(start);
                        }
                        else if (startsStack.Count == 0)
                        {
                            matchedPairs.Add(new Tuple <ITagMatch, ITagMatch>(start, start));
                        }
                    }
                    else
                    {
                        if (startsStack.Count > 0)
                        {
                            ITagMatch start;
                            var       end = startOrEndTag as IEndTagMatch;

                            if (ignoreNoClosingError)
                            {
                                start = NonstrickStartTagSearch(startsStack, end, text);

                                if (start == null)
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                start = startsStack.Pop();

                                if (!VerifyMatch(text, start, end))
                                {
                                    throw CreateParsingErrorExceptionAtPosition(Language.Message("TagMismatch", GetErrorString(start), GetErrorString(end)), start.Index);
                                }
                            }

                            matchedPairs.Add(new Tuple <ITagMatch, ITagMatch>(start, end));
                        }
                        else if (!ignoreNoClosingError)
                        {
                            throw CreateParsingErrorExceptionAtPosition(Language.Message("RedundantEndingTag", GetErrorString(tag)), tag.Index);
                        }
                    }
                }
                else
                {
                    startsStack.Push(tag);
                }
            }

            // non-StartOrEnd tags parsing e.g. **bold**
            var nonStartEndStartsStack = new Stack <ITagMatch>();
            var potentialEnds          = startsStack.Where(e => !(e is IStartOrEndTagMatch)).ToList();

            potentialEnds.Reverse();

            foreach (var potentialEnd in potentialEnds)
            {
                var start = NonstrickStartTagSearch(nonStartEndStartsStack, potentialEnd, text);

                if (start != null && nonStartEndStartsStack.Count == 0)
                {
                    matchedPairs.Add(new Tuple <ITagMatch, ITagMatch>(start, potentialEnd));
                }
                else
                {
                    nonStartEndStartsStack.Push(potentialEnd);
                }
            }

            if (!ignoreNoClosingError && startsStack.Count > 0)
            {
                var start = startsStack.Pop();

                throw CreateParsingErrorExceptionAtPosition(Language.Message("MissingEndingTag", GetErrorString(start)), start.Index);
            }

            return(CreateLevelZeroElements(text, matchedPairs));
        }
示例#38
0
        static void Main()
        {
            List <Student> objstud = new List <Student>();

            objstud.Add(new Student {
                Rollno = 101, Name = "shubham", Subject1 = 60, Subject2 = 65
            });
            objstud.Add(new Student {
                Rollno = 102, Name = "kunal", Subject1 = 60, Subject2 = 65
            });
            objstud.Add(new Student {
                Rollno = 103, Name = "Pratiksha", Subject1 = 60, Subject2 = 65
            });
            objstud.Add(new Student {
                Rollno = 104, Name = "Shikha", Subject1 = 60, Subject2 = 65
            });

            foreach (Student e in objstud)
            {
                e.display();
            }

            Console.WriteLine();
            Console.WriteLine("Enter Roll no to get details");
            int rn = Convert.ToInt32(Console.ReadLine());

            foreach (Student e in objstud)
            {
                if (e.Rollno == rn)
                {
                    e.display();
                }
            }
            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("Enter Roll no to delete details");
            int     trn = Convert.ToInt32(Console.ReadLine());
            Student s   = null;

            foreach (Student e in objstud)
            {
                if (e.Rollno == trn)
                {
                    s = e;
                }
            }

            objstud.Remove(s);
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("after deleting {0}", trn);
            foreach (Student e in objstud)
            {
                e.display();
            }

            Console.WriteLine();
            Console.WriteLine();
            //=================================================

            SortedList <int, Student> objSortedList = new SortedList <int, Student>();

            objSortedList.Add(1, new Student {
                Rollno = 101, Name = "shubham", Subject1 = 60, Subject2 = 65
            });
            objSortedList.Add(2, new Student {
                Rollno = 102, Name = "rohan", Subject1 = 80, Subject2 = 65
            });
            objSortedList.Add(3, new Student {
                Rollno = 103, Name = "Pratiksha", Subject1 = 90, Subject2 = 65
            });
            objSortedList.Add(4, new Student {
                Rollno = 104, Name = "shikha", Subject1 = 40, Subject2 = 65
            });

            foreach (KeyValuePair <int, Student> objKvp in objSortedList)
            {
                Console.Write(objKvp.Key + "  " + objKvp.Value.Rollno + "  "
                              + objKvp.Value.Name + " " + objKvp.Value.Subject1 + "  " + objKvp.Value.Subject2);
                Console.WriteLine();
            }



            Console.ReadLine();
        }
示例#39
0
 protected override ElfRelocator CreateRelocator(ElfLoader loader, SortedList <Address, ImageSymbol> imageSymbols)
 {
     return(new x86Relocator((ElfLoader32)loader, imageSymbols));
 }
示例#40
0
        public SetBasicView()
        {
            InitializeComponent();

            try
            {
                StringBuilder buff = new StringBuilder(512);
                buff.Clear();
                IniFileHandler.GetPrivateProfileString("SET", "DataSavePath", SettingPath.DefSettingFolderPath, buff, 512, SettingPath.CommonIniPath);
                textBox_setPath.Text = buff.ToString();

                string defRecExe = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\EpgDataCap_Bon.exe";
                buff.Clear();
                IniFileHandler.GetPrivateProfileString("SET", "RecExePath", defRecExe, buff, 512, SettingPath.CommonIniPath);
                textBox_exe.Text = buff.ToString();

                int num = IniFileHandler.GetPrivateProfileInt("SET", "RecFolderNum", 0, SettingPath.CommonIniPath);
                if (num == 0)
                {
                    listBox_recFolder.Items.Add(SettingPath.DefSettingFolderPath);
                }
                else
                {
                    for (uint i = 0; i < num; i++)
                    {
                        string key = "RecFolderPath" + i.ToString();
                        buff.Clear();
                        IniFileHandler.GetPrivateProfileString("SET", key, "", buff, 512, SettingPath.CommonIniPath);
                        if (buff.Length > 0)
                        {
                            listBox_recFolder.Items.Add(buff.ToString());
                        }
                    }
                }

                string[] files = Directory.GetFiles(SettingPath.SettingFolderPath, "*.ChSet4.txt");
                SortedList <Int32, TunerInfo> tunerInfo = new SortedList <Int32, TunerInfo>();
                foreach (string info in files)
                {
                    try
                    {
                        TunerInfo item     = new TunerInfo();
                        String    fileName = System.IO.Path.GetFileName(info);
                        item.BonDriver  = GetBonFileName(fileName);
                        item.BonDriver += ".dll";
                        item.TunerNum   = IniFileHandler.GetPrivateProfileInt(item.BonDriver, "Count", 0, SettingPath.TimerSrvIniPath).ToString();
                        if (IniFileHandler.GetPrivateProfileInt(item.BonDriver, "GetEpg", 1, SettingPath.TimerSrvIniPath) == 0)
                        {
                            item.IsEpgCap = false;
                        }
                        else
                        {
                            item.IsEpgCap = true;
                        }
                        int priority = IniFileHandler.GetPrivateProfileInt(item.BonDriver, "Priority", 0xFFFF, SettingPath.TimerSrvIniPath);
                        while (true)
                        {
                            if (tunerInfo.ContainsKey(priority) == true)
                            {
                                priority++;
                            }
                            else
                            {
                                tunerInfo.Add(priority, item);
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
                    }
                }
                foreach (TunerInfo info in tunerInfo.Values)
                {
                    listBox_bon.Items.Add(info);
                }
                if (listBox_bon.Items.Count > 0)
                {
                    listBox_bon.SelectedIndex = 0;
                }

                comboBox_HH.DataContext   = CommonManager.Instance.HourDictionary.Values;
                comboBox_HH.SelectedIndex = 0;
                comboBox_MM.DataContext   = CommonManager.Instance.MinDictionary.Values;
                comboBox_MM.SelectedIndex = 0;

                serviceList = new List <ServiceItem2>();
                try
                {
                    foreach (ChSet5Item info in ChSet5.Instance.ChList.Values)
                    {
                        ServiceItem2 item = new ServiceItem2();
                        item.ServiceInfo = info;
                        if (info.EpgCapFlag == 1)
                        {
                            item.IsSelected = true;
                        }
                        else
                        {
                            item.IsSelected = false;
                        }
                        serviceList.Add(item);
                    }
                }
                catch
                {
                }
                listView_service.DataContext = serviceList;

                if (IniFileHandler.GetPrivateProfileInt("SET", "BSBasicOnly", 1, SettingPath.CommonIniPath) == 1)
                {
                    checkBox_bs.IsChecked = true;
                }
                else
                {
                    checkBox_bs.IsChecked = false;
                }
                if (IniFileHandler.GetPrivateProfileInt("SET", "CS1BasicOnly", 1, SettingPath.CommonIniPath) == 1)
                {
                    checkBox_cs1.IsChecked = true;
                }
                else
                {
                    checkBox_cs1.IsChecked = false;
                }
                if (IniFileHandler.GetPrivateProfileInt("SET", "CS2BasicOnly", 1, SettingPath.CommonIniPath) == 1)
                {
                    checkBox_cs2.IsChecked = true;
                }
                else
                {
                    checkBox_cs2.IsChecked = false;
                }

                buff.Clear();
                timeList = new ObservableCollection <EpgCaptime>();
                int capCount = IniFileHandler.GetPrivateProfileInt("EPG_CAP", "Count", 0, SettingPath.TimerSrvIniPath);
                if (capCount == 0)
                {
                    EpgCaptime item = new EpgCaptime();
                    item.IsSelected = true;
                    item.Time       = "23:00";
                    timeList.Add(item);
                }
                else
                {
                    for (int i = 0; i < capCount; i++)
                    {
                        buff.Clear();
                        EpgCaptime item = new EpgCaptime();
                        IniFileHandler.GetPrivateProfileString("EPG_CAP", i.ToString(), "", buff, 512, SettingPath.TimerSrvIniPath);
                        item.Time = buff.ToString();
                        if (IniFileHandler.GetPrivateProfileInt("EPG_CAP", i.ToString() + "Select", 0, SettingPath.TimerSrvIniPath) == 1)
                        {
                            item.IsSelected = true;
                        }
                        else
                        {
                            item.IsSelected = false;
                        }
                        timeList.Add(item);
                    }
                }
                ListView_time.DataContext = timeList;

                textBox_ngCapMin.Text   = IniFileHandler.GetPrivateProfileInt("SET", "NGEpgCapTime", 20, SettingPath.TimerSrvIniPath).ToString();
                textBox_ngTunerMin.Text = IniFileHandler.GetPrivateProfileInt("SET", "NGEpgCapTunerTime", 20, SettingPath.TimerSrvIniPath).ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
            }
        }
示例#41
0
        public static void EnsurePopulated(IApplicationBuilder app)
        {
            ApplicationDbContext context = app.ApplicationServices.GetRequiredService <ApplicationDbContext>();

            context.Database.Migrate();
            List <Location> Locations = new List <Location>();

            if (!context.Locations.Any())
            {
                Locations.Add(new Location {
                    Name = "Front Door"
                });
                Locations.Add(new Location {
                    Name = "Family Room"
                });
                Locations.Add(new Location {
                    Name = "Rear Door"
                });
                // first, add Locations
                foreach (var l in Locations)
                {
                    context.Locations.Add(l);
                    context.SaveChanges();
                }
                //context.SaveChanges();
            }
            if (!context.Events.Any())
            {
                DateTime localDate = DateTime.Now;
                // subtract 6 months from date
                DateTime eventDate = localDate.AddMonths(-6);
                // random numbers will be needed
                Random rnd = new Random();
                // loop for each day in the range from 6 months ago to today
                while (eventDate < localDate)
                {
                    // random between 0 and 5 determines the number of events to occur on a given day
                    int num = rnd.Next(0, 6);

                    // a sorted list will be used to store daily events sorted by time
                    // each time an eventr is added, the list is re-sorted
                    SortedList <DateTime, Event> dailyEvents = new SortedList <DateTime, Event>();
                    // for loop to generate times for each event
                    for (int i = 0; i < num; i++)
                    {
                        // random between 0 and 23 for hour of the day
                        int hour = rnd.Next(0, 24);
                        // random between 0 and 59 for minute of the day
                        int minute = rnd.Next(0, 60);
                        // random between 0 and 59 for seconds of the day
                        int second = rnd.Next(0, 60);

                        // random location
                        int loc = rnd.Next(0, Locations.Count());

                        // generate event date/time
                        DateTime x = new DateTime(eventDate.Year, eventDate.Month, eventDate.Day, hour, minute, second);
                        // create event from date/time and location
                        Event e = new Event {
                            TimeStamp = x, Flagged = false, Location = context.Locations.FirstOrDefault(l => l.Name == Locations[loc].Name)
                        };
                        // add daily events to sorted list
                        dailyEvents.Add(e.TimeStamp, e);
                    }
                    // using sorted list for daily events, add to event list
                    foreach (var item in dailyEvents)
                    {
                        context.Events.Add(item.Value);
                        // save changes to database
                        context.SaveChanges();
                    }
                    // add 1 day
                    eventDate = eventDate.AddDays(1);
                }
                //context.SaveChanges();
            }
        }
示例#42
0
        private void ResolveMultiStringValue(SortedList <string, string> directoryIds, SortedList <string, string> fileIds, MultiStringValue multiStringValue)
        {
            string value = multiStringValue.Content.ToLower(CultureInfo.InvariantCulture);

            // Replace file paths with ids.

            foreach (KeyValuePair <string, string> pair in fileIds)
            {
                int index;
                while ((index = value.IndexOf(pair.Key)) != -1)
                {
                    // Replace the non-lower case value itself.

                    multiStringValue.Content = multiStringValue.Content.Remove(index, (pair.Key).Length);
                    multiStringValue.Content = multiStringValue.Content.Insert(index, pair.Value);
                    value = multiStringValue.Content.ToLower(CultureInfo.InvariantCulture);
                }
            }

            // Replace directory paths with ids.

            foreach (KeyValuePair <string, string> pair in directoryIds)
            {
                int index;
                while ((index = value.IndexOf(pair.Key)) != -1)
                {
                    // Replace the non-lower case value itself.

                    multiStringValue.Content = multiStringValue.Content.Remove(index, (pair.Key).Length);
                    multiStringValue.Content = multiStringValue.Content.Insert(index, pair.Value);
                    value = multiStringValue.Content.ToLower(CultureInfo.InvariantCulture);
                }
            }
        }
示例#43
0
        /// <summary>
        /// 事物处理个人收费"调价"
        /// </summary>
        /// <returns></returns>
        public bool BillIndividualUpdatePrice(IList <Ordergrouptest> oldList, IList <Ordergrouptest> newList, double?customerid, string ordernum, double dictlabid, string remark)
        {
            UserInfo userInfo = GetUserInfo();

            try
            {
                //获得财务清单核对人
                LoginService loginService = new LoginService();

                List <Dictcustomer> customerList = loginService.GetDictcustomer();
                int customercode             = (int)ParamStatus.PersonalCustomerID.SingleCustomerCode;
                List <Dictcustomer> customer = (from a in customerList where a.Customercode == customercode.ToString() select a).ToList();

                SortedList SQLlist = new SortedList(new MySort());
                double?    d       = 0;
                //生成账单头表数据
                Billhead head = new Billhead();
                head.Dictlabid = dictlabid;
                int sta = (int)ParamStatus.BillheadStatus.PrepareOut;
                head.Status             = sta.ToString();
                head.Remark             = remark;
                head.Createdate         = System.DateTime.Now;
                head.Billby             = userInfo.userId;
                head.Duedate            = System.DateTime.Now;
                head.Receipno           = "";
                head.Dictcustomerid     = customerid;
                head.Dictcheckbillid    = customer.Count > 0 ? customer[0].Dictcheckbillid : null;
                head.Customertype       = "0";
                head.Billtype           = "个检账单";
                head.Totalcontractprice = newList.Sum(c => c.Contractprice);
                head.Totalfinalprice    = newList.Sum(c => c.Finalprice);
                head.Totalstandardprice = newList.Sum(c => c.Standardprice);
                head.Totalgrouprprice   = newList.Sum(c => c.Groupprice);
                head.Billheadid         = this.getSeqID("SEQ_BILLHEAD");
                head.Invoiceno          = head.Billheadid.Value.ToString();
                head.Begindate          = DateTime.Now;
                head.Enddate            = DateTime.Now;
                SQLlist.Add(new Hashtable()
                {
                    { "INSERT", "Bill.InsertBillhead" }
                }, head);

                //循环生成账单明细信息
                foreach (Ordergrouptest test in newList)
                {
                    Billdetail detail = new Billdetail();
                    detail = SetBillDetail(head.Billheadid, ordernum, test, remark);

                    detail.Billdetailid = this.getSeqID("SEQ_BILLDETAIL");
                    SQLlist.Add(new Hashtable()
                    {
                        { "INSERT", "Bill.InsertBilldetail" }
                    }, detail);


                    //更新ordergrouptest表实收价格
                    Hashtable htgrouptest = new Hashtable();
                    htgrouptest["flag"]           = "nosendout";
                    htgrouptest["ordernum"]       = ordernum;
                    htgrouptest["dicttestitemid"] = test.Dicttestitemid;
                    htgrouptest["finalprice"]     = test.Finalprice;
                    SQLlist.Add(new Hashtable()
                    {
                        { "UPDATE", "Order.UpdateOrdergrouptestFinalPrice" }
                    }, htgrouptest);
                }

                bool result = this.ExecuteSqlTran(SQLlist);
                if (result)
                {
                    //修改价钱日志记录
                    for (int i = 0; i < oldList.Count; i++)
                    {
                        if (!oldList[i].Finalprice.Equals(newList[i].Finalprice))
                        {
                            UpdateBilldetailFinalpriceLog(oldList[i], newList[i], ordernum);
                        }
                    }

                    //已付款日志记录
                    AddOperationLog(ordernum, "", "财务管理", "已收费", "节点信息", "");
                }
                return(result);
            }
            catch (Exception ex)
            {
                return(false);

                throw new Exception(ex.Message);
            }
        }
示例#44
0
 /// <summary><para>Löscht alle Elemente aus dem Cache.</para></summary>
 internal static void Clear()
 {
     _cache   = new Dictionary <MapService, Image>(_size);
     _lruList = new SortedList <long, MapService>();
 }
示例#45
0
        /// <summary>
        /// 事物处理"预出账"操作
        /// </summary>
        /// <returns></returns>
        public bool BillPrepareOutOperation(Billhead billhead, Hashtable ht, string flag)
        {
            try
            {
                BilldetailService  service    = new BilldetailService();
                IList <Billdetail> detailList = service.SelectBilldetailList(ht);
                SortedList         SQLlist    = new SortedList(new MySort());
                billhead.Billheadid = this.getSeqID("SEQ_BILLHEAD");
                billhead.Invoiceno  = billhead.Billheadid.ToString();
                SQLlist.Add(new Hashtable()
                {
                    { "INSERT", "Bill.InsertBillhead" }
                }, billhead);

                foreach (Billdetail detail in detailList)
                {
                    //更新BILLDETAIL 表
                    Hashtable htdetail = new Hashtable();
                    htdetail["Billdetailids"] = detail.Billdetailid;
                    htdetail["Billheadid"]    = billhead.Billheadid;
                    SQLlist.Add(new Hashtable()
                    {
                        { "UPDATE", "Bill.UpdateBilldetailHeadId" }
                    }, htdetail);

                    //更新ordergrouptest表
                    Hashtable htgrouptest = new Hashtable();
                    htgrouptest["flag"]           = flag;
                    htgrouptest["billdetailid"]   = detail.Billdetailid;
                    htgrouptest["ordernum"]       = detail.Ordernum;
                    htgrouptest["dicttestitemid"] = detail.Dicttestitemid;
                    SQLlist.Add(new Hashtable()
                    {
                        { "UPDATE", "Order.UpdateOrdergrouptestPrice" }
                    }, htgrouptest);
                }
                bool result = this.ExecuteSqlTran(SQLlist);
                if (result)
                {
                    IEnumerator <Billdetail> ordernumList = (from a in detailList
                                                             group a by new { a.Ordernum } into g
                                                             select new Billdetail
                    {
                        Ordernum = g.Key.Ordernum
                    }).ToList().GetEnumerator();

                    //预出账日志
                    while (ordernumList.MoveNext())
                    {
                        this.AddOperationLog(ordernumList.Current.Ordernum, "", "财务管理", "预出账", "节点信息", "");
                    }
                }
                return(result);
            }
            catch (Exception ex)
            {
                return(false);

                throw new Exception(ex.Message);
            }
        }
示例#46
0
    // Use this for initialization
    void Start()
    {
        Debug.Log("@ Dictionary");

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

        tDictionary.Add("one", 1);
        tDictionary["two"]   = 2;
        tDictionary["two"]   = 22;
        tDictionary["three"] = 3;


        Debug.Log(tDictionary["two"]);
        Debug.Log(tDictionary.ContainsKey("one")); //키로 검색은 빠름
        Debug.Log(tDictionary.ContainsValue(3));   //값으로 검색은 느림


        Debug.Log(tDictionary.ContainsKey("onE"));

        int tOutValue = 0;

        if (false == tDictionary.TryGetValue("onE", out tOutValue))
        {
            Debug.Log("그런 값 없음. " + tOutValue.ToString());
        }
        if (true == tDictionary.TryGetValue("one", out tOutValue))
        {
            Debug.Log("Value : " + tOutValue.ToString());
        }

        //나열하기
        foreach (string tString in tDictionary.Keys)
        {
            Debug.Log(tString);
        }
        foreach (int tValue in tDictionary.Values)
        {
            Debug.Log(tValue.ToString());
        }
        foreach (KeyValuePair <string, int> tKVP in tDictionary)
        {
            Debug.Log(tKVP.Key + " : " + tKVP.Value);
        }



        Debug.Log("@ SortedList");
        //var 은 C++로 치자면 auto키워드와 같다. 타입을 추론한다.
        //var tSortedList = new SortedList<string, MethodInfo>();
        SortedList <string, MethodInfo> tSortedList = new SortedList <string, MethodInfo>();

        foreach (MethodInfo tInfo in typeof(object).GetMethods())
        {
            //tSortedList.Add( tInfo.Name, tInfo); //이것은 예외를 일으킨다. 왜냐하면 중복된 내용을 처리하지 못하기 때문이다.
            tSortedList[tInfo.Name] = tInfo;
        }
        foreach (string tName in tSortedList.Keys)
        {
            Debug.Log(tName);
        }
        foreach (MethodInfo tInfo in tSortedList.Values)
        {
            Debug.Log(tInfo.Name + "의 반환 형식은 " + tInfo.ReturnType);
        }


        Debug.Log("@ Sorted Dictionary");


        SortedDictionary <string, MethodInfo> tSortedDictionary = new SortedDictionary <string, MethodInfo>();

        foreach (MethodInfo tInfo in typeof(object).GetMethods())
        {
            //tSortedDictionary.Add( tInfo.Name, tInfo); //이것은 예외를 일으킨다. 왜냐하면 중복된 내용을 처리하지 못하기 때문이다.
            tSortedDictionary[tInfo.Name] = tInfo;
        }
        foreach (string tName in tSortedDictionary.Keys)
        {
            Debug.Log(tName);
        }
        foreach (MethodInfo tInfo in tSortedDictionary.Values)
        {
            Debug.Log(tInfo.Name + "의 반환 형식은 " + tInfo.ReturnType);
        }
    }
示例#47
0
        /////////////////////////////////////////////////////////////////////////////////////////
        // Private Methods
        /////////////////////////////////////////////////////////////////////////////////////////
        private void ParseFiles()
        {
            SortedList <DateTime, DeviceData> sortedDeviceDatas = new SortedList <DateTime, DeviceData>();

            // Start Thread that archives .N42 files
            ThreadStart threadStart = new ThreadStart(ArchiveFiles);
            Thread      thread      = new Thread(threadStart);

            thread.Start();

            // Parse spe files
            int filesCompleted = 0;

            foreach (string filePath in filePaths)
            {
                Invoke_ParsingUpdate((float)filesCompleted++ / (float)filePaths.Count());

                // Check if background file
                string fileName = Path.GetFileName(filePath);

                // Clear data
                Clear();

                // Deserialize file to N42 object
                if (DeserializeN42(filePath) == false)
                {
                    continue;
                }

                // Create RadSeeker and set FileName
                deviceData          = new DeviceData(DeviceInfo.Type.SymetricaSN33N);
                deviceData.FileName = fileName;

                // Parse data from N42 object
                if (ParseN42File() == false)
                {
                    continue;
                }

                // Add to other parsed
                if (sortedDeviceDatas.ContainsKey(deviceData.StartDateTime))
                {
                    continue;
                }
                sortedDeviceDatas.Add(deviceData.StartDateTime, deviceData);
            }

            // Number all the events
            int trailNumber = 1;

            foreach (KeyValuePair <DateTime, DeviceData> device in sortedDeviceDatas)
            {
                device.Value.TrialNumber = trailNumber++;
            }

            if (ErrorsOccurred)
            {
                StringBuilder errorBuilder = new StringBuilder();
                errorBuilder.AppendLine("The files listed below failed to parse..");
                int errorIndex;
                for (errorIndex = 0; errorIndex < fileErrors.Count && errorIndex < 8; errorIndex += 1)
                {
                    errorBuilder.AppendLine(string.Format("\t{0}", fileErrors[errorIndex].Key));
                }
                if (errorIndex < fileErrors.Count)
                {
                    errorBuilder.AppendLine(string.Format("\tand {0} others", fileErrors.Count - errorIndex));
                }
                MessageBox.Show(errorBuilder.ToString(), "Parsing Error");
            }
            ClearErrors();

            // Wait for thread to zip files
            thread.Join();

            deviceDatasParsed = sortedDeviceDatas.Values.ToList();
        }
示例#48
0
        /// <summary>
        /// 事物处理"调整价钱"
        /// </summary>
        /// <returns></returns>
        public bool UpdateBilldetailFinalprice(IList <Billdetail> oldList, IList <Billdetail> newList, string billheadid, string ordernum, string state)
        {
            try
            {
                bool flag   = false;
                bool result = true;

                SortedList SQLlist = new SortedList(new MySort());
                for (int i = 0; i < oldList.Count; i++)
                {
                    Hashtable ht = new Hashtable();
                    ht["billdetailid"] = newList[i].Billdetailid;
                    ht["finalprice"]   = newList[i].Finalprice;
                    SQLlist.Add(new Hashtable()
                    {
                        { "UPDATE", "Bill.UpdateBilldetailFinalprice" }
                    }, ht);

                    //修改ordergrouptest表实收价格
                    Hashtable htgrouptest = new Hashtable();
                    htgrouptest["ordernum"]       = ordernum;
                    htgrouptest["dicttestitemid"] = newList[i].Dicttestitemid;
                    htgrouptest["price"]          = newList[i].Finalprice;
                    htgrouptest["state"]          = state;

                    SQLlist.Add(new Hashtable()
                    {
                        { "UPDATE", "Order.UpdateOrdergrouptestFinalPrice" }
                    }, htgrouptest);

                    if (!oldList[i].Finalprice.Equals(newList[i].Finalprice))
                    {
                        flag = true;
                    }
                }

                //集合中有记录修改时重算BIIHEAD表汇总价钱
                if (!string.IsNullOrEmpty(billheadid) && flag)
                {
                    Hashtable hthead = new Hashtable();
                    hthead["billheadid"] = billheadid;
                    hthead["ordernum"]   = ordernum;
                    SQLlist.Add(new Hashtable()
                    {
                        { "UPDATE", "Bill.UpdateBillheadTotalFinalprice" }
                    }, hthead);
                }
                result = this.ExecuteSqlTran(SQLlist);

                if (!flag) //没有修改任一条记录直接返回
                {
                    return(result);
                }

                //日志记录
                for (int i = 0; i < oldList.Count; i++)
                {
                    if (!oldList[i].Finalprice.Equals(newList[i].Finalprice))
                    {
                        UpdateBilldetailFinalpriceLog(oldList[i], newList[i], ordernum);
                    }
                }
                return(result);
            }
            catch (Exception ex)
            {
                return(false);

                throw new Exception(ex.Message);
            }
        }
        private void addItem(DataRow dr, SortedList arrGTemp, SPWeb curWeb)
        {
            Guard.ArgumentIsNotNull(curWeb, nameof(curWeb));
            Guard.ArgumentIsNotNull(arrGTemp, nameof(arrGTemp));
            Guard.ArgumentIsNotNull(dr, nameof(dr));

            dtTemp = new DataTable();
            dtTemp.Columns.Add("WebId");
            dtTemp.Columns.Add("ListId");
            dtTemp.Columns.Add(IdText);
            dtTemp.Columns.Add(TitleText);
            dtTemp.Columns.Add("SiteUrl");
            dtTemp.Columns.Add("SiteId");
            dtTemp.Columns.Add(ProjectText);
            dtTemp.Columns.Add("TSDisableItem");
            dtTemp.Columns.Add(ListText);

            dtTemp.Rows.Add(
                dr[WebUId].ToString(),
                dr[ListUId].ToString(),
                dr[ItemId].ToString(),
                dr[TitleText].ToString(),
                curWeb.Site.ServerRelativeUrl,
                curWeb.Site.ID,
                dr[ProjectText].ToString(),
                1,
                dr[ListText].ToString());

            var counter = 9;

            foreach (var drCol in dsTSMeta.Tables[0]
                     .Select($"list_uid=\'{dr[ListUId]}\' and item_id={dr[ItemId]}")
                     .Where(drCol => !dtTemp.Columns.Contains(drCol[ColumnNameText].ToString())))
            {
                dtTemp.Columns.Add(drCol[ColumnNameText].ToString());
                dtTemp.Rows[0][counter] = drCol[ColumnValueText].ToString();
                counter++;
            }

            var tempGroup = new string[1] {
                null
            };

            if (arrGroupFields != null)
            {
                foreach (var groupBy in arrGroupFields)
                {
                    var field    = list.Fields.GetFieldByInternalName(groupBy);
                    var newGroup = string.Empty;

                    try
                    {
                        newGroup = dr[groupBy].ToString();
                        newGroup = formatField(newGroup, groupBy, dr, true);
                    }
                    catch (Exception exception)
                    {
                        DiagTrace.WriteLine(exception);
                    }

                    if (string.IsNullOrWhiteSpace(newGroup))
                    {
                        newGroup = $" No {field.Title}";
                    }

                    GroupHelper.ProcessTempGroups(arrGTemp, field, newGroup, ref tempGroup);
                }
            }

            arrItems.Add($"{dr[WebUId]}.{dr[ListUId]}.{dr[ItemId]}", tempGroup);
            queueAllItems.Enqueue(dtTemp.Rows[0]);
        }
示例#50
0
        void LoadUI()
        {
            if (BaseObjectMgr == null)
            {
                return;
            }
            m_sortRestrictColumnAccessType = Program.User.GetRestrictColumnAccessTypeList(BaseObjectMgr.Table);

            if (BaseObject == null) //新建
            {
                BaseObject        = BaseObjectMgr.CreateBaseObject();
                BaseObject.Ctx    = BaseObjectMgr.Ctx;
                BaseObject.TbCode = BaseObjectMgr.TbCode;
                m_bIsNew          = true;
            }

            List <CBaseObject> lstCol = BaseObjectMgr.Table.ColumnMgr.GetList();
            int nTop = 5;

            foreach (CBaseObject obj in lstCol)
            {
                CColumn col = (CColumn)obj;
                //判断禁止权限字段
                bool bReadOnly = false;
                if (m_sortRestrictColumnAccessType.ContainsKey(col.Id))
                {
                    AccessType accessType = m_sortRestrictColumnAccessType[col.Id];
                    if (accessType == AccessType.forbide)
                    {
                        continue;
                    }
                    else if (accessType == AccessType.read)
                    {
                        bReadOnly = true;
                    }
                }
                //

                if (col.Code.Equals("id", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                else if (col.Code.Equals("Created", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                else if (col.Code.Equals("Creator", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                else if (col.Code.Equals("Updated", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                else if (col.Code.Equals("Updator", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                //if (!col.IsVisible)
                //    continue;

                if (m_sortNotShowCol.ContainsKey(col.Code.ToLower()))
                {
                    continue;
                }

                Control ctrl = ColumnMapControl(col);
                if (ctrl != null)
                {
                    ctrl.Name = col.Code;
                    ctrl.Left = 10;
                    ctrl.Top  = nTop;
                    //ctrl.Width = lbCaption.Width;
                    //ctrl.Height = lbCaption.Height;
                    this.Controls.Add(ctrl);
                    //只读权限
                    if (bReadOnly)
                    {
                        ctrl.Enabled = false;
                    }

                    if (m_sortDisableCol.ContainsKey(col.Code.ToLower()))
                    {
                        ctrl.Enabled = false;
                    }
                }
                nTop = ctrl.Bottom + 5;
            }
            this.Height = nTop;
        }
示例#51
0
 /// <summary>
 /// Instantiate a new RowCollection class.
 /// </summary>
 public FileRowCollection()
 {
     this.hashedCollection = new Hashtable();
     this.sortedCollection = new SortedList();
 }
 /// <summary>
 /// Get the interval in between which all keys lie.
 /// </summary>
 /// <param name = "source">The source for this extension method.</param>
 /// <returns>The interval in between which all keys lie.</returns>
 public static IInterval <TKey> GetKeysInterval <TKey, TValue>(this SortedList <TKey, TValue> source)
     where TKey : IComparable <TKey>
 {
     return(new Interval <TKey>(source.Keys[0], source.Keys[source.Count - 1]));
 }
示例#53
0
 public ColorShift(Color startColor, Color endColor)
 {
     colors = new SortedList <float, Color>();
     colors.Add(1, startColor);
     colors.Add(0, endColor);
 }
示例#54
0
 /// <summary>
 /// Instantiate a new RowCollection class.
 /// </summary>
 public FileRowCollection(bool duplicateFileIds)
 {
     this.hashedCollection = duplicateFileIds ? null : new Hashtable();
     this.sortedCollection = new SortedList();
 }
示例#55
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MountFileSystem"/> class with a default backup filesystem.
 /// </summary>
 /// <param name="defaultBackupFileSystem">The default backup file system.</param>
 /// <param name="owned">True if <paramref name="defaultBackupFileSystem"/> and mounted filesytems should be disposed when this instance is disposed.</param>
 public MountFileSystem(IFileSystem?defaultBackupFileSystem, bool owned = true) : base(defaultBackupFileSystem, owned)
 {
     _mounts   = new SortedList <UPath, IFileSystem>(new UPathLengthComparer());
     _watchers = new List <AggregateWatcher>();
 }
        void LoadUI()
        {
            if (View == null)
            {
                return;
            }
            if (BaseObjectMgr == null)
            {
                return;
            }

            m_sortRestrictColumnAccessType = Program.User.GetRestrictColumnAccessTypeList(BaseObjectMgr.Table);

            if (BaseObject == null) //新建
            {
                BaseObject        = BaseObjectMgr.CreateBaseObject();
                BaseObject.Ctx    = BaseObjectMgr.Ctx;
                BaseObject.TbCode = BaseObjectMgr.TbCode;
                m_bIsNew          = true;
            }

            this.Controls.Clear();
            List <CBaseObject> lstCIV = View.ColumnInViewMgr.GetList();
            int nTop = 5;

            foreach (CBaseObject obj in lstCIV)
            {
                CColumnInView civ = (CColumnInView)obj;
                CColumn       col = (CColumn)BaseObjectMgr.Table.ColumnMgr.Find(civ.FW_Column_id);
                if (col == null)
                {
                    continue;
                }
                //判断禁止权限字段
                bool bReadOnly = false;
                if (m_sortRestrictColumnAccessType.ContainsKey(col.Id))
                {
                    AccessType accessType = m_sortRestrictColumnAccessType[col.Id];
                    if (accessType == AccessType.forbide)
                    {
                        continue;
                    }
                    else if (accessType == AccessType.read)
                    {
                        bReadOnly = true;
                    }
                }
                //

                Control ctrl = ColumnMapControl(col);
                if (ctrl != null)
                {
                    ctrl.Name = col.Code;
                    ctrl.Left = 10;
                    ctrl.Top  = nTop;
                    //ctrl.Width = lbCaption.Width;
                    //ctrl.Height = lbCaption.Height;
                    this.Controls.Add(ctrl);
                    //只读权限
                    if (bReadOnly)
                    {
                        ctrl.Enabled = false;
                    }
                }
                nTop = ctrl.Bottom + 5;
            }

            //具有默认值的字段
            List <CBaseObject> lstObj = View.ColumnDefaultValInViewMgr.GetList();

            foreach (CBaseObject obj in lstObj)
            {
                CColumnDefaultValInView cdviv = (CColumnDefaultValInView)obj;
                CColumn col = (CColumn)baseObjectMgr.Table.ColumnMgr.Find(cdviv.FW_Column_id);
                if (col == null)
                {
                    continue;
                }
                if (View.ColumnInViewMgr.FindByColumn(col.Id) != null) //在视图列中
                {
                    Control[] ctrls = this.Controls.Find(col.Code, true);
                    if (ctrls.Length > 0)
                    {
                        if (m_bIsNew) //新建
                        {
                            ((IColumnCtrl)ctrls[0]).SetValue(GetColumnDefaultVal(cdviv));
                        }
                        if (cdviv.ReadOnly)
                        {
                            ctrls[0].Enabled = false;
                        }
                    }
                }
                else  //不在视图列中
                {
                    Control ctrl = ColumnMapControl(col);
                    if (ctrl != null)
                    {
                        ctrl.Name = col.Code;
                        if (m_bIsNew) //新建
                        {
                            ((IColumnCtrl)ctrl).SetValue(GetColumnDefaultVal(cdviv));
                        }
                        ctrl.Visible = false; //作为隐藏字段
                        this.Controls.Add(ctrl);
                    }
                }
            }
            //
            //明细
            CViewDetail vd   = (CViewDetail)View.ViewDetailMgr.GetFirstObj();
            ViewTab     vtab = new ViewTab();

            vtab.View         = View;
            vtab.ParentObject = BaseObject;
            vtab.ShowTitleBar = false;
            vtab.ShowToolBar  = true;
            vtab.Left         = 10;
            vtab.Top          = nTop;
            vtab.Width        = this.Width - 20;
            vtab.Height       = 300;
            this.Controls.Add(vtab);

            nTop        = vtab.Bottom + 5;
            this.Height = nTop;
        }
示例#57
0
 protected override void Add(SortedList<TKey, TValue> collection, int index, TKey key, TValue value)
 {
     collection.Add(key, value);
 }
示例#58
0
        public void Save()
        {
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(this.m_filename, false, Encoding.Unicode))
            {
                // header
                writer.Write("Name");
                if (this.m_locales != null)
                {
                    foreach (string locale in this.m_locales)
                    {
                        writer.Write("\tName(");
                        writer.Write(locale);
                        writer.Write(")\tDescription(");
                        writer.Write(locale);
                        writer.Write(")");
                    }
                }
                writer.WriteLine();

                // blank line separates row data
                writer.WriteLine();

                // split into two lists alphabetically for easier translation
                SortedList <string, DocObject> sortlistEntity = new SortedList <string, DocObject>();
                SortedList <string, DocObject> sortlistType   = new SortedList <string, DocObject>();
                SortedList <string, DocObject> sortlistPset   = new SortedList <string, DocObject>();
                SortedList <string, DocObject> sortlistQset   = new SortedList <string, DocObject>();
                SortedList <string, DocObject> sortlistEnum   = new SortedList <string, DocObject>();

                // rows
                foreach (DocSection docSection in this.m_project.Sections)
                {
                    foreach (DocSchema docSchema in docSection.Schemas)
                    {
                        foreach (DocEntity docEntity in docSchema.Entities) // have attributes
                        {
                            sortlistEntity.Add(docEntity.Name, docEntity);
                        }

                        foreach (DocType docEntity in docSchema.Types) //docEnumeration docConstant
                        {
                            sortlistType.Add(docEntity.Name, docEntity);
                        }

                        foreach (DocPropertyEnumeration docPE in docSchema.PropertyEnums) //docPropertyConstant
                        {
                            sortlistEnum.Add(docPE.Name, docPE);
                        }

                        foreach (DocPropertySet docPset in docSchema.PropertySets) //Property
                        {
                            sortlistPset.Add(docPset.Name, docPset);
                        }

                        foreach (DocQuantitySet docQset in docSchema.QuantitySets) //Quantities
                        {
                            sortlistQset.Add(docQset.Name, docQset);
                        }
                    }
                }

                WriteList(writer, sortlistEntity);
                WriteList(writer, sortlistType);
                WriteList(writer, sortlistPset);
                WriteList(writer, sortlistEnum);
                WriteList(writer, sortlistQset);
            }
        }
示例#59
0
 /// <summary>Create an instance of a table</summary>
 public Table()
 {
     table        = new SortedList <string, SortedList <string, T> >();
     rowTitles    = new string[0];
     columnTitles = new string[0];
 }
	public static int test_0_fullaot_comparer_t () {
		var l = new SortedList <TimeSpan, int> ();
		return l.Count;
	}