//In this exercise we want to reuse the same loop construct. //Only a single loop shall be present in this class. //You can use helepr methods that are ready for You. public IEnumerable<SpaceWarship> GetBigCruisers(SampleData data) { //This function should return a collection of ships //that belong to cruiser class and have at least 2000 crew members. return null; }
public int GetTotalCrew(SampleData data) { //This method shall return number of all crewmembers on all ships //Use loop to implement it. return int.MinValue; }
internal static async Task<IInputStream> GetStreamAsync(SampleData sampleData) { var folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("SampleData"); var file = await folder.GetFileAsync(sampleData.ToString() + ".zip"); return await file.OpenReadAsync(); }
internal static async Task<string> GetTextAsync(SampleData sampleData) { var folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("SampleData"); var file = await folder.GetFileAsync(sampleData.ToString() + ".xml"); return await FileIO.ReadTextAsync(file); }
public int TotalCrewOnDestroyers_2(SampleData data) { //this method shall introduce variables that hold intermediary results, //but still use normal static forms of methods return int.MinValue; }
//Its easy to leverage query syntax using Your own map and filer functions. //Just name Your methods Select and Where, make sure Your namespace is visible //and You're ready to go. public IEnumerable<string> GetNamesOfBattleships(SampleData data) { return from s in data.Ships where s.ShipClass == WarshipClass.Battleship select s.Name; }
public bool AreThereScouts(SampleData data) { //This method has to answer whether there are any scout class ships. //Use loop to implement it. return false; }
public SpaceWarship GetSmallestShip(SampleData data) { //A ship with smallest crew shall be returned here; //You can use GetSmallerShip() method present in this class to compare ships return null; }
//In this exercise we want to reuse the same loop construct. //Only a single loop shall be present in this class. public IEnumerable<SpaceWarship> GetBigCruisers(SampleData data) { //This function should return a collection of ships //that belong to cruiser class and have at least 2000 crew members. return GetShipsSatisfyingCondition(data, IsCruiserWithCrewOver2000); }
public string GetCommaSeparatedCommandersNames(SampleData data) { //This shall be a single string in form "name1,name2,name3," //Pay attention to the trailing comma - it's there for Your convenience return null; }
//In this exercise we want to reuse the same loop construct. //Only a single loop shall be present in this class. public IEnumerable<int> GetShipsCaptainsExperience(SampleData data) { //we want to map list of ships into //list of ship's captain's experience (years of service) return null; }
public IEnumerable<SpaceWarship> GetQuickReactingDestroyers(SampleData data) { //This function should return a collection of ships //that belong to destroyer class and are members of quick reaction fleet. return null; }
/// <summary> /// Setup the GazeModel and save the current ScreenResoultion /// </summary> /// <param name="currentScreenHeight"></param> /// <param name="currentScreenWidth"></param> public GazeModel(int currentScreenWidth, int currentScreenHeight) { this.currentScreenHeight = currentScreenHeight; this.currentScreenWidth = currentScreenWidth; //init a emptySample dataSample = new SampleData(); }
private MenuItem CreateMenuItem(SampleData data) { MenuItem item = new MenuItem { Header = "Change Item" }; item.Tag = data; item.Click += new RoutedEventHandler(item_Click); return item; }
public int TotalCrewOnDestroyers_3(SampleData data) { //this version should make use of map, filter and reduce as extension methods return data.Ships .Filter(s => s.ShipClass == WarshipClass.Destroyer) .Map(s => s.Crew) .Reduce(0, (acc, shipcrew) => acc + shipcrew); }
public bool matches (SampleData sample, int arg) { bool match = false; if ( sample.data.long_3 <= arg ) { match = true; } return match; }
private List<SpaceWarship> GetShipsSatisfyingCondition(SampleData data, Func<SpaceWarship, bool> condition) { var result = new List<SpaceWarship>(); foreach (var ship in data.Ships) { if (condition(ship)) result.Add(ship); } return result; }
public IEnumerable<SpaceWarship> GetShipsWithYoungCaptains(SampleData data) { //This function should return a collection of ships //that are commanded by captains with service //no longer than 25 years. //Use a loop to implement it. return null; }
public IEnumerable<SpaceWarship> GetQuickReactingDestroyers(SampleData data) { //This function should return a collection of ships //that belong to destroyer class and are members of quick reaction fleet. return GetShipsSatisfyingCondition( data, (ship) => IsDestroyerInQuickReactionFleet(data, ship) ); }
static void Main(string[] args) { // Create your own testData class to try other combinations! SampleData data = null; try { TestFileReader inputFile = new TestFileReader("input.txt"); data = new SampleData(inputFile.Graph, inputFile.ExpectedAnswers); } catch (Exception e) { Console.WriteLine("There was an issue reading the input file, defaulting to sample data"); data = new SampleData(); } var builder = new GraphBuilder(); Graph graph = builder.BuildFromString(data.GraphData) .setTitle("Kiwiland Rail") .getGraph(); // Display the Graph Console.Write(graph + "\n"); var planner = new Finder(graph); foreach (Tuple<string, int?, SampleData.TestType> route in data.RouteData) { var answer = planner.DoJob(route); string displayableAnswer = answer == null ? "NO SUCH ROUTE" : answer.ToString(); // Std out for how we did. if (route.Item2 == null) { if (answer == null) { Console.WriteLine(displayableAnswer); } else { Console.WriteLine("We figured " + displayableAnswer + ", but the correct answer was " + route.Item2); } } else { if (answer != route.Item2) { Console.WriteLine("We figured " + displayableAnswer + ", but the correct answer was " + route.Item2); } else { Console.WriteLine("Output: " + answer); } } } }
public bool AreThereScouts(SampleData data) { //This method has to answer whether there are any scout class ships. //Use loop to implement it. foreach (var ship in data.Ships) { if (ship.ShipClass == WarshipClass.Scout) return true; } return false; }
public int TotalCrewOnDestroyers_4(SampleData data) { //and now, implement the same calculation with a loop var result = 0; foreach(var s in data.Ships) if(s.ShipClass == WarshipClass.Destroyer) result = result + s.Crew; return result; }
//Refactor these methods to use map/filter/reduce instead of loops public IEnumerable<SpaceWarship> GetShipsWithYoungCaptains(SampleData data) { var result = new List<SpaceWarship>(); foreach (var ship in data.Ships) { if (ship.Captain.YearsOfService <= 25) result.Add(ship); } return result; }
public IEnumerable<string> AddRandomNumbersToShipsAndPickPositiveOnes_2(SampleData data) { //Use anonymous object instead of ShipAssignment class var rand = new Random(); return data.Ships .Map(ship => new {Name = ship.Name, Number = rand.Next()}) .Filter(sn => sn.Number % 2 == 1) .Map(sn => String.Format("{0}: {1}", sn.Name, sn.Number)); }
public int TotalCrewOnDestroyers_2(SampleData data) { //this method shall introduce variables that hold intermediary results, //but still use normal static forms of methods var destroyers = MFR.Filter(data.Ships, s => s.ShipClass == WarshipClass.Destroyer); var destroyersCrews = MFR.Map(destroyers, s => s.Crew); var result = MFR.Reduce(destroyersCrews, 0, (acc, shipcrew) => acc + shipcrew); return result; }
public int GetTotalCrew(SampleData data) { //This method shall return number of all crewmembers on all ships //Use loop to implement it. var count = 0; foreach (var s in data.Ships) { count += s.Crew; } return count; }
//All methods in this class shall calculate same result but using a different style. public int TotalCrewOnDestroyers_1(SampleData data) { //This is a dummy implementation - not a good style return MFR.Reduce( MFR.Map( MFR.Filter( data.Ships, s => s.ShipClass == WarshipClass.Destroyer), s => s.Crew), 0, (acc, shipcrew) => acc + shipcrew); }
//This exercise shall present how convenient anonymous objects are. //They were introduced exactly for the reason of making linq experience better. public IEnumerable<string> AddRandomNumbersToShipsAndPickPositiveOnes_1(SampleData data) { //each ship shall have a random number assigned, //then list of strings in form "{ship name}: {number}" //only for ships with odd number shall be returned var rand = new Random(); return data.Ships .Map(ship => new ShipAssignment(ship.Name, rand.Next())) .Filter(sn => sn.Number % 2 == 1) .Map(sn => String.Format("{0}: {1}", sn.ShipName, sn.Number)); }
public void When_bytes_of_data_are_hashed_using_opensubtitles_algorithm_Then_returns_expected_hash() { var inputData = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; var expectedHash = "18161412100e0c1a"; var fakeFileHelper = new Mock<IFileHelper>(); var fakeFileInfoHelper = new Mock<IFileInfoHelper>(); fakeFileInfoHelper.SetupProperty(x => x.Exists, true); var hashHelper = new OpenSubtitlesHash(fakeFileHelper.Object, fakeFileInfoHelper.Object); var sampleData = new SampleData(inputData.Length, inputData); var hash = hashHelper.ComputeHash(sampleData); StringAssert.AreEqualIgnoringCase(expectedHash, hash); }
public IEnumerable<SpaceWarship> GetShipsWithYoungCaptains(SampleData data) { //This function should return a collection of ships //that are commanded by captains with service //no longer than 25 years. //Use a loop to implement it. var result = new List<SpaceWarship>(); foreach (var ship in data.Ships) { if(ship.Captain.YearsOfService <= 25) result.Add(ship); } return result; }
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(minLevel: LogLevel.Warning); app.UseStatusCodePagesWithRedirects("~/Home/StatusCodePage"); // Error page middleware displays a nice formatted HTML page for any unhandled exceptions in the request pipeline. // Note: Not recommended for production. app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); // Configure Session. app.UseSession(); // Add static files to the request pipeline app.UseStaticFiles(); // Add cookie-based authentication to the request pipeline app.UseIdentity(); app.UseFacebookAuthentication(new FacebookOptions { AppId = "[AppId]", AppSecret = "[AppSecret]", Events = new OAuthEvents() { OnCreatingTicket = TestFacebookEvents.OnCreatingTicket, OnTicketReceived = TestFacebookEvents.OnTicketReceived, OnRedirectToAuthorizationEndpoint = TestFacebookEvents.RedirectToAuthorizationEndpoint }, BackchannelHttpHandler = new FacebookMockBackChannelHttpHandler(), StateDataFormat = new CustomStateDataFormat(), Scope = { "email", "read_friendlists", "user_checkins" } }); app.UseGoogleAuthentication(new GoogleOptions { ClientId = "[ClientId]", ClientSecret = "[ClientSecret]", AccessType = "offline", Events = new OAuthEvents() { OnCreatingTicket = TestGoogleEvents.OnCreatingTicket, OnTicketReceived = TestGoogleEvents.OnTicketReceived, OnRedirectToAuthorizationEndpoint = TestGoogleEvents.RedirectToAuthorizationEndpoint }, StateDataFormat = new CustomStateDataFormat(), BackchannelHttpHandler = new GoogleMockBackChannelHttpHandler() }); app.UseTwitterAuthentication(new TwitterOptions { ConsumerKey = "[ConsumerKey]", ConsumerSecret = "[ConsumerSecret]", Events = new TwitterEvents() { OnCreatingTicket = TestTwitterEvents.OnCreatingTicket, OnTicketReceived = TestTwitterEvents.OnTicketReceived, OnRedirectToAuthorizationEndpoint = TestTwitterEvents.RedirectToAuthorizationEndpoint }, StateDataFormat = new CustomTwitterStateDataFormat(), BackchannelHttpHandler = new TwitterMockBackChannelHttpHandler() }); app.UseMicrosoftAccountAuthentication(new MicrosoftAccountOptions { DisplayName = "MicrosoftAccount - Requires project changes", ClientId = "[ClientId]", ClientSecret = "[ClientSecret]", Events = new OAuthEvents() { OnCreatingTicket = TestMicrosoftAccountEvents.OnCreatingTicket, OnTicketReceived = TestMicrosoftAccountEvents.OnTicketReceived, OnRedirectToAuthorizationEndpoint = TestMicrosoftAccountEvents.RedirectToAuthorizationEndpoint }, BackchannelHttpHandler = new MicrosoftAccountMockBackChannelHandler(), StateDataFormat = new CustomStateDataFormat(), Scope = { "wl.basic", "wl.signin" } }); // Add MVC to the request pipeline app.UseMvc(routes => { routes.MapRoute( name: "areaRoute", template: "{area:exists}/{controller}/{action}", defaults: new { action = "Index" }); routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); routes.MapRoute( name: "api", template: "{controller}/{id?}"); }); //Populates the MusicStore sample data SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices).Wait(); }
public void Configure(IBuilder app) { var configuration = new Configuration() .AddJsonFile("Config.json") .AddEnvironmentVariables(); app.UseServices(services => { // Add options accessors to the service container services.SetupOptions <IdentityDbContextOptions>(options => { options.DefaultAdminUserName = configuration.Get("DefaultAdminUsername"); options.DefaultAdminPassword = configuration.Get("DefaultAdminPassword"); options.UseSqlServer(configuration.Get("Data:IdentityConnection:ConnectionString")); }); services.SetupOptions <MusicStoreDbContextOptions>(options => options.UseSqlServer(configuration.Get("Data:DefaultConnection:ConnectionString"))); // Add MVC services to the service container services.AddMvc(); // Add EF services to the service container services.AddEntityFramework() .AddSqlServer(); // Add Identity services to the service container services.AddIdentity <ApplicationUser>() .AddEntityFramework <ApplicationUser, ApplicationDbContext>() .AddHttpSignIn(); // Add application services to the service container services.AddScoped <MusicStoreContext>(); services.AddTransient(typeof(IHtmlHelper <>), typeof(AngularHtmlHelper <>)); }); // Initialize the sample data SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices).Wait(); SampleData.InitializeIdentityDatabaseAsync(app.ApplicationServices).Wait(); // Configure the HTTP request pipeline // Add cookie auth app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login") }); // Add static files app.UseStaticFiles(new StaticFileOptions { FileSystem = new PhysicalFileSystem("wwwroot") }); // Add MVC app.UseMvc(routes => { // TODO: Move these back to attribute routes when they're available routes.MapRoute(null, "api/genres/menu", new { controller = "GenresApi", action = "GenreMenuList" }); routes.MapRoute(null, "api/genres", new { controller = "GenresApi", action = "GenreList" }); routes.MapRoute(null, "api/genres/{genreId}/albums", new { controller = "GenresApi", action = "GenreAlbums" }); routes.MapRoute(null, "api/albums/mostPopular", new { controller = "AlbumsApi", action = "MostPopular" }); routes.MapRoute(null, "api/albums/all", new { controller = "AlbumsApi", action = "All" }); routes.MapRoute(null, "api/albums/{albumId}", new { controller = "AlbumsApi", action = "Details" }); routes.MapRoute(null, "{controller}/{action}/{id?}", new { controller = "Home", action = "Index" }); }); }
public CategoriesController(SampleData data) { this.data = data; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context) { // setting Ru culture helped for showing right currency, but does not for DateTime var cultureInfo = new CultureInfo("ru-RU"); cultureInfo.NumberFormat.CurrencyDecimalDigits = 0; CultureInfo.DefaultThreadCurrentCulture = cultureInfo; CultureInfo.DefaultThreadCurrentUICulture = cultureInfo; Thread.CurrentThread.CurrentCulture = cultureInfo; Thread.CurrentThread.CurrentUICulture = cultureInfo; // don't see a diff, but leaving the following lines too var localizationOptions = new RequestLocalizationOptions() { SupportedCultures = new List <CultureInfo>() { cultureInfo }, SupportedUICultures = new List <CultureInfo>() { cultureInfo }, DefaultRequestCulture = new RequestCulture(cultureInfo), FallBackToParentCultures = false, FallBackToParentUICultures = false, RequestCultureProviders = null }; app.UseRequestLocalization(localizationOptions); loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); } Migrate(app); //app.UseIISPlatformHandler(); // options => options.AuthenticationDescriptions.Clear()); app.UseStaticFiles(); app.UseCors(CORS_POLICY_NAME); app.UseAuthentication(); // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715 app.UseMvc(routes => { routes.MapRoute(null, "{controller}/{action}"); routes.MapRoute( name: "default", template: "{controller=Order}/{action=Index}/{id?}"); }); SampleData.Initialize(app.ApplicationServices); //ExtractClients.Process(app.ApplicationServices); //ReadClients.ReadFromFile(app.ApplicationServices); //PassportCheck.LimitExpiredPassports("36"); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); AuthData.SeedAuth(app.ApplicationServices).Wait(); }
protected ResfitSteps() { this.FileSystem = new SelfPurgingFileSystem(SampleData.TestingPath()); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SampleData seeder) { //seeder.SeedAdminUser(); //seeds our database with posts on startup //tells app to use Identity on configuration app.UseIdentity(); //tells app to use our wwwroot folder for css/js/images app.UseStaticFiles(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseBrowserLink(); loggerFactory.AddConsole(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(routes => { routes.MapRoute( name: "default", //will determine where the app directs to first template: "{controller=Home}/{action=Index}/{id?}"); }); app.Run(async(error) => { await error.Response.WriteAsync("You should not see this message. An error has occured."); }); }
public override void Execute() { foreach (SiteCollInfo siteCollInfo in Owner.WorkingSiteCollections) { using (var siteColl = Owner.ObjectsFactory.GetSite(siteCollInfo.URL)) { foreach (SiteInfo siteInfo in siteCollInfo.Sites) { using (var web = siteColl.OpenWeb(siteInfo.ID)) { var available = siteInfo.Lists; //shuffle because of big lists available.Shuffle(); foreach (ListInfo listInfo in available) { _titleUsage.Clear(); if (!listInfo.isLib) { var list = web.GetList(listInfo.Name); if (listInfo.TemplateType == SPDGListTemplateType.Tasks) { Owner.IncrementCurrentTaskProgress("Start adding items to tasks list: " + listInfo.Name + " in site: " + web.Url, 0); } else if (listInfo.TemplateType == SPDGListTemplateType.Events) { Owner.IncrementCurrentTaskProgress("Start adding events to calendar: " + listInfo.Name + " in site: " + web.Url, 0); } else { Owner.IncrementCurrentTaskProgress("Start adding items to list: " + listInfo.Name + " in site: " + web.Url, 0); } List <ISPDGListItemInfo> batch = new List <ISPDGListItemInfo>(); int itemCount = listInfo.isBigList ? WorkingDefinition.MaxNumberofItemsBigListToGenerate : WorkingDefinition.MaxNumberofItemsToGenerate; itemCount = SampleData.GetRandomNumber(itemCount * 3 / 4, itemCount); for (int i = 0; i < itemCount; i++) { var itemInfo = new SPDGListItemInfo(); if (listInfo.TemplateType == SPDGListTemplateType.Tasks) { populateTask(itemInfo); } else if (listInfo.TemplateType == SPDGListTemplateType.Events) { populateEvent(itemInfo); } else { populateItemInfo(list, itemInfo, false); } batch.Add(itemInfo); if (batch.Count > 400) { list.AddItems(batch); Owner.IncrementCurrentTaskProgress(string.Format("Created {0}/{1} items for list {2}: ", i + 1, itemCount, list.RootFolder.Url), batch.Count); batch.Clear(); } } if (batch.Count > 0) { list.AddItems(batch); Owner.IncrementCurrentTaskProgress(string.Format("Created {0} items for list {1}: ", itemCount, list.RootFolder.Url), batch.Count); batch.Clear(); } listInfo.ItemCount = itemCount; } else { _docsAdded = 0; var list = web.GetList(listInfo.Name); Owner.IncrementCurrentTaskProgress("Start adding documents to library: " + listInfo.Name + " in site: " + web.Url, 0); while (_docsAdded < WorkingDefinition.MaxNumberofDocumentLibraryItemsToGenerate) { addDocumentToFolder(list, list.RootFolder); } listInfo.ItemCount = _docsAdded; } } } } } } }
public Idea AddIdea([FromBody] Idea idea) { return(SampleData.First()); }
public void Configure(IApplicationBuilder app) { //Error page middleware displays a nice formatted HTML page for any unhandled exceptions in the request pipeline. //Note: ErrorPageOptions.ShowAll to be used only at development time. Not recommended for production. app.UseErrorPage(ErrorPageOptions.ShowAll); app.UseServices(services => { //Sql client not available on mono var useInMemoryStore = Type.GetType("Mono.Runtime") != null; // Add EF services to the services container if (useInMemoryStore) { services.AddEntityFramework(Configuration) .AddInMemoryStore() .AddDbContext <MusicStoreContext>(); } else { services.AddEntityFramework(Configuration) .AddSqlServer() .AddDbContext <MusicStoreContext>(); } // Add Identity services to the services container services.AddIdentity <ApplicationUser, IdentityRole>(Configuration) .AddEntityFrameworkStores <MusicStoreContext>() .AddDefaultTokenProviders() .AddMessageProvider <EmailMessageProvider>() .AddMessageProvider <SmsMessageProvider>(); services.ConfigureFacebookAuthentication(options => { options.AppId = "[AppId]"; options.AppSecret = "[AppSecret]"; options.Notifications = new FacebookAuthenticationNotifications() { OnAuthenticated = FacebookNotifications.OnAuthenticated, OnReturnEndpoint = FacebookNotifications.OnReturnEndpoint, OnApplyRedirect = FacebookNotifications.OnApplyRedirect }; options.BackchannelHttpHandler = new FacebookMockBackChannelHttpHandler(); options.StateDataFormat = new CustomStateDataFormat(); options.Scope.Add("email"); options.Scope.Add("read_friendlists"); options.Scope.Add("user_checkins"); }); // Add MVC services to the services container services.AddMvc(); //Add all SignalR related services to IoC. services.AddSignalR(); //Add InMemoryCache services.AddSingleton <IMemoryCache, MemoryCache>(); }); //To gracefully shutdown the server - Not for production scenarios app.Map("/shutdown", shutdown => { shutdown.Run(async context => { var appShutdown = context.ApplicationServices.GetService <IApplicationShutdown>(); appShutdown.RequestShutdown(); await Task.Delay(10 * 1000, appShutdown.ShutdownRequested); if (appShutdown.ShutdownRequested.IsCancellationRequested) { await context.Response.WriteAsync("Shutting down gracefully"); } else { await context.Response.WriteAsync("Shutting down token not fired"); } }); }); //Configure SignalR app.UseSignalR(); // Add static files to the request pipeline app.UseStaticFiles(); // Add cookie-based authentication to the request pipeline app.UseIdentity(); app.UseFacebookAuthentication(); app.UseGoogleAuthentication(options => { options.ClientId = "[ClientId]"; options.ClientSecret = "[ClientSecret]"; options.AccessType = "offline"; options.Notifications = new GoogleAuthenticationNotifications() { OnAuthenticated = GoogleNotifications.OnAuthenticated, OnReturnEndpoint = GoogleNotifications.OnReturnEndpoint, OnApplyRedirect = GoogleNotifications.OnApplyRedirect }; options.StateDataFormat = new CustomStateDataFormat(); options.BackchannelHttpHandler = new GoogleMockBackChannelHttpHandler(); }); app.UseTwitterAuthentication(options => { options.ConsumerKey = "[ConsumerKey]"; options.ConsumerSecret = "[ConsumerSecret]"; options.Notifications = new TwitterAuthenticationNotifications() { OnAuthenticated = TwitterNotifications.OnAuthenticated, OnReturnEndpoint = TwitterNotifications.OnReturnEndpoint, OnApplyRedirect = TwitterNotifications.OnApplyRedirect }; options.StateDataFormat = new CustomTwitterStateDataFormat(); options.BackchannelHttpHandler = new TwitterMockBackChannelHttpHandler(); #if ASPNET50 options.BackchannelCertificateValidator = null; #endif }); app.UseMicrosoftAccountAuthentication(options => { options.Caption = "MicrosoftAccount - Requires project changes"; options.ClientId = "[ClientId]"; options.ClientSecret = "[ClientSecret]"; options.Notifications = new MicrosoftAccountAuthenticationNotifications() { OnAuthenticated = MicrosoftAccountNotifications.OnAuthenticated, OnReturnEndpoint = MicrosoftAccountNotifications.OnReturnEndpoint, OnApplyRedirect = MicrosoftAccountNotifications.OnApplyRedirect }; options.BackchannelHttpHandler = new MicrosoftAccountMockBackChannelHandler(); options.StateDataFormat = new CustomStateDataFormat(); options.Scope.Add("wl.basic"); options.Scope.Add("wl.signin"); }); // Add MVC to the request pipeline app.UseMvc(routes => { routes.MapRoute( name: "areaRoute", template: "{area:exists}/{controller}/{action}", defaults: new { action = "Index" }); routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); routes.MapRoute( name: "api", template: "{controller}/{id?}"); }); //Populates the MusicStore sample data SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices).Wait(); }
public IActionResult Get() { var blogs = SampleData.Blogs(); return(Ok(blogs)); }
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(minLevel: LogLevel.Warning); app.UseStatusCodePagesWithRedirects("~/Home/StatusCodePage"); // Display custom error page in production when error occurs // During development use the ErrorPage middleware to display error information in the browser app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); // Configure Session. app.UseSession(); // Add static files to the request pipeline app.UseStaticFiles(); // Add cookie-based authentication to the request pipeline app.UseIdentity(); // Create an Azure Active directory application and copy paste the following var options = new OpenIdConnectOptions { Authority = "https://login.windows.net/[tenantName].onmicrosoft.com", ClientId = "c99497aa-3ee2-4707-b8a8-c33f51323fef", BackchannelHttpHandler = new OpenIdConnectBackChannelHttpHandler(), StringDataFormat = new CustomStringDataFormat(), StateDataFormat = new CustomStateDataFormat(), ResponseType = OpenIdConnectResponseType.CodeIdToken, UseTokenLifetime = false, Events = new OpenIdConnectEvents { OnMessageReceived = TestOpenIdConnectEvents.MessageReceived, OnAuthorizationCodeReceived = TestOpenIdConnectEvents.AuthorizationCodeReceived, OnRedirectToIdentityProvider = TestOpenIdConnectEvents.RedirectToIdentityProvider, OnTokenValidated = TestOpenIdConnectEvents.TokenValidated, } }; options.TokenValidationParameters.ValidateLifetime = false; options.ProtocolValidator.RequireNonce = true; options.ProtocolValidator.NonceLifetime = TimeSpan.FromDays(36500); app.UseOpenIdConnectAuthentication(options); // Add MVC to the request pipeline app.UseMvc(routes => { routes.MapRoute( name: "areaRoute", template: "{area:exists}/{controller}/{action}", defaults: new { action = "Index" }); routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); routes.MapRoute( name: "api", template: "{controller}/{id?}"); }); //Populates the MusicStore sample data SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices).Wait(); }
public void Configure(IApplicationBuilder app) { // Configure Session. app.UseSession(); // Add static files to the request pipeline app.UseStaticFiles(); // Add cookie-based authentication to the request pipeline app.UseIdentity(); app.UseFacebookAuthentication(new FacebookOptions { AppId = "550624398330273", AppSecret = "10e56a291d6b618da61b1e0dae3a8954" }); app.UseGoogleAuthentication(new GoogleOptions { ClientId = "995291875932-0rt7417v5baevqrno24kv332b7d6d30a.apps.googleusercontent.com", ClientSecret = "J_AT57H5KH_ItmMdu0r6PfXm" }); app.UseTwitterAuthentication(new TwitterOptions { ConsumerKey = "lDSPIu480ocnXYZ9DumGCDw37", ConsumerSecret = "fpo0oWRNc3vsZKlZSq1PyOSoeXlJd7NnG4Rfc94xbFXsdcc3nH" }); // The MicrosoftAccount service has restrictions that prevent the use of // http://localhost:5001/ for test applications. // As such, here is how to change this sample to uses http://ktesting.com:5001/ instead. // Edit the Project.json file and replace http://localhost:5001/ with http://ktesting.com:5001/. // From an admin command console first enter: // notepad C:\Windows\System32\drivers\etc\hosts // and add this to the file, save, and exit (and reboot?): // 127.0.0.1 ktesting.com // Then you can choose to run the app as admin (see below) or add the following ACL as admin: // netsh http add urlacl url=http://ktesting:5001/ user=[domain\user] // The sample app can then be run via: // dnx . web app.UseMicrosoftAccountAuthentication(new MicrosoftAccountOptions { DisplayName = "MicrosoftAccount - Requires project changes", ClientId = "000000004012C08A", ClientSecret = "GaMQ2hCnqAC6EcDLnXsAeBVIJOLmeutL" }); // Add MVC to the request pipeline app.UseMvc(routes => { routes.MapRoute( name: "areaRoute", template: "{area:exists}/{controller}/{action}", defaults: new { action = "Index" }); routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); routes.MapRoute( name: "api", template: "{controller}/{id?}"); }); //Populates the MusicStore sample data SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices).Wait(); }
public IEnumerable <Person> GetAllPeople() { var people = SampleData.GetPeople(); return(people); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SampleData seeder) { app.UseAuthentication(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors("Cors"); app.UseMvc(); //seeder.SeedAdminUser(); //seeder.SeedQuizes(); seeder.SeedFeeds(); }
public void EnsureCreated() { for (int i = 1; i <= 10; i++) //10 équipes { var teamName = "Équipe de " + SampleData.GenerateName(i); Teams.Add(new Team(i, teamName, i)); //équipe 1, capitaine > player 1, //équpe 2, capitaine > player 2 } for (int i = 1; i < 100; i++) { var name = SampleData.GenerateName(10 + i);//pour pas avoir le même nom var player = new Player(i, $"{name}Alias", $"{name}@bataillonMail.com", SampleData.GeneratePhoneNumber(i), name, SampleData.GenerateLastName(i), SampleData.GenerateLevel()); Players.Add(player); //avec les navigations qu'on vous demande, il devrait y avoir un teamid } //int Id, DateTime GameDateTime, int TeamDefendant, int TeamAttacker Games.Add(new Game(1, new DateTime(2020, 10, 24), 1, 3)); Games.Add(new Game(2, new DateTime(2020, 10, 24), 4, 6)); Games.Add(new Game(3, new DateTime(2020, 10, 24), 7, 2)); }
private void DoCreateUpdateModify(string testGroupName) { // Clean up any previous data SampleData.DeleteTestGroups(); var options = new ClientConnectorUploadOptions(); // options.MaximumBatchSize = 1; //--------------------------------------------------------------- // Initial creation of the objects Debug.WriteLine("Part 1: Upload that initially creates objects"); string initialInputTaxml = this.GetTestResource("InitialInput", testGroupName); LocalTermStore initialTermStore = TaxmlLoader.LoadFromString(initialInputTaxml); initialTermStore.SyncAction = new SyncAction() { IfMissing = SyncActionIfMissing.Create, IfPresent = SyncActionIfPresent.Error, IfElsewhere = SyncActionIfElsewhere.Error }; this.connector.Upload(initialTermStore, SampleData.TermStoreId, options); string initialOutputTaxml = FunctionalTests.DownloadTestDataAsTaxml(this.connector); this.AssertXmlMatchesResource(initialOutputTaxml, "InitialOutput", testGroupName); //--------------------------------------------------------------- // Perform a second upload of the exact same content, to verify that // no changes were committed to the term store Debug.WriteLine("Part 2: Duplicate upload that doesn't change anything"); initialTermStore.SyncAction = new SyncAction() { IfMissing = SyncActionIfMissing.Error, IfPresent = SyncActionIfPresent.Update, IfElsewhere = SyncActionIfElsewhere.Error }; DateTime changeTimeBefore = this.GetChangeTimeForTermStore(); this.connector.Upload(initialTermStore, SampleData.TermStoreId, options); DateTime changeTimeAfter = this.GetChangeTimeForTermStore(); Assert.AreEqual(changeTimeAfter, changeTimeBefore); //--------------------------------------------------------------- // Upload a modified input that changes every property Debug.WriteLine("Part 3: Upload that makes modifications"); string modifiedInputTaxml = this.GetTestResource("ModifiedInput", testGroupName); LocalTermStore modifiedTermStore = TaxmlLoader.LoadFromString(modifiedInputTaxml); modifiedTermStore.SyncAction = new SyncAction() { IfMissing = SyncActionIfMissing.Error, IfPresent = SyncActionIfPresent.Update, IfElsewhere = SyncActionIfElsewhere.Error }; this.connector.Upload(modifiedTermStore, SampleData.TermStoreId, options); string modifiedOutputTaxml = FunctionalTests.DownloadTestDataAsTaxml(this.connector); this.AssertXmlMatchesResource(modifiedOutputTaxml, "ModifiedOutput", testGroupName); }
int Constraints = 60000 | (50 << 22); // 1 минута и 50 альтернатив private bool Sentence2Features(System.IO.StreamWriter crf_file, SampleData sample) { // Морфологический разбор if (sample.morphology.IsNull()) { sample.morphology = gren.AnalyzeMorphology(sample.sample, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY, Constraints); } if (sample.tokenization.IsNull()) { sample.tokenization = gren.AnalyzeMorphology(sample.sample, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_TOKENIZE_ONLY, 0); } // if( sample.syntax_tree.IsNull() ) // sample.syntax_tree = gren.AnalyzeSyntax( sample.sample, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY, 0, Constraints ); if (sample.morphology.Count != sample.tokenization.Count) { return(false); } // ---------------------------------------------- // Готовим наборы признаков для каждого токена // ---------------------------------------------- List <TokenizerTokenFeatures> token_features = new List <TokenizerTokenFeatures>(); token_features.AddRange(GetFeatures(0, sample.morphology.Count, sample.morphology[0], sample.tokenization[0])); for (int iword = 1; iword < sample.morphology.Count - 1; ++iword) { List <TokenizerTokenFeatures> f = GetFeatures(iword, sample.morphology.Count, sample.morphology[iword], sample.tokenization[iword]); token_features.AddRange(f); } token_features.AddRange(GetFeatures(sample.morphology.Count - 1, sample.morphology.Count, sample.morphology[sample.morphology.Count - 1], sample.tokenization[sample.morphology.Count - 1])); System.Text.StringBuilder b = new System.Text.StringBuilder(); for (int iword = 0; iword < token_features.Count; ++iword) { b.Length = 0; TokenizerTokenFeatures f_this = token_features[iword]; PullFeatures1(b, token_features, iword, 0); // и соседние слова if (CONTEXT_SPAN > 4) { PullFeatures1(b, token_features, iword, -5); } if (CONTEXT_SPAN > 3) { PullFeatures1(b, token_features, iword, -4); } if (CONTEXT_SPAN > 2) { PullFeatures1(b, token_features, iword, -3); } if (CONTEXT_SPAN > 1) { PullFeatures1(b, token_features, iword, -2); } PullFeatures1(b, token_features, iword, -1); PullFeatures1(b, token_features, iword, 1); if (CONTEXT_SPAN > 1) { PullFeatures1(b, token_features, iword, 2); } if (CONTEXT_SPAN > 2) { PullFeatures1(b, token_features, iword, 3); } if (CONTEXT_SPAN > 3) { PullFeatures1(b, token_features, iword, 4); } if (CONTEXT_SPAN > 4) { PullFeatures1(b, token_features, iword, 5); } crf_file.Write("{0}", f_this.output_tag); crf_file.WriteLine("{0}", b.ToString()); n_train_patterns++; } crf_file.WriteLine(""); // пустые строки отделяют предложения crf_file.Flush(); return(true); }
public ActionResult Scatter() { return(View(SampleData.GetScatterData())); }
public void Configure(IApplicationBuilder app) { Console.WriteLine("Social Testing mode..."); //Below code demonstrates usage of multiple configuration sources. For instance a setting say 'setting1' is found in both the registered sources, //then the later source will win. By this way a Local config can be overridden by a different setting while deployed remotely. var configuration = new Configuration() .AddJsonFile("config.json") .AddEnvironmentVariables(); //All environment variables in the process's context flow in as configuration values. //Error page middleware displays a nice formatted HTML page for any unhandled exceptions in the request pipeline. //Note: ErrorPageOptions.ShowAll to be used only at development time. Not recommended for production. app.UseErrorPage(ErrorPageOptions.ShowAll); app.SetDefaultSignInAsAuthenticationType("External"); app.UseServices(services => { //If this type is present - we're on mono var runningOnMono = Type.GetType("Mono.Runtime") != null; // Add EF services to the services container if (runningOnMono) { services.AddEntityFramework() .AddInMemoryStore(); } else { services.AddEntityFramework() .AddSqlServer(); } services.AddScoped <MusicStoreContext>(); // Configure DbContext services.SetupOptions <MusicStoreDbContextOptions>(options => { options.DefaultAdminUserName = configuration.Get("DefaultAdminUsername"); options.DefaultAdminPassword = configuration.Get("DefaultAdminPassword"); if (runningOnMono) { options.UseInMemoryStore(); } else { options.UseSqlServer(configuration.Get("Data:DefaultConnection:ConnectionString")); } }); // Add Identity services to the services container services.AddIdentitySqlServer <MusicStoreContext, ApplicationUser>() .AddAuthentication(); // Add MVC services to the services container services.AddMvc(); //Add all SignalR related services to IoC. services.AddSignalR(); //Add InMemoryCache //Currently not able to AddSingleTon services.AddInstance <IMemoryCache>(new MemoryCache()); }); //Configure SignalR app.UseSignalR(); // Add static files to the request pipeline app.UseStaticFiles(); // Add cookie-based authentication to the request pipeline app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "External", AuthenticationMode = AuthenticationMode.Passive, ExpireTimeSpan = TimeSpan.FromMinutes(5) }); // Add cookie-based authentication to the request pipeline app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = ClaimsIdentityOptions.DefaultAuthenticationType, LoginPath = new PathString("/Account/Login") }); app.UseTwoFactorSignInCookies(); var facebookOptions = new FacebookAuthenticationOptions() { AppId = "[AppId]", AppSecret = "[AppSecret]", Notifications = new FacebookAuthenticationNotifications() { OnAuthenticated = FacebookNotifications.OnAuthenticated, OnReturnEndpoint = FacebookNotifications.OnReturnEndpoint, OnApplyRedirect = FacebookNotifications.OnApplyRedirect }, BackchannelHttpHandler = new FacebookMockBackChannelHttpHandler(), StateDataFormat = new CustomStateDataFormat() }; facebookOptions.Scope.Add("email"); facebookOptions.Scope.Add("read_friendlists"); facebookOptions.Scope.Add("user_checkins"); app.UseFacebookAuthentication(facebookOptions); app.UseGoogleAuthentication(new GoogleAuthenticationOptions() { ClientId = "[ClientId]", ClientSecret = "[ClientSecret]", AccessType = "offline", Notifications = new GoogleAuthenticationNotifications() { OnAuthenticated = GoogleNotifications.OnAuthenticated, OnReturnEndpoint = GoogleNotifications.OnReturnEndpoint, OnApplyRedirect = GoogleNotifications.OnApplyRedirect }, StateDataFormat = new CustomStateDataFormat(), BackchannelHttpHandler = new GoogleMockBackChannelHttpHandler() }); app.UseTwitterAuthentication(new TwitterAuthenticationOptions() { ConsumerKey = "[ConsumerKey]", ConsumerSecret = "[ConsumerSecret]", Notifications = new TwitterAuthenticationNotifications() { OnAuthenticated = TwitterNotifications.OnAuthenticated, OnReturnEndpoint = TwitterNotifications.OnReturnEndpoint, OnApplyRedirect = TwitterNotifications.OnApplyRedirect }, StateDataFormat = new CustomTwitterStateDataFormat(), BackchannelHttpHandler = new TwitterMockBackChannelHttpHandler() }); app.UseMicrosoftAccountAuthentication(new MicrosoftAccountAuthenticationOptions() { Caption = "MicrosoftAccount - Requires project changes", ClientId = "[ClientId]", ClientSecret = "[ClientSecret]", }); // Add MVC to the request pipeline app.UseMvc(routes => { routes.MapRoute( name: "areaRoute", template: "{area:exists}/{controller}/{action}", defaults: new { action = "Index" }); routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); routes.MapRoute( name: "api", template: "{controller}/{id?}"); }); //Populates the MusicStore sample data SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices).Wait(); }
public object GetCoordLinesData() { return(SampleData.GetCoordLinesData()); }
public void Action_ChangedWithSampleData_ShouldUpdatePictures() { // Setup initial Mongo project has 1 picture and 2 captions var lfProj = _lfProj; var data = new SampleData(); _conn.UpdateMockLfLexEntry(data.bsonTestData); string expectedInternalFileName = Path.Combine("Pictures", data.bsonTestData["senses"][0]["pictures"][0]["fileName"].ToString()); string expectedExternalFileName = data.bsonTestData["senses"][0]["pictures"][1]["fileName"].ToString(); int newMongoPictureCount = data.bsonTestData["senses"][0]["pictures"].AsBsonArray.Count; int newMongoCaptionCount = data.bsonTestData["senses"][0]["pictures"][0]["caption"].AsBsonDocument.Count(); Assert.That(newMongoPictureCount, Is.EqualTo(2)); Assert.That(newMongoCaptionCount, Is.EqualTo(2)); // Initial FDO project has 63 entries, 3 internal pictures, and 1 externally linked picture FdoCache cache = _cache; ILexEntryRepository entryRepo = _servLoc.GetInstance <ILexEntryRepository>(); int originalNumOfFdoPictures = entryRepo.AllInstances(). Count(e => (e.SensesOS.Count > 0) && (e.SensesOS[0].PicturesOS.Count > 0)); Assert.That(entryRepo.Count, Is.EqualTo(OriginalNumOfFdoEntries)); Assert.That(originalNumOfFdoPictures, Is.EqualTo(3 + 1)); string expectedGuidStr = data.bsonTestData["guid"].AsString; Guid expectedGuid = Guid.Parse(expectedGuidStr); var entryBefore = cache.ServiceLocator.GetObject(expectedGuid) as ILexEntry; Assert.That(entryBefore.SensesOS.Count, Is.GreaterThan(0)); Assert.That(entryBefore.SensesOS.First().PicturesOS.Count, Is.EqualTo(1)); // Exercise adding 1 picture with 2 captions. Note that the picture that was previously attached // to this FDO entry will end up being deleted, because it does not have a corresponding picture in LF. data.bsonTestData["authorInfo"]["modifiedDate"] = DateTime.UtcNow; _conn.UpdateMockLfLexEntry(data.bsonTestData); sutMongoToFdo.Run(lfProj); // Verify "Added" picture is now the only picture on the sense (because the "old" picture was deleted), // and that it has 2 captions with the expected values. entryRepo = _servLoc.GetInstance <ILexEntryRepository>(); int numOfFdoPictures = entryRepo.AllInstances(). Count(e => (e.SensesOS.Count > 0) && (e.SensesOS[0].PicturesOS.Count > 0)); Assert.That(entryRepo.Count, Is.EqualTo(OriginalNumOfFdoEntries)); Assert.That(numOfFdoPictures, Is.EqualTo(originalNumOfFdoPictures)); var entry = cache.ServiceLocator.GetObject(expectedGuid) as ILexEntry; Assert.IsNotNull(entry); Assert.That(entry.Guid, Is.EqualTo(expectedGuid)); Assert.That(entry.SensesOS.Count, Is.GreaterThan(0)); Assert.That(entry.SensesOS.First().PicturesOS.Count, Is.EqualTo(2)); Assert.That(entry.SensesOS[0].PicturesOS[0].PictureFileRA.InternalPath.ToString(), Is.EqualTo(expectedInternalFileName)); Assert.That(entry.SensesOS[0].PicturesOS[1].PictureFileRA.InternalPath.ToString(), Is.EqualTo(expectedExternalFileName)); LfMultiText expectedNewCaption = ConvertFdoToMongoLexicon. ToMultiText(entry.SensesOS[0].PicturesOS[0].Caption, cache.ServiceLocator.WritingSystemManager); int expectedNumOfNewCaptions = expectedNewCaption.Count(); Assert.That(expectedNumOfNewCaptions, Is.EqualTo(2)); string expectedNewVernacularCaption = expectedNewCaption["qaa-x-kal"].Value; string expectedNewAnalysisCaption = expectedNewCaption["en"].Value; Assert.That(expectedNewVernacularCaption.Equals("First Vernacular caption")); Assert.That(expectedNewAnalysisCaption.Equals("Internal path reference")); var testSubEntry = cache.ServiceLocator.GetObject(Guid.Parse(TestSubEntryGuidStr)) as ILexEntry; Assert.That(testSubEntry, Is.Not.Null); Assert.That(testSubEntry.SensesOS[0].PicturesOS[0].PictureFileRA.InternalPath.ToString(), Is.EqualTo("Pictures\\TestImage.tif")); var kenEntry = cache.ServiceLocator.GetObject(Guid.Parse(KenEntryGuidStr)) as ILexEntry; Assert.That(kenEntry, Is.Not.Null); Assert.That(kenEntry.SensesOS[0].PicturesOS[0].PictureFileRA.InternalPath.ToString(), Is.EqualTo("F:\\src\\xForge\\web-languageforge\\test\\php\\common\\TestImage.jpg")); }
static void Main(string[] args) { Console.WriteLine("Start performance test..."); Console.WriteLine($"Stopwatch.Frequency: {Stopwatch.Frequency}"); // 샘플데이터 SampleData sampleData = new SampleData(); // 압축기 리스트 var compressors = new List <ICompressor>() { new DeflateCompressor(), new GZipCompressor(), // new SevenZip.Compression.LZMA.SevenZipHelper() // 압축률은 좋은데 너무 느려서 못쓰겠음 new IonWikiLZ4(), new K4osLZ4(), new OzoneSnappy() }; foreach (var compressor in compressors) { // 통계 long[,] stat = new long[sampleData.Texts.Count, (int)StatColumn.MAX_VALUE]; int maxDataSize = sampleData.Texts.Max((text) => text.Length); Stopwatch stopwatch = new Stopwatch(); for (int i = 0; i < sampleData.Texts.Count; i++) { Console.WriteLine($"Sample data index: {i}"); // 수행횟수 계산 double basicCount = (double)maxDataSize / sampleData.Texts[i].Length; double scaledCount = Math.Sqrt(basicCount); double scaledFactor = Math.Max(1.0d, Math.Log(basicCount)); stat[i, (int)StatColumn.TrialCount] = (long)(scaledCount * scaledFactor * scaledFactor * TRIAL_FACTOR); bool equality = false; for (int j = 0; j < stat[i, (int)StatColumn.TrialCount]; j++) { // 인코딩 stopwatch.Restart(); byte[] encodedData = Encoding.UTF8.GetBytes(sampleData.Texts[i]); stopwatch.Stop(); stat[i, (int)StatColumn.Encoding] += stopwatch.ElapsedTicks; stat[i, (int)StatColumn.EncodedSize] += encodedData.Length; // 압축 stopwatch.Restart(); byte[] compressedData = compressor.Compress(encodedData); stopwatch.Stop(); stat[i, (int)StatColumn.Compression] += stopwatch.ElapsedTicks; stat[i, (int)StatColumn.CompressedSize] += compressedData.Length; // 압축해제 stopwatch.Restart(); byte[] decompressedData = compressor.Decompress(compressedData); stopwatch.Stop(); stat[i, (int)StatColumn.Decompression] += stopwatch.ElapsedTicks; // 디코딩 stopwatch.Restart(); string decodedText = Encoding.UTF8.GetString(decompressedData); stopwatch.Stop(); stat[i, (int)StatColumn.Decoding] += stopwatch.ElapsedTicks; // 전/후 데이터 비교 (샘플데이터마다 한 번만 수행) if (!equality) { // 원본 데이터 비교 Console.WriteLine($"Original text length : {sampleData.Texts[i].Length}"); Console.WriteLine($"Processed text length: {decodedText.Length}"); equality = string.Compare(sampleData.Texts[i], decodedText) == 0; if (!equality) { Console.WriteLine($"Two texts are mismatch!"); return; } // 인코딩 데이터 비교 Console.WriteLine($"Encoded data length : {encodedData.Length}"); Console.WriteLine($"Processed data length: {decompressedData.Length}"); equality = encodedData.SequenceEqual(decompressedData); if (!equality) { Console.WriteLine($"Two data are mismatch"); return; } } } } // 스탯 출력 Console.WriteLine("---------- " + compressor.GetType().Name + "Statistics ----------"); Console.WriteLine("Original Length, Encoded Size, Compressed Size, Compression Ratio, Trial Count, Encoding Time, Compression Time, Decompression Time, Decoding Time"); for (int i = 0; i < sampleData.Texts.Count; i++) { Console.WriteLine(string.Format(@"{0}, {1}, {2}, ,{3}, {4:F4}, {5:F4}, {6:F4}, {7:F4}", sampleData.Texts[i].Length, stat[i, (int)StatColumn.EncodedSize] / stat[i, (int)StatColumn.TrialCount], stat[i, (int)StatColumn.CompressedSize] / stat[i, (int)StatColumn.TrialCount], stat[i, (int)StatColumn.TrialCount], ((double)stat[i, (int)StatColumn.Encoding] / (Stopwatch.Frequency / TIME_RESOLUTION)) / stat[i, (int)StatColumn.TrialCount], ((double)stat[i, (int)StatColumn.Compression] / (Stopwatch.Frequency / TIME_RESOLUTION)) / stat[i, (int)StatColumn.TrialCount], ((double)stat[i, (int)StatColumn.Decompression] / (Stopwatch.Frequency / TIME_RESOLUTION)) / stat[i, (int)StatColumn.TrialCount], ((double)stat[i, (int)StatColumn.Decoding] / (Stopwatch.Frequency / TIME_RESOLUTION)) / stat[i, (int)StatColumn.TrialCount] )); } } }
public void AddToIndex(SampleData sampleData) { LuceneSearch.AddUpdateLuceneIndex(sampleData); }
private void OnShow() { Weathers = SampleData.GetWeathers(Count).ToObservable(); }
private byte[] GetSampleHeaderData(SampleData sampleData, int baseNote, int fineTune, int sampleLen, byte bitsPerSample, int chans, int sampleRate) { MemoryStream stream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(stream); const byte deltaPackedSample = 0; const int maxNameLen = 22; bool isStereo = chans > 1; //int fineTune = 0; //int relNoteNumber = 0; //ModCommons.GetRelNoteAndFTuneProperties(sampleData.RelNoteNumber, sampleData.FineTune, sampleRate, out relNoteNumber, out fineTune); int offset; offset = 0; writer.Seek(offset, SeekOrigin.Begin); writer.Write(Utility.MakeByte4FromInt(sampleLen)); offset = 4; writer.Seek(offset, SeekOrigin.Begin); writer.Write(Utility.MakeByte4FromInt(XMUtils.GetSampleLoopValue(sampleData.LoopStart, bitsPerSample, isStereo))); offset = 8; writer.Seek(offset, SeekOrigin.Begin); // Loop End value is relative to LoopStart writer.Write(Utility.MakeByte4FromInt(XMUtils.GetSampleLoopValue((sampleData.LoopEnd - sampleData.LoopStart), bitsPerSample, isStereo))); offset = 12; writer.Seek(offset, SeekOrigin.Begin); writer.Write((byte)sampleData.DefaultVolume); offset = 13; writer.Seek(offset, SeekOrigin.Begin); writer.Write((sbyte)fineTune); offset = 14; writer.Seek(offset, SeekOrigin.Begin); byte loopMode = XMUtils.GetSampleLoopMode(sampleData.LoopMode); byte type = (byte)(loopMode + (bitsPerSample) + (isStereo ? 0x20 : 0)); writer.Write(type); offset = 15; writer.Seek(offset, SeekOrigin.Begin); writer.Write(XMUtils.GetPanning(sampleData.Panning)); offset = 16; writer.Seek(offset, SeekOrigin.Begin); writer.Write((sbyte)baseNote); //writer.Write((sbyte)XMUtil.GetRelNoteNumber(sampleData.RelNoteNumber, sampleRate, relNoteNumber, fineTune)); offset = 17; writer.Seek(offset, SeekOrigin.Begin); writer.Write(deltaPackedSample); offset = 18; writer.Seek(offset, SeekOrigin.Begin); writer.Write(Utility.GetBytesFromString(sampleData.Name, maxNameLen)); writer.Seek(0, SeekOrigin.Begin); return(Utility.GetBytesFromStream(stream, stream.Length)); }
public async Task BuildAsync_GivenUser_SetsContactInfo() { _fakeUserManager.Setup(x => x.LoadUserByIdAsync(123)).Returns(Task.FromResult((User)SampleData.Consultant())); EditContactInfoViewModelBuilder subject = _fixture.Create <EditContactInfoViewModelBuilder>(); var viewModel = await subject.BuildAsync(123); Assert.AreEqual(123, viewModel.UserId); Assert.AreEqual("Bill", viewModel.FirstName); Assert.AreEqual("Smith", viewModel.LastName); Assert.AreEqual("*****@*****.**", viewModel.EmailAddress); Assert.AreEqual("1234567890", viewModel.PhoneNumber); }
private static async Task SeedSampleData(IServiceProvider serviceProvider) { var db = serviceProvider.GetRequiredService <MainDbContext>(); //Look for any menus. if (await db.SampleData.CountAsync() > 0) { return; // DB has been seeded } var quotes = new SampleData[] { new SampleData { Quote = "Be a good person but don’t waste time to prove it.", CreatedBy = 1 }, new SampleData { Quote = "Your heart is too valuable. Don’t allow arrogance, jealousy, and hatred to be within it.", CreatedBy = 1 }, new SampleData { Quote = "Our train is heading towards death, and we are worried about life.", CreatedBy = 1 }, new SampleData { Quote = "Do good and good will come to you.", CreatedBy = 1 }, new SampleData { Quote = "Forgive and forget not revenge and regret.", CreatedBy = 1 }, new SampleData { Quote = "Be strong when you are weak, Be brave when you are scared, Be humble when you are victorious.", CreatedBy = 1 }, new SampleData { Quote = "Search a beautiful heart, not a beautiful face. Beautiful things are not always good, but good things are always beautiful.", CreatedBy = 1 }, new SampleData { Quote = "Time is like a sword, cut it before it cuts you.", CreatedBy = 1 }, new SampleData { Quote = "Do not sit idle, for indeed death is seeking you.", CreatedBy = 1 }, new SampleData { Quote = "When you learn to accept rather than expect, you’ll have more smiles and less disappointments.", CreatedBy = 1 }, new SampleData { Quote = "You are truly lost when the fear of Allah no longer exists in your heart.", CreatedBy = 1 }, new SampleData { Quote = "The most amazing thing about Allah’s Mercy is that it’s constant, never stops, whether you realize it, or not.", CreatedBy = 1 }, new SampleData { Quote = "The first to give salam is better, the first to apologise is braver, the first to forgive is stronger.", CreatedBy = 1 }, new SampleData { Quote = "Forgive and forget not revenge and regret.", CreatedBy = 1 }, new SampleData { Quote = "Always speak truth, even if there is fear in speaking the truth.", CreatedBy = 1 } }; foreach (SampleData q in quotes) { db.SampleData.Add(q); } db.SaveChanges(); }
public void CanQueryDatesByDayOfWeek() { using (var store = GetDocumentStore()) { var knownDay = DateTime.Parse("2014-03-31", CultureInfo.InvariantCulture).Date; // This is a Monday using (var session = store.OpenSession()) { var monday = new SampleData { Date = knownDay }; var tuesday = new SampleData { Date = knownDay.AddDays(1) }; var wednesday = new SampleData { Date = knownDay.AddDays(2) }; var thursday = new SampleData { Date = knownDay.AddDays(3) }; var friday = new SampleData { Date = knownDay.AddDays(4) }; var saturday = new SampleData { Date = knownDay.AddDays(5) }; var sunday = new SampleData { Date = knownDay.AddDays(6) }; Assert.Equal(DayOfWeek.Monday, monday.Date.DayOfWeek); Assert.Equal(DayOfWeek.Tuesday, tuesday.Date.DayOfWeek); Assert.Equal(DayOfWeek.Wednesday, wednesday.Date.DayOfWeek); Assert.Equal(DayOfWeek.Thursday, thursday.Date.DayOfWeek); Assert.Equal(DayOfWeek.Friday, friday.Date.DayOfWeek); Assert.Equal(DayOfWeek.Saturday, saturday.Date.DayOfWeek); Assert.Equal(DayOfWeek.Sunday, sunday.Date.DayOfWeek); session.Store(monday); session.Store(tuesday); session.Store(wednesday); session.Store(thursday); session.Store(friday); session.Store(saturday); session.Store(sunday); session.SaveChanges(); } WaitForIndexing(store); using (var session = store.OpenSession()) { var onKnownDay = session.Query <SampleData>() .Customize(x => x.WaitForNonStaleResults()) .Where(x => x.Date == knownDay) .ToList(); Assert.Equal(1, onKnownDay.Count()); Assert.Equal(DayOfWeek.Monday, onKnownDay.Single().Date.DayOfWeek); var monday = session.Query <SampleData>().Where(x => x.Date.DayOfWeek == DayOfWeek.Monday).ToList(); var tuesday = session.Query <SampleData>().Where(x => x.Date.DayOfWeek == DayOfWeek.Tuesday).ToList(); var wednesday = session.Query <SampleData>().Where(x => x.Date.DayOfWeek == DayOfWeek.Wednesday).ToList(); var thursday = session.Query <SampleData>().Where(x => x.Date.DayOfWeek == DayOfWeek.Thursday).ToList(); var friday = session.Query <SampleData>().Where(x => x.Date.DayOfWeek == DayOfWeek.Friday).ToList(); var saturday = session.Query <SampleData>().Where(x => x.Date.DayOfWeek == DayOfWeek.Saturday).ToList(); var sunday = session.Query <SampleData>().Where(x => x.Date.DayOfWeek == DayOfWeek.Sunday).ToList(); Assert.Equal(1, monday.Count); Assert.Equal(1, tuesday.Count); Assert.Equal(1, wednesday.Count); Assert.Equal(1, thursday.Count); Assert.Equal(1, friday.Count); Assert.Equal(1, saturday.Count); Assert.Equal(1, sunday.Count); } } }
private void addDocumentToFolder(SPDGList docLib, SPDGFolder folder) { fileTypeRotator(); byte[] fileContent = getFileContent(); Random rnd = new Random(); int randomValue = rnd.Next(7); string url = ""; if ((randomValue % 6) == 0) { url = SampleData.GetSampleValueRandom(SampleData.Documents) + " " + SampleData.GetSampleValueRandom(SampleData.Departments.Select(d => d.Department).ToList()) + "." + _currentFileType; } else if ((randomValue % 5) == 0) { url = SampleData.GetSampleValueRandom(SampleData.Years) + " " + SampleData.GetSampleValueRandom(SampleData.Documents) + " " + SampleData.GetSampleValueRandom(SampleData.Departments.Select(d => d.Department).ToList()) + "." + _currentFileType; } else if ((randomValue % 4) == 0) { url = SampleData.GetSampleValueRandom(SampleData.Documents) + " " + SampleData.GetSampleValueRandom(SampleData.FirstNames) + "." + _currentFileType; } else if ((randomValue % 3) == 0) { url = SampleData.GetSampleValueRandom(SampleData.Documents) + " " + SampleData.GetSampleValueRandom(SampleData.Years) + "." + _currentFileType; } else { url = SampleData.GetSampleValueRandom(SampleData.Documents) + "." + _currentFileType; } var spFile = folder.AddFile(url, fileContent, true); var fileItem = spFile.Item; if (fileItem != null) { populateItemInfo(docLib, fileItem, true); fileItem.Update(); } _docsAdded++; foreach (var childFolder in folder.SubFolders) { if (_docsAdded >= WorkingDefinition.MaxNumberofDocumentLibraryItemsToGenerate) { break; } if (childFolder.Url.IndexOf("/Forms") == -1) { addDocumentToFolder(docLib, childFolder); } } Owner.IncrementCurrentTaskProgress("Adding document to folder: " + folder.Url); }
public void Configure(IApplicationBuilder app) { // force the en-US culture, so that the app behaves the same even on machines with different default culture var supportedCultures = new[] { new CultureInfo("en-US") }; app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = supportedCultures, SupportedUICultures = supportedCultures }); app.UseStatusCodePagesWithRedirects("~/Home/StatusCodePage"); // Error page middleware displays a nice formatted HTML page for any unhandled exceptions in the // request pipeline. // Note: Not recommended for production. app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.Use((context, next) => { context.Response.Headers["Arch"] = RuntimeInformation.ProcessArchitecture.ToString(); return(next()); }); app.Use(async(context, next) => { // Who will get admin access? For demo sake I'm listing the currently logged on user as the application // administrator. But this can be changed to suit the needs. var identity = (ClaimsIdentity)context.User.Identity; if (context.User.Identity.Name == WindowsIdentity.GetCurrent().Name) { identity.AddClaim(new Claim("ManageStore", "Allowed")); } await next.Invoke(); }); // Configure Session. app.UseSession(); // Add static files to the request pipeline app.UseStaticFiles(); // Add the endpoint routing matcher middleware to the request pipeline app.UseRouting(); // Add cookie-based authentication to the request pipeline app.UseAuthentication(); // Add the authorization middleware to the request pipeline app.UseAuthorization(); // Add endpoints to the request pipeline app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "areaRoute", pattern: "{area:exists}/{controller}/{action}", defaults: new { action = "Index" }); endpoints.MapControllerRoute( name: "default", pattern: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); endpoints.MapControllerRoute( name: "api", pattern: "{controller}/{id?}"); }); //Populates the MusicStore sample data SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices, false).Wait(); }