Blog

  • controlCartography

    controlCartography

    Public code release for: Flexible coordinator and switcher hubs for adaptive task control Cocuzza et al., 2020 (In Press). Journal of Neuroscience.

    Carrisa Cocuzza (carrisacocuzza@gmail.com), The Cole Lab (http://www.colelab.org/)

    See genUsage.txt for general usage instructions and comments

    Directory Structure

    Ordered by project workflow (e.g., not alphabetical)

    Directory: partitionDemos/

    • Contains demo code for implementing the Cole-Anticevic (CA) network partition to organize functional connectivity (FC) estimates (e.g., adjacency matrices) into a network community structure. Also contains demo code for assessing empirical resting-state reassignments in relation to the CA partition and applying this empirically adjusted partition to task-evoked FC data (and to be used for analyses represented in the following directories)

    Directory: restTaskFC_Comparisons/

    • Contains MATLAB functions for computing resting-state FC and task-state FC with Pearson’s Correlation Coefficient
    • Contains demo code for assessing rest-to-task changes in FC; e.g., descriptive analyses of changes to FC architecture between resting state and task-evoked state(s); as opposed to mechanistic and/or functional analyses (see below)

    Directory: networkDiagnosticMetrics/

    • Contains demo code for diagnosing network-mechanisms of interest. Diagnostic metrics demonstrated include: global variability coefficient (GVC), between-network variability coefficient (BVC), and network flexibility (NF)
    • See networkDiagnosticMetrics/References.md for a full reference list associated with each metric (and additional info on public repositories outside of github)

    Directory: cartographicMethod/

    • Contains demo code for implementing our cartographic representation of cognitive control system functioning, vis-a-vis the previously demonstrated analyses and diagnostic metrics

    Directory: sampleResults/

    • Contains sample figures and videos associated with the project herein. See sampleResultsText.txt for associated text.

    Visit original content creator repository
    https://github.com/ColeLab/controlCartography

  • bank_acccount

    Banking account V1 ⚡️

    Getting Started

    These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.

    You’ll need Git and Docker.

    How To Use

    From your command line, clone and run Bank account:

    # Clone this repository
    git clone https://github.com/renatocosta/turnoverbnb.git
    
    # Go into the repository
    cd turnoverbnb
    
    ### Docker Commands
    BUILD IMAGE : docker-compose build &&  docker-compose up -d
    
    ### Docker Commands
    docker-compose exec app bash -c "cd framework && composer install"
    docker-compose exec app bash -c "cd framework && php artisan migrate"
    docker-compose exec app bash -c "cd framework && php artisan db:seed --class=UserSeeder"
    docker-compose exec app bash -c "cd framework && php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider""
    docker-compose exec app bash -c "cd framework && php artisan l5-swagger:generate"
    docker-compose exec app bash -c "cd framework && php artisan vendor:publish --provider="Nwidart\Modules\LaravelModulesServiceProvider""

    Unit testing

    1) Bank Account: docker-compose exec app framework/vendor/bin/phpunit --testsuite BankAccount --coverage-html framework/storage/tests
    
    2) Bank Account Operations: docker-compose exec app framework/vendor/bin/phpunit --testsuite BankAccountOperations --coverage-html framework/storage/tests
    
    3) End-to-End: docker-compose exec php-fpm framework/vendor/bin/phpunit --testsuite BankSystem --coverage-html framework/storage/tests
    
    ### Coverage Report: framework/storage/tests/
    

    Image

    Let’s Run the Application

    http://localhost/api/documentation
    
    ### Logs: framework/storage/logs/laravel.log
    

    Event Storming

    Go through all of the learning journey using Event Storming for understanding the business needs as shown below

    Steps

    Image

    Bounded contexts

    Image

    BankAccount

    BankAccountOperations

    Warning

    I am not taking security, performance, concurrency and among other concerns into consideration.
    I am also aware of low unit testing code coverage.

    Improvements

    Repository method names should be replaced with ones that meet the good practices.
    Swagger URL root should be replaced with a CONSTANT.
    Replace HTTP response codes with the right ones.
    In order to make sure the right balance I strongly recommend use Event Sourcing as an approach to capture every changing state.
    Add authentication in order to protect the routes as well.
    Allow creating new users.

    Knowledgements

    Domain-Driven Design, Event Storming

    Visit original content creator repository https://github.com/renatocosta/bank_acccount
  • bank_acccount

    Banking account V1 ⚡️

    Getting Started

    These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.

    You’ll need Git and Docker.

    How To Use

    From your command line, clone and run Bank account:

    # Clone this repository
    git clone https://github.com/renatocosta/turnoverbnb.git
    
    # Go into the repository
    cd turnoverbnb
    
    ### Docker Commands
    BUILD IMAGE : docker-compose build &&  docker-compose up -d
    
    ### Docker Commands
    docker-compose exec app bash -c "cd framework && composer install"
    docker-compose exec app bash -c "cd framework && php artisan migrate"
    docker-compose exec app bash -c "cd framework && php artisan db:seed --class=UserSeeder"
    docker-compose exec app bash -c "cd framework && php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider""
    docker-compose exec app bash -c "cd framework && php artisan l5-swagger:generate"
    docker-compose exec app bash -c "cd framework && php artisan vendor:publish --provider="Nwidart\Modules\LaravelModulesServiceProvider""

    Unit testing

    1) Bank Account: docker-compose exec app framework/vendor/bin/phpunit --testsuite BankAccount --coverage-html framework/storage/tests
    
    2) Bank Account Operations: docker-compose exec app framework/vendor/bin/phpunit --testsuite BankAccountOperations --coverage-html framework/storage/tests
    
    3) End-to-End: docker-compose exec php-fpm framework/vendor/bin/phpunit --testsuite BankSystem --coverage-html framework/storage/tests
    
    ### Coverage Report: framework/storage/tests/
    

    Image

    Let’s Run the Application

    http://localhost/api/documentation
    
    ### Logs: framework/storage/logs/laravel.log
    

    Event Storming

    Go through all of the learning journey using Event Storming for understanding the business needs as shown below

    Steps

    Image

    Bounded contexts

    Image

    BankAccount

    BankAccountOperations

    Warning

    I am not taking security, performance, concurrency and among other concerns into consideration.
    I am also aware of low unit testing code coverage.

    Improvements

    Repository method names should be replaced with ones that meet the good practices.
    Swagger URL root should be replaced with a CONSTANT.
    Replace HTTP response codes with the right ones.
    In order to make sure the right balance I strongly recommend use Event Sourcing as an approach to capture every changing state.
    Add authentication in order to protect the routes as well.
    Allow creating new users.

    Knowledgements

    Domain-Driven Design, Event Storming

    Visit original content creator repository https://github.com/renatocosta/bank_acccount
  • org.mozilla.Thunderbird

    Visit original content creator repository
    https://github.com/RogueScholar/org.mozilla.Thunderbird

  • MRF

    MRF Utility

    Excel Add-In for Streamlined Stock Taking and Tallying

    Welcome to the MRF Utility—an advanced Excel add-in designed to optimize stock-taking and tallying processes. Whether you’re managing stock data or automating workflows, this tool ensures precision and saves valuable time.

    🚀 Key Features

    1. Stock Taking Program

      Easily manage stock-taking sheets by product groups and efficiently tally data for the INS Tube Flap.

    2. Customizable Reports

      Export data directly from SAP transactions (ZNBPSTK, ZDL) and process it seamlessly in Excel.

    3. Set Checker Tool

      Validate and cross-check set billings with a single click for accurate reporting.

    4. Pull Compliance Tool

      Automate the FDC to SOF workflows using predefined templates, streamlining data handling.

    📋 Getting Started

    Prerequisites

    Microsoft Excel 2010 or Later
    Ensure compatibility with the add-in.
    Trust Center Settings
    Modify these settings during the initial setup (one-time requirement).
    

    🛠️ Installation Steps

    Download the latest release of the add-in from the GitHub Releases page.
    Locate the .xlam file, right-click it, and select Properties. Under Security, check Unblock, and click OK.
    Open Excel and navigate to:
    File > Options > Add-ins > Manage: Excel Add-ins > Go...
    Click Browse, locate the .xlam file, and click OK to add it.
    Access the utility via the M R F tab in the Excel Ribbon.
    

    ⚙️ How to Use

    1. Export Data from SAP

      Generate spreadsheets from relevant SAP transactions (e.g., ZNBPSTK, ZDL).

    2. Utilize the MRF Utility Features

      Stock Taking Program: Use the M R F tab to execute the INS Tube Flap tallying process.
      Set Checker Tool: Validate and report on set billings effortlessly.
      Pull Compliance Tool: Manage FDC to SOF workflows with ease using predefined templates.

    🤝 Contributing

    If you know Excel Programming and wants to improve and add your own new features. Follow these steps to enhance this tool:

    Fork this repository.

    Create a new branch for your feature:

        git checkout -b feature/your-feature-name
    

    Commit your changes:

        git commit -m "Add your feature"
    

    Push the branch:

        git push origin feature/your-feature-name
    

    Submit a pull request for review.

    💬 Support

    Have questions, suggestions, or issues? Feel free to reach out via the Issues section on GitHub.

    Visit original content creator repository
    https://github.com/MRF-UTILITY/MRF

  • Express-Authentication-Template

    API To API Communication

    API to API Connection is federated through Identity Server. We are using Client Credential bearer token authentication model for this. For this we need to create 2 API projects. Let’s say API-A and API-B. Then we need to create an Identity Server to sit in the middle and federate secure access.

    We need to communicate to an endpoint in API-B from API-A

    Configure API Project A

    Create a new ASP.NET Core WebAPI Project. We call it it API-A

    Configure API Project B

    Create a new ASP.NET Core WebAPI Project. We call it it API-B

    Configure Identity Server

    Create a new ASP.NET Core MVC Project. We call it it Identity Server


    CONFIGURE IDENTITY SERVER

    Create a new ASP.NET Core MVC Project. We call it it Identity Server

    Install NuGet Packages

    IdentityServer4
    IdentityServer4.AspNetIdentity
    Microsoft.AspNetCore.Identity.EntityFrameworkCore
    Microsoft.EntityFrameworkCore
    Microsoft.EntityFrameworkCore.Design
    Microsoft.EntityFrameworkCore.SqlServer
    

    Package Why we are using it?
    IdentityServer4 This is the core library Identity Server 4
    IdentityServer4.AspNetIdentity There are lot of ways to store user info on our application. The secure and recomended way is to use AspNetIdentity system
    Microsoft.EntityFrameworkCore We are using EF Core 6 to access our databases
    Microsoft.AspNetCore.Identity.EntityFrameworkCore EF Core 6 support for AspNEtCore Identity
    Microsoft.EntityFrameworkCore.Design This is a design component required for EF Core 6 migrations and more
    Microsoft.EntityFrameworkCore.SqlServer EF 6 Core Support for SQL Server. We are going to store our data on an SQL Server database

    Configure AppSettings.json

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
    
      "AllowedHosts": "*",
    
      "ConnectionStrings": {
        "TIS": "Server=DB_SERVER;Database=DATABASE;Trusted_Connection=True;"
      },
    
      "IdentityServer": {
        "Scopes": [ "ScxWebApi", "ScxWebApiDev" ],
        "Resources": [
          {
            "Name": "ScxWebApi",
            "DisplayName": "Production Web API",
            "Scopes": [ "ScxWebApi" ]
          },
          {
            "Name": "ScxWebApiDev",
            "DisplayName": "Development Web API",
            "Scopes": [ "ScxWebApiDev" ]
          }
        ],
        "Clients": [
          {
            "Name": "Postman Client",
            "ClientId": "admin",
            "ClientSecrets": [ "admin123" ],
            "Scopes": [ "ScxWebApi", "ScxWebApiDev" ],
            "GrandType": "ClientCredentials"
          },
    
          {
            "Name": "Mobile Client",
            "ClientId": "sangee",
            "ClientSecrets": [ "sangee123" ],
            "Scopes": [ "ScxWebApi", "ScxWebApiDev" ],
            "GrandType": "ResourceOwnerPasswordAndClientCredentials"
          }
        ]
      }
    
    }
    

    Options Why we are using it?
    ConnectionStrings Connection String to work with EF 6 Core
    IdentityServer — Scopes An array of all scopes (API Names) our Identity Server 4 need to handle
    IdentityServer — Resources A list of resources (API Infos) to be configured with Identity Server 4
    IdentityServer — Clients A list of clients and their allowed scopes and token mechanism

    Setup Startup.cs

    public void ConfigureServices(IServiceCollection services)
            {
                //Configure EF6
                services.AddDbContext<AppDbContext>(config =>
                {
                    config.UseSqlServer(Configuration.GetConnectionString("TIS"));
                });
    
                //Configure Identity
                services.AddIdentity<IdentityUser, IdentityRole>(config =>
                {
                    config.Password.RequiredLength = 4;
                    config.Password.RequireDigit = false;
                    config.Password.RequiredUniqueChars = 0;
                    config.Password.RequireNonAlphanumeric = false;
                    config.Password.RequireUppercase = false;
                    config.SignIn.RequireConfirmedEmail = false;
                })                
                    .AddEntityFrameworkStores<AppDbContext>()
                    .AddDefaultTokenProviders();
    
                //Configure IdentityServer
                services.AddIdentityServer()
                    .AddInMemoryApiResources(Config.GetApiResources(Configuration))
                    .AddInMemoryClients(Config.GetApiClients(Configuration))
                    .AddInMemoryApiScopes(Config.GetApiScopes(Configuration))
                    .AddDeveloperSigningCredential()
                    .AddAspNetIdentity<IdentityUser>()
                    .AddCustomResourceOwnerPasswordValidaton();
    
                services.AddControllersWithViews();
            }
            
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                app.UseHttpsRedirection();
                app.UseStaticFiles();
                app.UseRouting();
                
                //Use Identity Servr
                app.UseIdentityServer();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                });
            }

    Identity Server Configurations

    Now we need to grab contents from AppSettings.json to be provided to Identity Server 4 in meaningfull format. Let’s create a model similar to AppSettings.json provided above for parsing

    namespace IdentityServer.Configurations.Configs
    {
        public class IdentityAppSettings
        {
            public List<IdentityResources> Resources { get; set; }
            public List<string> Scopes { get; set; }
            public List<IdentityClient> Clients { get; set; }
        }
    
        public class IdentityResources
        {
            public string Name { get; set; }
            public string DisplayName { get; set; }
            public List<string> Scopes { get; set; }
        }
    
        public class IdentityClient
        {
            public string Name { get; set; }
            public string ClientId { get; set; }
            public List<string> ClientSecrets { get; set; }
            public string GrandType { get; set; }
            public List<string> Scopes { get; set; }
        }
    }

    Identity Server Configurations II

    Now let’s create a class that parses AppSettings.json and exposes config endpoints to be used in Startup.cs

    namespace IdentityServer.Configurations.Configs
    {
        public static class Config
        {
    
            public static IEnumerable<ApiResource> GetApiResources(IConfiguration config)
            {
                var appsettingsResources = config.GetSection("IdentityServer:Resources").Get<IEnumerable<IdentityResources>>();
                var resources = new List<ApiResource>();
                foreach (var res in appsettingsResources)
                {
                    resources.Add(new ApiResource(res.Name, res.DisplayName) { Scopes = res.Scopes });
                }
                return resources;
            }
    
            public static IEnumerable<Client> GetApiClients(IConfiguration config)
            {
                var appsettingsClients = config.GetSection("IdentityServer:Clients").Get<IEnumerable<IdentityClient>>();
                var clients = new List<Client>();
                foreach (var client in appsettingsClients)
                {
                    var grandType = GrantTypes.ResourceOwnerPasswordAndClientCredentials;
                    switch (client.GrandType)
                    {
                        case "ResourceOwnerPasswordAndClientCredentials":
                            grandType = GrantTypes.ResourceOwnerPasswordAndClientCredentials;
                            break;
                        case "ClientCredentials":
                            grandType = GrantTypes.ResourceOwnerPasswordAndClientCredentials;
                            break;
                    } 
                    var clientSecrets = new List<Secret>();
                    foreach(var secret in client.ClientSecrets)
                    {
                        clientSecrets.Add(new Secret(secret.Sha256()));
                    }
                    clients.Add(new Client
                    {
                        ClientId = client.ClientId,
                        ClientSecrets = clientSecrets,
                        AllowedScopes = client.Scopes,
                        AllowedGrantTypes = grandType,
                        AccessTokenType = AccessTokenType.Jwt,
                        AccessTokenLifetime = 120,
                        IdentityTokenLifetime = 120,
                        UpdateAccessTokenClaimsOnRefresh = true,
                        SlidingRefreshTokenLifetime = 30,
                        AllowOfflineAccess = true,
                        RefreshTokenExpiration = TokenExpiration.Absolute,
                        RefreshTokenUsage = TokenUsage.OneTimeOnly,
                        AlwaysSendClientClaims = true,
                        Enabled = true,
                    });
                }
                return clients;
            }
    
            public static IEnumerable<ApiScope> GetApiScopes(IConfiguration config)
            {
                var appsettingsScopes = config.GetSection("IdentityServer:Scopes").Get<IEnumerable<string>>();
                var scopes = new List<ApiScope>();
                foreach (var scope in appsettingsScopes)
                {
                    scopes.Add(new ApiScope(scope));
                }
                return scopes;
            }
    
        }
    }

    Setup Entity Framework Core 6

    Now create a DbContext class for EF 6 to operate

    namespace IdentityServer.Configurations.EF
    {
        public class AppDbContext : IdentityDbContext
        {
            public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
            {
            }
        }
    }

    OverRide Resource Owner Password Validation Extension Methord

    Now we are going to implement custom “Resource Owner Password” validatior. There we try to check if the user is logged in or not using AspNet Identity. Let’s create an extention methord that can be attached to IdentityServer builder in Startup.cs file

    namespace IdentityServer.Configurations.IdentityOverrides
    {
        public static class ResourceOwnerPasswordValidatonExtension
        {
            public static IIdentityServerBuilder AddCustomResourceOwnerPasswordValidaton(this IIdentityServerBuilder builder)
            {
                builder.AddProfileService<ProfileService>();
                builder.AddResourceOwnerValidator<ResourceOwnerPasswordValidator>();
                return builder;
            }
        }
    }

    Implement OverRide Resource Owner Password Validatior

    Let’s Implement validator and profile service used by Identity Server 4

    namespace IdentityServer.Configurations.IdentityOverrides
    {
        public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
        {
            private readonly UserManager<IdentityUser> _userManager;
            private readonly SignInManager<IdentityUser> _signinManager;
            private readonly RoleManager<IdentityRole> _roleManager;
    
            public ResourceOwnerPasswordValidator(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signinManager, RoleManager<IdentityRole> roleManager)
            {
                _userManager = userManager;
                _signinManager = signinManager;
                _roleManager = roleManager;
            }
    
            public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
            {
                //Custom Validation
                var user = await _userManager.FindByNameAsync(context.UserName);
                if (user != null)
                {
                    try
                    {
                        var isLoggedIn = await _signinManager.PasswordSignInAsync(user, context.Password, false, lockoutOnFailure: false);
                        if (isLoggedIn.Succeeded)
                        {
                            context.Result = new GrantValidationResult(user.Id, OidcConstants.AuthenticationMethods.Password);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
        }
    }

    Create Profile Service

    We also need to create a profile service override

    namespace IdentityServer.Configurations.IdentityOverrides
    {
        public class ProfileService : IProfileService
        {
            private readonly UserManager<IdentityUser> _userManager;
    
            public ProfileService(UserManager<IdentityUser> userManager)
            {
                _userManager = userManager;
            }
    
            public async Task GetProfileDataAsync(ProfileDataRequestContext context)
            {
                var id = context.Subject.GetSubjectId();
                var user = await _userManager.FindByIdAsync(id);
                var claims = await _userManager.GetClaimsAsync(user) as List<Claim>;
                claims.Add(new Claim("username", user.UserName));
                context.IssuedClaims = claims;
            }
    
            public async Task IsActiveAsync(IsActiveContext context)
            {
                var sub = context.Subject.GetSubjectId();
                var user = _userManager.FindByIdAsync(context.Subject.GetSubjectId());
                context.IsActive = user != null;
            }
        }
    }

    EntityFramework 6 MIGRATION

    Migration is required for persisting AspNetIdenity entries.

    1. We need to install Entity Framework Core 6 first. For that run the command dotnet tool install --global dotnet-ef
    2. Create a migration by going to the project folder and run dotnet ef migrations add FirstMigration
    3. Wait for build to finish
    4. Update database by running dotnet ef database update

    CONFIGURE API-A

    Create a new ASP.NET Core API Project. We call it it APIA

    Install NuGet Packages

    Microsoft.AspNetCore.Authentication.JwtBearer
    Microsoft.AspNet.Identity.Core
    Microsoft.AspNetCore.Identity.EntityFrameworkCore
    Microsoft.EntityFrameworkCore
    Microsoft.EntityFrameworkCore.Design
    Microsoft.EntityFrameworkCore.SqlServer
    

    Configure AppSettings.json

    Add Authority & Audiance on API

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "AllowedHosts": "*",
    
      "ConnectionStrings": {
        "TIS": "Server=DESKTOP-708EN4A\\SQLEXPRESS;Database=TIS;Trusted_Connection=True;"
      },
    
      "Security": {
        "IdentityServer": {
          "Authority": "https://localhost:44393/",
          "Audiance": "ScxWebApi"
        }
      }
    }

    Setup Startup.cs

    Setup Startup.cs to work with Identity And EF 6

    public void ConfigureServices(IServiceCollection services)
            {
                //Configure EF6
                services.AddDbContext<AppDbContext>(config =>
                {
                    config.UseSqlServer(Configuration.GetConnectionString("TIS"));
                });
    
                //Configure Identity
                services.AddIdentity<IdentityUser, IdentityRole>(config =>
                {
                    config.Password.RequiredLength = 4;
                    config.Password.RequireDigit = false;
                    config.Password.RequiredUniqueChars = 0;
                    config.Password.RequireNonAlphanumeric = false;
                    config.Password.RequireUppercase = false;
                    config.SignIn.RequireConfirmedEmail = false;
                })
                    .AddEntityFrameworkStores<AppDbContext>()
                    .AddDefaultTokenProviders();
    
                //Identity Server Configuration
                var identityAuthority = Configuration.GetSection("Security:IdentityServer:Authority").Value;
                var identityScope = Configuration.GetSection("Security:IdentityServer:Audiance").Value;
                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                }).AddJwtBearer("Bearer", config =>
                {
                    config.Authority = identityAuthority;
                    config.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateAudience = true
                    };
                    config.Audience = identityScope;
                });
                
                services.AddControllersWithViews();
            }
            
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                app.UseHttpsRedirection();
                app.UseStaticFiles();
    
                app.UseRouting();
    
                app.UseAuthentication();
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                });
            }

    Add DbContext class

    Add a DBContext class to work with EF 6
    *Also don’t forget to add custom classes for these table declarations. They are used for EF 6 migrations and ORM mappings, LINQ and quering DB

    namespace APIA.EF
    {
        public class AppDbContext : IdentityDbContext
        {
            public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
            {
            }
    
            //Required database tables can come below as DbSet<T>
        }
    }

    Controller

    Using the HttpContext you will get the logged in user’s details

    namespace APIA.Controllers
    {
        public class HomeController : Controller
        {
            private readonly UserManager<IdentityUser> _userManager;
    
            public HomeController(UserManager<IdentityUser> userManager)
            {
                _userManager = userManager;
            }
    
            public IActionResult Index()
            {
                return View();
            }
    
            [Authorize]
            public async Task<IActionResult> OpenBox()
            {
                // We will get all inoformations of logged in user here including claims
                var userInfo = await _userManager.GetUserAsync(HttpContext.User);
                return Ok("Yeahhh");
            }
        }
    }

    From this implementation (_userManager.GetUserAsync(HttpContext.User);). You will get information about the logged in client if he iuses ResourceOwner password validaton as GrandType


    CONFIGURE API-B

    Lets configure API-B that can be used to call API-A. Most of the configurations are same. Let’s create another WebAPI project that we can call APIB

    Install NuGet Packages

    Microsoft.AspNetCore.Authentication.JwtBearer
    IdentityModel
    

    AppSettings.json

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
    
      "AllowedHosts": "*",
    
      "Security": {
        "IdentityServer": {
          "Authority": "https://localhost:44393/",
          "Audiance": "ScxWebApiDev"
        }
      }
    }

    Startup.cs

    In this API we are not using ASPNet Identity

     public void ConfigureServices(IServiceCollection services)
            {
                //Identity Server Configuration
                var identityAuthority = Configuration.GetSection("Security:IdentityServer:Authority").Value;
                var identityScope = Configuration.GetSection("Security:IdentityServer:Audiance").Value;
                services.AddAuthentication("Bearer").AddJwtBearer("Bearer", config =>
                {
                    config.Authority = identityAuthority;
                    config.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateAudience = true
                    };
                    config.Audience = identityScope;
                });
    
                services.AddHttpClient();
                services.AddControllersWithViews();
            }
    
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                app.UseHttpsRedirection();
                app.UseStaticFiles();
    
                app.UseRouting();
    
                app.UseAuthentication();
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                });
            }

    Call API-A from API-B

    namespace APIB.Controllers
    {
        public class HomeController : Controller
        {
            private readonly IHttpClientFactory _httpClient;
    
            public HomeController(IHttpClientFactory httpClient)
            {
                _httpClient = httpClient;
            }
    
            public IActionResult Index()
            {
                return View();
            }
    
            public async Task<IActionResult> ShowSecret()
            {
                var authClient = _httpClient.CreateClient();
                var discoveryDocument = await authClient.GetDiscoveryDocumentAsync("https://localhost:44393/");
                var tokenResponse = await authClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
                {
                    Address = discoveryDocument.TokenEndpoint,
                    ClientId = "admin",
                    ClientSecret = "admin123",
                    Scope = "ScxWebApi"
                });
                var apiClient = _httpClient.CreateClient();
                apiClient.SetBearerToken(tokenResponse.AccessToken);
                var response = await apiClient.GetAsync("https://localhost:44354/Home/Secret");
                var content = await response.Content.ReadAsStringAsync();
                return View();
            }
        }
    }

    Visit original content creator repository
    https://github.com/sangeethnandakumar/Express-Authentication-Template

  • neuvector-demo-server

    Neuvector Demo Server

    About Neuvector (now part of SUSE)

    NeuVector Full Lifecycle Container Security Platform delivers the only cloud-native security with uncompromising end-to-end protection from DevOps vulnerability protection to automated run-time security, and featuring a true Layer 7 container firewall.

    Learn more about Neuvector

    Intended usage of this script

    This script is for demo purposes only. It deploys a bare minimum, single node K3s Kubernetes cluster, Longhorn Storage, and the Beta of Neuvector and provides links to the interfaces and login information.

    Prerequisites

    • Ubuntu 20.04+ Server
    • Minimum Recommended 4vCPU and 8GB of RAM (Try Hetzner or DigitalOcean)
    • DNS or Hosts file entry pointing to server IP

    Installed as part of script

    • Helm
    • K3s
    • Rancher UI
    • Longhorn Storage
    • cert-manager
    • Neuvector 5 Beta

    Full Server Setup with Neuvector Helm Chart

    1. git clone https://github.com/AlphaBravoCompany/neuvector-demo-server.git
    2. cd neuvector-demo-server
    3. chmod +x install-neuvector.sh
    4. ./install-neuvector.sh subdomain.yourdomain.tld
    5. Install will take approximately 5 minutes and will output links and login information for Rancher and your Neuvector installation.
    6. Details for accessing Neuvector and Rancher will be printed to the screen once the script completes and saved to server-details.txt

    Uninstall

    1. /usr/local/bin/k3s-uninstall.sh (removes K3s, Rancher, Longhorn and Neuvector)

    Special Thanks

    Thanks to Andy Clemenko for his expertise and repos for providing the foundation for this script.

    About Alphabravo

    AlphaBravo provides products, services, and training for Kubernetes, Cloud, and DevSecOps. We are a Rancher and SUSE partner.

    Contact AB today to learn how we can help you.

    Visit original content creator repository
    https://github.com/AlphaBravoCompany/neuvector-demo-server

  • wordcloud_github

    Text Analysis Flask Application

    This is a web application built with Flask that allows users to upload image files, extract the text from these files, generate a word cloud from the extracted text, and then serve the word cloud image for download.

    Features

    Text extraction from different file types:

    • Images (.png): The pytesseract library, an OCR (Optical Character Recognition) tool

    • Word cloud generation: The word cloud library generates a word cloud from the combined text extracted from all uploaded files. The word cloud is saved as a PNG image with a unique filename, generated using the uuid library.

    • File download: The Flask send_from_directory function serves the generated word cloud image for download when the user navigates to the appropriate download URL.

    How It Works

    When a user navigates to the root URL, the index() function is called to handle the request. If the request method is POST, which means the user has submitted the form with files, the application checks if the user consented to process the files.

    If consent is given, the application gets a list of uploaded images from the form data and processes each image. The text extracted from each file is added to a combined text string.

    After all files have been processed, the application generates a word cloud from the combined text and saves it as a PNG image in a static directory. The user is then redirected to a download URL to download the word cloud image.

    Running the Application

    To run the application, use the command python/ python3 app.py in the terminal, where app.py is the file name containing this application. This will start the Flask web server, and the application will be accessible in a web browser at the URL localhost:5000 or 127.0.0.1:5000 unless otherwise specified.

    Remember to install the necessary libraries (Flask, pytesseract, wordcloud) using pip/pip3 before running the application.

    Visit original content creator repository
    https://github.com/felisawiley/wordcloud_github

  • kaku

    awesome-rice-badge

    革 | kaku

    PLEASE RESPECT THE CREDITS IF YOU USE SOMETHING FROM MY DESKTOP/SETUP.


    SETUPGUIDESKEYBINDSGALLERY
    

    • Window ManagerNiri🎨 Scrolleable WM!
    • ShellNu 🐚 with starship Cross Shell Platform!
    • TerminalGhostty 💻 A powerful Hyped term
    • PanelAstal 🍧 Astal GTK-shell :3!
    • Notify DaemonDunst 🍃 Minimalist and functional!
    • LauncherAnyRun 🚀 Fast AnyRunner!
    • File ManagerYazi 🔖 Rustacean File Manager!
    • GUI Basic-IDEHelix ✴️ Rustacean vim version!
    • GTK ThemeGTK 🐾 My Fork of colloid
    • LockScreenHyprlock 🔒 hyprland locker

    🌼 INSTALLATION (NixOS)

    Request: NixOs

    • Download ISO.
    wget -O https://channels.nixos.org/nixos-24.05/latest-nixos-minimal-x86_64-linux.iso
    • Boot Into the Installer.

    • Switch to Root: sudo -i

    • Partitions:

    I prefer to use 1GB on the EFI partition. Specifically because the ‘generations’ list may become very long, and to avoid overloading the partition.

    # Replace nvme with your disk partition
    gdisk /dev/nvme0n1
    - `o` (create new partition table)
    - `n` (add partition, 512M, type ef00 EFI)
    - `n` (add partition, remaining space, type 8300 Linux)
    `w` (write partition table and exit)
    
    • Format Partitions:
    mkfs.fat -F 32 -n EFI /dev/nvme0n1p1
    mkfs.xfs -L NIXOS /dev/nvme0n1p2
    • Mount Partitions:
    mount /dev/disk/by-label/NIXOS /mnt
    mkdir -p /mnt/boot
    mount /dev/disk/by-label/EFI /mnt/boot
    • Enable nixFlakes
    nix-shell -p nixVersions.stable git
    • Clone my Dotfiles
    git clone --depth 1 https://github.com/linuxmobile/kaku /mnt/etc/nixos
    • Generate your Own Nix Hardware Settings:

    DON’T FORGET IT

    sudo nixos-generate-config --dir /mnt/etc/nixos/hosts/aesthetic --force
    
    # Remove configuration.nix
    rm -rf /mnt/etc/nixos/hosts/aesthetic/configuration.nix
    • Install Dotfiles Using Flake
    # Move to folder
    cd mnt/etc/nixos/
    
    # Install
    nixos-install --flake .#aesthetic
    • Reboot

    🐙 Remember Default User & password are: nixos

    • Change Default password for User.
    passwd YourUser
    • Install w/ Home-Manager the config
    home-manager switch --flake 'github:linuxmobile/kaku#linudev@aesthetic'

    🌸 SCREENSHOTS

    🌻 TODO LIST

    🎋 ADDITIONALS

    🍀 KEY BINDINGS

    💐 ACKNOWLEDGEMENTS

    Inspiration and Resources
    1 owl4ce
    2 Ilham25
    3 Siduck
    4 NvChad
    5 Rxyhn
    6 HeinzDev
    7 fufexan
    8 AmitGolden
    Based Community Membership Status
    🗺 3 r/unixp*rn Not working there anymore.

    🌳 CONTRIBUTING

    WIP

    🎃 SECURITY POLICY

    BACK TO TOP
    
    Visit original content creator repository https://github.com/linuxmobile/kaku
  • sebas-jimenez-aws-terraform

    About

    In this repo you’re going to find a VPC created with Terraform. This repo was made with the purpose of using some of the services of AWS.

    Technologies

    This project is working with Terraform

    Note

    The whole project was created on Linux (Ubuntu), so make sure to run it on similar OS. Also, you can modify the path given on main.tf according to your OS to avoid errors.

    Prerequisites

    You must have installed terraform on the computer that you’re trying to run the project, make sure to follow the documentation below:

    Additionally, don’t forget to set-up the whole AWS environment on your CLI following its documentation

    How to

    Step 1: Clone the repo on your editor text of preferences

    git clone https://github.com/SebastianJimenez2/VPC-Terraform.git
    

    Step 2: Initialize the project

    terraform init
    

    Step 3: Verify if the configuration is valid or not

    terraform validate
    

    Step 4:

    terraform plan
    

    Warning

    If you have an error trying this command, make sure you have the files config and credentials on the directory .aws, if not make sure to follow the documentation for aws configure command.

    Step 5: Create or update the infrastructure

    terraform apply
    

    Step 6:

    terraform destroy
    

    Note

    Make sure you destroyed the infrastructure on the AWS account you created the credentials, otherwise you’ll get charged money on your bank account while the service is active.

    Contributing

    Contributions are always welcome! So don’t be afraid of forking the repo and make a pull request.

    Also, you can add any issue found on the project so it can be fixed asap.

    Visit original content creator repository
    https://github.com/AEIS-FIS-EPN/sebas-jimenez-aws-terraform