/* * TODO: city data service access for desired shards. * Need to maintain connections to shards and request from their data services... * Either that or online status has to at least writeback to DB. */ public CityInfoController(IDAFactory daFactory, IServerNFSProvider nfs) : base("/userapi/city") { DAFactory = daFactory; NFS = nfs; After.AddItemToEndOfPipeline(x => { x.Response.WithHeader("Access-Control-Allow-Origin", "*"); }); Get["/{shardid}/{id}.png"] = parameters => { using (var da = daFactory.Get) { var lot = da.Lots.GetByLocation((int)parameters.shardid, (uint)parameters.id); if (lot == null) { return(HttpStatusCode.NotFound); } return(Response.AsImage(Path.Combine(NFS.GetBaseDirectory(), "Lots/" + lot.lot_id.ToString("x8") + "/thumb.png"))); } }; Get["/{shardid}/city.json"] = parameters => { var now = Epoch.Now; if (LastModelUpdate < now - 15) { LastModelUpdate = now; lock (ModelLock) { LastModel = new CityInfoModel(); using (var da = daFactory.Get) { var lots = da.Lots.AllLocations((int)parameters.shardid); var lotstatus = da.LotClaims.AllLocations((int)parameters.shardid); LastModel.reservedLots = lots.ConvertAll(x => x.location).ToArray(); LastModel.names = lots.ConvertAll(x => x.name).ToArray(); LastModel.activeLots = lotstatus.ConvertAll(x => x.location).ToArray(); LastModel.onlineCount = lotstatus.ConvertAll(x => x.active).ToArray(); } } } lock (ModelLock) { return(Response.AsJson(LastModel)); } }; }
public BTreeListNode Find(int value) { for (BTreeListNode node = Root; node != null; node = node.Next) { if (value == node.Value) { return(node); } else if (value < node.Value) { return(node.Branch.Find(value)); } } return(After.Find(value)); }
public Module() { After.AddItemToEndOfPipeline((ctx) => ctx.Response.WithHeader("Access-Control-Allow-Origin", "*").WithHeader("Access-Control-Allow-Methods", "POST,GET").WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type")); Options["/"] = _ => new Response(); Get["/{printerName?printi}"] = (ctx) => { var model = new PrinterPageModel(ctx.printerName, ctx.printerName == "printi"); int.TryParse(Request.Query["log"], out model.ShowDebug); return(View["Index", model]); }; Get["/ping"] = para => "OK"; Get["/snel"] = Get["/sneller"] = Get["/fast"] = Get["/faster"] = para => Response.AsRedirect("http://192.168.2.42/"); }
public void Validate() { if (First.IsSpecified) { Preconditions.AtLeast(First, 1, nameof(First)); Preconditions.AtMost(First, 100, nameof(First)); } if (After.IsSpecified) { Preconditions.NotNullOrWhitespace(After.ToString(), nameof(After)); } if (Before.IsSpecified) { Preconditions.NotNullOrWhitespace(Before.ToString(), nameof(Before)); } }
private void RevertCollectionChange <T>(IEnumerable entities) where T : class, IDbEntity { ICollection <T> collection = entities as ICollection <T>; if (Before == null && After != null && DbEntityUtilities.IsIDbEntity(After.GetType())) { // This property change refers to a newly added entity to this collection. To revert it, remove the added entity from the collection collection.Remove(After as T); } else if (Before != null && DbEntityUtilities.IsIDbEntity(Before.GetType()) && After == null && !collection.Contains(Before as T)) { // This property change refers to an entity removed from this collection. To revert it, re-add the removed entity to the collection collection.Add(Before as T); } }
void HandleDecimalType() { var decimalId = SwiftGenerator.GeneratedIdentifier($"{Parameter.Name}_decimal"); var @var = IsByRefParameter ? "var" : "let"; Before.WriteLine($"{@var} {decimalId} : MonoDecimal = mono_embeddinator_string_to_decimal(\"\")"); var pointerId = "pointer"; if (IsByRefParameter) { Before.WriteLine($"withUnsafeMutablePointer(to: &{decimalId}) {{ ({pointerId}) in"); After.WriteLine("}"); } Return.Write(IsByRefParameter ? pointerId : decimalId); }
protected override void OnInit() { m_progress = 0.0f; if (Before is LevelState) { LevelState beforeLevel = (LevelState)Before; Matrix4 cameraTransInv = Game.Camera.Transform; cameraTransInv.Invert(); Vector3 right = Vector3.TransformVector(Vector3.UnitX, cameraTransInv); beforeLevel.Level.Transform = Matrix4.CreateTranslation( right * DISTANCE * ((m_direction == SlideDirection.Right) ? -1.0f : 1.0f) ) * beforeLevel.Level.Transform; } After.Reveal(); }
private void ApplyCollectionChange <T>(IEnumerable entities) where T : class, IDbEntity { // If remove (i.e. before = typeof(IDbEntity), after = null), remove before value ICollection <T> collection = entities as ICollection <T>; if (Before == null && After != null && DbEntityUtilities.IsIDbEntity(After.GetType()) && !collection.Contains(After as T)) { // This property change refers to a newly added entity to this collection. To re-apply it, re-add the added entity to the collection collection.Add(After as T); } else if (Before != null && DbEntityUtilities.IsIDbEntity(Before.GetType()) && After == null) { // This property change refers to an entity removed from this collection. To re-apply it, remove the removed entity from the collection collection.Remove(Before as T); } }
public LoginServer() { After.AddItemToEndOfPipeline(ctx => ctx.Response .WithHeader("Access-Control-Allow-Origin", "*") .WithHeader("Access-Control-Allow-Methods", "POST,GET") .WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type")); Get("/token", x => { if (LauncherLogic.User != null) { return(JsonConvert.SerializeObject(new { StatusCode = 0, UserName = Base64Encode(LauncherLogic.User.UserName), Token = LauncherLogic.User.AuthCode })); } //1 = Not Authenticated return(JsonConvert.SerializeObject(new { StatusCode = 1 })); }); }
public RestApiModule() : base("/api/v0.1") { //todo: debug code, get rid of this later Before.AddItemToStartOfPipeline(x => { _stopwatch = new Stopwatch(); _stopwatch.Start(); return(null); }); //version number request Get["/version"] = _ => { return(_GetVersion()); }; //list the current boxes Get["/boxes"] = _ => { return(_GetBoxList()); }; //create a new box Put["/boxes/{box}"] = x => { return(_CreateBox(x["box"])); }; //delete a box Delete["/boxes/{box}"] = x => { return(_DeleteBox(x["box"])); }; //list messages in a box Get["/boxes/{box}"] = x => { return(_GetMessagesInBox(x["box"])); }; //create a new message Put["/boxes/{box}/{message}"] = x => { var msg = this.Bind <Message>(); return(_CreateMessage(x["box"], x["message"], msg)); }; //delete a message Delete["/boxes/{box}/{message}"] = x => { return(_DeleteMessage(x["box"], x["message"])); }; //get message details Get["/boxes/{box}/{message}"] = x => { return(_GetMessage(x["box"], x["message"])); }; //todo: debug code, get rid of this later After.AddItemToEndOfPipeline(x => { _stopwatch.Stop(); Console.WriteLine("> ({0}ms) {1}: {2}", _stopwatch.ElapsedMilliseconds, Request.Method, Request.Url.Path); }); }
public Endpoints() { Options["/{catchAll*}"] = parmeters => { return(new Response { StatusCode = HttpStatusCode.Accepted }); }; After.AddItemToEndOfPipeline(context => { context.Response.WithHeader("Access-Control-Allow-Origin", "*") .WithHeader("Access-Control-Allow-Methods", "POST, GET") .WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type"); }); Get[nameof(PreviousRun)] = _ => PreviousRun(); Get[$"{nameof(PreviousRun)}/{{runId}}"] = parameters => PreviousRun(parameters.runId); Get[nameof(RuleDefinitions)] = _ => RuleDefinitions(); Post[nameof(NewAnalysis)] = _ => NewAnalysis(); }
public IEnumerator TransitionTo(Vector3 pos, After then) { float tCurrent = 0; float tMax = 0.1f; while (tCurrent < tMax) { transform.position = Vector3.Lerp( transform.position, pos, tCurrent / tMax ); tCurrent += Time.deltaTime; yield return(null); } transform.position = pos; then(); }
/// <summary> /// Returns the query string for the request /// </summary> /// <returns></returns> public virtual string ToQueryString() { QueryStringBuilder builder = new QueryStringBuilder(); builder.Add("limit", Limit.ToString()); if (Before.HasValue) { builder.Add("before", Before.ToString()); } if (After.HasValue) { builder.Add("after", After.ToString()); } return(builder.ToString()); }
public AdminShardOpController(IDAFactory daFactory, JWTFactory jwt, ApiServer server) : base("/admin/shards") { JWTTokenAuthentication.Enable(this, jwt); DAFactory = daFactory; Server = server; After.AddItemToEndOfPipeline(x => { x.Response.WithHeader("Access-Control-Allow-Origin", "*"); }); Post["/shutdown"] = _ => { this.DemandAdmin(); var shutdown = this.Bind <ShutdownModel>(); var type = ShutdownType.SHUTDOWN; if (shutdown.update) { type = ShutdownType.UPDATE; } else if (shutdown.restart) { type = ShutdownType.RESTART; } //JWTUserIdentity user = (JWTUserIdentity)this.Context.CurrentUser; Server.RequestShutdown((uint)shutdown.timeout, type); return(Response.AsJson(true)); }; Post["/announce"] = _ => { this.DemandModerator(); var announce = this.Bind <AnnouncementModel>(); Server.BroadcastMessage(announce.sender, announce.subject, announce.message); return(Response.AsJson(true)); }; }
public ItemRange With(LineSegment ls, bool includeItem = true) { if (IsForward && Index <= ls.Index) //F, F | B { return(new ItemRange(After.Where(w => w.Index < ls.Index || (includeItem && w.Index == ls.Index)))); } else if (Index <= ls.Index) // B B { return(new ItemRange(ls.After.Where(w => w.Index > Index || (includeItem && w.Index == Index)))); } else if (!ls.IsForward) // F | B, B { return(new ItemRange(ls.Where(w => w.Index <= Index))); } else // F F { return(new ItemRange(ls.After.Where(w => w.Index <= Index))); } }
public void Validate() { if (CommunityIds.IsSpecified) { Preconditions.CountGreaterThan(CommunityIds, 100, nameof(CommunityIds)); Preconditions.CountLessThan(CommunityIds, 1, nameof(CommunityIds)); } if (GameIds.IsSpecified) { Preconditions.CountGreaterThan(GameIds, 100, nameof(GameIds)); Preconditions.CountLessThan(GameIds, 1, nameof(GameIds)); } if (Languages.IsSpecified) { Preconditions.CountGreaterThan(Languages, 100, nameof(Languages)); Preconditions.CountLessThan(Languages, 1, nameof(Languages)); } if (UserIds.IsSpecified) { Preconditions.CountGreaterThan(UserIds, 100, nameof(UserIds)); Preconditions.CountLessThan(UserIds, 1, nameof(UserIds)); } if (UserNames.IsSpecified) { Preconditions.CountGreaterThan(UserNames, 100, nameof(UserNames)); Preconditions.CountLessThan(UserNames, 1, nameof(UserNames)); } if (First.IsSpecified) { Preconditions.AtLeast(First, 1, nameof(First)); Preconditions.AtMost(First, 100, nameof(First)); } if (After.IsSpecified) { Preconditions.NotNullOrWhitespace(After.ToString(), nameof(After)); } if (Before.IsSpecified) { Preconditions.NotNullOrWhitespace(Before.ToString(), nameof(Before)); } }
public override string ToString() { if (String.IsNullOrEmpty(_url)) { return(string.Empty); } else { StringBuilder sb = new StringBuilder(_url); if (Page > 1) { sb.Append(appendQuery(_url, PAGE_QUERYSTRING)); sb.Append(Page); } if (Embed) { sb.Append(appendQuery(sb.ToString(), EMBED_QUERYSTRING)); } if (Per_Page != 10) { sb.Append(appendQuery(sb.ToString(), PER_PAGE_QUERYSTRING)); sb.Append(Per_Page); } if (Offset > 0) { sb.Append(appendQuery(sb.ToString(), OFFSET_QUERYSTRING)); sb.Append(Offset); } if (After != DateTime.MinValue) { sb.Append(appendQuery(sb.ToString(), AFTER_QUERYSTRING)); sb.Append(After.ToString("yyyy-MM-ddTHH:mm:ss")); } if (OrderBy != OrderBy.Date) { sb.Append(appendQuery(sb.ToString(), ORDER_BY_QUERYSTRING)); sb.Append(Convert.ToInt32(OrderBy)); } //Console.WriteLine(sb.ToString()); return(sb.ToString()); } }
private void SendExecutionInfo(After after, Alternation alternation, ScenarioCast[] casts) { SendSound(SoundNotification.Apply, casts); if (after.Value != 0) { var unit = "секунд(ы)"; switch (after.Unit) { case TimeUnit.Minute: unit = "минут(ы)"; break; case TimeUnit.Hour: unit = "часа(ов)"; break; } SendInfo(string.Format("Выполнить: {0}\r\nчерез {1} {2}.", alternation.Synonym, after.Value, unit), casts); } else { SendInfo("Выполняю: " + alternation.Synonym + ".", casts); } }
public void HandleRefOutNonDefaultIntegerEnum(Enumeration @enum) { // This deals with marshaling of managed enums with non-C default // backing types (ie. enum : short). // Unlike C++ or Objective-C, C enums always have the default integer // type size, so we need to create a local variable of the right type // for marshaling with the managed runtime and cast it back to the // correct type. var backingType = @enum.BuiltinType.Type; var typePrinter = new CppTypePrinter(); var integerType = typePrinter.VisitPrimitiveType(backingType); var newArgName = CGenerator.GenId(ArgName); Before.WriteLine("{0} {1} = *(({0}*) {2});", integerType, newArgName, ArgName); Return.Write("&{0}", newArgName); After.WriteLine("*{0} = ({1}) {2};", ArgName, @enum.Visit(CTypePrinter), newArgName); }
public NancyDemo() : base("/nancy") { Before.AddItemToEndOfPipeline(async(ctx, ct) => { this.AddToLog("Before Hook Delay\n"); await Task.Delay(5000); return(null); }); After.AddItemToEndOfPipeline(async(ctx, ct) => { this.AddToLog("After Hook Delay\n"); await Task.Delay(5000); this.AddToLog("After Hook Complete\n"); ctx.Response = this.GetLog(); }); Get["/", runAsync : true] = async(x, ct) => { this.AddToLog("Delay 1\n"); await Task.Delay(1000); this.AddToLog("Delay 2\n"); await Task.Delay(1000); this.AddToLog("Executing async http client\n"); using (var client = new HttpClient()) { var res = await client.GetAsync("http://nancyfx.org"); var content = await res.Content.ReadAsStringAsync(); this.AddToLog("Response: " + content + "\n"); } return((Response)this.GetLog()); }; Get["/nancy/demo"] = parameters => new string[] { "Hello", "World" }; }
public ComputerInfoApi() { #if DEBUG After.AddItemToEndOfPipeline((ctx) => ctx.Response .WithHeader("Access-Control-Allow-Origin", "*") .WithHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS") .WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type")); #endif Get("/", x => { return(View["Web/index.html"]); }); Get("/GetTemp", x => { var cdata = ComputerData.Get(); cdata.Refresh();//todo 可能需要改成独立线程刷新 //Dictionary<string, string> result = new Dictionary<string, string>(); //result.Add("cputemp", cdata.GetCpuTemperature()); //result.Add("gputemp", cdata.GetGpuTemperature()); //result.Add("cpuload", cdata.GetCpuLoad()); //result.Add("ramload", cdata.GetMemoryLoad()); ComputerInfoModel result = new ComputerInfoModel() { CpuLoad = cdata.GetCpuLoad(), CpuTemp = cdata.GetCpuTemperature(), RamLoad = cdata.GetMemoryLoad(), GpuTemp = cdata.GetGpuTemperature(), DiskLoad = cdata.GetDiskLoad() }; return(Response.AsJson(result)); }); Get("/test", x => { var cpu = ComputerData.Get().GetCpu(); if (cpu == null) { return("Cant find cpu"); } return(ComputerData.Get().GetTemperature(cpu)); }); }
#pragma warning disable CS0114 // Member hides inherited member; missing override keyword protected override void Execute(CodeActivityContext context) #pragma warning restore CS0114 // Member hides inherited member; missing override keyword { var STR = Main_String.Get(context); var vBefore = Before.Get(context); var vAfter = After.Get(context); int Pos1 = STR.IndexOf(vBefore) + vBefore.Length; int Pos2 = STR.IndexOf(vAfter); string FinalString; if (vAfter == "") { FinalString = STR.Substring(Pos1); } else { FinalString = STR.Substring(Pos1, Pos2 - Pos1); } FinalString = FinalString.Trim(); Final_text.Set(context, FinalString); }
public IResult <TOutput> Parse(IParseState <TInput> state) { Assert.ArgumentNotNull(state, nameof(state)); var startCheckpoint = state.Input.Checkpoint(); var startConsumed = state.Input.Consumed; Before?.Invoke(new Context(Inner, state, null)); var result = Inner.Parse(state); After?.Invoke(new Context(Inner, state, result)); var totalConsumed = state.Input.Consumed - startConsumed; // The callbacks have access to Input, so the user might consume data. Make sure // to report that if it happens. if (!result.Success) { startCheckpoint.Rewind(); return(result); } return(result.AdjustConsumed(totalConsumed)); }
public void MustBeLoggedInToRegister() { After.Setup((Action <SetupContext>)(ctx => { ctx.CopyFrom((Incubation.Incubator)CoreServiceRegistryContainer.GetServiceRegistry()); })) .WhenA <CoreApplicationRegistrationService>("tries to register application when not logged in", cars => { ProcessDescriptor descriptor = ProcessDescriptor.ForApplicationRegistration(cars.CoreRegistryRepository, "localhost", 8080, "testApp", "testOrg"); return(cars.RegisterApplication(descriptor)); }) .TheTest .ShouldPass(because => { CoreServiceResponse result = because.ResultAs <CoreServiceResponse>(); because.ItsTrue("the response was not successful", !result.Success, "request should have failed"); because.ItsTrue("the message says 'You must be logged in to do that'", result.Message.Equals("You must be logged in to do that")); because.IllLookAtIt(result.Message); }) .SoBeHappy() .UnlessItFailed(); }
private void SetupModelDefaults() { Before.AddItemToEndOfPipeline(ctx => { var guid = System.Guid.NewGuid().ToString(); if (Request.Cookies.ContainsKey("NerdGuid")) { guid = Request.Cookies["NerdGuid"]; } Model.NerdGuid = guid; Model.Nerd = DB.Nerds.FindByGuid(guid) ?? DB.Nerds.Insert(Name: "John Doe", Guid: guid); Model.Title = "NerdBeers"; IEnumerable <BeerEvent> ube = DB.BeerEvents.FindAllByEventDate(DateTime.Now.to(DateTime.Now.AddYears(1))).Cast <BeerEvent>(); Model.UpcomingEvents = ube.OrderBy(e => e.EventDate).Take(10); Model.SubscribedEvents = DB.BeerEvents.FindAll(DB.BeerEvents.NerdSubscriptions.Nerds.Guid == Model.Nerd.Guid).Cast <BeerEvent>(); return(null); }); After.AddItemToEndOfPipeline(ctx => { ctx.Response.AddCookie("NerdGuid", Model.NerdGuid); }); }
public void Validate() { int specified = 0; if (UserId.IsSpecified) { specified++; Preconditions.NotZero(UserId, nameof(UserId)); } if (VideoId.IsSpecified) { specified++; Preconditions.NotZero(VideoId, nameof(VideoId)); } if (specified > 1) { throw new ArgumentException($"Only one of {nameof(UserId)} or {nameof(VideoId)} can be specified for this request."); } if (specified == 0) { throw new ArgumentException($"Either {nameof(UserId)} or {nameof(VideoId)} must be specified for this request."); } if (First.IsSpecified) { Preconditions.AtLeast(First, 1, nameof(First)); Preconditions.AtMost(First, 100, nameof(First)); } if (After.IsSpecified) { Preconditions.NotNullOrWhitespace(After.ToString(), nameof(After)); } if (Before.IsSpecified) { Preconditions.NotNullOrWhitespace(Before.ToString(), nameof(Before)); } }
public void Confirm() { // Persist preferences _settingsService.LastExportFormat = SelectedFormat; _settingsService.LastPartitionLimit = PartitionLimit; _settingsService.LastShouldDownloadMedia = ShouldDownloadMedia; // If single channel - prompt file path if (Channels != null && IsSingleChannel) { var channel = Channels.Single(); var defaultFileName = ExportRequest.GetDefaultOutputFileName( Guild !, channel, SelectedFormat, After?.Pipe(Snowflake.FromDate), Before?.Pipe(Snowflake.FromDate) ); // Filter var ext = SelectedFormat.GetFileExtension(); var filter = $"{ext.ToUpperInvariant()} files|*.{ext}"; OutputPath = _dialogManager.PromptSaveFilePath(filter, defaultFileName); } // If multiple channels - prompt dir path else { OutputPath = _dialogManager.PromptDirectoryPath(); } if (string.IsNullOrWhiteSpace(OutputPath)) { return; } Close(true); }
/// <summary> /// Splits data between parts /// </summary> /// <param name="cur">Data</param> public void AddData(List <Token> cur) { List <Token> data = new List <Token>(); ICompilable last = null; foreach (var x in cur) { switch (x.t) { case TType.ou: FinishBlock(ref data, last); last = new OutInit(); break; case TType.init: FinishBlock(ref data, last); last = new Init(); break; case TType.Beg: FinishBlock(ref data, last); last = new Body(); break; case TType.End: FinishBlock(ref data, last); break; default: data.Add(x); break; } } var v = new After(); v.AddData(data); com.Add(v); }
public Resource() : base(Constants.Path) { After.AddItemToEndOfPipeline(ctx => ctx.Response .WithHeader("Access-Control-Allow-Credentials", "true") .WithHeader("Access-Control-Allow-Origin", "*") .WithHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD") .WithHeader("Access-Control-Allow-Headers", "origin, content-type, accept, authorization, X-HTTP-Method-Override, Accept-Encoding, Content-Encoding")); Get["/portal"] = _ => { // Return the UI's script var jsonBytes = Encoding.UTF8.GetBytes(System.IO.File.ReadAllText(@"../../Client/build/ServiceConfiguration.bundle.js")); return(new Response { StatusCode = HttpStatusCode.OK, ContentType = "text/plain", Contents = c => c.Write(jsonBytes, 0, jsonBytes.Length) }); }; Options["/portal"] = _ => new Response { StatusCode = HttpStatusCode.OK }; }
public void MustBeLoggedInToRegister() { After.Setup(setupContext => { setupContext.CopyFrom((CoreServiceRegistryContainer.GetServiceRegistry())); }) .WhenA <ApplicationRegistryService>("tries to register application when not logged in", applicationRegistryService => { ProcessDescriptor descriptor = ProcessDescriptor.ForApplicationRegistration(applicationRegistryService.ApplicationRegistrationRepository, "localhost", 8080, "testApp", "testOrg"); return(applicationRegistryService.RegisterApplicationProcess(descriptor)); }) .TheTest .ShouldPass((because, objectUnderTest) => { because.ItsTrue($"object under test is of type {nameof(ApplicationRegistryService)}", objectUnderTest.GetType() == typeof(ApplicationRegistryService)); CoreServiceResponse result = because.ResultAs <CoreServiceResponse>(); because.ItsTrue("the response was not successful", !result.Success, "request should have failed"); because.ItsTrue("the message says 'You must be logged in to do that'", result.Message.Equals("You must be logged in to do that")); because.IllLookAtIt(result.Message); }) .SoBeHappy() .UnlessItFailed(); }
private void _ToEnd(float end) { _Step = CastStep.Ending; var stage = new After(end); stage.DoneEvent += _OnDone; _Machine.Push(stage); }
private void _ToBegin(float begin) { _Step = CastStep.Beginning; var stage = new After(begin); stage.DoneEvent += () => { _ToEffective(_Prototype.Effective); }; _Machine.Push(stage); }