예제 #1
0
        public static SerializableDictionary<string, SerializableDictionary<string, double>> GenerateWeights(List<string> states, SIMDIST weightFlag)
        {
            SerializableDictionary<string, SerializableDictionary<string, double>> weights = new SerializableDictionary<string, SerializableDictionary<string, double>>();
            if (weightFlag == SIMDIST.SIMILARITY)
            {
                foreach (var item in states)
                {
                    weights.Add(item, new SerializableDictionary<string, double>());
                    weights[item].Add(item, 1.0);
                }
            }
            else
                foreach (var item in states)
                {
                    weights.Add(item, new SerializableDictionary<string, double>());
                    foreach (var item1 in states)
                    {
                        if (item != item1)                                                    
                            weights[item].Add(item1, 1.0);                        
                    }
                }


            return weights;
        }
예제 #2
0
파일: Region.cs 프로젝트: naegelyd/therawii
        public Region()
        {
            rParams = new SerializableDictionary<regPT,RegionParameter>();
            rParams.Add(regPT.X, new RegionParameter());
            rParams.Add(regPT.Y, new RegionParameter());
            rParams.Add(regPT.Z, new RegionParameter());

            regionEnabled = false;
        }
예제 #3
0
        /// <summary>
        /// Calculate the probability for each category,
        /// and will determine which one is the largest
        /// and whether it exceeds the next largest by more than its threshold
        /// </summary>
        /// <param name="item">Item</param>
        /// <param name="defaultCat">Default category</param>
        /// <returns>Category which item mostly belongs to</returns>
        public string Classify(string item, string defaultCat = "unknown")
        {
            SerializableDictionary<string, double> probs = new SerializableDictionary<string, double>();
            string best = "";
            string possible = "";

            // Find the category with highest probability
            double max = 0.0;
            foreach (var category in Categories())
            {
                probs.Add(category, Probability(item, category));
                if (probs[category] > max)
                {
                    max = probs[category];
                    best = category;
                }
            }

                // Find the second suitable category
                if (probs.ContainsKey(best))
                {
                    probs.Remove(best);
                }
                max = 0.0;
                foreach (var category in probs)
                {
                    if (category.Value > max)
                    {
                        max = category.Value;
                        possible = category.Key;
                    }
                }
            probs.Add(best, Probability(item, best));
            

            // Make sure the probability exceeds threshould*next best
            foreach (var cat in probs)
            {
                if (cat.Key == best)
                {
                    continue;
                }
                if (cat.Value * GetThreshold(best) > probs[best])
                {
                    return defaultCat;
                }
            }
            return best + (possible.Length > 0 ? (" or " + possible) : "");
        }
        public static SerializableDictionary<string, string> GetLanguageStrings(Stream javaMessagesStream)
        {
            var result = new SerializableDictionary<string, string>();

            using (var reader = new StreamReader(javaMessagesStream))
            {
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();

                    var deviderIndex = line.IndexOf('=');
                    if (deviderIndex != -1 && line[0] != '#')
                    {
                        var text = line.Substring(deviderIndex + 1);

                        var regex = new Regex(@"\\u[A-Za-z0-9]{4}");

                        text = regex.Replace(text, m => ((Char)UInt16.Parse(m.Value.Substring(2), System.Globalization.NumberStyles.AllowHexSpecifier)).ToString());

                        var key = line.Substring(0, deviderIndex);
                        if (!result.ContainsKey(key))
                            result.Add(key, text);
                    }
                }
            }
            return result;
        }
예제 #5
0
    private ItemData CreateItemDataFromGameObject(GameObject gameObject)
    {
        ValidateGameObject (gameObject);

        ItemData itemData = new ItemData ();
        itemData.transformData.position = gameObject.transform.position;
        itemData.transformData.rotation = gameObject.transform.eulerAngles;
        itemData.transformData.scale = gameObject.transform.localScale;
        itemData.name = gameObject.name;

        foreach (IPersistable persistable in gameObject.GetComponents<IPersistable>()) {

          SerializableDictionary<string, object> componentConfiguration = new SerializableDictionary<string, object> ();
          foreach (FieldInfo field in persistable.GetType().GetFields()) {
        componentConfiguration.Add (field.Name, field.GetValue (persistable));
          }

          string componentName = persistable.GetType ().FullName;

          itemData.componentData.configurations.Add (componentName, componentConfiguration);
        }

        foreach (Transform child in gameObject.transform) {
          if (child.GetComponents<IPersistable> ().Length > 0) {
        itemData.children.Add (CreateItemDataFromGameObject (child.gameObject));
          }
        }

        return itemData;
    }
예제 #6
0
        /// <summary>
        /// If you need to get a clear savegame, use this method. But be careful, could erase other data
        /// </summary>
        public SaveData()
        {
            KilledPoulpis = 0;
            GameHasBeenEnded = false;

            #if DEBUG
            LastLevel = LevelSelectionScreen.WorldCount;
            #else
            LastLevel = 0;
            #endif
            ScoresBylevel = new SerializableDictionary<ScoreType, SerializableDictionary<String, ScoreLine[]>>();
            ScoresBylevel.Add(ScoreType.Single, new SerializableDictionary<String, ScoreLine[]>());
            ScoresBylevel.Add(ScoreType.Coop, new SerializableDictionary<String, ScoreLine[]>());

            this.OptionsData = new OptionsData();
        }
 public Frm_FanPowerAdvanceSetting(List<ILEDDisplayInfo> oneLedInfos,string sn,string commPort,
                                   SerializableDictionary<string, byte> curAllSettingDic, 
                                   SettingCommInfo commInfo)
 {
     InitializeComponent();
     _oneLedInfos = oneLedInfos;
     _sn = sn;
     _commPort = commPort;
     _curConfigDic = new SerializableDictionary<string, byte>();
     if (curAllSettingDic != null)
     {
         foreach(string addr in curAllSettingDic.Keys)
         {
             _curConfigDic.Add(addr, curAllSettingDic[addr]);
         }
     }
     try
     {
         _commonInfo = (SettingCommInfo)commInfo.Clone();
     }
     catch
     {
         _commonInfo = new SettingCommInfo();
     }
 }
        internal static SerializableDictionary<string, object> Parse(string worstPointFile)
        {
            IEnumerable<string> lines = System.IO.File.ReadLines(worstPointFile);

            if (lines == null || lines.Count() < 2) throw new ArgumentException("Invalid file");
            else
            {
                lines = lines.Skip(1);
                SerializableDictionary<string, object> input = new SerializableDictionary<string, object>();
                string[] numbers = (lines.First()).Split(',');
                input.Add("Frequency", Double.Parse(numbers[0], CultureInfo.InvariantCulture));
                input.Add("Desired", Double.Parse(numbers[1], CultureInfo.InvariantCulture));
                input.Add("ObjectiveFunctionValue", ObjectiveFunctionValueParser.Parse(numbers[2]));

                return input;
            }
        }
		public ServerState()
		{
			Accounts = new SerializableDictionary<string, Hash>();
			if (!Accounts.ContainsKey("guest")) {
				Accounts.Add("guest", Hash.HashString("guest"));
			}
            UpgradeData = new SerializableDictionary<string, List<UpgradeDef>>();
		}
        public void Test1()
        {
            SerializableDictionary<string, string> value;
            using (MemoryStream ms = new MemoryStream(0x1000))
            {
                SerializableDictionary<string, string> value0 = new SerializableDictionary<string, string>();
                value0.Add("a", "b");
                value0.Add("c", "d");
                value0.Add("e", "f");

                Util.Serialize(ms, value0);
                ms.Position = 0;

                value = Util.Deserialize<SerializableDictionary<string, string>>(ms);
            }
            Assert.AreEqual("b", value["a"]);
            Assert.AreEqual("d", value["c"]);
            Assert.AreEqual("f", value["e"]);
        }
예제 #11
0
파일: Region.cs 프로젝트: naegelyd/therawii
 public Region(Region r)
 {
     regionEnabled = r.regionEnabled;
     rParams = new SerializableDictionary<regPT, RegionParameter>();
     foreach (regPT rPT in r.rParams.Keys)
     {
         rParams.Add(rPT, new RegionParameter(r.rParams[rPT]));
     }
     Shape = r.Shape;
 }
예제 #12
0
파일: Table.cs 프로젝트: piaolingzxh/Justin
        public override SerializableDictionary<string, string> GetDeafultColumnMapping()
        {
            SerializableDictionary<string, string> columnMapping = new SerializableDictionary<string, string>();

            IEnumerable<Field> fields = this.PrimaryKeys.Union(this.Fields).Union(this.ForeKeys).Where(row => row.Enable);

            foreach (var item in fields.Select(row => row.Name).Distinct())
            {
                columnMapping.Add(item, item);
            }
            return columnMapping;
        }
예제 #13
0
        public void CreateNavMap()
        {
            List<PathNode> nodes = this.CreateNode();

            SerializableDictionary<PathNode, List<PathNode>> edges = new SerializableDictionary<PathNode, List<PathNode>>();

            foreach (PathNode node in nodes)
            {
                edges.Add(node, node.Location.CreateEdges(nodes));
            }

            this.NavMap.GenerateArbitraryMap(edges);
        }
예제 #14
0
        public static string AllSettingsAsXML()
        {
            // Defaults would be...
            //foreach (System.Configuration.SettingsProperty prop in Properties.Settings.Default.Properties)

            // Current values
            SerializableDictionary<string, string> serialisedSettings = new SerializableDictionary<string, string>();
            foreach (System.Configuration.SettingsPropertyValue prop in Properties.Settings.Default.PropertyValues)
            {
                serialisedSettings.Add(prop.Name, (string)prop.SerializedValue);
            }

            return XMLHelper.Serialize<SerializableDictionary<string, string>>(serialisedSettings);
        }
예제 #15
0
파일: View.cs 프로젝트: piaolingzxh/Justin
        public override SerializableDictionary<string, string> GetDeafultColumnMapping()
        {
            SerializableDictionary<string, string> columnMapping = new SerializableDictionary<string, string>();
            string sql = this.SQL + " where 1=0";
            DataTable table = OleDbHelper.ExecuteDataTable(this.Connection, sql);

            IEnumerable<DataColumn> fields = table.Columns.Cast<DataColumn>().Where(col => col.ColumnName != "_row_num");

            foreach (var item in fields.Select(row => row.ColumnName).Distinct())
            {
                columnMapping.Add(item, item);
            }
            return columnMapping;
        }
예제 #16
0
        private void OkBtn_Click(object sender, EventArgs e)
        {

            if (textBox3.Text.Length == 0)
            {
                this.DialogResult = DialogResult.None;
                MessageBox.Show("Output filename must be provided");
                return;
            }
            if (textBox1.Text.Length == 0)
            {
                this.DialogResult = DialogResult.None;
                MessageBox.Show("Name of the profile must be provided");
                return;

            }

            profile.profName = textBox1.Text;
            profile.profProgram = textBox2.Text;
            profile.OutFileName = textBox3.Text;
            profile.removeOutFile = checkBox1.Checked;
            profile.progParameters =textBox4.Text;

            this.DialogResult = DialogResult.OK;

            profile.profWeights.Clear();
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                if (dataGridView1.Rows[i].Cells[0].Value != null && dataGridView1.Rows[i].Cells[0].Value != null && dataGridView1.Rows[i].Cells[1].Value != null)
                {
                    string item1 = (string)dataGridView1.Rows[i].Cells[0].Value;
                    string item2 = (string)dataGridView1.Rows[i].Cells[1].Value;
                    if (profile.profWeights.ContainsKey(item1))
                    {
                        if (profile.profWeights[item1].ContainsKey(item2))
                            profile.profWeights[item1].Remove(item2);
                        profile.profWeights[item1].Add(item2, Convert.ToDouble((string)dataGridView1.Rows[i].Cells[2].Value));
                    }
                    else
                    {
                        SerializableDictionary<string, double> ww = new SerializableDictionary<string, double>();
                        ww.Add(item2, Convert.ToDouble((string)dataGridView1.Rows[i].Cells[2].Value));
                        profile.profWeights.Add(item1, ww);
                    }
                }

            }

            this.Close();
        }
 /// <summary>
 /// Computes the effectiveness all measure of the given similarity matrix using the answer matrix provided.
 /// </summary>
 protected override void ComputeImplementation()
 {
     _oracle.Threshold = 0;
     Results           = new SerializableDictionary <string, double>();
     foreach (string query in _oracle.SourceArtifactsIds)
     {
         TLLinksList links = _matrix.GetLinksAboveThresholdForSourceArtifact(query);
         links.Sort();
         for (int i = 0; i < links.Count; i++)
         {
             if (_oracle.IsLinkAboveThreshold(query, links[i].TargetArtifactId))
             {
                 Results.Add(String.Format("{0}_{1}", query, links[i].TargetArtifactId), i);
             }
         }
     }
 }
예제 #18
0
        private static SerializableDictionary <string, AnalyzerCodeStats> GenerateRandomValues()
        {
            var codeStats            = new SerializableDictionary <string, AnalyzerCodeStats>();
            var maxRangeIndex        = ErrorCodes.Length - 1;
            var randomErrorCodeCount = RandomGenerator.Next(maxRangeIndex);

            for (var i = 0; i < randomErrorCodeCount; i++)
            {
                var errorCode = ErrorCodes[RandomGenerator.Next(maxRangeIndex)];
                if (!codeStats.ContainsKey(errorCode))
                {
                    codeStats.Add(errorCode, GenerateRandomStats());
                }
            }

            return(codeStats);
        }
예제 #19
0
        internal static void UpdateGateList()
        {
            if (!(Game1.currentLocation is Farm))
            {
                return;
            }

            GateList = new SerializableDictionary <Vector2, Fence>();

            OldTile     = new Point();
            OldAdjTiles = new Vector2[] { };

            Game1.currentLocation.Objects.AsParallel().OfType <Dictionary <Vector2, Fence> >().SelectMany(d => d)
            .Where(kv => (kv.Value is Fence gate) && gate.isGate.Value &&
                   (gate.name.Contains("Fence") || gate.name.Contains("Gate")))
            .ForAll(gate => GateList.Add(gate.Key, gate.Value));
        }
        private SerializableDictionary <string, TimeSeries> AverageCellTimeSeries(SerializableDictionary <string, MpiTimeSeries>[] allCellResults, int cellCount)
        {
            SerializableDictionary <string, MpiTimeSeries> averages = new SerializableDictionary <string, MpiTimeSeries>();

            foreach (SerializableDictionary <string, MpiTimeSeries> cellResult in allCellResults)
            {
                foreach (KeyValuePair <string, MpiTimeSeries> cellResultTimeSeries in cellResult)
                {
                    if (averages.ContainsKey(cellResultTimeSeries.Key))
                    {
                        // add the time series values
                        double[] dst = averages[cellResultTimeSeries.Key].TimeSeries;
                        double[] src = cellResultTimeSeries.Value.TimeSeries;

                        for (int i = 0; i < src.Length; i++)
                        {
                            dst[i] += src[i];
                        }
                    }
                    else
                    {
                        averages.Add(cellResultTimeSeries.Key, (MpiTimeSeries)cellResultTimeSeries.Value.Clone());
                    }
                }
            }

            // convert the sums to the mean
            foreach (MpiTimeSeries value in averages.Values)
            {
                for (int i = 0; i < value.TimeSeries.Length; i++)
                {
                    value[i] /= cellCount;
                }
            }

            // convert back to the Time.Data.TimeSeries objects for use by the statistics objects.
            SerializableDictionary <string, TimeSeries> result = new SerializableDictionary <string, TimeSeries>();

            foreach (KeyValuePair <string, MpiTimeSeries> keyValuePair in averages)
            {
                MpiTimeSeries value = keyValuePair.Value;
                result.Add(keyValuePair.Key, new TimeSeries(value.Start, value.TimeStep, value.TimeSeries));
            }

            return(result);
        }
예제 #21
0
        private void export_status_Click_1(object sender, EventArgs e)
        {
            SerializableDictionary <int, StructureOfProblem> problems    = ProblemList.GetAll();
            SerializableDictionary <int, StructureOfProblem> problemlist = new SerializableDictionary <int, StructureOfProblem>();
            XmlOperator xmlOperator = new XmlOperator();

            foreach (int key in problems.Keys)
            {
                StructureOfProblem p = new StructureOfProblem();
                p.AcceptsRate  = ProblemList.GetProblem(key).AcceptsRate;
                p.QuestionName = ProblemList.GetProblem(key).QuestionName;
                p.ProblemID    = ProblemList.GetProblem(key).ProblemID;
                problemlist.Add(p.ProblemID, p);
            }
            xmlOperator.XMLSerialized("Problem//ProblemStatus.xml", problemlist);
            //MessageBox.Show("导出成功");
        }
예제 #22
0
        private void OnClientConnected(object sender, EventArgs e)
        {
            int reqid      = 1;
            int responseid = 2;
            SerializableDictionary <int, string> aa = new SerializableDictionary <int, string>();

            aa.Add(1, "param_1");
            Random r = new Random();

            RequestType t = RequestType.Connect;

            RIPMessage alertData = PrepareEvent("moti", "oleg", reqid, responseid, t, aa);

            alertData.EventData = DateTime.Now.ToString();
            _proxy.Publish(alertData, "RegisterForAnyEvents");
            _eventCounter += 1;
        }
        public static SerializableDictionary <string, List <string> > GetProperties(DirectoryEntry de)
        {
            SerializableDictionary <string, List <string> > properties = null;

            if (de.Properties != null)
            {
                properties = new SerializableDictionary <string, List <string> >();
                IDictionaryEnumerator ide = de.Properties.GetEnumerator();
                while (ide.MoveNext())
                {
                    List <string> propValues = GetPropertyValues(ide.Key.ToString(), ide.Value);
                    properties.Add(ide.Key.ToString(), propValues);
                }
            }

            return(properties);
        }
예제 #24
0
        private void ConstructOperatorPhysicianOptionDictionary(
            string key,
            string physicianName,
            List <string> physicianOption,
            ref SerializableDictionary <string, PhysicianOption> dict)
        {
            ObservableCollection <string> names = new ObservableCollection <string>();

            names.Add(physicianName);
            int i = 0;

            if (physicianOption.Contains(physicianName))
            {
                foreach (string name in physicianOption)
                {
                    if (!name.Equals(physicianName) && !string.IsNullOrEmpty(name))
                    {
                        names.Add(name);
                        i++;
                        if (i == 4)
                        {
                            break;
                        }
                    }
                }
            }
            else
            {
                foreach (string name in physicianOption)
                {
                    if (!string.IsNullOrEmpty(name))
                    {
                        names.Add(name);
                        i++;
                        if (i == 4)
                        {
                            break;
                        }
                    }
                }
            }
            dict.Add(key, new PhysicianOption {
                Name = names
            });
            GlobalDefinition.LoggerWrapper.LogTraceInfo("Exit function ConstructPhysicianOptionDictionary");
        }
예제 #25
0
        /// <summary>
        /// Load the User Settings
        /// </summary>
        private void Load()
        {
            try
            {
                // Load up the users current settings file.
                if (File.Exists(_settingsFile))
                {
                    using (var reader = new StreamReader(_settingsFile))
                    {
                        var data = (SerializableDictionary <string, object>)_serializer.Deserialize(reader);
                        _userSettings = data;
                    }
                }
                else
                {
                    _userSettings = new SerializableDictionary <string, object>();
                }

                // Add any missing / new settings
                var defaults = GetDefaults();
                foreach (var item in defaults.Where(item => !_userSettings.Keys.Contains(item.Key)))
                {
                    _userSettings.Add(item.Key, item.Value);
                    Save();
                }
            }
            catch (Exception exc)
            {
                try
                {
                    _userSettings = GetDefaults();
                    if (File.Exists(_settingsFile))
                    {
                        File.Delete(_settingsFile);
                    }
                    Save();

                    throw new GeneralApplicationException("Warning, your settings have been reset!", "Your user settings file was corrupted or inaccessible. Settings have been reset to defaults.", exc);
                }
                catch (Exception)
                {
                    throw new GeneralApplicationException("Unable to load user settings.", "Your user settings file appears to be inaccessible or corrupted. You may have to delete the file and let HandBrake generate a new one.", exc);
                }
            }
        }
 private static void SaveNotifications(
   SerializableDictionary<string, GenericNotificationItem> lstItem)
 {
   using (XmlTextWriter xmlTextWriter = new XmlTextWriter(GenericNotificationManager.GenericNotificationFilePath, Encoding.UTF8)
   {
     Formatting = Formatting.Indented
   })
   {
     SerializableDictionary<string, GenericNotificationItem> serializableDictionary = new SerializableDictionary<string, GenericNotificationItem>();
     foreach (KeyValuePair<string, GenericNotificationItem> keyValuePair in (Dictionary<string, GenericNotificationItem>) lstItem)
     {
       if (!keyValuePair.Value.IsDeleted)
         serializableDictionary.Add(keyValuePair.Key, keyValuePair.Value);
     }
     new XmlSerializer(typeof (SerializableDictionary<string, GenericNotificationItem>)).Serialize((XmlWriter) xmlTextWriter, (object) serializableDictionary);
     xmlTextWriter.Flush();
   }
 }
예제 #27
0
        public void DictionaryofIPAddrSerialization()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary <IPAddr, IPAddr>));
            MemoryStream  ms         = new MemoryStream();
            IPAddr        outAddr    = IPAddr.Parse("192.168.1.1");
            SerializableDictionary <IPAddr, IPAddr> list = new SerializableDictionary <IPAddr, IPAddr>();

            list.Add(outAddr, outAddr);
            serializer.Serialize(ms, list);
            ms.Position = 0;
            SerializableDictionary <IPAddr, IPAddr> inAddr = (SerializableDictionary <IPAddr, IPAddr>)serializer.Deserialize(ms);

            foreach (KeyValuePair <IPAddr, IPAddr> pair in inAddr)
            {
                Assert.AreEqual("192.168.1.1", pair.Key.ToString());
                Assert.AreEqual("192.168.1.1", pair.Value.ToString());
            }
        }
        public static void CreateNewGeneticPool()
        {
            GenerationCount = 0;

            EnemyTypeChromosomes = new SerializableDictionary <EnemyTypes, List <SerializableChromosome> >();

            foreach (EnemyTypes enemyType in Enum.GetValues(typeof(EnemyTypes)))
            {
                var chromosomeList = new List <SerializableChromosome>();

                for (var i = 0; i < PopulationSize; i++)
                {
                    chromosomeList.Add(GenerateNewChromsome());
                }

                EnemyTypeChromosomes.Add(enemyType, chromosomeList);
            }
        }
예제 #29
0
 public static void Dispose(int k2_workflowId, Dictionary <string, string> dataFields)
 {
     try
     {
         SerializableDictionary <string, string> new_dataFields = new SerializableDictionary <string, string>();
         foreach (KeyValuePair <string, string> item in dataFields)
         {
             new_dataFields.Add(item.Key, item.Value);
         }
         WF_GetRelatedLinks.connectionType = connectionType;
         string            url     = WF_GetRelatedLinks.GetRelatedLinks(k2_workflowId.ToString());
         DynamicWebService service = new DynamicWebService(url);
         //InstanceService service = new InstanceService(url);
         service.DoServiceEvent(k2_workflowId, new_dataFields);
     }
     catch
     {
     }
 }
        // Token: 0x0600108A RID: 4234 RVA: 0x00154110 File Offset: 0x00152310
        public override void shiftObjects(int dx, int dy)
        {
            base.shiftObjects(dx, dy);
            foreach (Furniture expr_1D in this.furniture)
            {
                expr_1D.tileLocation.X = expr_1D.tileLocation.X + (float)dx;
                expr_1D.tileLocation.Y = expr_1D.tileLocation.Y + (float)dy;
                expr_1D.boundingBox.X  = expr_1D.boundingBox.X + dx * Game1.tileSize;
                expr_1D.boundingBox.Y  = expr_1D.boundingBox.Y + dy * Game1.tileSize;
                expr_1D.updateDrawPosition();
            }
            SerializableDictionary <Vector2, TerrainFeature> shifted = new SerializableDictionary <Vector2, TerrainFeature>();

            foreach (Vector2 v in this.terrainFeatures.Keys)
            {
                shifted.Add(new Vector2(v.X + (float)dx, v.Y + (float)dy), this.terrainFeatures[v]);
            }
            this.terrainFeatures = shifted;
        }
        private void btnDismissApp_Click(object sender, RoutedEventArgs e)
        {
            persistedQueries.Clear();
            int i = 0;

            foreach (var s in PeristedQList)
            {
                persistedQueries.Add(i++, s);
            }

            var serializer = new XmlSerializer(persistedQueries.GetType());

            var writer = new StreamWriter(_fileName);

            serializer.Serialize(writer, persistedQueries);
            writer.Close();

            Application.Current.Shutdown();
        }
예제 #32
0
        public override void shiftObjects(int dx, int dy)
        {
            base.shiftObjects(dx, dy);
            foreach (Furniture furniture in this.furniture)
            {
                furniture.tileLocation.X += (float)dx;
                furniture.tileLocation.Y += (float)dy;
                furniture.boundingBox.X  += dx * Game1.tileSize;
                furniture.boundingBox.Y  += dy * Game1.tileSize;
                furniture.updateDrawPosition();
            }
            SerializableDictionary <Vector2, TerrainFeature> serializableDictionary = new SerializableDictionary <Vector2, TerrainFeature>();

            foreach (Vector2 key in this.terrainFeatures.Keys)
            {
                serializableDictionary.Add(new Vector2(key.X + (float)dx, key.Y + (float)dy), this.terrainFeatures[key]);
            }
            this.terrainFeatures = serializableDictionary;
        }
예제 #33
0
        /// <summary>
        /// Determines if the print job is rendered on the client or on the server.
        /// </summary>
        /// <param name="queues">The list of queues.</param>
        /// <returns>
        ///   <c>true</c> if Render Print Jobs on Client is set for the specified queue name; otherwise, <c>false</c>.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">queues</exception>
        public SerializableDictionary <string, string> GetJobRenderLocation(Collection <string> queues)
        {
            if (queues == null)
            {
                throw new ArgumentNullException("queues");
            }

            SerializableDictionary <string, string> values = new SerializableDictionary <string, string>();

            foreach (string queueName in queues)
            {
                PrintQueue queue    = PrintQueueController.GetPrintQueue(queueName);
                var        location = PrintQueueController.GetJobRenderLocation(queue);
                values.Add(queueName, location.ToString());
                TraceFactory.Logger.Debug("Render On Client {0}:{1}".FormatWith(queueName, location));
            }

            return(values);
        }
예제 #34
0
 private void CreatedStairs(object sender, EventArgsLocationObjectsChanged e)
 {
     if (Game1.currentLocation is MineShaft)
     {
         Layer currentLayer = Game1.currentLocation.map.GetLayer("Buildings");
         for (int yTile = 0; yTile < currentLayer.LayerHeight; yTile++)
         {
             for (int xTile = 0; xTile < currentLayer.LayerWidth; xTile++)
             {
                 Tile currentTile = currentLayer.Tiles[xTile, yTile];
                 if (currentTile != null && currentTile.TileIndex == 173 && !ladderList.ContainsKey(new Vector2(xTile, yTile)))
                 {
                     ladderList.Add(new Vector2(xTile, yTile), currentTile);
                     Game1.currentLocation.map.GetLayer("Buildings").Tiles[xTile, yTile].TileIndexProperties.Add(new KeyValuePair <string, PropertyValue>("Passable", propValue));
                 }
             }
         }
     }
 }
예제 #35
0
 static void Main(string[] args)
 {
     //模拟从数据库加载索引到内存中,形成内存中的数据库
     //这里的 "Dictionary" 用来表达“一个用户注册过多少店铺“,即UserID与ShopID的一对多关系
     SerializableDictionary<int, List<int>> dic = new SerializableDictionary<int, List<int>>();
     List<int> shopIDList = new List<int>();
     for (int shopID = 300000; shopID < 300050; shopID++)
         shopIDList.Add(shopID);
     int UserID = 15;
     //假设这里已经维护好了UserID与ShopID的关系
     dic.Add(UserID, shopIDList);
     XmlSerializer xml = new XmlSerializer(dic.GetType());
     var memoryStream = new MemoryStream();
     xml.Serialize(memoryStream, dic);
     memoryStream.Seek(0, SeekOrigin.Begin);
     //将Dictionary持久化,相当于模拟保存在Mencache里面
     File.AppendAllText("F://1.txt", Encoding.UTF8.GetString(memoryStream.ToArray()));
     Console.WriteLine("数据加载成功!");
     Console.Read();
 }
예제 #36
0
        public void Save(string projectFile, Globals.ProjectType projectType)
        {
            SerializableDictionary <string, object> dictPacked = new SerializableDictionary <string, object>();

            dictPacked.Add("_projectType", projectType);

            if (ProjectSaved != null) //something has been added to the list?
            {
                PackEventArgs e = new PackEventArgs(dictPacked);
                ProjectSaved(this, e);
            }

            FileInfo _fi = new FileInfo(projectFile);

            _projectName = _fi.Name;

            XmlSerializer serializerDict = new XmlSerializer();

            serializerDict.Serialize(dictPacked, projectFile);
        }
예제 #37
0
 public void doneTossing(Farmer who)
 {
     who.forceTimePass = false;
     this.resetForPlayerEntry(who.currentLocation);
     who.CanMove = true;
     who.forceCanMove();
     who.faceDirection(0);
     this.drawOnTop = false;
     this.doEmote(20, true);
     if (!who.friendships.ContainsKey(this.name))
     {
         SerializableDictionary <string, int[]> friendships = who.friendships;
         string name     = this.name;
         int[]  numArray = new int[6];
         numArray[0] = 250;
         friendships.Add(name, numArray);
     }
     who.talkToFriend((NPC)this, 20);
     Game1.playSound("tinyWhip");
 }
예제 #38
0
        public void AddPlayer(Guid id, PlayerHandler player)
        {
            Players.Add(id, player);
            ChunkManager.Get.AddPlayer(player);
            var data = UsernameDatabase.Load(player.username, id);

            if (data != null)
            {
                player.inventory          = data.Inventory;
                player.transform.position = data.Pos + new Vector3(0, 0.5f, 0);
                player.transform.rotation = data.Rot;
            }
            else
            {
                player.transform.position = World.Get.GenerateSpawnPoint(id);
            }

            InventoryManager.Get.AddInventory(player);
            Debug.Log("Added Player at Position: " + player.transform.position);
        }
예제 #39
0
        private void Load(string name, double iexpires)
        {
            place   = name;
            expires = iexpires;
            var cookie = HttpContext.Current.Request.Cookies[name];

            if (cookie == null)
            {
                HttpCookie hcookie = new HttpCookie(place);
                hcookie.Expires = DateTime.Now.AddSeconds(iexpires);
                HttpContext.Current.Response.Cookies.Set(hcookie);
            }
            else
            {
                foreach (var key in cookie.Values.AllKeys)
                {
                    Store.Add(key, cookie[key]);
                }
            }
        }
예제 #40
0
        public bool Validate(CustomValidationService service)
        {
            ValidationErrors = new SerializableDictionary <string, string>();

            if (string.IsNullOrWhiteSpace(ExternalServiceId))
            {
                ValidationErrors.Add(LambdaHelper <Service> .GetPropertyName(x => x.ExternalServiceId), "Service.ExternalServiceId is a mandatory field.");
            }

            if (Priority == null || Priority < 1)
            {
                ValidationErrors.Add(LambdaHelper <Service> .GetPropertyName(x => x.Priority), "Service.Priority is a mandatory field.");
            }

            if (ProvisionSequence == null || ProvisionSequence < 1)
            {
                ValidationErrors.Add(LambdaHelper <Service> .GetPropertyName(x => x.ProvisionSequence), "Service.ProvisionSequence is a mandatory field and must be greater then 0.");
            }

            if (ProvisionDate == null || ProvisionDate == DateTime.MinValue)
            {
                ValidationErrors.Add(LambdaHelper <Service> .GetPropertyName(x => x.ProvisionDate), "Service.ProvisionDate is a mandatory field.");
            }

            //Note: Validation the child class as well.

            if (Locations == null)
            {
                ValidationErrors.Add(LambdaHelper <Service> .GetPropertyName(x => x.Locations), "Service.Locations is a mandatory field.");
            }
            else
            {
                foreach (var location in Locations)
                {
                    if (location.Validate(service))
                    {
                        foreach (var validationError in location.ValidationErrors)
                        {
                            if (!ValidationErrors.ContainsKey(validationError.Key))
                            {
                                ValidationErrors.Add(validationError.Key, validationError.Value);
                            }
                        }
                    }
                }
            }

            return(ValidationErrors.Count > 0);
        }
예제 #41
0
 public void doneTossing(Farmer who)
 {
     who.forceTimePass = false;
     this.resetForPlayerEntry(who.currentLocation);
     who.CanMove = true;
     who.forceCanMove();
     who.faceDirection(0);
     this.drawOnTop = false;
     base.doEmote(20, true);
     if (!who.friendships.ContainsKey(this.name))
     {
         SerializableDictionary <string, int[]> arg_64_0 = who.friendships;
         string arg_64_1 = this.name;
         int[]  expr_5C  = new int[6];
         expr_5C[0] = 250;
         arg_64_0.Add(arg_64_1, expr_5C);
     }
     who.talkToFriend(this, 20);
     Game1.playSound("tinyWhip");
 }
예제 #42
0
        /// <summary>
        /// Computes the recall of each source artifact in the similarity matrix using the answer matrix provided.
        /// </summary>
        protected override void ComputeImplementation()
        {
            SerializableDictionary <string, double> sourceRecall = new SerializableDictionary <string, double>();

            _oracle.Threshold = 0;
            foreach (string sourceArtifact in _oracle.SourceArtifactsIds)
            {
                TLLinksList links   = _matrix.GetLinksAboveThresholdForSourceArtifact(sourceArtifact);
                int         correct = 0;
                foreach (TLSingleLink link in links)
                {
                    if (_oracle.IsLinkAboveThreshold(link.SourceArtifactId, link.TargetArtifactId))
                    {
                        correct++;
                    }
                }
                sourceRecall.Add(sourceArtifact, correct / (double)_oracle.GetCountOfLinksAboveThresholdForSourceArtifact(sourceArtifact));
            }
            Results = sourceRecall;
        }
예제 #43
0
        /// <summary>
        /// Called from MetricComputation
        /// </summary>
        protected override void ComputeImplementation()
        {
            Results = new SerializableDictionary <string, double>();
            double      sumOfPrecisions = 0.0;
            int         currentLink     = 0;
            int         correctSoFar    = 0;
            TLLinksList links           = _matrix.AllLinks;

            links.Sort();
            foreach (TLSingleLink link in links)
            {
                currentLink++;
                if (_oracle.IsLinkAboveThreshold(link.SourceArtifactId, link.TargetArtifactId))
                {
                    correctSoFar++;
                    sumOfPrecisions += correctSoFar / (double)currentLink;
                }
            }
            Results.Add("AveragePrecision", sumOfPrecisions / _oracle.AllLinks.Count);
        }
예제 #44
0
        public void f1()
        {
            try
            {
                //SettingsConfigDict s = new SettingsConfigDict(InitSettingDictObjecForDebugModeSettingFileCreationDelegate);

                Settings _tSettings = null;

                _tSettings = new Settings();

                _tSettings.BackupDestinationRootPath = @"C:\Development";

                _tSettings.BackupTime = new DateTime(1, 1, 1, 5, 0, 0);

                _tSettings.BackupDays = (int)(enumWeekdays.Monday | enumWeekdays.Tuesday | enumWeekdays.Wednesday | enumWeekdays.Thursday | enumWeekdays.Friday);

                m_Settings.Add(_tSettings.GetUnitKey(), _tSettings);

                m_Settings.SaveData();

                // if(_tSettings.BackupDays & (int)enumWeekdays.Friday == (int)enumWeekdays.Friday)
                // if( _tSettings.BackupDays & (int)enumWeekdays.Friday > 0)

                FolderInfo fi = null;

                foreach (string path in Directory.GetDirectories(@"C:\Development"))
                {
                    fi = new FolderInfo();
                    fi.FolderSourcePath          = path;
                    fi.NumberOfFilesInSource     = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Count();
                    fi.NumberOfSubFolderInSource = Directory.GetDirectories(path, "*", SearchOption.AllDirectories).Count();
                    m_FI.Add(fi.GetUnitKey(), fi);
                }

                m_FI.SaveData();
            }
            catch (Exception exp)
            {
                Logger.WriteError(exp, "cb720904-ae44-4536-9c72-e1d0828ef0bd");
            }
        }
예제 #45
0
        public SerializableDictionary <string, string> Validate(tUserData userData)
        {
            var validationErrors = new SerializableDictionary <string, string>();

            if (userData == null)
            {
                validationErrors.Add(LambdaHelper <tUserData> .GetPropertyName(x => x), "UserData is a mandatory field.");
            }
            else
            {
                if (userData.ShData == null)
                {
                    validationErrors.Add(LambdaHelper <tShData> .GetPropertyName(x => x), "ShData is a mandatory field.");
                }
                else
                {
                    if (userData.ShData.RepositoryData == null)
                    {
                        validationErrors.Add(LambdaHelper <tTransparentData> .GetPropertyName(x => x), "RepositoryData is a mandatory field.");
                    }
                    else
                    {
                        if (string.IsNullOrWhiteSpace(userData.ShData.RepositoryData.ServiceIndication))
                        {
                            validationErrors.Add("ServiceIndication", "ServiceIndication is a mandatory field.");
                        }

                        if (userData.ShData.RepositoryData.ServiceData == null)
                        {
                            ItemChoiceType gggg = userData.ShData.RepositoryData.ServiceData.Item.ItemElementName;
                            validationErrors.Add(LambdaHelper <tServiceData> .GetPropertyName(x => x), "ServiceData is a mandatory field.");
                        }
                        else
                        {
                            if (userData.ShData.RepositoryData.ServiceData.Item == null)
                            {
                                validationErrors.Add(LambdaHelper <tMetaSwitchData> .GetPropertyName(x => x), "MetaSwitchData is a mandatory field.");
                            }
                            else
                            {
                            }
                        }
                    }
                }
            }

            return(validationErrors);
        }
예제 #46
0
        public void TestProfilesProvider()
        {
            var provider = new ProfilesProvider();

            var profile = new SerializableDictionary <string, ProfileSettings>();

            profile.Add("ABC", new ProfileSettings()
            {
                Name        = "myName",
                TeamProject = "myProject"
            });
            provider.Set("dummyUrl", profile);

            provider.SaveAsJson(_file);

            var loadedProfiler = new ProfilesProvider();

            loadedProfiler.LoadAsJson(_file);

            CollectionAssert.AreEqual(provider.GetAllProfiles().ToList(), loadedProfiler.GetAllProfiles().ToList());
        }
    public void UpdateLayerMask()
    {
        _walkableTerrainTypesDictionary = new SerializableDictionary <int, int>();
        _networkLayerMask = 0;
        foreach (var terrainType in WalkableTerrainTypes)
        {
            if ((terrainType.TerrainMask == (1 << NodeNetwork.UnwalkableLayer | terrainType.TerrainMask) ||
                 (terrainType.TerrainMask == (1 << NodeNetwork.CustomLayer | terrainType.TerrainMask))) && terrainType.TerrainMask > 0)
            {
                Debug.LogError("Cannot add unwalkable or custom layer to walkable terrain.");
                terrainType.TerrainMask = 0;
            }
            else if (!_walkableTerrainTypesDictionary.Has(terrainType.TerrainMask.value))
            {
                _walkableTerrainTypesDictionary.Add(terrainType.TerrainMask.value, terrainType.TerrainPenalty);
                _networkLayerMask |= (1 << terrainType.TerrainMask);
            }
        }

        _networkLayerMask |= 1 << NodeNetwork.UnwalkableLayer;
    }
예제 #48
0
        public void UnitTestSerialize()
        {
            SerializableDictionary<string, string> dictionary = new SerializableDictionary<string, string>();
            dictionary.Add("myKey", "myValue");
            XmlSerializer xmlSerializer = new XmlSerializer(dictionary.GetType());
            string xml;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8))
                {
                    using (StreamReader streamReader = new StreamReader(memoryStream, Encoding.UTF8))
                    {
                        xmlSerializer.Serialize(xmlTextWriter, dictionary);
                        memoryStream.Position = 0;
                        xml = streamReader.ReadToEnd();
                        streamReader.Close();
                    }
                }
            }

            Assert.AreEqual("<?xml version=\"1.0\" encoding=\"utf-8\"?><Dictionary><item><key><string>myKey</string></key><value><string>myValue</string></value></item></Dictionary>", xml, "The XML representing the serialized dictionary was not as expected.");
        }
예제 #49
0
        private VideoInfo GetProduct(JToken product)
        {
            SerializableDictionary<string, string> other = new SerializableDictionary<string, string>();
            JToken content = product["content"];
            JToken user = product["user"];
            JToken epg = product["epg"];
            string airTime = string.Empty;
            if (epg != null)
            {
                airTime = ((DateTime)epg["start"]).ToLocalTime().ToString("g", OnlineVideoSettings.Instance.Locale);
            }
            string format = "{0}|{1}|{2}|{3}|{4}|{5}";
            other.Add("starred", (user != null && user["starred"] != null && (bool)user["starred"]).ToString());
            if (product["type"] != null && product["type"].Value<string>() == "movie")
            {
                string tracktitle = string.Empty;
                string imdb = string.Empty;
                string year = string.Empty;
                if (content["title"] != null)
                    tracktitle = content["title"].Value<string>();
                if (content["imdb"] != null && content["imdb"]["id"] != null)
                    imdb = content["imdb"]["id"].Value<string>();
                if (content["production"] != null && content["production"]["year"] != null)
                    year = content["production"]["year"].ToString();

                other.Add("tracking", string.Format(format,"Movie", tracktitle,year,imdb,string.Empty,string.Empty));

            }
            else if (product["type"] != null && product["type"].Value<string>() == "episode")
            {
                string tracktitle = string.Empty;
                string season = string.Empty;
                string episode = string.Empty;
                string year = string.Empty;
                if (content["series"] != null)
                {
                    if (content["series"]["title"] != null)
                        tracktitle = content["series"]["title"].Value<string>();
                    if (content["series"]["episodeNumber"] != null)
                        episode = content["series"]["episodeNumber"].ToString();
                    if (content["series"]["season"] != null && content["series"]["season"]["seasonNumber"] != null)
                        season = content["series"]["season"]["seasonNumber"].ToString();
                }
                if (content["production"] != null && content["production"]["year"] != null)
                    year = content["production"]["year"].ToString();
                other.Add("tracking", string.Format(format, "TvSeries", tracktitle, year, string.Empty, season, episode));
            }
            if (product["_links"]["viaplay:star"] != null)
                other.Add("starUrl", ((string)product["_links"]["viaplay:star"]["href"]).Replace("{starred}", string.Empty));
            if (product["_links"]["viaplay:deleteProgress"] != null)
                other.Add("watchedUrl", ((string)product["_links"]["viaplay:deleteProgress"]["href"]));
            if (product["_links"]["viaplay:peopleSearch"] != null)
                other.Add("peopleSearchUrl", ((string)product["_links"]["viaplay:peopleSearch"]["href"]));
            var people = content["people"];
            if (people != null)
            {
                if (people["directors"] != null)
                    other.Add("directors", (string)(people["directors"].Aggregate((current, next) => (string)current + ";" + (string)next)));
                if (people["actors"] != null)
                    other.Add("actors", (string)(people["actors"].Aggregate((current, next) => (string)current + ";" + (string)next)));
            }


            string lenght = string.Empty;
            if (content["duration"] != null && content["duration"]["readable"] != null)
                lenght = (string)content["duration"]["readable"];

            bool isEpisode = (string)product["type"] == "episode";
            string title;
            if (isEpisode)
            {
                int s = content["series"]["season"] != null ? (int)content["series"]["season"]["seasonNumber"]:0;
                int e = content["series"]["episodeNumber"] != null?(int)content["series"]["episodeNumber"]:0;
                string stitle = content["series"]["title"] != null ? (string)content["series"]["title"] : string.Empty;
                string ctitle = (string)content["title"];
                string etitle = content["series"]["episodeTitle"] != null ? (string)content["series"]["episodeTitle"]:string.Empty;
                title = !string.IsNullOrEmpty(stitle)? stitle + " - " : string.Empty;
                title += s > 9 ? "S" + s.ToString()  : "S0" + s.ToString();
                title += e > 9 ? "E" + e.ToString() : "E0" + e.ToString();
                if (stitle == ctitle)
                    title += " " + etitle;
                else
                    title += " " + ctitle;
            }
            else
            {
                title = (string)content["title"];
            }

            return new VideoInfo()
            {
                Title = title,
                Thumb = (string)product["type"] == "movie" ? (string)content["images"]["boxart"]["url"] : (string)content["images"]["landscape"]["url"],
                Description = (string)content["synopsis"],
                VideoUrl = (string)product["_links"]["viaplay:page"]["href"],
                Airdate = airTime,
                Length = lenght,
                Other = other
            };
        }
 /// <summary>
 /// Computes the precision of the given similarity matrix using the answer matrix provided.
 /// </summary>
 protected override void ComputeImplementation()
 {
     _oracle.Threshold = 0;
     int correct = 0;
     foreach (TLSingleLink link in _matrix.AllLinks)
     {
         if (_oracle.IsLinkAboveThreshold(link.SourceArtifactId, link.TargetArtifactId))
         {
             correct++;
         }
     }
     Results = new SerializableDictionary<string, double>();
     Results.Add("Precision", correct / (double)_matrix.Count);
 }
        public SerializableDictionary<string, UserAuthenticationTyp> GetUserList()
        {
            SerializableDictionary<string, UserAuthenticationTyp> users = new SerializableDictionary<string, UserAuthenticationTyp>();

            using (NpgsqlConnection con = GetPgConnection())
            {
                using (NpgsqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = "SELECT * FROM \"GetUserList\"()";

                    NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);

                    while (reader.Read())
                    {
                        string username = reader["username"].ToString();
                        UserAuthenticationTyp authTyp = (UserAuthenticationTyp)Enum.Parse(typeof(UserAuthenticationTyp), reader["typ"].ToString());

                        if (authTyp == UserAuthenticationTyp.FormsAuthentication) //only allow forms authentication
                            users.Add(username, authTyp);
                    }

                    reader.Close();
                }
            }

            return users;
        }
        public SerializableDictionary<int, string> GetLearningModulesList()
        {
            if ((int)Session["uid"] < 0)
                throw new NoValidUserException();

            SerializableDictionary<int, string> LMs = new SerializableDictionary<int, string>();

            using (NpgsqlConnection con = GetPgConnection())
            {
                using (NpgsqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = "SELECT id, title FROM \"LearningModules\"";
                    NpgsqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess);

                    while (reader.Read())
                        LMs.Add(Convert.ToInt32(reader["id"]), reader["title"].ToString());
                }
            }

            return LMs;
        }
예제 #53
0
        public void UpdateFileMetada(string name, string address)
        {
            if (this.PendingFiles.Count > 0)
            {
                SerializableDictionary<string, int> updated = new SerializableDictionary<string, int>();
                string command = string.Format("UPDATE {0} {1}", name, address);

                foreach (string f in this.PendingFiles.Keys)
                {
                    Metadata meta = this.Files[f];
                    meta.AddDataServers(address);
                    this.ServersLoad[name]++;

                    command += string.Format(" {0}", f);

                    if (this.OpenFiles.ContainsKey(f))
                    {
                        List<string> clients = this.OpenFiles[f];

                        foreach (string c in clients)
                        {
                            IClient client = (IClient)Activator.GetObject(typeof(IClient), this.Clients[c]);

                            if (client != null)
                            {
                                client.UpdateFileMetadata(f, meta);
                            }
                        }
                    }

                    string input = GetToken().ToString() + (char)0x7f + meta.Filename;

                    int n = this.PendingFiles[f] - 1;

                    if (n > 0)
                    {
                        updated.Add(f, n);
                    }

                }

                this.PendingFiles = new SerializableDictionary<string, int>(updated);

                this.Log.Append(command);
                ThreadPool.QueueUserWorkItem(AppendToLog, command);
            }
        }
예제 #54
0
        private List<VideoInfo> VideosForCategory(HtmlAgilityPack.HtmlNode node)
        {
            List<VideoInfo> videoList = new List<VideoInfo>();

            var sections = node.Descendants("section").Where(s => s.GetAttributeValue("class", "") == "tv");
            if (sections != null)
            {
                foreach (var section in sections)
                {
                    var a = section.SelectSingleNode("a");
                    if (a != null)
                    {
                        VideoInfo video = new VideoInfo();
                        video.VideoUrl = baseUrl + a.GetAttributeValue("href", "");
                        var img = a.Descendants("img");
                        if (img != null && img.First() != null)
                        {
                            video.Thumb = img.First().GetAttributeValue("src", "");
                            video.Title = img.First().GetAttributeValue("alt", "");
                        }
                        var dd = a.Descendants("dd");
                        if (dd != null && dd.FirstOrDefault() != null)
                            video.Length = dd.FirstOrDefault().InnerText;
                        var h1 = a.Descendants("h1");
                        var descP = section.Descendants("p").Where(p => p.GetAttributeValue("class", "") == "ellipsis-lastline");
                        if (descP != null && descP.FirstOrDefault() != null)
                            video.Description = descP.FirstOrDefault().InnerText;
                        if (EnableAOSearch)
                        {
                            SerializableDictionary<string, string> other = new SerializableDictionary<string, string>();
                            var ul = section.SelectSingleNode("div[@class = 'details']/ul[@class = 'keywords']");
                            if (ul != null)
                            {
                                IEnumerable<HtmlNode> keyAs = ul.Descendants("a");
                                foreach (HtmlNode keyA in keyAs)
                                {
                                    other.Add(keyA.GetAttributeValue("data-keyword", ""), keyA.GetAttributeValue("href", ""));
                                }
                            }
                            video.Other = other;
                        }
                        videoList.Add(video);
                    }
                }
            }
            return videoList;
        }
예제 #55
0
 private SerializableDictionary<Guid, GuideUpcomingProgram> BuildUpcomingProgramsDictionary(ScheduleType scheduleType)
 {
     SerializableDictionary<Guid, GuideUpcomingProgram> result = new SerializableDictionary<Guid, GuideUpcomingProgram>();
     foreach (GuideUpcomingProgram upcomingProgram in _model.UpcomingProgramsByType[scheduleType])
     {
         if (!result.ContainsKey(upcomingProgram.UpcomingProgramId))
         {
             result.Add(upcomingProgram.UpcomingProgramId, upcomingProgram);
         }
     }
     return result;
 }
 /// <summary>
 /// Computes the precision-recall curve of the given similarity matrix using the answer matrix provided.
 /// </summary>
 protected override void ComputeImplementation()
 {
     _oracle.Threshold = 0;
     int correct = 0;
     TLLinksList links = _matrix.AllLinks;
     links.Sort();
     Results = new SerializableDictionary<string, double>();
     for (int linkNumber = 1; linkNumber <= links.Count; linkNumber++)
     {
         if (_oracle.IsLinkAboveThreshold(links[linkNumber - 1].SourceArtifactId, links[linkNumber - 1].TargetArtifactId))
         {
             correct++;
         }
         Results.Add(String.Format(_precisionFormat, linkNumber), correct / (double)linkNumber);
         Results.Add(String.Format(_recallFormat, linkNumber), correct / (double)_oracle.Count);
     }
 }
 void GetLatestVideos(ref List<VideoInfo> result, HtmlNode li_container)
 {
     foreach (var li in li_container.Elements("li"))
     {
         if (li.GetAttributeValue("class", "").Contains("more_reiter"))
         {
             HasNextPage = true;
             nextPageUrl = "http://www.heise.de/video/" + li.Element("a").GetAttributeValue("href", "") + "&hajax=1";
         }
         else
         {
             SerializableDictionary<string, string> tags = null;
             if (li.Element("ul") != null)
             {
                 tags = new SerializableDictionary<string, string>();
                 foreach (var tag_li in li.Element("ul").Elements("li"))
                 {
                     tags.Add(tag_li.Element("a").InnerText, "http://www.heise.de" + tag_li.Element("a").GetAttributeValue("href", ""));
                 }
             }
             var a = li.Descendants("h3").First().Element("a");
             result.Add(new VideoInfo()
             {
                 Title = a.InnerText,
                 VideoUrl = "http://www.heise.de" + a.GetAttributeValue("href", ""),
                 Thumb = "http://www.heise.de" + li.Descendants("img").First().GetAttributeValue("src", ""),
                 Description = li.Descendants("p").First().FirstChild.InnerText.Trim(),
                 Other = tags
             });
         }
     }
 }
예제 #58
0
파일: Util.cs 프로젝트: nunofmaia/padi-fs
        public static SerializableDictionary<string, int> SortServerLoad(SerializableDictionary<string, int> dic)
        {
            SerializableDictionary<string, int> res = new SerializableDictionary<string, int>();

            foreach (var item in dic.OrderBy(i => i.Value))
            {
                res.Add(item.Key, item.Value);
            }

            return res;
        }
 /// <summary>
 /// Called from MetricComputation
 /// </summary>
 protected override void ComputeImplementation()
 {
     Results = new SerializableDictionary<string, double>();
     IMetricComputation avgP = new AveragePrecisionQueryComputation(_matrix, _oracle);
     avgP.Compute();
     Results.Add("MeanAveragePrecision", avgP.Results.Values.Average());
 }
예제 #60
0
 public void SaveItemCost(TextWriter writer)
 {
     SerializableDictionary<int, float> data = new SerializableDictionary<int, float>();
     foreach (Item item in AllItems)
     {
         if (item.Cost > 0.0f)
         {
             data.Add(item.Id, item.Cost);
         }
     }
     XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary<int, float>));
     serializer.Serialize(writer, data);
     writer.Close();
 }