public void RestoreListViewSelected() { try { if (listBox != null && oldItem != null && oldItems != null) { if (this.allSelected == true) { listBox.SelectAll(); return; } //このUnselectAll()は無いと正しく復元出来ない状況があり得る listBox.UnselectAll(); //上限越えの場合は、選択を解除して終了。 if (oldItems.Count >= this.MaxRestoreNum) return; //選択数が少ないときは逆に遅くなる気もするが、Dictionaryにしておく var listKeys = new Dictionary<ulong, object>(); if (getKey == null) { getKey = CtrlCmdDefEx.GetKeyFunc(oldItem.GetType()); } foreach (object listItem1 in listBox.Items) { //重複するキーは基本的に無いという前提 try { listKeys.Add(getKey(listItem1), listItem1); } catch { } } object setItem; if (listKeys.TryGetValue(getKey(oldItem), out setItem)) { listBox.SelectedItem = setItem; } foreach (object oldItem1 in oldItems) { if (listKeys.TryGetValue(getKey(oldItem1), out setItem)) { //数が多いとき、このAddが致命的に遅い listBox.SelectedItems.Add(setItem); } } //画面更新が入るので最後に実行する。SelectedItem==nullのときScrollIntoViewは何もしない。 listBox.ScrollIntoView(listBox.SelectedItem); } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); } }
public BatArg(Dictionary<string, string> keys) { Model = (BatModel)(int.Parse(keys["Model"])); Hierarchy = (DestHierarchy)(int.Parse(keys["DestHierarchy"])); PC = keys.ContainsKey("PC"); IOS = keys.ContainsKey("IOS"); AND = keys.ContainsKey("AND"); if (keys.TryGetValue("SrcFolder", out SrcFolder)) { SrcFolder = Application.dataPath + SrcFolder; SrcFolder.Replace("\\", "/"); } if (keys.TryGetValue("SrcFolderName", out SrcFolderName)) SrcFolderName.Replace("\\", "/"); SearchLoop = keys.ContainsKey("SearchLoop"); if (keys.TryGetValue("SearchPrefix", out SearchPrefix)) SearchPrefix.Replace("\\", "/"); if (keys.TryGetValue("DestFolder", out DestFolderPath)) { DestFolderPath = Application.dataPath + "/../.." + DestFolderPath; DestFolderPath.Replace("\\", "/"); } if (keys.TryGetValue("DestFolderName", out DestFolderName)) DestFolderName.Replace("\\", "/"); // Debug.Log(JsonWriter.Serialize(this)); }
/// <summary> /// Emails the given password to the given emailaddress. No username is specified. /// </summary> /// <param name="password">The password to email</param> /// <param name="emailAddress">The recipient's emailaddress.</param> /// <param name="emailTemplate">The email template.</param> /// <param name="emailData">The email data.</param> /// <returns>true if succeeded, false otherwise</returns> public static bool EmailPassword(string password, string emailAddress, string emailTemplate, Dictionary<string, string> emailData) { StringBuilder mailBody = new StringBuilder(emailTemplate); string applicationURL = string.Empty; emailData.TryGetValue("applicationURL", out applicationURL); if (!string.IsNullOrEmpty(emailTemplate)) { // Use the existing template to format the body string siteName = string.Empty; emailData.TryGetValue("siteName", out siteName); mailBody.Replace("[URL]", applicationURL); mailBody.Replace("[SiteName]", siteName); mailBody.Replace("[Password]", password); } // format the subject string subject = string.Empty; emailData.TryGetValue("emailPasswordSubject", out subject); subject += applicationURL; string fromAddress = string.Empty; emailData.TryGetValue("defaultFromEmailAddress", out fromAddress); // send it // host and smtp credentials are set in .config file SmtpClient client = new SmtpClient(); client.Send(fromAddress, emailAddress, subject, mailBody.ToString()); return true; }
/// <summary>Returns at most the 4 closest addresses in order.</summary> protected List<Connection> GetClosest(List<Connection> cons) { List<Connection> closest = new List<Connection>(cons); // Since MeasuredLatency could change the duration of our sorting we make // a copy as necessary Dictionary<Connection, double> latencies = new Dictionary<Connection, double>(); Comparison<Connection> comparer = delegate(Connection x, Connection y) { double lat_x, lat_y; if(!latencies.TryGetValue(x, out lat_x)) { lat_x = _ncservice.GetMeasuredLatency(x.Address); latencies[x] = lat_x; } if(!latencies.TryGetValue(y, out lat_y)) { lat_y = _ncservice.GetMeasuredLatency(y.Address); latencies[y] = lat_y; } // Remember that smaller is better but -1 is bad... // If either is smaller than 0 invert the comparison.. if(lat_x < 0 || lat_y < 0) { return lat_y.CompareTo(lat_x); } else { return lat_x.CompareTo(lat_y); } }; closest.Sort(comparer); if(closest.Count > 4) { closest.RemoveRange(4, closest.Count - 4); } return closest; }
public Popup(Dictionary<string, object> options) { object name; if (options.TryGetValue("name", out name)) { _name = (string)name; } object depth; if (options.TryGetValue("depth", out depth)) { _depth = (int)depth; } }
private static void ReadClassDataContractMembers(DataContractJsonSerializer serializer, ClassDataContract dataContract, Dictionary<string, object> deserialzedValue, object newInstance, XmlObjectSerializerReadContextComplexJson context) { if (dataContract.BaseContract != null) { ReadClassDataContractMembers(serializer, dataContract.BaseContract, deserialzedValue, newInstance, context); } for (int i = 0; i < dataContract.Members.Count; i++) { DataMember member = dataContract.Members[i]; object currentMemberValue; if (deserialzedValue.TryGetValue(XmlConvert.DecodeName(dataContract.Members[i].Name), out currentMemberValue) || dataContract.IsKeyValuePairAdapter && deserialzedValue.TryGetValue(XmlConvert.DecodeName(dataContract.Members[i].Name.ToLowerInvariant()), out currentMemberValue)) { if (member.MemberType.GetTypeInfo().IsPrimitive || currentMemberValue == null) { SetMemberValue(newInstance, serializer.ConvertObjectToDataContract(member.MemberTypeContract, currentMemberValue, context), dataContract.Members[i].MemberInfo, dataContract.UnderlyingType); } else { context.PushKnownTypes(dataContract); object subMemberValue = serializer.ConvertObjectToDataContract(member.MemberTypeContract, currentMemberValue, context); Type declaredType = (member.MemberType.GetTypeInfo().IsGenericType && member.MemberType.GetGenericTypeDefinition() == Globals.TypeOfNullable) ? Nullable.GetUnderlyingType(member.MemberType) : member.MemberType; if (!(declaredType == Globals.TypeOfObject && subMemberValue.GetType() == Globals.TypeOfObjectArray) && declaredType != subMemberValue.GetType()) { DataContract memberValueContract = DataContract.GetDataContract(subMemberValue.GetType()); context.CheckIfTypeNeedsVerifcation(member.MemberTypeContract, memberValueContract); } if (member.IsGetOnlyCollection) { PopulateReadOnlyCollection(newInstance, member, (IEnumerable)subMemberValue); } else { SetMemberValue(newInstance, subMemberValue, dataContract.Members[i].MemberInfo, dataContract.UnderlyingType); } context.PopKnownTypes(dataContract); } } else if (member.IsRequired) { XmlObjectSerializerWriteContext.ThrowRequiredMemberMustBeEmitted(dataContract.MemberNames[i].Value, dataContract.UnderlyingType); } } }
public static TypeSummary[] BuildSummary(MigrationReport report) { IDictionary<string, TypeSummary> types = new Dictionary<string, TypeSummary>(); foreach (MigrationReportMessage message in report.Messages) { TypeSummary type; string sourceType = message.SourceType ?? string.Empty; if (!types.TryGetValue(sourceType, out type)) { type = new TypeSummary(sourceType); types.Add(sourceType, type); } type.AddMessage(message); } int typeCount = types.Count; string[] keys = new string[typeCount]; TypeSummary[] values = new TypeSummary[typeCount]; types.Keys.CopyTo(keys, 0); types.Values.CopyTo(values, 0); Array.Sort(keys, values); return values; }
private void InstantiatePrefabs(Vector3[,] worldPositions, string[,] map, Dictionary<string, GameObject> objectDictionary) { int width = map.GetLength(0); int height = map.GetLength(1); GameObject container = new GameObject("Generated Map Container"); container.transform.parent = this.transform; Dictionary<string, GameObject> containerDictionary = new Dictionary<string, GameObject>(objectDictionary.Keys.Count); foreach (string typeName in objectDictionary.Keys) { GameObject typeContainer = new GameObject(typeName); typeContainer.transform.parent = container.transform; containerDictionary.Add(typeName, typeContainer); } container.transform.parent = this.transform; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { string mapValue = map[i, j]; GameObject prefab; if (mapValue != null && objectDictionary.TryGetValue(mapValue, out prefab)) { GameObject instance = (GameObject)Instantiate(prefab); instance.transform.position = worldPositions[i, j]; instance.transform.parent = containerDictionary[mapValue].transform; if (instance.CompareTag("Player")) { player = instance; } } } } }
// TODO: Insert code to perform custom authentication using the provided username and password // (See http://go.microsoft.com/fwlink/?LinkId=35339). // The custom principal can then be attached to the current thread's principal as follows: // My.User.CurrentPrincipal = CustomPrincipal // where CustomPrincipal is the IPrincipal implementation used to perform authentication. // Subsequently, My.User will return identity information encapsulated in the CustomPrincipal object // such as the username, display name, etc. private void loginButton_Click(System.Object sender, System.EventArgs e) { FixtureBuilder fb = new FixtureBuilder(); Dictionary<string, int> userDictionary = new Dictionary<string, int>(); userDictionary = fb.getUsersAndIds(); string username = usernameTextBox.Text.ToLower(); userId = -1; if (string.IsNullOrEmpty(username)) { Interaction.MsgBox("Please enter your username"); } else { if (userDictionary.ContainsKey(username)) { userDictionary.TryGetValue(username, out userId); My.MyProject.Forms.FixturesForm.currentUser = userId; My.MyProject.Forms.MenuForm.Show(); this.Close(); } else { Interaction.MsgBox("Username not recognised"); usernameTextBox.Clear(); } } }
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; }
public static TermVector GetCentroid(IEnumerable<TermVector> vectors) { Dictionary<string, long> sum = new Dictionary<string, long>(); int vectorCount = 0; // Sum the lengths of dimensions foreach (TermVector vector in vectors) { vectorCount++; foreach (string term in vector.Terms) { long count = 0; sum.TryGetValue(term, out count); sum.Remove(term); sum.Add(term, count + vector.GetDimensionLength(term)); } } // Divide the dimensions Dictionary<string, int> centroid = new Dictionary<string, int>(); foreach (KeyValuePair<string, long> dimension in sum) { centroid.Add(dimension.Key, (int)(dimension.Value / vectorCount)); } return new TermVector(centroid); }
/// <summary> /// Function to add a new material reference and returning its index in the material reference array. /// </summary> /// <param name="material"></param> /// <param name="fontAsset"></param> /// <param name="materialReferences"></param> /// <param name="materialReferenceIndexLookup"></param> /// <returns></returns> public static int AddMaterialReference(Material material, TMP_FontAsset fontAsset, MaterialReference[] materialReferences, Dictionary<int, int> materialReferenceIndexLookup) { int materialID = material.GetInstanceID(); int index = 0; if (materialReferenceIndexLookup.TryGetValue(materialID, out index)) { return index; } else { index = materialReferenceIndexLookup.Count; // Add new reference index materialReferenceIndexLookup[materialID] = index; materialReferences[index].index = index; materialReferences[index].fontAsset = fontAsset; materialReferences[index].spriteAsset = null; materialReferences[index].material = material; materialReferences[index].isDefaultMaterial = materialID == fontAsset.material.GetInstanceID() ? true : false; //materialReferences[index].padding = 0; materialReferences[index].referenceCount = 0; return index; } }
public static IEnumerable<RegionalNode> PrepareRegional(IEnumerable<ScheduleInfo> model,out Dictionary<DayOfWeek,String> days) { var result = new Dictionary<String, RegionalNode>(); days = new Dictionary<DayOfWeek, string>(7); var mappings = new Dictionary<DayOfWeek, String> { {DayOfWeek.Monday, GSchedule.Mo}, {DayOfWeek.Tuesday, GSchedule.Tu}, {DayOfWeek.Wednesday, GSchedule.We}, {DayOfWeek.Thursday, GSchedule.Th}, {DayOfWeek.Friday, GSchedule.Fr}, {DayOfWeek.Saturday, GSchedule.Sa}, {DayOfWeek.Sunday, GSchedule.Su}, }; foreach (var item in model) { var time = String.Format("{0:hh\\:mm}-{1:hh\\:mm}", item.Starts, item.Ends); RegionalNode node; if (!result.TryGetValue(time, out node)) { result[time] = node = new RegionalNode(time); } node.AddItem(item); var dayOfWeek = (DayOfWeek) item.Day; if (!days.ContainsKey(dayOfWeek)) { days.Add(dayOfWeek,mappings[dayOfWeek]); } } return result.Values; }
public void Init(IDictionary<DateTime, int> dates, DateTime selectedDate) { Dictionary<int, TreeNode> dictionary1 = new Dictionary<int, TreeNode>(); Dictionary<int, TreeNode> dictionary2 = new Dictionary<int, TreeNode>(); this.treeView.BeginUpdate(); foreach (KeyValuePair<DateTime, int> keyValuePair in (IEnumerable<KeyValuePair<DateTime, int>>) dates) { DateTime key = keyValuePair.Key; int year = key.Year; int month = key.Month; int day = key.Day; TreeNode node1; if (!dictionary1.TryGetValue(year, out node1)) { node1 = (TreeNode) new DateNode(key, "yyyy"); dictionary1.Add(year, node1); this.treeView.Nodes.Add(node1); } TreeNode node2; if (!dictionary2.TryGetValue(month, out node2)) { node2 = (TreeNode) new DateNode(key, "MMM"); dictionary2.Add(month, node2); node1.Nodes.Add(node2); } DayNode dayNode = new DayNode(key, keyValuePair.Value); node2.Nodes.Add((TreeNode) dayNode); if (key == selectedDate) this.treeView.SelectedNode = (TreeNode) dayNode; } this.treeView.TreeViewNodeSorter = (IComparer) new DateNodeComparer(); this.treeView.Sort(); this.treeView.EndUpdate(); this.UpdateOKButtonStatus(); }
Type FindType(string @namespace, string name) { if (_types == null) { _types = new Dictionary<string, Dictionary<string, Type>>(); foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) foreach (Type type in a.GetTypes()) { var attribute = type.GetCustomAttribute<MarkupElementAttribute>(false); if (attribute != null) { Dictionary<string, Type> typesInNamespace; if (!_types.TryGetValue(attribute.NameSpace, out typesInNamespace)) { typesInNamespace = new Dictionary<string, Type>(); _types.Add(attribute.NameSpace, typesInNamespace); } typesInNamespace.Add(attribute.Name, type); } } } try { return _types[@namespace][name]; } catch (KeyNotFoundException e) { throw new Exception(String.Format("Type '{0}.{1}' is not found.", @namespace, name), e); } }
private static bool register(Dictionary<string, List<Pair>> events, string eventname, object obj, string funcname) { deregister(events, eventname, obj, funcname); List<Pair> lst = null; Pair pair = new Pair(); pair.obj = obj; pair.funcname = funcname; pair.method = obj.GetType().GetMethod(funcname); if(pair.method == null) { Dbg.ERROR_MSG("Event::register: " + obj + "not found method[" + funcname + "]"); return false; } Monitor.Enter(events); if(!events.TryGetValue(eventname, out lst)) { lst = new List<Pair>(); lst.Add(pair); Dbg.DEBUG_MSG("Event::register: event(" + eventname + ")!"); events.Add(eventname, lst); Monitor.Exit(events); return true; } Dbg.DEBUG_MSG("Event::register: event(" + eventname + ")!"); lst.Add(pair); Monitor.Exit(events); return true; }
public static object ConvertDictionaryToClassDataContract(DataContractJsonSerializer serializer, ClassDataContract dataContract, Dictionary<string, object> deserialzedValue, XmlObjectSerializerReadContextComplexJson context) { if (deserialzedValue == null) { return null; } if (dataContract.UnderlyingType == Globals.TypeOfDateTimeOffsetAdapter) { var tuple = deserialzedValue["DateTime"] as Tuple<DateTime, string>; DateTimeOffset dto = new DateTimeOffset(tuple != null ? tuple.Item1 : (DateTime)deserialzedValue["DateTime"]); return dto.ToOffset(new TimeSpan(0, (int)deserialzedValue["OffsetMinutes"], 0)); } object serverTypeStringValue; if (deserialzedValue.TryGetValue(JsonGlobals.ServerTypeString, out serverTypeStringValue)) { dataContract = ResolveDataContractFromTypeInformation(serverTypeStringValue.ToString(), dataContract, context); } object o = CreateInstance(dataContract); CheckDuplicateNames(dataContract); DataContractJsonSerializer.InvokeOnDeserializing(o, dataContract, context); ReadClassDataContractMembers(serializer, dataContract, deserialzedValue, o, context); DataContractJsonSerializer.InvokeOnDeserialized(o, dataContract, context); if (dataContract.IsKeyValuePairAdapter) { return dataContract.GetKeyValuePairMethodInfo.Invoke(o, Array.Empty<Type>()); } return o; }
// return index of point in the middle of p1 and p2 private static int getMiddlePoint(int p1, int p2, ref List<Vector3> vertices, ref Dictionary<long, int> cache, float altitude) { // first check if we have it already bool firstIsSmaller = p1 < p2; long smallerIndex = firstIsSmaller ? p1 : p2; long greaterIndex = firstIsSmaller ? p2 : p1; long key = (smallerIndex << 32) + greaterIndex; int ret; if (cache.TryGetValue(key, out ret)) { return ret; } // not in cache, calculate it Vector3 point1 = vertices[p1]; Vector3 point2 = vertices[p2]; Vector3 middle = new Vector3 ( (point1.x + point2.x) / 2f, (point1.y + point2.y) / 2f, (point1.z + point2.z) / 2f ); // add vertex makes sure point is on unit sphere int i = vertices.Count; vertices.Add(middle.normalized * altitude); // store it, return index cache.Add(key, i); return i; }
/// <summary> /// Returns items in at least MinT lists. The output is not necessarily sorted. /// </summary> public void SearchTThreshold(IList<IList<int>> lists, int MinT, out IList<int> docs, out IList<short> cardinalities) { var L = new Dictionary<int,short> (); var output_set = new HashSet<int> (); int i = 0; foreach (var list in lists) { foreach (var item in list) { short counter; if (L.TryGetValue (item, out counter)) { counter++; } else { /*if (MinT < i) { continue; }*/ counter = 1; } if (counter == MinT) { output_set.Add (item); } L [item] = counter; } i++; } docs = new int[ output_set.Count ]; cardinalities = new short[ docs.Count ]; i = 0; foreach (var item in output_set) { docs [i] = item; cardinalities [i] = L [item]; i++; } if (this.sorted_output) { Sorting.Sort<int,short> (docs, cardinalities); } }
//***************************************************************************************** //add a new random postive trait to unit private bool addPositiveTrait(APlayableEntity unit) { Dbg.trc(Dbg.Grp.Units, 5); List<string> posPrefs = new List<string> {"trait.hardworker","trait.goodvision","trait.charismatic","trait.courageous","trait.athletic","trait.quicklearner","trait.strongback"}; List<string> notHasPrefs = new List<string>(); foreach(string pref in posPrefs) { if(unit.preferences[pref] != true) { notHasPrefs.Add(pref); } } if(notHasPrefs.Count >= 1) { Dictionary<string,string> traitsChangedStrings = new Dictionary<string,string>{ {"trait.hardworker","is a hard worker"}, {"trait.goodvision","has good vision"}, {"trait.charismatic","is charismatic"}, {"trait.courageous","is courageous"}, {"trait.athletic","is athletic"}, {"trait.quicklearner","is a quick learner"}, {"trait.strongback","has a strong back"}, }; int add = UnityEngine.Random.Range(0, notHasPrefs.Count - 1); unit.preferences[notHasPrefs[add]] = true; string outString; traitsChangedStrings.TryGetValue(notHasPrefs[add], out outString); UI.print("All this training paid off! " + unit.unitName + " now " + outString + "!"); return true; } return false; }
private double GetTeamWinPercentage(Team team, Dictionary<Guid, WinLossRecord> winLossRecords) { // Option 1: Total wins/losses, giving players who have played more a higher weight in the rating // var record = new WinLossRecord(); // foreach (var player in team.Members) // { // WinLossRecord winLossRecord; // if (winLossRecords.TryGetValue(player.Id, out winLossRecord)) // { // record.Wins += winLossRecord.Wins; // record.Losses += winLossRecord.Losses; // record.Ties += winLossRecord.Ties; // } // } // return record.WinPercentage; // Option 2: Average win percentage, equally weighted double winPercentage = 0.0; foreach (var player in team.Members) { WinLossRecord winLossRecord; if (winLossRecords.TryGetValue(player.Id, out winLossRecord)) { winPercentage += winLossRecord.WinPercentage; } else { winPercentage += 0.5; } } return winPercentage/team.Members.Count; }
public static string[,] buildMatrix(Dictionary<Color, string> dictionary, PngReader reader) { ImageInfo info = reader.ImgInfo; var matrix = new string[info.Cols, info.Rows]; for (int i = 0; i < info.Rows; i++) { ImageLine line = reader.ReadRow(i); int[] lineInts = line.Scanline; for (int j = 0, col = 0; j < lineInts.Length; j += info.Channels, col++) { int red = lineInts[j]; int green = lineInts[j + 1]; int blue = lineInts[j + 2]; int alpha = 255; if (info.Channels == 4) { alpha = lineInts[j + 3]; } Color color = new Color(red / 255f, green / 255f, blue / 255f, alpha / 255f); string val; if (dictionary.TryGetValue(color, out val)) { matrix[col, i] = val; } } } return matrix; }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public MiResultValueTuple (string variable, List<MiResultValue> values) : base (variable) { if (values == null) { throw new ArgumentNullException ("values"); } m_valueList = values; // // Build a searchable dictionary of available result variables (fields). // m_fieldDictionary = new Dictionary<string, List <MiResultValue>> (); foreach (MiResultValue value in m_valueList) { List <MiResultValue> fieldList; if (!m_fieldDictionary.TryGetValue (value.Variable, out fieldList)) { fieldList = new List <MiResultValue> (); } fieldList.Add (value); m_fieldDictionary [value.Variable] = fieldList; } }
public static void DumpInfo(TextWriter tw) { for (var i = 0; i < 8; ++i) { tw.WriteLine("Priority: {0}", (TimerPriority)i); tw.WriteLine(); var hash = new Dictionary<string, List<Timer>>(); for (var j = 0; j < mTimers[i].Count; ++j) { var t = mTimers[i][j]; var key = t.ToString(); List<Timer> list; hash.TryGetValue(key, out list); if (list == null) { hash[key] = list = new List<Timer>(); } list.Add(t); } foreach (var kv in hash) { var key = kv.Key; var list = kv.Value; tw.WriteLine("Type: {0}; Count: {1}; Percent: {2}%", key, list.Count, (int)(100 * (list.Count / (double)mTimers[i].Count))); } tw.WriteLine(); tw.WriteLine(); } }
public void SetNewHashFunction(LSHashFunction hashFunction) { lock (accessLock) { Dictionary<CustomBitArray, LSHashTableCell> oldValues = _values; _values = new Dictionary<CustomBitArray, LSHashTableCell>(); _hashFunction = hashFunction; //Re-hash all the old tweets using the new hash function foreach (LSHashTableCell oldCell in oldValues.Values) { foreach (LSHashTweet tweet in oldCell.GetTweets()) { bool anyTrue = false; CustomBitArray hash = _hashFunction.CalculateHashScore(tweet.Vector, out anyTrue); LSHashTableCell cell; if (_values.TryGetValue(hash, out cell)) { cell.Add(tweet); } else { cell = new LSHashTableCell(_cellCapacity); cell.Add(tweet); _values.Add(hash, cell); } } } } }
// Count instances of unique string output values and return multinomial probability vector public static Dictionary<string, double> BootstrapFrequency(IEnumerable<FunctionOutput<string>> boots) { var counts = new Dictionary<string, int>(); foreach (FunctionOutput<string> boot in boots) { string key = boot.GetValue(); int count; if (counts.TryGetValue(key, out count)) { counts[key] = count + 1; } else { counts.Add(key, 1); } } var p_values = new Dictionary<string,double>(); var bootcount = (double)boots.Count(); foreach (KeyValuePair<string,int> pair in counts) { p_values.Add(pair.Key, (double)pair.Value / bootcount); } return p_values; }
public string writeXML(string rootElement, Dictionary<string, object> keyValueDictionary) { try { StringWriter stringWriter = new StringWriter(); XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter); //xmlWriter.Formatting = Formatting.Indented; //xmlWriter.Indentation = indentation; // write root element xmlWriter.WriteStartElement(rootElement); xmlWriter.WriteAttributeString("xmlns", "ns", null, "http://ilab.mit.edu/iLab"); foreach (string s in keyValueDictionary.Keys) { xmlWriter.WriteStartElement(s); object value = new object(); keyValueDictionary.TryGetValue(s, out value); xmlWriter.WriteString(value.ToString()); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); return stringWriter.ToString(); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } return null; }
private object GetModel(Dictionary<string, object> scopeArgs) { object model; if (!scopeArgs.TryGetValue(this.MemberVarName, out model)) throw new ArgumentException(this.MemberVarName + " does not exist"); return model; }
/* void DisplayArticles() { for(int i=1; i<2; i++) { GameObject gObj = Instantiate(ArticleTemplate,Vector3.zero,Quaternion.identity) as GameObject; gObj.transform.parent = this.transform; gObj.transform.localPosition = new Vector3(0,-500 *i, 0); } }*/ private string getDataValueForKey(Dictionary<string, object> dict, string key) { object objectForKey; if (dict.TryGetValue(key, out objectForKey)) { return (string)objectForKey; } else { return ""; } }
public WorkItemFetcher(String serverAddress, String projectName, ICredentials credentials, Dictionary<String, String> configuration) { String configValue = ""; WORK_REMAINING_FIELD = (configuration.TryGetValue("tfswi-remaining-field", out configValue)) ? configValue : WORK_REMAINING_FIELD; ESTIMATED_EFFORT_FIELD = (configuration.TryGetValue("tfswi-estimated-field", out configValue)) ? configValue : ESTIMATED_EFFORT_FIELD; this.projectName = projectName; tfsServer = new TeamFoundationServer(serverAddress, credentials); tfsServer.Authenticate(); workItemStore = tfsServer.GetService(typeof (WorkItemStore)) as WorkItemStore; }