public List<Edge<int>> mfas(BidirectionalGraph<int, Edge<int>> G) { List<Edge<int>> F = new List<Edge<int>>(); IDictionary<int, int> P = new Dictionary<int, int>(); int sccCount = G.StronglyConnectedComponents(out P); if (sccCount == 0) { return F; } if (sccCount == 1) { Tuple<List<int>, List<int>> T = bisect(G); F = mfas(subGraph(T.Item1, G)); F.AddRange(mfas(subGraph(T.Item2, G))); F.AddRange(fromV2toV1(T, G)); } else { var scc = new HashSet<int>(P.Values); foreach (int k in scc) { List<int> S = P.Select(x => x).Where(x => x.Value == k).Select(x => x.Key).ToList<int>(); F.AddRange(mfas(subGraph(S, G))); } } return F; }
public static Dictionary<string, PropertyInfo> ApplyPropertyCasing(DeserializationContext context, Dictionary<string, PropertyInfo> properties) { if (context.JsonContractResolver is CamelCasePropertyNamesContractResolver) { var camel = new Func<string, string>(name => string.Format("{0}{1}", name.Substring(0,1).ToLowerInvariant(), name.Substring(1, name.Length-1))); return properties.Select(x => new { Key = camel(x.Key), x.Value }).ToDictionary(x => x.Key, x => x.Value); } return properties; }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { DsiPage page = (DsiPage)this.Page; var musicTypes = new Dictionary<string, int>() {{"All Music", 0}}; var musicTypeSet = new MusicTypeSet(new Query(new Q(Bobs.MusicType.Columns.K, page.RelevantMusic.ToArray()))); foreach (var musicType in musicTypeSet) { musicTypes[musicType.Name] = musicType.K; } foreach (var musicType in Identity.Current.FavouriteMusicTypes.ConvertAll(k => new MusicType(k))) { musicTypes[musicType.Name] = musicType.K; } this.uiMusicTypes.Items.AddRange(musicTypes.Select(mt => new ListItem(mt.Key, mt.Value.ToString())).ToArray()); var places = new Dictionary<string, int>() {{"Anywhere", -1}}; var placeSet = new PlaceSet(new Query(new Q(Bobs.Place.Columns.K, page.RelevantMusic.ToArray()))); foreach (var place in placeSet) { places[place.Name] = place.K; } foreach (var place in Identity.Current.PlacesVisited.ConvertAll(k => new Place(k))) { places[place.Name] = place.K; } this.uiPlaces.Items.AddRange(places.Select(mt => new ListItem(mt.Key, mt.Value.ToString())).ToArray()); } //if (Common.Settings.UseCometToServeRequests) //{ // this.uiBuddyMultiSelector.WebServiceMethod = ""; // this.uiBuddyMultiSelector.WebServiceUrl = ""; // this.uiBuddyMultiSelector.CometServiceUrl = @"/WebServices/CometAutoComplete/GetBuddiesThenUsrs.ashx"; //} uiBuddyMultiSelector.TextBoxTabIndex = TabIndexBase + 1; uiJustBuddiesRadio.TabIndex = (short)(TabIndexBase + 2); uiAllMembersRadio.TabIndex = (short)(TabIndexBase + 3); uiShowBuddyList.TabIndex = (short)(TabIndexBase + 4); uiBuddyList.TabIndex = (short)(TabIndexBase + 5); uiShowAddAll.TabIndex = (short)(TabIndexBase + 6); uiAddAllButton.Attributes["tabindex"] = (TabIndexBase + 7).ToString(); uiShowAddBy.TabIndex = (short)(TabIndexBase + 8); uiPlaces.TabIndex = (short)(TabIndexBase + 9); uiMusicTypes.TabIndex = (short)(TabIndexBase + 10); uiAddByMusicAndPlace.Attributes["tabindex"] = (TabIndexBase + 11).ToString(); uiShowAllTownsAndMusic.TabIndex = (short)(TabIndexBase + 12); }
public static string CreateQueryString(Dictionary<string, object> dict) { return (dict == null || dict.Count == 0) ? string.Empty : CreateQueryString( dict.Select(kv => kv.Value is bool ? new KeyValuePair<string, string>(kv.Key, (bool)kv.Value ? "1" : "0") : new KeyValuePair<string, string>(kv.Key, kv.Value != null ? kv.Value.ToString() : null) ) ); }
protected override object DoDeserializeValue(XmlReader reader, bool isSimpleValue) { IDictionary<string, MediaCategory_DTO> result_dtos = new Dictionary<string, MediaCategory_DTO>(); if (SoapHelper.ReadEmptyStartElement(reader)) // Read start of enclosing element return new List<MediaCategory>(); while (reader.NodeType != XmlNodeType.EndElement) { MediaCategory_DTO result_dto = MediaCategory_DTO.Deserialize(reader); result_dtos.Add(result_dto.CategoryName, result_dto); } reader.ReadEndElement(); // End of enclosing element return new List<MediaCategory>(result_dtos.Select(mCatDtoKvp => mCatDtoKvp.Value.GetMediaCategory(result_dtos))); }
// Methods public static string Serialize(object value = null, string prefix = null) { // Require if (value == null) return string.Empty; // Result var nameValueDictionary = new Dictionary<string, string>(); // Serialize SerializeObject(ref nameValueDictionary, value, prefix); // Return return string.Join("&", nameValueDictionary.Select(nameValuePair => (nameValuePair.Key + "=" + Uri.EscapeDataString(nameValuePair.Value)))); }
/// <summary> /// Updates errorEntryList with a page of errors from the repository in descending order of logged time and returns /// total number of entries /// </summary> public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList) { var errors = new Dictionary<string, ErrorRecord>(); // todo: proper async support var totalCount = _errorRepository.GetErrorsAsync(pageIndex, pageSize, errors).Result; var errorLogEntries = errors.Select(error => new ErrorLogEntry(this, error.Key, error.Value.ToError())); foreach (var errorLogEntry in errorLogEntries) { errorEntryList.Add(errorLogEntry); } return totalCount; }
private static void OnGameLoad(EventArgs args) { try { pSkins = GetSkins(ObjectManager.Player.ChampionName); Config = new Menu("鐨偆淇敼", "Skin Changer", true); var SelectedSkin = Config.AddItem(new MenuItem("currentSkin", " ").SetValue(new StringList(pSkins.Select(item => item.Value).ToArray())).DontSave()); var SwitchSkin = Config.AddItem(new MenuItem("keySwitch", "鐐规垜淇敼").SetValue(new KeyBind("9".ToCharArray()[0], KeyBindType.Press))); SelectedSkin.ValueChanged += (object sender, OnValueChangeEventArgs vcArgs) => { Packet.S2C.UpdateModel.Encoded(new Packet.S2C.UpdateModel.Struct(ObjectManager.Player.NetworkId, vcArgs.GetNewValue<StringList>().SelectedIndex, ObjectManager.Player.ChampionName)).Process(PacketChannel.S2C); }; { Config.AddSubMenu(new Menu("L#涓枃绀惧尯姹夊寲", "LOLL35.Com")); Config.SubMenu("LOLL35.Com").AddItem(new MenuItem("wangzhi", "www.loll35.com")); Config.SubMenu("LOLL35.Com").AddItem(new MenuItem("qunhao2", "姹夊寲缇わ細397983217")); } SwitchSkin.ValueChanged += (object sender, OnValueChangeEventArgs vcArgs) => { if (vcArgs.GetOldValue<KeyBind>().Active) return; var currentSkin = Config.Item("currentSkin"); var OldValues = currentSkin.GetValue<StringList>(); var newSkinId = OldValues.SelectedIndex + 1 >= OldValues.SList.Count() ? 0 : OldValues.SelectedIndex + 1; currentSkin.SetValue(new StringList(OldValues.SList, newSkinId)); }; Config.AddToMainMenu(); Game.PrintChat("<font color=\"#0066FF\">[<font color=\"#FFFFFF\">madk</font>]</font><font color=\"#FFFFFF\"> Skin Changer loaded!</font>"); } catch(Exception ex) { Game.PrintChat("<font color=\"#0066FF\">[<font color=\"#FFFFFF\">madk</font>]</font><font color=\"#FFFFFF\"> An error ocurred loading Skin Changer.</font>"); Console.WriteLine("~~ Skin Changer exception found ~~"); Console.WriteLine(ex); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); } }
/// <summary> /// Given a Lucene Query, this will build the facets and append them to find the Bit comparison of two queries. /// </summary> /// <returns>List of FacetReturn</returns> /// <param name="query">The initial query</param> /// <param name="searchQuery">The raw search query</param> /// <param name="locationFilter">The location used to determine which index to use</param> /// <param name="baseQuery">The initial queries bit array</param> public List<FacetReturn> Filter(Query query, List<SearchStringModel> searchQuery, string locationFilter, BitArray baseQuery) { var listOfDates = new Dictionary<DateTime, string> { { DateTime.Now.AddDays(-1), "Within a Day" }, { DateTime.Now.AddDays(-7), "Within a Week" }, { DateTime.Now.AddMonths(-1), "Within a Month" }, { DateTime.Now.AddYears(-1), "Within a Year" }, { DateTime.Now.AddYears(-3), "Older" } }; var returnFacets = this.GetSearch(query, listOfDates.Select(date => date.Key.ToString() + "|" + date.Value).ToList(), searchQuery, locationFilter, baseQuery).Select( facet => new FacetReturn { KeyName = DecodeDateSearch(DateTime.Parse(facet.Key.Split('|')[0]), listOfDates), Value = facet.Value.ToString(), Type = "date range" }); return returnFacets.ToList(); }
//REMOVER private string generateJson(Dictionary<string, string> fields) { var entries = fields.Select(d => string.Format("\"{0}\":\"{1}\"", d.Key, string.Join(",", d.Value))); string json = "{" + string.Join(",", entries) + "}"; return json; }
private string SerializeDictionary(Dictionary<string, object> obj) { return string.Format ("{{{0}}}", string.Join (",", obj.Select (kvp => string. Format ("{0}:{1}", SerializeString (kvp.Key), Serialize(kvp.Value))))); }
/// <summary> /// Determines the expected shape of store results. We expect a column for every property /// of the mapped type (or types) and a column for every discriminator column. We make no /// assumptions about the order of columns: the provider is expected to determine appropriate /// types by looking at the names of the result columns, not the order of columns, which is /// different from the typical handling of row types in the EF. /// </summary> /// <remarks> /// Requires that the given function import mapping refers to a Collection(Entity) or Collection(ComplexType) CSDL /// function. /// </remarks> /// <returns>Row type.</returns> internal TypeUsage GetExpectedTargetResultType(int resultSetIndex) { var resultMapping = GetResultMapping(resultSetIndex); // Collect all columns as name-type pairs. var columns = new Dictionary<string, TypeUsage>(); // Figure out which entity types we expect to yield from the function. IEnumerable<StructuralType> structuralTypes; if (0 == resultMapping.NormalizedEntityTypeMappings.Count) { // No explicit type mappings; just use the type specified in the ReturnType attribute on the function. StructuralType structuralType; MetadataHelper.TryGetFunctionImportReturnType(FunctionImport, resultSetIndex, out structuralType); Debug.Assert(null != structuralType, "this method must be called only for entity/complextype reader function imports"); structuralTypes = new[] { structuralType }; } else { // Types are explicitly mapped. structuralTypes = resultMapping.MappedEntityTypes.Cast<StructuralType>(); } // Gather columns corresponding to all properties. foreach (var structuralType in structuralTypes) { foreach (EdmProperty property in TypeHelpers.GetAllStructuralMembers(structuralType)) { // NOTE: if a complex type is encountered, the column map generator will // throw. For now, we just let them through. // We expect to see each property multiple times, so we use indexer rather than // .Add. columns[property.Name] = property.TypeUsage; } } // Gather discriminator columns. foreach (var discriminatorColumn in GetDiscriminatorColumns(resultSetIndex)) { if (!columns.ContainsKey(discriminatorColumn)) { // CONSIDER: we assume that discriminatorColumns are all string types. In practice, // we're flexible about the runtime type during materialization, so the provider's // decision is hopefully irrelevant. The alternative is to require typed stored // procedure declarations in the SSDL, which is too much of a burden on the user and/or the // tools (there is no reliable way of determining this metadata automatically from SQL // Server). var type = TypeUsage.CreateStringTypeUsage( MetadataWorkspace.GetModelPrimitiveType(PrimitiveTypeKind.String), true, false); columns.Add(discriminatorColumn, type); } } // Expected type is a collection of rows var rowType = new RowType(columns.Select(c => new EdmProperty(c.Key, c.Value))); var result = TypeUsage.Create(new CollectionType(TypeUsage.Create(rowType))); return result; }
private static IEnumerable<KeyValuePair<string, ErrorsSummary>> _getPackSummary( Dictionary<string, PackClasterizedErrors> errorClassificationData, Func<PackClasterizedErrors, IEnumerable<IGrouping<int, ClasterizedSentenceError>>> errorsSelector) { return errorClassificationData.Select( pair => new KeyValuePair<string, ErrorsSummary>(pair.Key, _getTotalSummary(errorsSelector(pair.Value)))); }
/// <summary> /// Determines the expected shape of store results. We expect a column for every property /// of the mapped type (or types) and a column for every discriminator column. We make no /// assumptions about the order of columns: the provider is expected to determine appropriate /// types by looking at the names of the result columns, not the order of columns, which is /// different from the typical handling of row types in the EF. /// </summary> /// <remarks> /// Requires that the given function import mapping refers to a Collection(Entity) or Collection(ComplexType) CSDL /// function. /// </remarks> /// <returns>Row type.</returns> internal TypeUsage GetExpectedTargetResultType(MetadataWorkspace workspace, int resultSetIndex) { FunctionImportStructuralTypeMappingKB resultMapping = this.GetResultMapping(resultSetIndex); // Collect all columns as name-type pairs. Dictionary<string, TypeUsage> columns = new Dictionary<string, TypeUsage>(); // Figure out which entity types we expect to yield from the function. IEnumerable<StructuralType> structuralTypes; if (0 == resultMapping.NormalizedEntityTypeMappings.Count) { // No explicit type mappings; just use the type specified in the ReturnType attribute on the function. StructuralType structuralType; MetadataHelper.TryGetFunctionImportReturnType<StructuralType>(this.FunctionImport, resultSetIndex, out structuralType); Debug.Assert(null != structuralType, "this method must be called only for entity/complextype reader function imports"); structuralTypes = new StructuralType[] { structuralType }; } else { // Types are explicitly mapped. structuralTypes = resultMapping.MappedEntityTypes.Cast<StructuralType>(); } // Gather columns corresponding to all properties. foreach (StructuralType structuralType in structuralTypes) { foreach (EdmProperty property in TypeHelpers.GetAllStructuralMembers(structuralType)) { // NOTE: if a complex type is encountered, the column map generator will // throw. For now, we just let them through. // We expect to see each property multiple times, so we use indexer rather than // .Add. columns[property.Name] = property.TypeUsage; } } // Gather discriminator columns. foreach (string discriminatorColumn in this.GetDiscriminatorColumns(resultSetIndex)) { if (!columns.ContainsKey(discriminatorColumn)) { // TypeUsage type = TypeUsage.CreateStringTypeUsage(workspace.GetModelPrimitiveType(PrimitiveTypeKind.String), true, false); columns.Add(discriminatorColumn, type); } } // Expected type is a collection of rows RowType rowType = new RowType(columns.Select(c => new EdmProperty(c.Key, c.Value))); TypeUsage result = TypeUsage.Create(new CollectionType(TypeUsage.Create(rowType))); return result; }
public static MapRepresentation CreateMap(Dictionary<string, object> exts) { OptionalProperty[] parms = exts.Select(e => new OptionalProperty(e.Key, e.Value)).ToArray(); return MapRepresentation.Create(parms); }
//public static string GetNewInputId() //(string id = null) //{ // _storage. // var service = EntryPointProxy.GetIOService(); // var req = new IOService.postDataRequest(); // req.DataID = null;//id; // //req.CalcPackage = null; // var resp = service.postData(req); // return resp.DataId; //} private static string SendToStorageCore(string method, Dictionary<string, string> args) { string coreUrl = Config.AppSettings["Storage"]; string coreToken = Config.AppSettings["StorageToken"]; using (var webClient = new WebClient()) { webClient.BaseAddress = coreUrl; webClient.Encoding = Encoding.UTF8; //.GetEncoding(1251); webClient.Headers.Add("Content-Type", "application/json"); args["secid"] = coreToken; string message = "{" + String.Join(", ", args.Select(pair => String.Format(@"""{0}"": ""{1}""", pair.Key, pair.Value))) + "}"; Log.Debug(String.Format("Sending to storage: {0} {1}", method, message)); string response = webClient.UploadString("", method, message); Log.Debug("Storage response: " + response); return response; } }
private static void RemoveTemporaryMembers(Dictionary<string, string> source) { var sourceNames = source.Select(x => x.Key).ToArray(); if (!_temporaryMemberNames.All(x => sourceNames.Contains(x))) return; foreach (var name in _temporaryMemberNames) source.Remove(name); }
/// <summary> /// Gets the clients by identifier. /// </summary> /// <param name="users">The users.</param> /// <returns>IEnumerable<GameClient>.</returns> internal IEnumerable<GameClient> GetClientsById(Dictionary<uint, MessengerBuddy>.KeyCollection users) => users.Select(GetClientByUserId).Where(clientByUserId => clientByUserId != null);
/// <summary> /// Returns all the resource strings for all cultures for a specific resource Id. /// Returned as a dictionary. /// </summary> /// <param name="resourceId">Resource Id to retrieve strings for</param> /// <param name="resourceSet">Resource Set on which to retrieve strings</param> /// <param name="forAllResourceSetLocales">If true returns empty entries for each locale that exists but has no value in this resource set</param> /// <returns></returns> public virtual Dictionary<string, string> GetResourceStrings(string resourceId, string resourceSet, bool forAllResourceSetLocales = false) { var Resources = new Dictionary<string, string>(); using (var data = GetDb()) { using (DbDataReader reader = data.ExecuteReader("select Value,LocaleId from " + Configuration.ResourceTableName + " where ResourceId=@ResourceId and ResourceSet=@ResourceSet order by LocaleId", data.CreateParameter("@ResourceId", resourceId), data.CreateParameter("@ResourceSet", resourceSet))) { if (reader == null) return null; while (reader.Read()) { Resources.Add(reader["LocaleId"] as string, reader["Value"] as string); } reader.Dispose(); } if (forAllResourceSetLocales) { var locales = GetAllLocalesForResourceSet(resourceSet); if (locales != null) { var usedLocales = Resources.Select(kv => kv.Key); var emptyLocales = locales.Where(s => !usedLocales.Contains(s)); foreach (var locale in emptyLocales) { Resources.Add(locale, ""); } } } } return Resources; }
public void CheckOrder(OrderMaster orderMaster) { BusinessException ex = new BusinessException(); if (orderMaster.Type == com.Sconit.CodeMaster.OrderType.CustomerGoods || orderMaster.Type == com.Sconit.CodeMaster.OrderType.Procurement) { ex.AddMessage("订单" + orderMaster.OrderNo + "无需检查库存"); } else { var paramList = new List<object>(); string sql = string.Empty; paramList.Add(orderMaster.LocationFrom); var itemQtyDic = new Dictionary<string, decimal>(); if (orderMaster.Type == CodeMaster.OrderType.Production) { TryLoadOrderBomDetails(orderMaster); if (orderMaster.OrderDetails != null) { itemQtyDic = orderMaster.OrderDetails .SelectMany(p => p.OrderBomDetails) .GroupBy(p => p.Item).ToDictionary(d => d.Key, d => d.Sum(q => q.OrderedQty)); } string hql = @"select distinct(isnull(d.LocFrom,f.LocFrom)) from Scm_FlowDet as d join SCM_FlowMstr f on d.Flow = f.Code where f.IsActive = ? and (d.LocTo =? or (d.LocTo is null and f.LocTo = ? )) and d.Item in(? "; var locations = genericMgr.FindAllWithNativeSqlIn<string> (hql, itemQtyDic.Select(p => p.Key), new object[] { true, orderMaster.LocationFrom, orderMaster.LocationFrom }); foreach (var location in locations) { if (sql == string.Empty) { sql = @" select l.* from VIEW_LocationDet as l with(nolock) where l.ATPQty>0 and l.Location in(?,? "; } else { sql += ",?"; } } paramList.AddRange(locations); } else { TryLoadOrderDetails(orderMaster); if (orderMaster.OrderDetails != null) { itemQtyDic = orderMaster.OrderDetails .GroupBy(p => p.Item).ToDictionary(d => d.Key, d => d.Sum(q => q.OrderedQty)); } sql = @" select l.* from VIEW_LocationDet as l with(nolock) where l.ATPQty>0 and (l.Location =? "; } sql += @" ) and l.Item in(? "; IList<LocationDetailView> locationDetailViewList = this.genericMgr.FindEntityWithNativeSqlIn<LocationDetailView> (sql, itemQtyDic.Select(p => p.Key), paramList); var invDic = (from p in locationDetailViewList group p by p.Item into g select new { Item = g.Key, Qty = g.Sum(q => q.ATPQty) }).ToDictionary(d => d.Item, d => d.Qty); foreach (var itemQty in itemQtyDic) { var diffQty = itemQty.Value - invDic.ValueOrDefault(itemQty.Key); if (diffQty > 0) { ex.AddMessage(string.Format("物料:{0}[{1}]没有足够的库存,缺口:{2}", itemQty.Key, itemMgr.GetCacheItem(itemQty.Key).FullDescription, diffQty.ToString("0.##"))); } } } if (ex.GetMessages() != null && ex.GetMessages().Count > 0) { throw ex; } }
/// <summary> /// Creates a grammatical relationship /// </summary> /// <param name="predicate">The main action or verb acting on the first argument, or the action connecting multiple arguments.</param> /// <param name="arguments">The mention(s), mapped to the argument number, of one or more arguments in the relationship</param> /// <param name="IDs">The IDs of the arguments, mapped to the corresponding argument number. The ID with key 1 should correspond to the argument with key 1.</param> /// <param name="temporals">Time frames of the action. May be empty.</param> /// <param name="locatives">Locations of the action. May be empty.</param> /// <param name="adjunts">All other parts of the relationship. May be empty.</param> /// <param name="confidence">A score for each relationship result, ranging from 0 to 1. You can use this measurement as a threshold to filter out undesired results.</param> /// <param name="modalities">The modalities of the relationship.</param> public RosetteRelationship(string predicate, Dictionary<int, string> arguments, Dictionary<int, string> IDs, List<string> temporals, List<string> locatives, List<string> adjunts, Nullable<decimal> confidence, HashSet<string> modalities) { this.Predicate = predicate; #pragma warning disable 618 this.Arguments = arguments.Select(kvp => kvp.Value).ToList(); this.ArgumentsFull = new List<Argument>(arguments.Select<KeyValuePair<int, string>, Argument>((kvp, index) => new Argument(kvp.Key, kvp.Value, IDs == null || !IDs.ContainsKey(kvp.Key) || IDs[kvp.Key] == null ? null : new EntityID(IDs[kvp.Key])))); #pragma warning restore 618 this.Temporals = temporals; this.Locatives = locatives; this.Adjucts = adjunts; this.Confidence = confidence; this.Modalities = modalities; }
private static void CreateTableForType(Type type, Type parent, Dictionary<string, Type> values, string embeddedPrefix = "") { // Save all scalar and inline types first, so we have the new entry id for our mn-table later foreach (var property in PersistentProperty.GetPersistentProperties(type, embeddedPrefix, parent)) { if (property.IsSimpleType) { // save array of basic types if (property.Type.IsArray && property.ArrayCount != -1) { for (int i = 0; i < property.ArrayCount; i++) { values.Add(property.ColumnName + "_" + i, property.Property.PropertyType); } } else { values.Add(property.ColumnName, property.Type); } continue; } if (property.IsGenericList || property.IsGenericDictionary) { string query = ""; if (property.IsGenericList) { query = "CREATE TABLE {0} ({1}Id NUMERIC, {2}Id NUMERIC)"; } if (property.IsGenericDictionary) { query = "CREATE TABLE {0} ({1}Id NUMERIC, {2}Id NUMERIC, Key TEXT)"; } query = String.Format(query, property.RelationTableName, parent == null ? type.Name : parent.Name, property.ListType.Name); using (var cmd = new SQLiteCommand(query, DBManager.MPQMirror)) { cmd.ExecuteNonQuery(); } CreateTableForType(property.ListType, null, new Dictionary<string, Type>()); continue; } values.Add(property.ColumnName + "_", typeof(string)); CreateTableForType(property.Type, parent == null ? type : parent, values, property.ColumnName + "_"); } // Only create tables for parent classes if (parent == null && !tableExists(type.Name)) { if (type.Namespace == "System") { values.Add("Value", typeof(string)); } var columnDefinitions = values.Select(v => v.Key + " " + ((v.Value == typeof(String) || v.Value == typeof(byte[])) ? "TEXT" : "NUMERIC")).ToList<string>(); columnDefinitions.Add("Id INTEGER PRIMARY KEY"); var tableDefinition = String.Join(",", columnDefinitions.ToArray<string>()); using (var cmd = new SQLiteCommand(String.Format("CREATE TABLE {0} ({1})", type.Name, tableDefinition), DBManager.MPQMirror)) { cmd.ExecuteNonQuery(); } } }
private static void testCAPTCHA() { var timer = new MyTimer(); int s = 100, K = 100, m = 180; string[] templatefiles = Directory.GetFiles(@"D:\Play Data\my_template_data\scq-" + K + "-" + m, "*.scq") .Take(10000).ToArray(); #region 打开量化的模板 int templatecount = templatefiles.Length; Debug("打开{0}个量化模板----------------------------------------", templatecount); timer.Restart(); int[][] templatehistograms = new int[templatecount][]; string[] templatechars = new string[templatecount]; for (int f = 0; f < templatecount; ++f) { string file = templatefiles[f]; string filename = Path.GetFileNameWithoutExtension(file); templatechars[f] = filename.Split('-')[1]; templatehistograms[f] = new int[K]; using (var fs = new FileStream(file, FileMode.Open)) { using (var br = new BinaryReader(fs)) { for (int i = 0; i < K; ++i) { templatehistograms[f][i] = br.ReadInt32(); } } } } Debug("打开完成,用时{0}ms.", timer.Stop()); #endregion #region 打开Shapeme Debug("打开{0}个Shapeme.", K); timer.Restart(); double[][] shapemes = new double[K][]; using (var fs = new FileStream(Path.Combine(@"D:\Play Data\my_template_data\sm-" + K, m + ".sm"), FileMode.Open)) { using (var br = new BinaryReader(fs)) { for (int i = 0; i < K; ++i) { shapemes[i] = new double[60]; for (int k = 0; k < 60; ++k) { shapemes[i][k] = br.ReadDouble(); } } } } Debug("Shapeme读取完成,用时{0}ms.", timer.Stop()); #endregion #region 识别 foreach (var challengeFile in Directory.GetFiles(@"D:\Play Data\字符\", "*.jpg")) { timer.Restart(); string filename = Path.GetFileNameWithoutExtension(challengeFile); Image<Gray, Byte> img = new Image<Gray, byte>(challengeFile); var mmp = img.Convert<Bgr, Byte>(); Graphics g = Graphics.FromImage(mmp.Bitmap); double width_height_ratio = (double)img.Width / img.Height; int sq = (int)(s * width_height_ratio * 1.2); int randcount = (int)(width_height_ratio * 2); //int windowcount = (int)(width_height_ratio * 2), // windowstep = (int)(img.Width / windowcount), // windowwidth = (int)(img.Width * 1.5 / windowcount); //int maxrandcount = randcount * 3; //Console.WriteLine("宽高比{0:F2},采样{1},随机数{2},随机上限{3}.", // width_height_ratio, sq, randcount, maxrandcount); int slice = 16,//(int)(width_height_ratio * width_height_ratio), overlap = 4, windowcount = 7;//slice - (overlap - 1); double slice_width = (double)img.Width / slice; Console.WriteLine("宽高比{0:F2},切片数{1},切片宽度{2:F2},窗口数{3}.", width_height_ratio, slice, slice_width, windowcount); var edge = getEdge(img).Sample(sq); foreach (var p in edge) { mmp[p] = new Bgr(0, 0, 127); } bool[] edge_vi = Utils.InitArray(sq, false); #region 计算采样点之间的距离 ValueIndexPair<double>[][] edgedists = new ValueIndexPair<double>[sq][]; for (int i = 0; i < sq; ++i) { edgedists[i] = new ValueIndexPair<double>[sq]; for (int j = 0; j < sq; ++j) { double xi = edge[i].X, yi = edge[i].Y, xj = edge[j].X, yj = edge[j].Y; double d = Math.Sqrt((xi - xj) * (xi - xj) + (yi - yj) * (yi - yj)); edgedists[i][j] = new ValueIndexPair<double> { Value = d, Index = j }; } Array.Sort(edgedists[i], (a, b) => a.Value.CompareTo(b.Value)); } #endregion var charlist = new List<Tuple<string, int, PointF>>(); // <ch, count, center> //for (int rc = 0, rt = 0; rc < randcount && rt < maxrandcount; ++rt) { // #region 随机取一个中心点,并且取离他近的点计算形状上下文 //int center = rand.Next(sq); //if (edge_vi[center]) continue; //else rc++; //rc++; //var nearby = new List<Point>(); //foreach (var pair in edgedists[center].Take((int)(s * 1.5))) { // nearby.Add(edge[pair.Index]); // edge_vi[pair.Index] = true; //} //nearby = nearby.Sample(s); for (int wd = 0; wd < windowcount; ++wd) { #region 滑动窗口位置 //int window_center = wd * windowstep + (windowwidth / 2); double window_center = (wd * 2 + overlap / 2.0) * slice_width; g.DrawLine(Pens.Green, (float)window_center, 0, (float)window_center, img.Height); var nearby = edge.Where(p => Math.Abs(p.X - window_center) < img.Height) .OrderBy(p => Math.Abs(p.X - window_center)) .Take((int)(s * 1.2)) .ToList().Sample(s); if (nearby.Average(p => Math.Abs(p.X - window_center)) > img.Height) continue; var sc = Jim.OCR.ShapeContext2D.ShapeContext.ComputeSC2(nearby); #endregion #region 对待测图的形状上下文进行量化 int[] histogram = new int[K]; for (int i = 0; i < s; ++i) { double[] ds = new double[K]; for (int j = 0; j < K; ++j) ds[j] = Jim.OCR.ShapeContext2D.ShapeContext.HistCost(sc[i], shapemes[j]); int id = ds.Select((v, idx) => new ValueIndexPair<double> { Value = v, Index = idx }) .OrderBy(p => p.Value) .First().Index; ++histogram[id]; } #endregion #region 计算量化后的比较距离 double[] dists = new double[templatecount]; for (int i = 0; i < templatecount; ++i) { //dists[i] = Jim.OCR.ShapeContext2D.ShapeContext.ChiSquareDistance(histogram, templatehistograms[i]); dists[i] = Jim.OCR.ShapeContext2D.ShapeContext.HistCost( histogram.Select(d => (double)d).ToArray(), templatehistograms[i].Select(d => (double)d).ToArray()); } #endregion #region 对结果进行排序和统计 var arr = dists.Select((d, i) => new ValueIndexPair<double> { Value = d, Index = i }) .OrderBy(p => p.Value) .Select(p => new { Distance = p.Value, Char = templatechars[p.Index] }) .Where(p => "0123456789".IndexOf(p.Char) != -1) .ToArray(); Dictionary<string, int> matchcount = new Dictionary<string, int>(); int knn = 10; foreach (var pair in arr.Take(knn)) { string ch = pair.Char; matchcount[ch] = matchcount.ContainsKey(ch) ? matchcount[ch] + 1 : 1; } var match = matchcount.Select(pair => new { Count = pair.Value, Ch = pair.Key }) .Where(v => v.Count > 0) .OrderByDescending(v => v.Count).ToArray(); var firstmatch = match[0]; PointF newcenter = new PointF(nearby.Average(p => (float)p.X), nearby.Average(p => (float)p.Y)); charlist.Add(new Tuple<string, int, PointF> { First = firstmatch.Ch, Second = firstmatch.Count, Third = newcenter }); #endregion } foreach (var tp in charlist) { string ch = tp.First; int acc = tp.Second; PointF center = tp.Third; //g.DrawString(num.ToString(), new Font("Arial", 24), new SolidBrush(Color.FromArgb(40 + 20 * acc, 0, 0)), // new PointF(center.X - 12, center.Y - 12)); g.DrawString(ch, new Font("Arial", 24), (acc >= 5 ? Brushes.Red : Brushes.DarkGreen), new PointF(center.X - 12, center.Y - 12)); } mmp.Save(Path.Combine(@"D:\Play Data\测试玩意\", filename + ".jpg")); Debug("{0}-{1}ms", filename, timer.Stop()); } #endregion }
private ArrayList TypeForCategoryJsonArray(string Category) { ArrayList typeList = new ArrayList(); dictionaryItem = TestTypes.TypeWithSecureFlag(Category); isSecuredFlag = dictionaryItem != null && dictionaryItem.Where(x => Boolean.Parse(x.Value.ToString())).Select(y => y.Key).ToList().Distinct().Any(); if (dictionaryItem != null && dictionaryItem.Select(c => c.Key).Any()) { if (isSecuredFlag && UserHasPermission(Permission.Access_SecureTesting)) { typeList.Add(new object[] { dictionaryItem.Select(c => c.Key).ToArray() }); } else { typeList.Add(new object[] { dictionaryItem.Where(c => !c.Value).Select(c => c.Key).ToArray() }); } } return typeList; }
private void LoadHyphenationSettings() { var ssf = _settingsHelper.GetSettingsFilename(_settingsHelper.Database); if (ssf != null && ssf.Trim().Length > 0) { if (AppDomain.CurrentDomain.FriendlyName.ToLower() == "paratext.exe") { var paratextpath = Path.Combine(Path.GetDirectoryName(ssf), _settingsHelper.Database); Param.DatabaseName = _settingsHelper.Database; Param.IsHyphen = false; Param.HyphenLang = Common.ParaTextDcLanguage(_settingsHelper.Database, true); foreach (string filename in Directory.GetFiles(paratextpath, "*.txt")) { if (filename.Contains("hyphen")) { Param.IsHyphen = true; Param.HyphenFilepath = filename; Param.HyphenationSelectedLanguagelist.AddRange(Param.HyphenLang.Split(',')); } } } if (AppDomain.CurrentDomain.FriendlyName.ToLower().Contains("fieldworks")) { var xdoc = new XmlDocument(); try { IDictionary<string,string> value=new Dictionary<string, string>(); var settingsFile = ssf; xdoc.Load(settingsFile); var curVernWssnode = xdoc.SelectSingleNode("//CurVernWss/Uni"); if (curVernWssnode != null) { foreach (var lang in curVernWssnode.InnerText.Split(' ')) { var langname = GetLanguageValues(lang); if (!string.IsNullOrEmpty(lang) && (langname != null) && !value.ContainsKey(lang)) value.Add(lang, langname.Replace(',',' ')); } } var curAnalysisWssnode = xdoc.SelectSingleNode("//CurAnalysisWss/Uni"); if (curAnalysisWssnode != null) { foreach (var lang in curAnalysisWssnode.InnerText.Split(' ')) { var langname = GetLanguageValues(lang); if (!string.IsNullOrEmpty(lang) && (langname != null) && !value.ContainsKey(lang)) value.Add(lang, langname.Replace(',', ' ')); } } Param.HyphenLang = string.Join(",", value.Select(x => x.Key + ":" + x.Value).ToArray()); } catch (Exception) { } } } Common.EnableHyphenation(); CreatingHyphenationSettings.ReadHyphenationSettings(_settingsHelper.Database, InputType); foreach (string lang in Param.HyphenLang.Split(',')) { clbHyphenlang.Items.Add(lang, (Param.HyphenationSelectedLanguagelist.Contains(lang) ? true : false)); } }
public virtual void EvolveTimingChromosome(LearningMode learningMode, Dictionary<BitArray,double> agents, double crossOverProbability, double mutationProbability) { switch (learningMode) { case LearningMode.Random: RandomizeTimingChromosome(_random); break; case LearningMode.GA: if (_random.NextDouble() < crossOverProbability) { //selection var chromosomes = agents.Select(a => new {a.Key, Rank = a.Value*_random.NextDouble()}); var chosenChromosome = chromosomes.OrderByDescending(c => c.Rank).First(); //crossover var crossOver = Math.Floor(_random.NextDouble()*TimingChromosome.Count); for (int i = 0; i < crossOver; i++) { TimingChromosome[i] = chosenChromosome.Key[i]; } } //mutation for (int i = 0; i < TimingChromosome.Count; i++) { TimingChromosome[i] = _random.NextDouble() < mutationProbability ? !TimingChromosome[i] : TimingChromosome[i]; } break; case LearningMode.MRE: //update propensities for (int i = 0; i < _learningLog.Count; i++) { double reward; if (_learningLog[i].TimingChromosome == TimingChromosome) { reward = CurrentProfit*(1 - _experimentation); } else { reward = _learningLog[i].Propensity * (_experimentation / (_learningLog.Count -1)); } _learningLog[i].Propensity = (1 - _recency)*_learningLog[i].Propensity + reward; } //update probabilities for (int i = 0; i < _learningLog.Count; i++) { _learningLog[i].Probability = Math.Exp(_learningLog[i].Propensity/_temperature)/ _learningLog.Sum(l => Math.Exp(l.Propensity/_temperature)); } //select chromosome TimingChromosome = _learningLog.OrderByDescending(l => l.Probability * _random.NextDouble()).First().TimingChromosome; break; default: throw new ArgumentOutOfRangeException("Unknown learning mode"); } CurrentProfit = 0; }
private string BuildDescriptorDeclaration(FieldDescriptorProto field, bool emitFieldLabel = true) { PushDescriptorName(field); string type = ResolveType(field); Dictionary<string, string> options = new Dictionary<string, string>(); if (!String.IsNullOrEmpty(field.default_value)) { string default_value = field.default_value; if (field.type == FieldDescriptorProto.Type.TYPE_STRING) default_value = String.Format("\"{0}\"", default_value); options.Add("default", default_value); } else if (field.type == FieldDescriptorProto.Type.TYPE_ENUM && field.label != FieldDescriptorProto.Label.LABEL_REPEATED) { options.Add("default", ResolveOrDeferEnumDefaultValue(type)); } Dictionary<string, string> fieldOptions = DumpOptions(field.options); foreach (var pair in fieldOptions) { options[pair.Key] = pair.Value; } string parameters = String.Empty; if (options.Count > 0) { parameters = " [" + String.Join(", ", options.Select(kvp => String.Format("{0} = {1}", kvp.Key, kvp.Value))) + "]"; } PopDescriptorName(); var descriptorDeclarationBuilder = new StringBuilder(); if (emitFieldLabel) { descriptorDeclarationBuilder.Append(GetLabel(field.label)); descriptorDeclarationBuilder.Append(" "); } descriptorDeclarationBuilder.AppendFormat("{0} {1} = {2}{3};", type, field.name, field.number, parameters); return descriptorDeclarationBuilder.ToString(); }
public static function_node DeduceFunction(function_node func, expressions_list fact, bool alone, location loc, List<SyntaxTree.expression> syntax_nodes_parameters = null) { parameter_list formal = func.parameters; int formal_count = formal.Count; int fact_count = fact.Count; int generic_type_params_count = func.generic_parameters_count; type_node[] deduced = new type_node[generic_type_params_count]; List<int> nils = new List<int>(); int count_params_to_see = fact_count; var lambda_syntax_nodes = new Dictionary<string, function_lambda_definition>(); //lroman Получим список фактических параметров-лямбд текущей вызываемой подпрограммы if (syntax_nodes_parameters != null && syntax_nodes_parameters.Count > 0) //lroman { lambda_syntax_nodes = syntax_nodes_parameters .OfType<function_lambda_definition>() .ToDictionary(f => f.lambda_name, f => f); } var lambda_in_parameters = lambda_syntax_nodes.Count > 0; var saved_lambdas_states = SaveLambdasStates(lambda_syntax_nodes.Select(ld => ld.Value)); // Сохраним типы лямбды перед вычислениями if (fact_count < formal_count) { //Сравниваем количества параметров parameter par = formal[fact_count]; if (par.default_value == null && !par.is_params) { if (alone) throw new NoFunctionWithSameParametresNum(loc, alone, func); return null; } } else { type_node last_params_type = null; bool last_is_params = false; parameter par = null; if (formal_count > 0) { par = formal[formal_count - 1]; last_is_params = par.is_params; } if (last_is_params) { array_internal_interface aii = par.type.get_internal_interface(internal_interface_kind.unsized_array_interface) as array_internal_interface; last_params_type = aii.element_type; } if (fact_count > formal_count) { //Фактических больше, чем формальных. Последний формальный должен быть params... if (last_is_params) { for (int i = formal_count - 1; i < fact_count; ++i) { //Проверяем фактические, попадающие под params... if (!DeduceInstanceTypes(last_params_type, fact[i].type, deduced, nils)) { if (alone) throw new SimpleSemanticError(loc, "GENERIC_FUNCTION_{0}_CAN_NOT_BE_CALLED_WITH_THESE_PARAMETERS", func.name); return null; } } count_params_to_see = formal_count - 1; } else { if (alone) throw new NoFunctionWithSameParametresNum(loc, alone, func); return null; } } } bool need_params_work = (count_params_to_see > 0 && formal[count_params_to_see - 1].is_params); if (need_params_work) { count_params_to_see -= 1; } var continue_trying_to_infer_types = true; Dictionary<string, delegate_internal_interface> formal_delegates = null; while (continue_trying_to_infer_types) //Продолжаем пытаться вычислить типы до тех пор пока состояние о выведенных типах не будет отличаться от состояния на предыдущей итерации { var previous_deduce_state = deduced // Текущее состояние выведенных на данный момент типов. Простой список индексов с уже выведенными типами из массива deduced .Select((t, i) => new { Type = t, Index = i }) .Where(t => t.Type != null) .Select(t => t.Index) .ToArray(); for (int i = 0; i < count_params_to_see; ++i) { if (!DeduceInstanceTypes(formal[i].type, fact[i].type, deduced, nils)) { if (alone) throw new SimpleSemanticError(loc, "GENERIC_FUNCTION_{0}_CAN_NOT_BE_CALLED_WITH_THESE_PARAMETERS", func.name); RestoreLambdasStates(lambda_syntax_nodes.Values.ToList(), saved_lambdas_states); return null; } } if (lambda_in_parameters) { if (formal_delegates == null) { formal_delegates = new Dictionary<string, delegate_internal_interface>(); for (int i = 0; i < count_params_to_see; ++i) //Выделим из формальных параметров те, которые соотвтествуют фактическим параметрам-лямбдам { var lambda_func = fact[i].type as delegated_methods; if (lambda_func != null && lambda_func.proper_methods.Count == 1 && LambdaHelper.IsLambdaName(lambda_func.proper_methods[0].simple_function_node.name)) { formal_delegates.Add(LambdaHelper.GetLambdaNamePartWithoutGenerics(lambda_func.proper_methods[0].simple_function_node.name), formal[i].type.get_internal_interface( internal_interface_kind.delegate_interface) as delegate_internal_interface); } } } foreach (var formal_delegate in formal_delegates) //Перебираем все полученные формальные параемтры, соотвтетсвующие фактическим лямбдам { var lambda_syntax_node = lambda_syntax_nodes[formal_delegate.Key]; Exception on_lambda_body_compile_exception; // Исключение которое может возникунть в результате компиляции тела лямбды если мы выберем неправильные типы параметров if (!TryToDeduceTypesInLambda(lambda_syntax_node, formal_delegate.Value, deduced, nils, out on_lambda_body_compile_exception)) //Пробуем вычислить типы из лямбд { RestoreLambdasStates(lambda_syntax_nodes.Values.ToList(), saved_lambdas_states); if (on_lambda_body_compile_exception != null) { if (alone) { throw on_lambda_body_compile_exception; } throw new FailedWhileTryingToCompileLambdaBodyWithGivenParametersException( on_lambda_body_compile_exception); } if (alone) { throw new SimpleSemanticError(loc, "GENERIC_FUNCTION_{0}_CAN_NOT_BE_CALLED_WITH_THESE_PARAMETERS", func.name); } return null; } } } var current_deduce_state = deduced //текущее состояние выведенных типов .Select((t, ii) => new {Type = t, Index = ii}) .Where(t => t.Type != null) .Select(t => t.Index) .ToArray(); if (previous_deduce_state.SequenceEqual(current_deduce_state)) // Если ничего с прошлой итерации не изменилось, то дальше нет смысла пробовать выводить. Выходим из цикла { continue_trying_to_infer_types = false; } } RestoreLambdasStates(lambda_syntax_nodes.Values.ToList(), saved_lambdas_states); if (need_params_work) { type_node[] tmp_deduced = (type_node[])deduced.Clone(); List<int> tmp_nils = new List<int>(); tmp_nils.AddRange(nils); if (!DeduceInstanceTypes(formal[count_params_to_see].type, fact[count_params_to_see].type, deduced, nils)) { //Второй шанс. Учитываем слово params. deduced = tmp_deduced; nils = tmp_nils; if (!DeduceInstanceTypes(formal[count_params_to_see].type.element_type, fact[count_params_to_see].type, deduced, nils)) { if (alone) throw new SimpleSemanticError(loc, "GENERIC_FUNCTION_{0}_CAN_NOT_BE_CALLED_WITH_THESE_PARAMETERS", func.name); return null; } } } //Вывели всё, что могли. Теперь проверяем. for (int i = 0; i < generic_type_params_count; ++i) { if (deduced[i] == null) { if (alone) throw new SimpleSemanticError(loc, "CAN_NOT_DEDUCE_TYPE_PARAMS_FROM_CALL_{0}", func.name); return null; } } foreach (int num in nils) { if (!type_table.is_with_nil_allowed(deduced[num])) { if (alone) throw new SimpleSemanticError(loc, "GENERIC_FUNCTION_{0}_CAN_NOT_BE_CALLED_WITH_THESE_PARAMETERS", func.name); return null; } } foreach (type_node tt in deduced) { CompilationErrorWithLocation check_err = generic_parameter_eliminations.check_type_generic_useful(tt, loc); if (check_err != null) { if (alone) throw check_err; return null; } } //Итак, вывели все параметры. Теперь инстанцируем. List<type_node> deduced_list = new List<type_node>(generic_type_params_count); deduced_list.AddRange(deduced); return func.get_instance(deduced_list, alone, loc); }
public void Build(string text) { if (text == null) { throw new ArgumentNullException("text"); } this._Root = null; var frequencies = new Dictionary<char, int>(); this._Codes.Clear(); foreach (var t in text) { int frequency; if (frequencies.TryGetValue(t, out frequency) == false) { frequency = 0; } frequencies[t] = frequency + 1; } var nodes = frequencies.Select( symbol => new Node() { Symbol = symbol.Key, Frequency = symbol.Value, }).ToList(); while (nodes.Count > 1) { var orderedNodes = nodes .OrderBy(n => n.Frequency).ToList(); if (orderedNodes.Count >= 2) { var taken = orderedNodes.Take(2).ToArray(); var first = taken[0]; var second = taken[1]; var parent = new Node() { Symbol = '\0', Frequency = first.Frequency + second.Frequency, Left = first, Right = second, }; nodes.Remove(first); nodes.Remove(second); nodes.Add(parent); } this._Root = nodes.FirstOrDefault(); } foreach (var frequency in frequencies) { var bits = Traverse(this._Root, frequency.Key, new List<bool>()); if (bits == null) { throw new InvalidOperationException(string.Format( "could not traverse '{0}'", frequency.Key)); } this._Codes.Add(frequency.Key, new BitArray(bits.ToArray())); } this.TotalBits = GetTotalBits(this._Root); }
private static string DictToString(Dictionary<string, object> dict) { var res = string.Join("; ", dict.Select( p => string.Format( "{0}, {1}" , p.Key , p.Value != null ? p.Value.ToString() : "" ) ).ToArray()); return res.ToString (); }