public static IYubicoResponse Validate(IEnumerable<string> urls, string userAgent) { var tasks = new List<Task<IYubicoResponse>>(); var cancellation = new CancellationTokenSource(); foreach (var url in urls) { var thisUrl = url; var task = new Task<IYubicoResponse>(() => DoVerify(thisUrl, userAgent), cancellation.Token); task.ContinueWith(t => { }, TaskContinuationOptions.OnlyOnFaulted); tasks.Add(task); task.Start(); } while (tasks.Count != 0) { // TODO: handle exceptions from the verify task. Better to be able to propagate cause for error. var completed = Task.WaitAny(tasks.Cast<Task>().ToArray()); var task = tasks[completed]; tasks.Remove(task); if (task.Result != null) { cancellation.Cancel(); return task.Result; } } return null; }
public void TwoListsHaveDifferentOrder() { var a = new List<int> { 1, 2, 3 }; var b = new List<int> { 2, 3, 1 }; var c = new List<int> { 1, 3, 2 }; var calculator = new NetDiff.DiffCalculator(); var result = calculator.DiffList( baseObj: a.Cast<object>(), antagonist: b.Cast<object>()); var secondResult = calculator.DiffList( baseObj: a.Cast<object>(), antagonist: c.Cast<object>()); Assert.Equal( expected: 3, actual: result.Count(n => n.Message.Equals(DiffMessage.DiffersInOrder))); Assert.Equal( expected: 2, actual: secondResult.Count(n => n.Message.Equals(DiffMessage.DiffersInOrder))); Assert.Equal( expected: 1, actual: secondResult.Count(n => n.Message.Equals(DiffMessage.NotApplicable))); }
private Delegate CreateActionDelegate(MethodInfo method) { List<ParameterExpression> parameters = new List<ParameterExpression>(); foreach (ParameterInfo parameterInfo in method.GetParameters()) { parameters.Add(Expression.Parameter(parameterInfo.ParameterType, parameterInfo.Name)); } LambdaExpression lambda; if (method.IsStatic) { lambda = Expression.Lambda( GetActionType(parameters.Select(p => p.Type).ToArray()), Expression.Call(method, parameters.Cast<Expression>().ToArray()), parameters.ToArray()); } else { Type bindingType = method.DeclaringType; Expression<Func<object>> getInstanceExpression = () => ScenarioContext.Current.GetBindingInstance(bindingType); lambda = Expression.Lambda( GetActionType(parameters.Select(p => p.Type).ToArray()), Expression.Call( Expression.Convert(getInstanceExpression.Body, bindingType), method, parameters.Cast<Expression>().ToArray()), parameters.ToArray()); } return lambda.Compile(); }
public static IEnumerable<IEmployee> GenerateEmployees() { var random = new Random(); var employees = new List<IEmployee>(); var sales = new List<ISale>(); sales.Add(new Sale("CPU", DateTime.Now.AddDays(1), (decimal)random.NextDouble() * 1000)); sales.Add(new Sale("RAM", DateTime.Now.AddDays(2), (decimal)random.NextDouble() * 1000)); sales.Add(new Sale("GPU", DateTime.Now.AddDays(3), (decimal)random.NextDouble() * 1000)); employees.Add(new Customer(1, "Alex", "Alex", random.Next(100, 5000), Department.Sales, 2312313123M)); employees.Add(new SalesEmployee(1, "Dimitar", "Dimitrov", random.Next(100, 5000), Department.Sales, sales.ToArray())); employees.Add(new SalesEmployee(2, "Chavdar", "Chavdarov", random.Next(100, 5000), Department.Marketing, sales.ToArray())); employees.Add(new SalesEmployee(3, "Qvor", "Qvorov", random.Next(100, 5000), Department.Production, sales.Take(2).ToArray())); employees.Add(new Developer(4, "Lazar", "Lazarov", random.Next(100, 5000), Department.Accounting, new Project("Homework", DateTime.Now.AddDays(1)))); employees.Add(new Developer(5, "Atanas", "Atanasov", random.Next(100, 5000), Department.Marketing, new Project("Homework", DateTime.Now.AddDays(2)))); employees.Add(new Developer(6, "Kolio", "Nikolov", random.Next(100, 5000), Department.Production, new Project("Homework", DateTime.Now.AddDays(3)))); employees.Add(new Manager(7, "Ivan", "Ivanov", random.Next(100, 5000), Department.Sales, employees.Cast<Employee>().Where(x => x.Department == Department.Sales).ToArray())); employees.Add(new Manager(8, "Stoqn", "Stoqnov", random.Next(100, 5000), Department.Marketing, employees.Cast<Employee>().Where(x => x.Department == Department.Marketing).ToArray())); employees.Add(new Manager(9, "Petar", "Petrov", random.Next(100, 5000), Department.Accounting, employees.Cast<Employee>().Where(x => x.Department == Department.Accounting).ToArray())); return employees; }
public double Calc(List<double> ls1, List<double> ls2) { if (ls1.Count == 0 || ls2.Count == 0) //check for empty list throw new Exception("One of the list is empty!"); //length is adjusted in the same length if (ls1.Count != ls2.Count) { int min = Math.Min(ls1.Count, ls2.Count); ls1 = ls1.Take(min).ToList(); ls2 = ls2.Take(min).ToList(); } var av1 = ls1.Cast<double>().Average(); var av2 = ls2.Cast<double>().Average(); var allav = ls1.Cast<double>().Zip(ls2.Cast<double>(), (a, b) => (a - av1) * (b - av2)); var allsum = allav.Sum(); var sum1 = ls1.Cast<double>().Sum(p => Math.Pow((p - av1), 2.0)); var sum2 = ls2.Cast<double>().Sum(p => Math.Pow((p - av2), 2.0)); return allsum / Math.Sqrt(sum1 * sum2); }
/// <summary> /// Matches the cards. /// </summary> /// <param name="octgnGame">The octgn game.</param> /// <param name="cardModels">The card models.</param> /// <param name="octgnCards">The octgn cards.</param> /// <param name="parsedCards">The parsed cards.</param> /// <returns>A collectoin of matched cards.</returns> /// <exception cref="System.InvalidOperationException"> /// This exception will be thrown when cards cannot be matched. /// </exception> public static IEnumerable<IWrappedMultiCard> MatchCards( Game octgnGame, IEnumerable<ICard> cardModels, IEnumerable<CardData> octgnCards, IEnumerable<CardData> parsedCards) { var result = new List<IWrappedMultiCard>(); var errorCards = new StringBuilder(); foreach (var parsedCard in parsedCards) { var trimmedName = parsedCard.Name.Trim(); var found = octgnCards.FirstOrDefault(c => c.Name.Trim().Equals(trimmedName, StringComparison.OrdinalIgnoreCase)); if (found == null) { errorCards.AppendLine(parsedCard.Name); } else { var card = cardModels.FirstOrDefault(c => c.Id.ToString().Equals(found.Id)); result.Add(new WrappedMultiCard(parsedCard.Count, card)); } } var numberOfCards = result.Sum(c => c.Quantity); // Subtract the heroic task and its support card which is put aside at the beginning of the game var singleQuest = result.Any(c => c.Name.ToUpperInvariant() == "HEROIC TASK"); if (singleQuest) { numberOfCards -= 2; } foreach (var multiCard in result.Cast<WrappedMultiCard>()) { multiCard.TotalDeckSize = numberOfCards; } if (!string.IsNullOrEmpty(errorCards.ToString())) { var details = new InvalidOperationException(Localization.ErrorCannotFindCards + Environment.NewLine + errorCards.ToString()); details.Data.Add("Cards", result); throw details; } return result.Cast<WrappedMultiCard>().OrderBy(c => c.InvasionCardTypeOrder).ThenBy(c => c.Name).ToArray(); }
public void CreateAreaListFromAreaTypeId(int profileId, int areaTypeId) { if (areaTypeId > NeighbourAreaType.IdAddition) //TODO: need to remove this { IList<Area> areas = new List<Area> { new Area{Name = "DUMMY AREA", ShortName = "DUMMY AREA", Code = "DUMMY"} }; Areas = areas.Cast<IArea>().ToList(); } else if (areaTypeId > CategoryAreaType.IdAddition) { // e.g All categories for a category type int categoryTypeId = CategoryAreaType.GetCategoryTypeIdFromAreaTypeId(areaTypeId); Areas = areasReader.GetCategories(categoryTypeId) .Select(CategoryArea.New).Cast<IArea>().ToList(); } else { IList<string> parentCodes = areasReader.GetProfileParentAreaCodes(profileId, areaTypeId); IList<Area> areas = parentCodes.Any() ? areasReader.GetAreasFromCodes(parentCodes) : areasReader.GetAreasByAreaTypeId(areaTypeId); Areas = areas.Cast<IArea>().ToList(); } }
public IsoJsonResult CreateNotes(JsonNote [] notes) { bool fromCache = notes != null && notes.Length > 0; var newNotesNumber = fromCache ? notes.Length : 1; List <Note> newNotes = new List<Note>(); for(ushort i = 0; i < newNotesNumber; i++) { Note newNote = new Note { ID = Guid.NewGuid().ToString(), UserId = User.Identity.GetUserId(), CreationDate = fromCache ? notes[i].CreationDate : DateTime.Now, Content = fromCache ? notes[i].Content : "" }; newNotes.Add(newNote); db.Notes.Add(newNote); } db.SaveChanges(); var generatedJsonEntities = EntityToJsonModelConverter.Convert(newNotes.Cast<BaseDbEntity>().ToList()); return new IsoJsonResult() { Data = generatedJsonEntities, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; }
public void testMultiShape(SpatialContext ctx) { this.ctx = ctx; if(ctx.IsGeo()) return;//TODO not yet supported! //come up with some random shapes int NUM_SHAPES = random.Next(1, 5); var shapes = new List<Rectangle>(NUM_SHAPES); while (shapes.Count < NUM_SHAPES) { shapes.Add(RandomRectangle(20)); } var multiShape = new MultiShape(shapes.Cast<Shape>(), ctx); //test multiShape.getBoundingBox(); Rectangle msBbox = multiShape.GetBoundingBox(); if (shapes.Count == 1) { Assert.Equal(shapes[0], msBbox.GetBoundingBox()); } else { foreach (Rectangle shape in shapes) { AssertRelation("bbox contains shape", SpatialRelation.CONTAINS, msBbox, shape); } } //TODO test multiShape.relate() }
internal string GestioneRicerca(string user) { sqlop = new SqlOperations(); sqlop.databaseConnection = ConfigurationManager.ConnectionStrings["cs"].ToString(); SqlCommandObject sco = new SqlCommandObject(); DbParameter[] dbp = new DbParameter[2]; dbp[0] = new SqlParameter(); dbp[0].ParameterName = "Utente"; dbp[0].DbType = DbType.String; dbp[0].Direction = ParameterDirection.Input; dbp[0].Value = user; dbp[1] = new SqlParameter(); dbp[1].ParameterName = "Ricerca"; dbp[1].DbType = DbType.Xml; dbp[1].Direction = ParameterDirection.Output; sco.SPParams = dbp; sco.SPName = "[Utility].[SP_ArchivioRicerca_Get]"; DataTable dt; List<ExpandoObject> outputList = new List<ExpandoObject>(); string proc = sqlop.ExecuteProcedure(sco, out dt, out outputList); IEnumerable<dynamic> Ricerca = outputList.Cast<dynamic>().Where(x => x.Nome.Contains("@Ricerca")); return Convert.ToString(Ricerca.First().Value); }
public Reference(int rowNum, IEnumerable<ReferenceFields> order, IEnumerable<string> values) { if (values.IsNullOrEmpty()) throw new ArgumentException("values"); if (order.IsNullOrEmpty()) throw new ArgumentException("order"); RowNum = rowNum; var vs = values.ToArray(); var fs = order.ToArray(); if (vs.Length != fs.Length) throw new InvalidOperationException(); var fillErrors = new List<ReferenceFields>(); for (var i = 0; i < vs.Length; i++) { try { SetValue(fs[i], vs[i]); } catch { fillErrors.Add(fs[i]); } } if (fillErrors.Any()) { throw new Exception("Error reading following fields: {0}". Fill(fillErrors.Cast<String>().CommaSeparated())); } }
/// <summary> /// Get all saved events for a specific aggregate. /// Beware: events are referenced directly, do not manipulate them. /// </summary> /// <param name="aggregateId">Aggregate Id</param> /// <typeparam name="TAggregateId">Aggregate id type</typeparam> /// <returns>Reference to all events for the given aggregate</returns> public IReadOnlyList <DomainEvent <TAggregateId> > GetEventsFor <TAggregateId>(TAggregateId aggregateId) where TAggregateId : AggregateId { List <IDomainEvent> events = null; this.lookup.TryGetValue(aggregateId, out events); return(events?.Cast <DomainEvent <TAggregateId> >()?.ToList()); }
//Func Desc: Used to map all objects in a list to an object of type destination type. // Input: List<object> of objects to perform mapping on, dest_type indicating the objects // to which each object in the list will be converted. // Output: List<object> of objects after mapping, or null public IEnumerable<object> MapAll(IEnumerable<object> source_list, Type dest_type) { //Input checks if (source_list == null) { return null; } if (source_list.ToList().Count == 0) { return null; } //Create local var to store object type Type source_type = source_list.ElementAt(0).GetType(); //Local declarations List<object> dest_list = new List<object>(); IEnumerable<object> dest_enum; //Perform mapping for each domain model foreach (var dom_model in source_list) { //Map domain model and then add it to destination list dest_list.Add( Map(dom_model, source_type, dest_type) ); } dest_enum = dest_list.Cast<object>().AsEnumerable(); //Return list of mapped objects return dest_enum; }
public BindingResult Bind(Type type, string name, string value, IRequest request, object owner) { var bindingErrors = new List<BindingError>(); var innerType = GetEnumerableInnerType(type); var list = new List<object>(); var innerBinder = BinderCollection.FindBinderFor(null, innerType, request, owner); var stringValue = value; if (!string.IsNullOrEmpty(stringValue)) { var strings = stringValue.Split(innerType == typeof(string) ? '\n' : ','); foreach (var str in strings) { var bound = innerBinder.Bind(innerType, name, str, request, owner); if (bound.BoundSuccessfully) list.Add(bound.Result); else bindingErrors.AddRange(bound.BindingErrors); } } var enumerable = list.Cast(innerType); return new BindingResult(enumerable, bindingErrors.ToArray()); }
protected override object[] Refresh() { var paths = new List<string>(); Guid hidGuid; NativeMethods.HidD_GetHidGuid(out hidGuid); NativeMethods.HDEVINFO devInfo = NativeMethods.SetupDiGetClassDevs(hidGuid, null, IntPtr.Zero, /*NativeMethods.DIGCF.AllClasses |*/ NativeMethods.DIGCF.DeviceInterface | NativeMethods.DIGCF.Present); if (devInfo.IsValid) { try { NativeMethods.SP_DEVICE_INTERFACE_DATA did = new NativeMethods.SP_DEVICE_INTERFACE_DATA(); did.Size = Marshal.SizeOf(did); for (int i = 0; NativeMethods.SetupDiEnumDeviceInterfaces(devInfo, IntPtr.Zero, hidGuid, i, ref did); i ++) { NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA didetail = new NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA(); didetail.Size = IntPtr.Size == 8 ? 8 : (4 + Marshal.SystemDefaultCharSize); if (NativeMethods.SetupDiGetDeviceInterfaceDetail(devInfo, ref did, ref didetail, Marshal.SizeOf(didetail) - (int)Marshal.OffsetOf(didetail.GetType(), "DevicePath"), IntPtr.Zero, IntPtr.Zero)) { paths.Add(didetail.DevicePath); } } } finally { NativeMethods.SetupDiDestroyDeviceInfoList(devInfo); } } return paths.Cast<object>().ToArray(); }
/***************************************************/ public static IEnumerable <IBHoMObject> FromRevit(this RoofBase roofBase, Discipline discipline, Transform transform = null, RevitSettings settings = null, Dictionary <string, List <IBHoMObject> > refObjects = null) { IEnumerable <IElement2D> result = null; switch (discipline) { case Discipline.Environmental: result = roofBase.EnvironmentPanelsFromRevit(settings, refObjects); break; case Discipline.Structural: result = roofBase.StructuralPanelsFromRevit(settings, refObjects); break; case Discipline.Facade: case Discipline.Architecture: case Discipline.Physical: result = new List <IElement2D> { roofBase.RoofFromRevit(settings, refObjects) }; break; } if (result != null && transform?.IsIdentity == false) { TransformMatrix bHoMTransform = transform.FromRevit(); result = result.Select(x => x.ITransform(bHoMTransform)); } return(result?.Cast <IBHoMObject>().ToList()); }
public ui.TextStyle getTextStyle(float textScaleFactor = 1.0f) { var backgroundPaint = new Paint(); if (background != null) { backgroundPaint = new Paint(); backgroundPaint.color = backgroundColor; } return(new ui.TextStyle( color: color, decoration: decoration, decorationColor: decorationColor, decorationStyle: decorationStyle, decorationThickness: decorationThickness, fontWeight: fontWeight, fontStyle: fontStyle, textBaseline: textBaseline, fontFamily: fontFamily, fontFamilyFallback: fontFamilyFallback, fontSize == null ? null : fontSize * textScaleFactor, letterSpacing: letterSpacing, wordSpacing: wordSpacing, height: height, // locale: locale, foreground: foreground, background: background ?? (backgroundColor != null ? backgroundPaint : null ), shadows: shadows?.Cast <Shadow>().ToList(), fontFeatures: fontFeatures )); }
public static Action<string, object[]> GetAssertMethodWithFormattedMessage(string assemblyName, string typeName, string methodName) { Assembly msTestAssembly = Assembly.Load(assemblyName); Type assertType = msTestAssembly.GetType(typeName, true); MethodInfo method = assertType.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(string), typeof(object[]) }, null); if (method == null) throw new SpecFlowException("Assert method not found: " + methodName); List<ParameterExpression> parameters = new List<ParameterExpression>(); foreach (ParameterInfo parameterInfo in method.GetParameters()) { parameters.Add(Expression.Parameter(parameterInfo.ParameterType, parameterInfo.Name)); } var lambda = Expression.Lambda<Action<string, object[]>>( Expression.Call(method, parameters.Cast<Expression>().ToArray()), parameters.ToArray()); #if WINDOWS_PHONE return ExpressionCompiler.ExpressionCompiler.Compile(lambda) as Action<string, object[]>; #else return lambda.Compile(); #endif }
public void SelectElementsASTGeneration() { var refPoints = new List<ReferencePoint>(); using (var trans = new Transaction(DocumentManager.Instance.CurrentDBDocument, "Create some ReferencePoints")) { trans.Start(); FailureHandlingOptions fails = trans.GetFailureHandlingOptions(); fails.SetClearAfterRollback(true); trans.SetFailureHandlingOptions(fails); refPoints.Add(DocumentManager.Instance.CurrentDBDocument.FamilyCreate.NewReferencePoint(new XYZ(0,0,0))); refPoints.Add(DocumentManager.Instance.CurrentDBDocument.FamilyCreate.NewReferencePoint(new XYZ(0,0,1))); refPoints.Add(DocumentManager.Instance.CurrentDBDocument.FamilyCreate.NewReferencePoint(new XYZ(0,0,2))); trans.Commit(); } var sel = new DSModelElementsSelection { SelectedElement = refPoints.Cast<Element>().Select(x => x.UniqueId).ToList() }; var buildOutput = sel.BuildOutputAst(new List<AssociativeNode>()); var funCall = (ExprListNode)((BinaryExpressionNode)buildOutput.First()).RightNode; Assert.AreEqual(funCall.list.Count, 3); Assert.Inconclusive("Need more robust testing here."); }
public LuaDropDown(List<string> items) : base() { Items.AddRange(items.Cast<object>().ToArray()); SelectedIndex = 0; DropDownStyle = ComboBoxStyle.DropDownList; }
/// <summary> /// Возвращает алфавит, использованный в списке операций для машины Тьюринга. /// </summary> /// <param name="operations">Список операций для машины Тьюринга.</param> /// <returns>Алфавит.</returns> public static SymbolSet GetAlphabet(List<Operation> operations) { List<TuringOperation> ops = operations.Cast<TuringOperation>().ToList(); SymbolSet result = new SymbolSet(); int i, j, n, m; n = ops.Count; for(i = 0; i < n; i++) { m = ops[i].State.Converts.Length; for(j = 0; j < m; j++) { try { AddChars(result, ops[i].State.Converts[j].Input); AddChars(result, ops[i].State.Converts[j].Output); } catch { throw new Exception("Размер алфавита операций превысил допустимое значение"); } } } return result; }
public IEnumerable<GuestRoomListing> GetGuestRoomListings(string categoryID, int maximumAmount = 30) { HabboDistributor habboDistributor = CoreManager.ServerCore.GetHabboDistributor(); List<int> loadedRoomIDs = new List<int>(); // TODO: Dusokay current rooms using (ISession db = CoreManager.ServerCore.GetDatabaseSession()) { IList<Room> rooms = db.CreateCriteria<Room>() .Add(Restrictions.Eq("category_id", categoryID)) .Add( new NotExpression( new InExpression("room_id", loadedRoomIDs.Cast<object>().ToArray()))) .AddOrder(Order.Desc("last_entry")) .SetMaxResults(maximumAmount - loadedRoomIDs.Count) .List<Room>(); foreach (Room room in rooms) { yield return new GuestRoomListing { ID = room.room_id, Name = room.name, Description = room.description, Owner = habboDistributor.GetHabbo(room.owner_id), // TODO: Other values Population = 0 // If people were inside it would already be loaded. }; } } }
public static CodeItem Create(FileCodeModel2 codeModel) { var list = new List<CodeElement2>(); CollectElements(list, codeModel.CodeElements, new [] { vsCMElement.vsCMElementClass }); if (list.Count == 0) { return new OtherItem("Unknow", null); } var item = list.Cast<CodeClass>().First(); if (item.IsDerivedFrom["MavenThought.Commons.Testing.BaseTest"]) { if (item.Name.Contains("Specification")) { return new SpecificationItem(item.Name, item.Namespace.Name, item.FullName, item.ProjectItem); } var spec = (CodeClass)item.Bases.Cast<CodeElement>().First(ce => ce is CodeClass); var spItem = new SpecificationItem(spec.Name, spec.Namespace.Name, spec.FullName, item.ProjectItem); return new SenarioItem(item.Name, item.Namespace.Name, item.FullName, spItem, item.ProjectItem); } return new ClassItem(item.Name, item.Namespace.Name, item.FullName, item.ProjectItem); }
private static IEnumerable<object[]> GetFilesPerTest(IList<string> tests, IList<string> skips = null) { var files = TestDocuments; if (tests == null) { yield return new object[0]; yield break; } if (skips == null) skips = new string[0]; foreach (var file in files) { var filenames = new List<string>(); var ok = false; foreach (var ext in tests) { if (!file.Value.Contains(ext)) { ok = false; break; } filenames.Add(Path.Combine("Data", file.Key + ext)); ok = true; } if (ok && !skips.Any(skip => file.Value.Contains(skip))) yield return filenames.Cast<object>().ToArray(); } }
public void SetCameraModels(List<string> cameras, string selectedCamera, string videoStandard) { cbxCameras.Items.Clear(); string videoStandardNameChunk = string.Concat("(", videoStandard, ")"); if (!string.IsNullOrEmpty(videoStandard)) cbxCameras.Items.AddRange(cameras.Where(x => x.Contains(videoStandardNameChunk)).Cast<object>().ToArray()); if (cbxCameras.Items.Count == 0) cbxCameras.Items.AddRange(cameras.Cast<object>().ToArray()); // First look for exact match string cameraToSelect = cameras.FirstOrDefault(x => x.Replace(" ", "").Equals(selectedCamera.Replace(" ", ""), StringComparison.InvariantCultureIgnoreCase) && x.Contains(videoStandardNameChunk)); if (cameraToSelect == null) // Then do a 'starts with' search cameraToSelect = cameras.FirstOrDefault(x => x.Replace(" ", "").Contains(selectedCamera.Replace(" ", "")) && x.Contains(videoStandardNameChunk)); if (cameraToSelect != null) { cbxCameras.SelectedIndex = cbxCameras.Items.IndexOf(cameraToSelect); rbCorrect.Checked = true; } else rbDontCorrect.Checked = true; }
protected override object[] Refresh() { var paths = new List<NativeMethods.io_string_t>(); var matching = NativeMethods.IOServiceMatching("IOHIDDevice").ToCFType(); // Consumed by IOServiceGetMatchingServices, so DON'T Dispose(). if (matching.IsSet) { int iteratorObj; if (NativeMethods.IOReturn.Success == NativeMethods.IOServiceGetMatchingServices(0, matching, out iteratorObj)) { using (var iterator = iteratorObj.ToIOObject()) { while (true) { using (var handle = NativeMethods.IOIteratorNext(iterator).ToIOObject()) { if (!handle.IsSet) { break; } NativeMethods.io_string_t path; if (NativeMethods.IOReturn.Success == NativeMethods.IORegistryEntryGetPath(handle, "IOService", out path)) { paths.Add(path); } } } } } } return paths.Cast<object>().ToArray(); }
protected BaseModel(SerializationInfo info, StreamingContext context) { Version = info.GetInt16("version"); IEnumerable<FieldInfo> fields = GetType() .GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) .Where(p => p.GetCustomAttribute(typeof (Versioning)) != null); IList<PropertyInfo> props = new List<PropertyInfo>( GetType() .GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) .Where(p => p.GetCustomAttribute(typeof (Versioning)) != null)); IEnumerable<MemberInfo> propsAndFields = props.Cast<MemberInfo>().Union(fields).ToList(); foreach (SerializationEntry entry in info) { MemberInfo prop = propsAndFields.FirstOrDefault( p => ((Versioning) p.GetCustomAttribute(typeof (Versioning))).Name == entry.Name); if (prop != null) { var fieldInfo = prop as FieldInfo; if (fieldInfo != null) { fieldInfo.SetValue(this, entry.Value); } else { ((PropertyInfo) prop).SetValue(this, entry.Value); } } } IEnumerable<MemberInfo> notSetProps = propsAndFields.Where(p => ((Versioning) p.GetCustomAttribute(typeof (Versioning))).Version > Version); foreach (MemberInfo notSet in notSetProps) { var ver = (Versioning) notSet.GetCustomAttribute(typeof (Versioning)); if (ver.AutoGenerated) { var set = notSet as FieldInfo; if (set != null) { set.SetValue(this, ver.DefaultValue); } else { ((PropertyInfo) notSet).SetValue(this, ver.DefaultValue); } } } }
public FrmSolutions(List<string> items) { InitializeComponent(); this.listBox1.Items.AddRange(items.Cast<object>().ToArray()); SelectIndex = -1; }
public virtual void Init() { InitializeComponent(); _themes = _themeService.GetThemes(); this.themeCheckBoxList.Items.AddRange(_themes.Cast<object>().ToArray()); }
public AggregateCommit(IAggregateRootId aggregateId, int revision, List<IEvent> events) { AggregateRootId = aggregateId.RawId; BoundedContext = aggregateId.GetType().GetBoundedContext().BoundedContextName; Revision = revision; InternalEvents = events.Cast<object>().ToList(); Timestamp = DateTime.UtcNow.ToFileTimeUtc(); }
public Divert (Parsed.Path target, List<Expression> arguments = null) { this.target = target; this.arguments = arguments; if (arguments != null) { AddContent (arguments.Cast<Parsed.Object> ().ToList ()); } }
public static IDisposable Create(Func<IDictionary<string, object>, Task> app, IDictionary<string, object> properties) { if (app == null) { throw new ArgumentNullException("app"); } if (properties == null) { throw new ArgumentNullException("properties"); } var capabilities = properties.Get<IDictionary<string, object>>(OwinKeys.ServerCapabilitiesKey) ?? new Dictionary<string, object>(); var addresses = properties.Get<IList<IDictionary<string, object>>>("host.Addresses") ?? new List<IDictionary<string, object>>(); var servers = new List<INowinServer>(); var endpoints = new List<IPEndPoint>(); foreach (var address in addresses) { var builder = ServerBuilder.New().SetOwinApp(app); int port; if (!int.TryParse(address.Get<string>("port"), out port)) throw new ArgumentException("port must be number from 0 to 65535"); builder.SetPort(port); builder.SetOwinCapabilities(capabilities); var certificate = address.Get<X509Certificate>("certificate"); if (certificate != null) builder.SetCertificate(certificate); servers.Add(builder.Build()); endpoints.Add(new IPEndPoint(IPAddress.Loopback,port)); } var disposer = new Disposer(servers.Cast<IDisposable>().ToArray()); try { foreach (var nowinServer in servers) { nowinServer.Start(); } // This is workaround to Windows Server 2012 issue by calling ReadLine after AcceptAsync, by making one bogus connection this problem goes away foreach (var ipEndPoint in endpoints) { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); socket.Connect(ipEndPoint); socket.Close(); } } catch (Exception) { disposer.Dispose(); throw; } return disposer; }
static void Main(string[] args) { List<Student> students = new List<Student>(); List<Worker> workers = new List<Worker>(); students.Add(new Student("Matey", "Mihaylov", 11453)); students.Add(new Student("Yasen", "Asenov", 91453)); students.Add(new Student("Todor", "Yasenov", 81453)); students.Add(new Student("Zdravko", "Todorov", 13453)); students.Add(new Student("Mihayl", "Zdravkov", 150453)); students.Add(new Student("Asen", "Vanev", 167453)); students.Add(new Student("Iliana", "Mihaylov", 065453)); students.Add(new Student("Polina", "Vaneva", 114453)); students.Add(new Student("Marta", "Genkova", 404453)); students.Add(new Student("Teodora", "Mihaylova", 156453)); students.Add(new Student("Denica", "Genkova", 124453)); students.Add(new Student("Ioana", "Todorova", 1113453)); workers.Add(new Worker("Matey", "Mihaylov", 24.5f,2000)); workers.Add(new Worker("Yasen", "Asenov", 60,90453)); workers.Add(new Worker("Todor", "Yasenov",12, 453)); workers.Add(new Worker("Zdravko", "Todorov", 80, 6453)); workers.Add(new Worker("Mihayl", "Zdravkov", 100,50453)); workers.Add(new Worker("Asen", "Vanev", 14,6453)); workers.Add(new Worker("Iliana", "Mihaylov",25.4f, 65453)); workers.Add(new Worker("Polina", "Vaneva", 35.5f, 1453)); workers.Add(new Worker("Marta", "Genkova", 40,4453)); workers.Add(new Worker("Teodora", "Mihaylova",30,5453)); workers.Add(new Worker("Denica", "Genkova", 2,53)); workers.Add(new Worker("Ioana", "Todorova",10,3453)); var orderedStudents = students.OrderBy(s => s.FacultyNumber); var orderedWorkers = workers.Select(s => new { worker = s, salary = s.MoneyPerHour()}).OrderByDescending(s => s.salary); var orderedHumans = students.Cast<Human>().Concat(workers).OrderBy(s => s.FirstName).ThenBy(s => s.LastName); Console.WriteLine("Students ----------------"); foreach (var student in orderedStudents) { Console.WriteLine(student); Console.WriteLine(); } Console.WriteLine("Workers ----------------"); foreach (var worker in orderedWorkers) { Console.WriteLine(worker.worker); Console.WriteLine("Money per hour: {0:C}",worker.salary); Console.WriteLine(); } Console.WriteLine("Workers/Students Sorted----"); foreach (var orderedHuman in orderedHumans) { Console.WriteLine(orderedHuman.FirstName + " " + orderedHuman.LastName); Console.WriteLine(); } }
public static IEnumerable <IBHoMObject> FromRevit(this Autodesk.Revit.DB.Plumbing.Pipe pipe, Discipline discipline, Transform transform = null, RevitSettings settings = null, Dictionary <string, List <IBHoMObject> > refObjects = null) { IEnumerable <IElement1D> result = null; switch (discipline) { case Discipline.Architecture: case Discipline.Physical: case Discipline.Environmental: result = new List <IElement1D>(pipe.PipeFromRevit(settings, refObjects)); break; } if (result != null && transform?.IsIdentity == false) { TransformMatrix bHoMTransform = transform.FromRevit(); result = result.Select(x => x.ITransform(bHoMTransform)); } return(result?.Cast <IBHoMObject>().ToList()); }
private Task <List <CurrencyRate> > GetCurrencies(int page, int pageSize) { return(Task.Run(() => _model?.Cast <CurrencyRate>().Skip((page - 1) * pageSize).Take(pageSize).ToList())); }
private static Point FindPointInPolygon(List <Vertex> contour, int limit, double eps) { var bounds = new Rectangle(); bounds.Expand(contour.Cast <Point>()); int length = contour.Count; var test = new Point(); Point a, b, c; // Current corner points. double bx, by; double dx, dy; double h; var predicates = new RobustPredicates(); a = contour[0]; b = contour[1]; for (int i = 0; i < length; i++) { c = contour[(i + 2) % length]; // Corner point. bx = b.x; by = b.y; // NOTE: if we knew the contour points were in counterclockwise order, we // could skip concave corners and search only in one direction. h = predicates.CounterClockwise(a, b, c); if (Math.Abs(h) < eps) { // Points are nearly co-linear. Use perpendicular direction. dx = (c.y - a.y) / 2; dy = (a.x - c.x) / 2; } else { // Direction [midpoint(a-c) -> corner point] dx = (a.x + c.x) / 2 - bx; dy = (a.y + c.y) / 2 - by; } // Move around the contour. a = b; b = c; h = 1.0; for (int j = 0; j < limit; j++) { // Search in direction. test.x = bx + dx * h; test.y = by + dy * h; if (bounds.Contains(test) && IsPointInPolygon(test, contour)) { return(test); } // Search in opposite direction (see NOTE above). test.x = bx - dx * h; test.y = by - dy * h; if (bounds.Contains(test) && IsPointInPolygon(test, contour)) { return(test); } h = h / 2; } } throw new Exception(); }
/// <summary> /// Salva os dados /// </summary> public void SalvarDados() { var exportador = FactoryExportar.RetornarExportador(EnumTipoExportacao.Csv, "clientes"); exportador.Exportar(Clientes.Cast <IExportarDados>().ToList()); }
//public static string[] words; static void Main(string[] args) { //Title and User input of file string title = "Welcome to Dr. L.J.'s Feedscrew Program Editor!"; Console.SetCursorPosition((Console.WindowWidth - title.Length) / 2, Console.CursorTop); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(title + '\n'); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("For all your editing needs, simply type in the name of the feedscrew file"); Console.Write("without the extension"); Console.ForegroundColor = ConsoleColor.Red; Console.Write(" (For example: W12345-1)"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(@" and I'll make your problems go away..."); Console.Write("\nName of Feedscrew file: "); string inputfile = Console.ReadLine(); //Open .RNC file and Check for Legitimacy try { logfile = File.ReadAllText(inputfile + ".RNC"); } catch (Exception) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error Opening File! :("); } //Open .ARC file and replaces stuff with new commands string core = inputfile.Substring(3, 3); string mpfcore = inputfile.Substring(2, 4); string outputfile = inputfile + ".ARC"; List <string> lines = logfile.Split('\n').ToList(); List <string> words = new List <string>(); List <List <string> > wordlist = new List <List <string> >(); List <string> test = new List <string>(); for (int i = 0; i < lines.Count; i++) { words = lines[i].Split(' ').ToList(); for (int j = 0; j < words.Count; j++) { //Simple replace whole word words[j] = words[j].Replace("M17", "RET"); words[j] = words[j].Replace("G59", "ATRANS"); words[j] = words[j].Replace("@714", "STOPRE"); words[j] = words[j].Replace("L101", "L" + core + "1"); words[j] = words[j].Replace("L102", "L" + core + "2"); words[j] = words[j].Replace("L103", "L" + core + "3"); words[j] = words[j].Replace("L104", "L" + core + "4"); words[j] = words[j].Replace("L105", "L" + core + "5"); words[j] = words[j].Replace("L106", "L" + core + "6"); words[j] = words[j].Replace("%SPF101", "%_N_L" + core + "1_SPF"); words[j] = words[j].Replace("%SPF102", "%_N_L" + core + "2_SPF"); words[j] = words[j].Replace("%SPF103", "%_N_L" + core + "3_SPF"); words[j] = words[j].Replace("%SPF104", "%_N_L" + core + "4_SPF"); words[j] = words[j].Replace("%SPF105", "%_N_L" + core + "5_SPF"); words[j] = words[j].Replace("%SPF106", "%_N_L" + core + "6_SPF"); words[j] = words[j].Replace("%MPF" + mpfcore, "%_N_MPF" + mpfcore + "_SPF"); } wordlist.Add(words); } // Print 2D list to .arc file using (StreamWriter writer = new StreamWriter(outputfile, false)) { for (int i = 0; i < wordlist.Count; i++) { List <string> line = wordlist[i].S writer.WriteLine(line.Cast <string>()); } } // File.WriteAllLines(outputfile, wordlist.SelectMany(x=>x)); // for (int lineIndex = 0; lineIndex < lines.Count; lineIndex++) // { // for (int charIndex = 0; charIndex < lines[lineIndex].Length; charIndex++) // { // //Moving words on to new line or moving somewhere else. // // if (words[lineIndex, charIndex] == "S1=R4") // { // words[i + 1].Add("N99910 S=R4"); // } // } // } //Reconstruct 2D list into string array and Write to file. // string[] newlines = new string[lines.Count]; // for (int i = 0; i < words.Count; i++) // { // for (int j = 0; j < words[i].Count; j++) // { // newlines[i] += words[i][j] + ((i == words.Count - 1) ? "" : " "); // } // } // File.WriteAllLines(outputfile, newlines); //File.WriteAllLines(outputfile, words.SelectMany(x => x)); //File.WriteAllLines(outputfile, lines); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("\nAnnnnd it's gone!"); //Thread.Sleep(1500); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("\nYou're .RNC file..."); //Thread.Sleep(1500); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("\nIt's gone!"); //Thread.Sleep(1500); Console.ReadKey(); }
public NeuraliumTransactionValidationResult(ValidationResults result, List <NeuraliumTransactionValidationErrorCode> errorCodes) : base(result, errorCodes?.Cast <EventValidationErrorCode>().ToList()) { }
static void Main(string[] args) { List <Student> students = new List <Student> { new Student { Name = "Nastya", Age = 30, IsMarried = true, Profession = Student.Professions.Teacher, Marks = new Byte[] { 10, 8, 7, 11, 3, 8, 11, 12 } }, new Student { Name = "Nastya", Age = 30, IsMarried = true, Profession = Student.Professions.Teacher, Marks = new Byte[] { 10, 8, 7, 11, 3, 8, 11, 12 } }, new Student { Name = "Nastya", Age = 30, IsMarried = true, Profession = Student.Professions.Teacher, Marks = new Byte[] { 10, 8, 7, 11, 3, 8, 11, 12 } }, new Student { Name = "Ira", Age = 18, IsMarried = false, Profession = Student.Professions.Doctor, Marks = new Byte[] { 6, 8, 7, 2, 3, 8, 6, 3 } }, new Student { Name = "Dima", Age = 34, IsMarried = true, Profession = Student.Professions.Programmer, Marks = new Byte[] { 10, 12, 12, 11, 12, 12, 11, 12 } }, new Student { Name = "Timur", Age = 25, IsMarried = false, Profession = Student.Professions.Tester, Marks = new Byte[] { 7, 8, 7, 7, 7, 8, 7, 7 } }, new Student { Name = "Kolya", Age = 23, IsMarried = true, Profession = Student.Professions.Doctor, Marks = new Byte[] { 5, 5, 5, 3, 3, 5, 5, 5 } }, new Student { Name = "Oleg", Age = 31, IsMarried = true, Profession = Student.Professions.Tester, Marks = new Byte[] { 9, 9, 9, 7, 9, 8, 9, 9 } }, new Student { Name = "Sergey", Age = 29, IsMarried = true, Profession = Student.Professions.Programmer, Marks = new Byte[] { 11, 11, 11, 11, 11, 8, 11, 11 } } }; List <Student> students1 = new List <Student> { new Student { Name = "Roma", Age = 30, IsMarried = true, Profession = Student.Professions.Teacher, Marks = new Byte[] { 10, 8, 7, 11, 3, 8, 11, 12 } }, new Student { Name = "Garic", Age = 18, IsMarried = false, Profession = Student.Professions.Doctor, Marks = new Byte[] { 6, 8, 7, 2, 3, 8, 6, 3 } }, new Student { Name = "Lyosha", Age = 34, IsMarried = true, Profession = Student.Professions.Programmer, Marks = new Byte[] { 10, 12, 12, 11, 12, 12, 11, 12 } }, new Student { Name = "Timur", Age = 25, IsMarried = false, Profession = Student.Professions.Tester, Marks = new Byte[] { 7, 8, 7, 7, 7, 8, 7, 7 } }, new Student { Name = "Tom", Age = 23, IsMarried = true, Profession = Student.Professions.Doctor, Marks = new Byte[] { 5, 5, 5, 3, 3, 5, 5, 5 } }, new Student { Name = "Oleg", Age = 31, IsMarried = true, Profession = Student.Professions.Tester, Marks = new Byte[] { 9, 9, 9, 7, 9, 8, 9, 9 } }, new Student { Name = "Sergey", Age = 29, IsMarried = true, Profession = Student.Professions.Programmer, Marks = new Byte[] { 11, 11, 11, 11, 11, 8, 11, 11 } } }; List <Student> students2 = new List <Student> { new Student { Name = "Roma", Age = 30, IsMarried = true, Profession = Student.Professions.Teacher, Marks = new Byte[] { 10, 8, 7, 11, 3, 8, 11, 12 } }, new Student { Name = "Garic1", Age = 18, IsMarried = false, Profession = Student.Professions.Doctor, Marks = new Byte[] { 6, 8, 7, 2, 3, 8, 6, 3 } }, new Student { Name = "Lyosha1", Age = 34, IsMarried = true, Profession = Student.Professions.Programmer, Marks = new Byte[] { 10, 12, 12, 11, 12, 12, 11, 12 } }, new Student { Name = "Timur1", Age = 25, IsMarried = false, Profession = Student.Professions.Tester, Marks = new Byte[] { 7, 8, 7, 7, 7, 8, 7, 7 } }, new Student { Name = "tom1", Age = 23, IsMarried = true, Profession = Student.Professions.Doctor, Marks = new Byte[] { 5, 5, 5, 3, 3, 5, 5, 5 } }, new Student { Name = "Oleg1", Age = 31, IsMarried = true, Profession = Student.Professions.Tester, Marks = new Byte[] { 9, 9, 9, 7, 9, 8, 9, 9 } }, new Student { Name = "Sergey1", Age = 29, IsMarried = true, Profession = Student.Professions.Programmer, Marks = new Byte[] { 11, 11, 11, 11, 11, 8, 11, 11 } } }; //1. Выбрать всех по имени Dima. var result = students.Where(s => s.Name == "Dima"); foreach (var item in result) { Console.WriteLine(item); } //2. Выбрать всех в возрасте от 24 до 30. var result2 = students.Where(s => s.Age > 24 && s.Age < 30); foreach (var item in result2) { Console.WriteLine(item); } ////3. Выбрать всех, у кого оценки не ниже 7 баллов по //профессии тестировщик. var result3 = students.Where (s => s.Profession == Student.Professions.Tester && s.Marks.Min() >= 7).OrderBy(p => p.Name).OrderByDescending(d => d.Age). Select(s => $"{s.Name}{s.Age}{s.Profession}"); //Linque только он организует коллекцию IEnumerable Console.WriteLine(students.All(s => s is IDisposable)); Console.WriteLine(students.Any(s => s.Age == 35)); //Cast приводит к IEnumerable IEnumerable <ISome> somes = students.Cast <ISome>(); foreach (var item in result3) { Console.WriteLine(item); } //4. Объединить две последовательности. //объединит две коллекции студентов в одну коллекцию var concat = students.Concat(students1); var union = students.Union(students1); //5. Определить, содержит ли последовательность указанный элемент. concat.Contains(new Student { Name = "Sergey", Age = 29, IsMarried = true, Profession = Student.Professions.Programmer, Marks = new byte[] { 11, 10, 12, 11, 10, 11, 10, 11 } }); Student st = new Student { Name = "Rammir", Age = 40, IsMarried = false, Profession = Student.Professions.Engineer, Marks = new byte[] { 6, 8, 9, 7, 6, 5, 8, 9, 12 } }; //вот здесь он присоединит все в большую коллекции List <Student> contains = concat.ToList(); contains.Add(st); Console.WriteLine(contains.Contains(st)); //7.Получить число элементов, удовлетворяющих заданному условию. Console.WriteLine(concat.Count(s => s.Name == "Nastya")); //8. Убрать из последовательности все повторяющиеся элементы. Console.WriteLine($"Убрать из последовательности все повторяющиеся элементы."); var distinct = concat.Distinct(new StudentComparer()); foreach (var item in distinct) { Console.WriteLine(item); } //9. Вернуть элемент по указанному индексу в последовательности. Console.WriteLine(distinct.ElementAt(1)); //10. Вернуть элемент по указанному индексу в последовательности или значение по умолчанию, если индекс вне допустимого диапазона. Student student23 = distinct.ElementAtOrDefault(1); Console.WriteLine(student23 != null ? student23.ToString():"Student null"); //11. Получить все элементы первой последовательности, которых нет во второй. Console.WriteLine($"Получить все элементы первой последовательности, которых нет во второй."); var except = distinct.Except(students2); foreach (var item in except) { Console.WriteLine(item); } //12. Получить первый элемент последовательности, который удовлетворяет указанному условию. //здесь опасно!!! здесь если не находит, то выбрасывает исключение //поэтому для них нужно делать трай кетч Console.WriteLine(distinct.First(s => s.Name == "Tom")); try { Console.WriteLine(distinct.First(s => s.Name == "fds")); } catch { } //13.Получить первый элемент последовательности или значение по умолчанию, если последовательность не содержит элементов. Console.WriteLine($"13. Получить первый элемент последовательности или значение по умолчанию, если последовательность не содержит элементов."); Student student = distinct.FirstOrDefault(s => s.Name == "Oleg"); if (student != null) { Console.WriteLine(student); } //14. Получить группу студентов, которые женаты. Console.WriteLine($"14. Получить группу студентов, которые женаты."); IEnumerable <IGrouping <bool, Student> > groupBy = distinct.GroupBy(s => s.IsMarried); foreach (IGrouping <bool, Student> item in groupBy) { Console.WriteLine(item.Key); foreach (Student value in item) { //Console.WriteLine($"{value.Name}"); //или Console.WriteLine(value.ToString()); } } //15. Получить элементы - общие для двух последовательностей (пересечение множеств, представленных двумя последовательностями). var intersect = concat.Intersect(students1); Console.WriteLine($"15. Получить элементы - общие для двух последовательностей" + $" (пересечение множеств, представленных двумя последовательностями)."); foreach (var item in intersect) { Console.WriteLine(item); } Console.ReadLine(); }
public void GoogleSearchAPI() { #region GoogleJson string json = @"{ results: [ { GsearchResultClass:""GwebSearch"", unescapedUrl : ""http://www.google.com/"", url : ""http://www.google.com/"", visibleUrl : ""www.google.com"", cacheUrl : ""http://www.google.com/search?q=cache:zhool8dxBV4J:www.google.com"", title : ""Google"", titleNoFormatting : ""Google"", content : ""Enables users to search the Web, Usenet, and images. Features include PageRank, caching and translation of results, and an option to find similar pages."" }, { GsearchResultClass:""GwebSearch"", unescapedUrl : ""http://news.google.com/"", url : ""http://news.google.com/"", visibleUrl : ""news.google.com"", cacheUrl : ""http://www.google.com/search?q=cache:Va_XShOz_twJ:news.google.com"", title : ""Google News"", titleNoFormatting : ""Google News"", content : ""Aggregated headlines and a search engine of many of the world's news sources."" }, { GsearchResultClass:""GwebSearch"", unescapedUrl : ""http://groups.google.com/"", url : ""http://groups.google.com/"", visibleUrl : ""groups.google.com"", cacheUrl : ""http://www.google.com/search?q=cache:x2uPD3hfkn0J:groups.google.com"", title : ""Google Groups"", titleNoFormatting : ""Google Groups"", content : ""Enables users to search and browse the Usenet archives which consist of over 700 million messages, and post new comments."" }, { GsearchResultClass:""GwebSearch"", unescapedUrl : ""http://maps.google.com/"", url : ""http://maps.google.com/"", visibleUrl : ""maps.google.com"", cacheUrl : ""http://www.google.com/search?q=cache:dkf5u2twBXIJ:maps.google.com"", title : ""Google Maps"", titleNoFormatting : ""Google Maps"", content : ""Provides directions, interactive maps, and satellite/aerial imagery of the United States. Can also search by keyword such as type of business."" } ], adResults: [ { GsearchResultClass:""GwebSearch.ad"", title : ""Gartner Symposium/ITxpo"", content1 : ""Meet brilliant Gartner IT analysts"", content2 : ""20-23 May 2007- Barcelona, Spain"", url : ""http://www.google.com/url?sa=L&ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB&num=1&q=http://www.gartner.com/it/sym/2007/spr8/spr8.jsp%3Fsrc%3D_spain_07_%26WT.srch%3D1&usg=__CxRH06E4Xvm9Muq13S4MgMtnziY="", impressionUrl : ""http://www.google.com/uds/css/ad-indicator-on.gif?ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB"", unescapedUrl : ""http://www.google.com/url?sa=L&ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB&num=1&q=http://www.gartner.com/it/sym/2007/spr8/spr8.jsp%3Fsrc%3D_spain_07_%26WT.srch%3D1&usg=__CxRH06E4Xvm9Muq13S4MgMtnziY="", visibleUrl : ""www.gartner.com"" } ] } "; #endregion JObject o = JObject.Parse(json); List <JObject> resultObjects = o["results"].Children <JObject>().ToList(); Assert.AreEqual(32, resultObjects.Properties().Count()); Assert.AreEqual(32, resultObjects.Cast <JToken>().Values().Count()); Assert.AreEqual(4, resultObjects.Cast <JToken>().Values("GsearchResultClass").Count()); Assert.AreEqual(5, o.PropertyValues().Cast <JArray>().Children().Count()); List <string> resultUrls = o["results"].Children().Values <string>("url").ToList(); List <string> expectedUrls = new List <string>() { "http://www.google.com/", "http://news.google.com/", "http://groups.google.com/", "http://maps.google.com/" }; CollectionAssert.AreEqual(expectedUrls, resultUrls); List <JToken> descendants = o.Descendants().ToList(); Assert.AreEqual(89, descendants.Count); }
static List <int> SetDim(List <object> dimVal) { return(dimVal?.Cast <int>().ToList()); }
protected void InstallInstallers( List <InstallerBase> normalInstallers, List <Type> normalInstallerTypes, List <ScriptableObjectInstaller> scriptableObjectInstallers, List <MonoInstaller> installers, List <MonoInstaller> installerPrefabs) { CheckInstallerPrefabTypes(installers, installerPrefabs); // Ideally we would just have one flat list of all the installers // since that way the user has complete control over the order, but // that's not possible since Unity does not allow serializing lists of interfaces // (and it has to be an inteface since the scriptable object installers only share // the interface) // // So the best we can do is have a hard-coded order in terms of the installer type // // The order is: // - Normal installers given directly via code // - ScriptableObject installers // - MonoInstallers in the scene // - Prefab Installers // // We put ScriptableObject installers before the MonoInstallers because // ScriptableObjectInstallers are often used for settings (including settings // that are injected into other installers like MonoInstallers) var allInstallers = normalInstallers.Cast <IInstaller>() .Concat(scriptableObjectInstallers.Cast <IInstaller>()) .Concat(installers.Cast <IInstaller>()).ToList(); foreach (var installerPrefab in installerPrefabs) { Assert.IsNotNull(installerPrefab, "Found null installer prefab in '{0}'", GetType()); GameObject installerGameObject; #if ZEN_INTERNAL_PROFILING using (ProfileTimers.CreateTimedBlock("GameObject.Instantiate")) #endif { installerGameObject = GameObject.Instantiate(installerPrefab.gameObject); } installerGameObject.transform.SetParent(transform, false); var installer = installerGameObject.GetComponent <MonoInstaller>(); Assert.IsNotNull(installer, "Could not find installer component on prefab '{0}'", installerPrefab.name); allInstallers.Add(installer); } foreach (var installerType in normalInstallerTypes) { var installer = (InstallerBase)Container.Instantiate(installerType); #if ZEN_INTERNAL_PROFILING using (ProfileTimers.CreateTimedBlock("User Code")) #endif { installer.InstallBindings(); } } foreach (var installer in allInstallers) { Assert.IsNotNull(installer, "Found null installer in '{0}'", GetType()); Container.Inject(installer); #if ZEN_INTERNAL_PROFILING using (ProfileTimers.CreateTimedBlock("User Code")) #endif { installer.InstallBindings(); } } }
/// <summary> /// The method has been created for returning the value for Grasshopper and Dynamo. /// The method can still be use for C# users. /// </summary> public static Dictionary <string, object> DeconstructShellInternalForce(List <FemDesign.Results.ShellInternalForce> Result, string LoadCase) { var shellForces = Result.Cast <FemDesign.Results.ShellInternalForce>(); // Return the unique load case - load combination var uniqueLoadCases = shellForces.Select(n => n.CaseIdentifier).Distinct().ToList(); // Select the Nodal Displacement for the selected Load Case - Load Combination if (uniqueLoadCases.Contains(LoadCase, StringComparer.OrdinalIgnoreCase)) { shellForces = shellForces.Where(n => String.Equals(n.CaseIdentifier, LoadCase, StringComparison.OrdinalIgnoreCase)); } else { var warning = $"Load Case '{LoadCase}' does not exist"; throw new ArgumentException(warning); } // Parse Results from the object var identifier = new List <string>(); var elementId = new List <int>(); var nodeId = new List <int?>(); var mx = new List <double>(); var my = new List <double>(); var mxy = new List <double>(); var nx = new List <double>(); var ny = new List <double>(); var nxy = new List <double>(); var txz = new List <double>(); var tyz = new List <double>(); var uniqueLoadCase = shellForces.Select(n => n.CaseIdentifier).Distinct().ToList(); foreach (var shellResult in shellForces) { // FemDesign Return a value in the center of the shell // The output is not necessary in this case as the user can compute the value // doing an average. if (shellResult.NodeId != null) { identifier.Add(shellResult.Id); elementId.Add(shellResult.ElementId); nodeId.Add(shellResult.NodeId); mx.Add(shellResult.Mx); my.Add(shellResult.My); mxy.Add(shellResult.Mxy); nx.Add(shellResult.Nx); ny.Add(shellResult.Ny); nxy.Add(shellResult.Nxy); txz.Add(shellResult.Txz); tyz.Add(shellResult.Tyz); } } return(new Dictionary <string, dynamic> { { "CaseIdentifier", uniqueLoadCase }, { "Identifier", identifier }, { "ElementId", elementId }, { "NodeId", nodeId }, { "Mx", mx }, { "My", my }, { "Mxy", mxy }, { "Nx", nx }, { "Ny", ny }, { "Nxy", nxy }, { "Txz", txz }, { "Tyz", tyz }, }); }
/// <summary> /// For every vertex in the vertexIdSet, retrieve their spilled edge documents to construct their forward or backward /// adjacency list. /// When connection.useReverseEdge is false, this method will retrieve all the forward edge documents whose sink /// is the target vertex to build a virtual reverse adjacency list. /// </summary> /// <param name="connection"></param> /// <param name="vertexIdSet"></param> public static void ConstructSpilledAdjListsOrVirtualRevAdjListsOfVertices(GraphViewConnection connection, HashSet <string> vertexIdSet) { if (!vertexIdSet.Any()) { return; } string inClause = string.Join(", ", vertexIdSet.Select(vertexId => $"'{vertexId}'")); string edgeDocumentsQuery = $"SELECT * " + $"FROM edgeDoc " + $"WHERE edgeDoc.{KW_EDGEDOC_VERTEXID} IN ({inClause})"; List <dynamic> edgeDocuments = connection.ExecuteQuery(edgeDocumentsQuery).ToList(); // Dictionary<vertexId, Dictionary<edgeDocumentId, edgeDocument>> Dictionary <string, Dictionary <string, JObject> > edgeDict = new Dictionary <string, Dictionary <string, JObject> >(); foreach (JObject edgeDocument in edgeDocuments) { // Save edgeDocument's etag if necessary connection.VertexCache.SaveCurrentEtagNoOverride(edgeDocument); } EdgeDocumentHelper.FillEdgeDict(edgeDict, edgeDocuments); // // Use all edges whose sink is vertexId to construct a virtual reverse adjacency list of this vertex // if (!connection.UseReverseEdges) { edgeDocumentsQuery = $"SELECT {{" + $" \"{EdgeDocumentHelper.VirtualReverseEdgeObject}\": edge, " + $" \"{KW_EDGE_SRCV}\": doc.{KW_DOC_ID}, " + $" \"{KW_EDGE_SRCV_LABEL}\": doc.{KW_EDGE_SRCV_LABEL}," + $" \"{KW_EDGEDOC_VERTEXID}\": doc.{KW_EDGEDOC_VERTEXID}" + $"}} AS {EdgeDocumentHelper.VirtualReverseEdge}\n" + $"FROM doc\n" + $"JOIN edge IN doc.{GraphViewKeywords.KW_VERTEX_EDGE}\n" + $"WHERE edge.{KW_EDGE_SINKV} IN ({inClause})"; edgeDocuments = connection.ExecuteQuery(edgeDocumentsQuery).ToList(); Dictionary <string, string> labelOfSrcVertexOfSpilledEdges = EdgeDocumentHelper.GetLabelOfSrcVertexOfSpilledEdges(connection, edgeDocuments); List <JObject> virtualReverseEdgeDocuments = EdgeDocumentHelper.ConstructVirtualReverseEdgeDocuments(edgeDocuments, labelOfSrcVertexOfSpilledEdges); EdgeDocumentHelper.FillEdgeDict(edgeDict, virtualReverseEdgeDocuments.Cast <dynamic>().ToList()); } foreach (KeyValuePair <string, Dictionary <string, JObject> > pair in edgeDict) { string vertexId = pair.Key; Dictionary <string, JObject> edgeDocDict = pair.Value; // contains both in & out edges VertexField vertexField; connection.VertexCache.TryGetVertexField(vertexId, out vertexField); vertexField.ConstructSpilledOrVirtualAdjacencyListField(edgeDocDict); vertexIdSet.Remove(vertexId); } foreach (string vertexId in vertexIdSet) { VertexField vertexField; connection.VertexCache.TryGetVertexField(vertexId, out vertexField); vertexField.ConstructSpilledOrVirtualAdjacencyListField(new Dictionary <string, JObject>()); } }
private static void Optimize(Yield[] yields) { var clock = Stopwatch.StartNew(); var context = SolverContext.GetContext(); context.ClearModel(); var model = context.CreateModel(); Console.WriteLine($"Solver-Clean/Create model={clock.ElapsedMilliseconds}"); var initialValue = yields[0].SpotMtm; var fwds = new List <Term>(); var forwards = new Term[yields.Length]; for (var i = 1; i < forwards.Length; i++) { if (yields[i].IsSameForward) { forwards[i] = forwards[i - 1]; } else { if (i == 1 && yields[i].YieldType == YieldType.DI1) { initialValue = yields[i].YieldType == YieldType.DI1 ? yields[i].SpotMtm : initialValue; forwards[i] = yields[i].SpotMtm; } else { initialValue = yields[i].YieldType == YieldType.DI1 ? yields[i].SpotMtm : initialValue; var decision = new Decision(Domain.RealNonnegative, null); decision.SetInitialValue(initialValue); forwards[i] = decision; fwds.Add(decision); model.AddDecision(decision); } } } var spotFactor = (Term)1d; var erro = (Term)0d; var forward = forwards.First(t => !Equals(t, null)); int j = 1; while (Equals(forwards[j], null)) { forwards[j++] = forward; } for (var i = 1; i < forwards.Length; i++) { var termDelta = yields[i].Term - yields[i - 1].Term; var forwardFactor = Microsoft.SolverFoundation.Services.Model.Power(1d + forwards[i] / 100d, termDelta / 252d); spotFactor *= forwardFactor; if (yields[i].YieldType != YieldType.DI1) { continue; } erro += Microsoft.SolverFoundation.Services.Model.Abs(yields[i].SpotMtmFactor - spotFactor) * 1000; } var erroGoal = model.AddGoal( "erro", GoalKind.Minimize, erro); Console.WriteLine($"Solver-create goal={clock.ElapsedMilliseconds}"); context.Solve(); Console.WriteLine($"Solver-solve={clock.ElapsedMilliseconds}"); foreach (var fwd in fwds.Cast <Decision>()) { fwd.SetInitialValue(fwd.GetDouble()); } var diff1 = new Term[fwds.Count - 1]; for (var i = 1; i <= diff1.Length; i++) { diff1[i - 1] = fwds[i] - fwds[i - 1]; } var diff2 = new Term[diff1.Length - 1]; for (var i = 1; i <= diff2.Length; i++) { diff2[i - 1] = diff1[i] - diff1[i - 1]; } for (var i = 1; i < diff2.Length; i++) { erro += Microsoft.SolverFoundation.Services.Model.Abs(diff2[i] - diff2[i - 1]); } model.RemoveGoals(erroGoal); model.AddGoal( "erro", GoalKind.Minimize, erro); Console.WriteLine($"Solver-create goal={clock.ElapsedMilliseconds}"); var solution = context.Solve(); clock.Stop(); Console.WriteLine($"Solver-solve={clock.ElapsedMilliseconds}"); var spotfactor = 1d; for (var i = 1; i < forwards.Length; i++) { if (yields[i].IsSameForward) { yields[i].Forward = yields[i - 1].Forward; } else if (i == 1 && yields[i].YieldType == YieldType.DI1) { yields[i].Forward = yields[i].SpotMtm; } else { yields[i].Forward = ((Decision)forwards[i]).GetDouble(); } spotfactor *= Math.Pow(1d + yields[i].Forward / 100, (yields[i].Term - yields[i - 1].Term) / 252); yields[i].SpotFactor = spotfactor; yields[i].Spot = (Math.Pow(spotfactor, 252d / yields[i].Term) - 1d) * 100d; yields[i].Bump = yields[i].Forward - yields[i - 1].Forward; } }
/// <inheritdoc cref="IMessagesSource.GetMessages" /> public IEnumerable <object>?GetMessages() => _events?.Cast <object>();
static void Main(string[] args) { List <Worker> workersList = new List <Worker>(); Worker w1 = new Worker("George", "Peterson", 280, 10); workersList.Add(w1); Worker w2 = new Worker("John", "Hamilton", 310, 12); workersList.Add(w2); Worker w3 = new Worker("Dave", "Maynard", 290, 11); workersList.Add(w3); Worker w4 = new Worker("Lloyd", "Mathinson", 310, 12); workersList.Add(w4); Worker w5 = new Worker("Gary", "Robinson", 400, 13); workersList.Add(w5); Worker w6 = new Worker("Douglas", "Harbin", 330, 12); workersList.Add(w6); Worker w7 = new Worker("Kenneth", "Hart", 320, 11); workersList.Add(w7); Worker w8 = new Worker("Denis", "Remy", 310, 11); workersList.Add(w8); Worker w9 = new Worker("Ken", "Copeland", 300, 11); workersList.Add(w9); Worker w10 = new Worker("Marilyn", "Chambers", 300, 10); workersList.Add(w10); List <Student> studentsList = new List <Student>(); Student s1 = new Student("William", "Matthers", 8); studentsList.Add(s1); Student s2 = new Student("Dan", "Smith", 7); studentsList.Add(s2); Student s3 = new Student("Rebecca", "Crowley", 9); studentsList.Add(s3); Student s4 = new Student("Keith", "Workman", 10); studentsList.Add(s4); Student s5 = new Student("Adrianna", "Avila", 6); studentsList.Add(s5); Student s6 = new Student("Carl", "Rayburn", 5); studentsList.Add(s6); Student s7 = new Student("Roger", "Le", 7); studentsList.Add(s7); Student s8 = new Student("Marvin", "Daniels", 9); studentsList.Add(s8); Student s9 = new Student("George", "Moore", 10); studentsList.Add(s9); Student s10 = new Student("Anne", "Delaney", 8); studentsList.Add(s10); Console.WriteLine("The students are the following:"); PrintAllTheStudents(studentsList); Console.WriteLine(); Console.WriteLine("The workers are the following:"); PrintAllTheWorkers(workersList); Console.WriteLine(); Console.WriteLine("The list of the students ordered ascending by their grades is:"); List <Student> orderedStudentsList = studentsList.OrderBy(student => student.Grade).ToList(); PrintAllTheStudents(orderedStudentsList); Console.WriteLine(); Console.WriteLine("The list of the workers ordered descending by their income per hour is:"); List <Worker> orderedWorkersList = workersList.OrderByDescending(worker => worker.MoneyPerHour()).ToList(); PrintAllTheWorkers(orderedWorkersList); Console.WriteLine(); Console.WriteLine("The list of the students and the list of the workers merged is:"); List <Human> humansList = studentsList.Cast <Human>().Concat(workersList).ToList(); PrintAllTheHumans(humansList); Console.WriteLine(); Console.WriteLine("The list of the students and the list of the workers merged and sorted by name is:"); List <Human> orderedHumansList = humansList.OrderBy(human => human.FirstName).ToList(); PrintAllTheHumans(orderedHumansList); Console.WriteLine(); }
public override int IndexOf(string parameterName) { var param = _list.Cast <DbParameter>().FirstOrDefault(p => p.ParameterName == parameterName); return(param == null ? -1 : _list.IndexOf(param)); }
public List <Entity> Upcast(List <Vehicle> entities) { return(entities.Cast <Entity>().ToList()); }
protected override bool TryExecuteWorker(IncidentParms parms) { Map map = (Map)parms.target; List <TargetInfo> list = new List <TargetInfo>(); List <Thing> list3 = ThingSetMakerDefOf.Meteorite.root.Generate(); ThingDef shipPartDef = def?.mechClusterBuilding; IntVec3 intVec = FindDropPodLocation(map, (IntVec3 spot) => CanPlaceAt(spot)); if (intVec == IntVec3.Invalid) { return(false); } float points = Mathf.Max(parms.points * 0.9f, 300f); List <Pawn> list2 = PawnGroupMakerUtility.GeneratePawns(new PawnGroupMakerParms { groupKind = PawnGroupKindDefOf.Combat, tile = map.Tile, faction = Faction.OfMechanoids, points = points }).ToList(); Thing thing = ThingMaker.MakeThing(shipPartDef); thing.SetFaction(Faction.OfMechanoids); LordMaker.MakeNewLord(Faction.OfMechanoids, new LordJob_SleepThenMechanoidsDefend(new List <Thing> { thing }, Faction.OfMechanoids, 28f, intVec, canAssaultColony: false, isMechCluster: false), map, list2); DropPodUtility.DropThingsNear(intVec, map, list2.Cast <Thing>()); foreach (Pawn item in list2) { item.TryGetComp <CompCanBeDormant>()?.ToSleep(); } list.AddRange(list2.Select((Pawn p) => new TargetInfo(p))); GenSpawn.Spawn(SkyfallerMaker.MakeSkyfaller(ThingDefOf.MeteoriteIncoming, thing), intVec, map); list.Add(new TargetInfo(intVec, map)); SendStandardLetter(parms, list); return(true); bool CanPlaceAt(IntVec3 loc) { CellRect cellRect = GenAdj.OccupiedRect(loc, Rot4.North, shipPartDef.Size); if (loc.Fogged(map) || !cellRect.InBounds(map)) { return(false); } if (!DropCellFinder.SkyfallerCanLandAt(loc, map, shipPartDef.Size)) { return(false); } foreach (IntVec3 item2 in cellRect) { RoofDef roof = item2.GetRoof(map); if (roof != null && roof.isNatural) { return(false); } } return(GenConstruct.CanBuildOnTerrain(shipPartDef, loc, map, Rot4.North)); } }
public override void Update(float deltaTime) { if (disallowed) { Finished(); return; } if (isFinished) { return; } if (spawnPos == null) { FindSpawnPosition(affectSubImmediately: true); spawnPending = true; } bool spawnReady = false; if (spawnPending) { //wait until there are no submarines at the spawnpos foreach (Submarine submarine in Submarine.Loaded) { if (submarine.Info.Type != SubmarineInfo.SubmarineType.Player) { continue; } float minDist = GetMinDistanceToSub(submarine); if (Vector2.DistanceSquared(submarine.WorldPosition, spawnPos.Value) < minDist * minDist) { return; } } //if spawning in a ruin/cave, wait for someone to be close to it to spawning //unnecessary monsters in places the players might never visit during the round if (spawnPosType == Level.PositionType.Ruin || spawnPosType == Level.PositionType.Cave || spawnPosType == Level.PositionType.Wreck) { bool someoneNearby = false; float minDist = Sonar.DefaultSonarRange * 0.8f; foreach (Submarine submarine in Submarine.Loaded) { if (submarine.Info.Type != SubmarineInfo.SubmarineType.Player) { continue; } if (Vector2.DistanceSquared(submarine.WorldPosition, spawnPos.Value) < minDist * minDist) { someoneNearby = true; break; } } foreach (Character c in Character.CharacterList) { if (c == Character.Controlled || c.IsRemotePlayer) { if (Vector2.DistanceSquared(c.WorldPosition, spawnPos.Value) < minDist * minDist) { someoneNearby = true; break; } } } if (!someoneNearby) { return; } } spawnPending = false; //+1 because Range returns an integer less than the max value int amount = Rand.Range(minAmount, maxAmount + 1); monsters = new List <Character>(); float offsetAmount = spawnPosType == Level.PositionType.MainPath ? 1000 : 100; for (int i = 0; i < amount; i++) { CoroutineManager.InvokeAfter(() => { //round ended before the coroutine finished if (GameMain.GameSession == null || Level.Loaded == null) { return; } System.Diagnostics.Debug.Assert(GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer, "Clients should not create monster events."); monsters.Add(Character.Create(speciesName, spawnPos.Value + Rand.Vector(offsetAmount), Level.Loaded.Seed + i.ToString(), null, false, true, true)); if (monsters.Count == amount) { spawnReady = true; //this will do nothing if the monsters have no swarm behavior defined, //otherwise it'll make the spawned characters act as a swarm SwarmBehavior.CreateSwarm(monsters.Cast <AICharacter>()); } }, Rand.Range(0f, amount / 2)); } } if (!spawnReady) { return; } Entity targetEntity = Submarine.FindClosest(GameMain.GameScreen.Cam.WorldViewCenter); #if CLIENT if (Character.Controlled != null) { targetEntity = Character.Controlled; } #endif bool monstersDead = true; foreach (Character monster in monsters) { if (!monster.IsDead) { monstersDead = false; if (targetEntity != null && Vector2.DistanceSquared(monster.WorldPosition, targetEntity.WorldPosition) < 5000.0f * 5000.0f) { break; } } } if (monstersDead) { Finished(); } }
private async void retrieveBackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { WebNovelSource selectedWebsite = null; string mode = string.Empty; string modeSelectedText = string.Empty; int amount = 0; Invoke((MethodInvoker) delegate { selectedWebsite = (WebNovelSource)websiteTypeComboBox.SelectedItem; mode = ((string)modeComboBox.SelectedItem).ToLower(); modeSelectedText = modeSelectedTextBox.Text; amount = (int)amountNumericUpDown.Value; }); if (!(modeSelectedText.StartsWith("http://") || modeSelectedText.StartsWith("https://"))) { modeSelectedText = "http://" + modeSelectedText; } WebNovelSource source = GetSource(modeSelectedText, selectedWebsite); WebNovelInfo novelInfo = await source.GetNovelInfoAsync(modeSelectedText); if (mode == "table of contents") { ChapterLink[] links = (await source.GetChapterLinksAsync(modeSelectedText)).ToArray(); Invoke((MethodInvoker) delegate { foreach (ChapterLink link in links) { if (link.Unknown) { unknownListBox.Items.Add(link); } else { chaptersListBox.Items.Add(link); } } if (novelInfo != null) { if (!string.IsNullOrEmpty(novelInfo.CoverUrl)) { try { string coverUrl = novelInfo.CoverUrl; coverUrl = coverUrl.StartsWith("//") ? coverUrl.Substring(2) : coverUrl; coverTextBox.Text = new UriBuilder(coverUrl).Uri.AbsoluteUri; } catch (UriFormatException) { } } if (!string.IsNullOrEmpty(novelInfo.Title)) { titleTextBox.Text = novelInfo.Title; } } progressBar.Visible = false; retrieveButton.Enabled = true; }); } else if (mode == "next chapter link") { ChapterLink firstChapter = new ChapterLink { Url = modeSelectedText }; ChapterLink current = firstChapter; int ctr = 1; var chapters = new List <WebNovelChapter>(); while (true) { WebNovelChapter chapter; try { chapter = await source.GetChapterAsync(current); } catch (HttpRequestException) { break; } if (chapter == null) { break; } if (string.IsNullOrEmpty(chapter.ChapterName)) { chapter.ChapterName = current.Url; } chapters.Add(chapter); WriteText($"Found Chapter {chapter.ChapterName}", Color.Green); if (string.IsNullOrEmpty(chapter.NextChapterUrl) || chapter.Url == chapter.NextChapterUrl) { break; } current = new ChapterLink { Url = chapter.NextChapterUrl }; if (ctr == amount) { break; } ctr++; } Invoke((MethodInvoker) delegate { chaptersListBox.Items.AddRange(chapters.Cast <object>().ToArray()); progressBar.Visible = false; retrieveButton.Enabled = true; }); } }
public static void SetObjectProperties(this OntologyResource resource, string propertyName, List <UriNode> nodes) { resource.SetProperties(propertyName, nodes?.Cast <INode>().ToList() ?? new List <INode>()); }
public override ICloudFileSystemEntry RequestResource(IStorageProviderSession session, string name, ICloudDirectoryEntry parent) { /* In this method name could be either requested resource name or it's ID. * In first case just refresh the parent and then search child with an appropriate. * In second case it does not matter if parent is null or not a parent because we use only resource ID. */ if (SkyDriveHelpers.HasResourceID(name) || name.Equals("/") && parent == null) //If request by ID or root folder requested { var id = SkyDriveHelpers.GetResourceID(name); var uri = id != string.Empty ? string.Format("{0}/{1}", SkyDriveConstants.BaseAccessUrl, id) : SkyDriveConstants.RootAccessUrl; if (SkyDriveHelpers.IsFolderID(id)) { var contents = new List <ICloudFileSystemEntry>(); /*var completeContent = new AutoResetEvent(false); * ThreadPool.QueueUserWorkItem(state => * { * contents.AddRange(RequestContentByUrl(session, uri + "/files")); * ((AutoResetEvent) state).Set(); * }, completeContent); * * var completeEntry = new AutoResetEvent(false); * ThreadPool.QueueUserWorkItem(state => * { * entry = RequestResourseByUrl(session, uri) as BaseDirectoryEntry; * ((AutoResetEvent) state).Set(); * }, completeEntry); * * WaitHandle.WaitAll(new WaitHandle[] {completeContent, completeEntry});*/ var entry = RequestResourseByUrl(session, uri) as BaseDirectoryEntry; contents.AddRange(RequestContentByUrl(session, uri + "/files")); if (entry != null && contents.Any()) { entry.AddChilds(contents.Cast <BaseFileEntry>()); } return(entry); } return(RequestResourseByUrl(session, uri)); } else { string uri; if (SkyDriveHelpers.HasParentID(name)) { uri = string.Format(SkyDriveConstants.FilesAccessUrlFormat, SkyDriveHelpers.GetParentID(name)); } else if (parent != null) { uri = string.Format(SkyDriveConstants.FilesAccessUrlFormat, parent.GetPropertyValue(SkyDriveConstants.InnerIDKey)); } else { uri = SkyDriveConstants.RootAccessUrl + "/files"; } name = Path.GetFileName(name); var entry = RequestContentByUrl(session, uri).FirstOrDefault(x => x.Name.Equals(name)); return(entry); } }
private void SetupMessaging( TFChunkDb db, QueuedHandler mainQueue, InMemoryBus mainBus, TimerService timerService, HttpService httpService) { _coreQueues = new List <QueuedHandler>(); _managerInputBus = new InMemoryBus("manager input bus"); _managerInputQueue = new QueuedHandler(_managerInputBus, "ProjectionManager"); while (_coreQueues.Count < _projectionWorkerThreadCount) { var coreInputBus = new InMemoryBus("bus"); var coreQueue = new QueuedHandler(coreInputBus, "ProjectionCoreQueue #" + _coreQueues.Count); var projectionNode = new ProjectionWorkerNode(db, coreQueue); projectionNode.SetupMessaging(coreInputBus); var forwarder = new RequestResponseQueueForwarder( inputQueue: coreQueue, externalRequestQueue: mainQueue); // forwarded messages projectionNode.CoreOutput.Subscribe <ClientMessage.ReadEvent>(forwarder); projectionNode.CoreOutput.Subscribe <ClientMessage.ReadStreamEventsBackward>(forwarder); projectionNode.CoreOutput.Subscribe <ClientMessage.ReadStreamEventsForward>(forwarder); projectionNode.CoreOutput.Subscribe <ClientMessage.ReadAllEventsForward>(forwarder); projectionNode.CoreOutput.Subscribe <ClientMessage.WriteEvents>(forwarder); projectionNode.CoreOutput.Subscribe( Forwarder.Create <ProjectionMessage.Projections.Management.StateReport>(_managerInputQueue)); projectionNode.CoreOutput.Subscribe( Forwarder.Create <ProjectionMessage.Projections.Management.StatisticsReport>(_managerInputQueue)); projectionNode.CoreOutput.Subscribe( Forwarder.Create <ProjectionMessage.Projections.StatusReport.Started>(_managerInputQueue)); projectionNode.CoreOutput.Subscribe( Forwarder.Create <ProjectionMessage.Projections.StatusReport.Stopped>(_managerInputQueue)); projectionNode.CoreOutput.Subscribe( Forwarder.Create <ProjectionMessage.Projections.StatusReport.Faulted>(_managerInputQueue)); projectionNode.CoreOutput.Subscribe(timerService); projectionNode.CoreOutput.Subscribe(Forwarder.Create <Message>(coreQueue)); // forward all coreInputBus.Subscribe(new UnwrapEnvelopeHandler()); _coreQueues.Add(coreQueue); } _projectionManagerNode = ProjectionManagerNode.Create( db, _managerInputQueue, httpService, _coreQueues.Cast <IPublisher>().ToArray()); _projectionManagerNode.SetupMessaging(_managerInputBus); { var forwarder = new RequestResponseQueueForwarder( inputQueue: _managerInputQueue, externalRequestQueue: mainQueue); _projectionManagerNode.Output.Subscribe <ClientMessage.ReadEvent>(forwarder); _projectionManagerNode.Output.Subscribe <ClientMessage.ReadStreamEventsBackward>(forwarder); _projectionManagerNode.Output.Subscribe <ClientMessage.ReadStreamEventsForward>(forwarder); _projectionManagerNode.Output.Subscribe <ClientMessage.WriteEvents>(forwarder); _projectionManagerNode.Output.Subscribe(Forwarder.Create <Message>(_managerInputQueue)); // self forward all mainBus.Subscribe(Forwarder.Create <SystemMessage.SystemInit>(_managerInputQueue)); mainBus.Subscribe(Forwarder.Create <SystemMessage.SystemStart>(_managerInputQueue)); mainBus.Subscribe(Forwarder.Create <SystemMessage.StateChangeMessage>(_managerInputQueue)); _managerInputBus.Subscribe(new UnwrapEnvelopeHandler()); } }
public IEnumerator <IPackageVersion> GetEnumerator() { return(m_Versions.Cast <IPackageVersion>().GetEnumerator()); }
public IEnumerable <AnimalBase> GetAnimals() { return(_Animals.Cast <AnimalBase>()); }
public OverloadSDPModel FormatOverload(Member overload, List <Member> members) { var sdpOverload = new OverloadSDPModel() { Uid = overload?.Uid, CommentId = overload?.CommentId, Name = overload?.DisplayName, FullName = overload?.FullDisplayName, Summary = overload?.Docs?.Summary, Remarks = overload?.Docs?.Remarks, Examples = overload?.Docs?.Examples, Type = members.First().ItemType.ToString().ToLower(), Members = members.Select(m => FormatSingleMember(m)).ToList() }; if (overload != null) { sdpOverload.NameWithType = members.First().Parent.Name + "." + sdpOverload.Name; } if (_withVersioning) { if (!_store.UWPMode) { sdpOverload.AssembliesWithMoniker = overload == null?sdpOverload.Members.First().AssembliesWithMoniker : MonikerizeAssemblyStrings(overload); sdpOverload.PackagesWithMoniker = overload == null?sdpOverload.Members.First().PackagesWithMoniker : MonikerizePackageStrings(overload, _store.PkgInfoMapping); } } else { sdpOverload.Assemblies = sdpOverload.Members .Where(m => m.Assemblies != null) .SelectMany(m => m.Assemblies) .Distinct().ToList().NullIfEmpty(); } sdpOverload.Namespace = sdpOverload.Members.First().Namespace; sdpOverload.DevLangs = sdpOverload.Members.SelectMany(m => m.DevLangs).Distinct().ToList(); sdpOverload.Monikers = sdpOverload.Members.Where(m => m.Monikers != null).SelectMany(m => m.Monikers).Distinct().ToList(); bool resetMemberThreadSafety = false; // One group members keep only one thread safety info var withThreadSafetyMembers = sdpOverload.Members.Where(p => p.ThreadSafety != null).ToList(); if (sdpOverload != null && overload?.Docs?.ThreadSafetyInfo != null) { sdpOverload.ThreadSafety = ConvertThreadSafety(overload); resetMemberThreadSafety = true; } foreach (var m in sdpOverload.Members) { m.Namespace = null; m.Assemblies = null; m.AssembliesWithMoniker = null; m.PackagesWithMoniker = null; m.DevLangs = null; if (resetMemberThreadSafety && m.ThreadSafety != null) { m.ThreadSafety = null; } } GenerateRequiredMetadata(sdpOverload, overload ?? members.First(), members.Cast <ReflectionItem>().ToList()); return(sdpOverload); }
private async Task SetAgentButton_Clicked(Button setAgentButton, ScriptProbe scriptProbe) { List <Input> agentSelectionInputs = new List <Input>(); // show any existing agents List <IScriptProbeAgent> currentAgents = null; // android allows us to dynamically load code assemblies, but iOS does not. so, the current approach // is to only support dynamic loading on android and force compile-time assembly inclusion on ios. #if __ANDROID__ // try to extract agents from a previously loaded assembly try { currentAgents = ScriptProbe.GetAgents(scriptProbe.AgentAssemblyBytes); } catch (Exception) { } #elif __IOS__ currentAgents = ScriptProbe.GetAgents(); // display warning message, as there is no other option to load agents. if (currentAgents.Count == 0) { await SensusServiceHelper.Get().FlashNotificationAsync("No agents available."); return; } #endif // let the user pick from currently available agents ItemPickerPageInput currentAgentsPicker = null; if (currentAgents != null && currentAgents.Count > 0) { currentAgentsPicker = new ItemPickerPageInput("Available agent" + (currentAgents.Count > 1 ? "s" : "") + ":", currentAgents.Cast <object>().ToList()) { Required = false }; agentSelectionInputs.Add(currentAgentsPicker); } #if __ANDROID__ // add option to scan qr code to import a new assembly QrCodeInput agentAssemblyUrlQrCodeInput = new QrCodeInput(QrCodePrefix.SURVEY_AGENT, "URL:", false, "Agent URL:") { Required = false }; agentSelectionInputs.Add(agentAssemblyUrlQrCodeInput); #endif List <Input> completedInputs = await SensusServiceHelper.Get().PromptForInputsAsync("Survey Agent", agentSelectionInputs, null, true, "Set", null, null, null, false); if (completedInputs == null) { return; } // check for QR code on android. this doesn't exist on ios. string agentURL = null; #if __ANDROID__ agentURL = agentAssemblyUrlQrCodeInput.Value?.ToString(); #endif // if there is no URL, check if the user has selected an agent. if (string.IsNullOrWhiteSpace(agentURL)) { if (currentAgentsPicker != null) { IScriptProbeAgent selectedAgent = (currentAgentsPicker.Value as List <object>).FirstOrDefault() as IScriptProbeAgent; // set the selected agent, watching out for a null (clearing) selection that needs to be confirmed if (selectedAgent != null || await DisplayAlert("Confirm", "Are you sure you wish to clear the survey agent?", "Yes", "No")) { scriptProbe.Agent = selectedAgent; setAgentButton.Text = "Set Agent" + (scriptProbe.Agent == null ? "" : ": " + scriptProbe.Agent.Id); if (scriptProbe.Agent == null) { await SensusServiceHelper.Get().FlashNotificationAsync("Survey agent cleared."); } } } } #if __ANDROID__ else { // download agent assembly from scanned QR code byte[] downloadedBytes = null; string downloadErrorMessage = null; try { // download the assembly and extract agents downloadedBytes = scriptProbe.AgentAssemblyBytes = await new WebClient().DownloadDataTaskAsync(new Uri(agentURL)); List <IScriptProbeAgent> qrCodeAgents = ScriptProbe.GetAgents(downloadedBytes); if (qrCodeAgents.Count == 0) { throw new Exception("No agents were present in the specified file."); } } catch (Exception ex) { downloadErrorMessage = ex.Message; } // if error message is null, then we have 1 or more agents in the downloaded assembly. if (downloadErrorMessage == null) { // redisplay the current input prompt including the agents we just downloaded scriptProbe.AgentAssemblyBytes = downloadedBytes; await SetAgentButton_Clicked(setAgentButton, scriptProbe); } else { SensusServiceHelper.Get().Logger.Log(downloadErrorMessage, LoggingLevel.Normal, typeof(Protocol)); await SensusServiceHelper.Get().FlashNotificationAsync(downloadErrorMessage); } } #endif }