问:
How to fix "Method 'ApplyServices' does not have an implementation" at Program with efCore 3 and .net core 3
I'm developing a new Web API on EfCore 3 and .net core 3 and not able to start this because of an error "Method 'ApplyServices' in type 'Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal.SqlServerOptionsExtension' from assembly 'Microsoft.EntityFrameworkCore.SqlServer, Version=3.0.0.0' does not have an implementation.

I should note that ApplicationContext that I inject to my project is located in another project (.net core 3 too).
Debugging showed that application is crashed in this part of code -->

```<code>
    services
                    .AddDbContext<ApplicationContext>(options =>
                        options.UseSqlServer(connectionString));

</code>```

Here you can see All StartUp Class

```<code>
    public Startup(IConfiguration configuration)
            {
                _configuration = configuration;
            }

            private readonly IConfiguration _configuration;

            public void ConfigureServices(IServiceCollection services)
            {
                services.AddOptions();

                var connectionString = _configuration.GetConnectionString("DefaultConnection");

                services
                    .AddDbContext<ApplicationContext>(options =>
                        options.UseSqlServer(connectionString));

                services.AddControllers()
                    .SetCompatibilityVersion(CompatibilityVersion.Latest)
                    .AddNewtonsoftJson(options =>
                    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

                services.AddHostedService<MigratorHostedService>();
            }

            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                app.UseCors("AllowAll");

                app.UseStaticFiles();

                app.UseRouting();
            }

</code>```

Here is MigratorHostedService

```<code>
    private readonly IServiceProvider _serviceProvider;
            public MigratorHostedService(IServiceProvider serviceProvider)
            {
                _serviceProvider = serviceProvider;
            }

            public async Task StartAsync(CancellationToken cancellationToken)
            {
                using (var scope = _serviceProvider.CreateScope())
                {
                    var myDbContext = scope.ServiceProvider.GetRequiredService<ApplicationContext>();

                    await myDbContext.Database.MigrateAsync();
                }
            }

            public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
</code>```

Here is Program

```<code> private const int Port = ...;

        public static async Task Main()
        {
            var cts = new CancellationTokenSource();

            var host = Host.CreateDefaultBuilder();

            host.ConfigureWebHostDefaults(ConfigureWebHost);

            await host.Build()
                .RunAsync(cts.Token)
                .ConfigureAwait(false);
        }

        private static void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.UseUrls($"http://*:{Port}");
            builder.UseStartup<Startup>();
            builder.UseDefaultServiceProvider((context, options) =>
            {
                options.ValidateOnBuild = true;
            });
        }
</code>```

As .net core 3 is new, I haven't found solution of this problem

Also my project packages:

```<code>
    <Project Sdk="Microsoft.NET.Sdk.Web">

      <PropertyGroup>
        <TargetFramework>netcoreapp3.0</TargetFramework>
        <NoWarn>$(NoWarn);NU1605</NoWarn>
      </PropertyGroup>

      <ItemGroup>
        <PackageReference Include="JetBrains.Annotations" Version="2019.1.3" />
        <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0-preview-18579-0056" />
        <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0-preview.19080.1" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0">
          <PrivateAssets>all</PrivateAssets>
          <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        </PackageReference>
        <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.0.0-preview.19080.1" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.0.0-preview.19080.1" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.6" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0">
          <PrivateAssets>all</PrivateAssets>
          <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        </PackageReference>
        <PackageReference Include="Microsoft.NETCore.DotNetAppHost" Version="3.0.0" />
        <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Utils" Version="3.0.0" />
        <PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
      </ItemGroup>

    </Project>

</code>```

ApplicationContext

```<code>public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)
        {

        }
</code>```

答:
after all tryings the right implementation of startup was there

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                x => x.MigrationsAssembly("CRM.API")));

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll",
                    builder =>
                    {
                        builder
                            .AllowAnyOrigin()
                            .AllowAnyMethod()
                            .AllowAnyHeader();
                        //.AllowCredentials();
                    });
            });

            services.AddControllers().AddNewtonsoftJson(options =>
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();

            app.UseRouting();

            app.UseCors("AllowAll");

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Departments}/{action=GetDepartments}/{id?}");
            });
        }```
</div>
</div>
</p>

<p>And right Program class implementation was there</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>public static async Task Main(string[] args)
        {
            var host = BuildWebHost(args);

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context = services.GetRequiredService<ApplicationContext>();

                    await context.Database.MigrateAsync();
                    await DbInitializer.InitializeAsync(context);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred while seeding the database.");
                }
            }

            host.Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();</code>```

Sure, this answer will help you

Body:
I'm developing a new Web API on EfCore 3 and .net core 3 and not able to start this because of an error "Method 'ApplyServices' in type 'Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal.SqlServerOptionsExtension' from assembly 'Microsoft.EntityFrameworkCore.SqlServer, Version=3.0.0.0' does not have an implementation.

I should note that ApplicationContext that I inject to my project is located in another project (.net core 3 too).
Debugging showed that application is crashed in this part of code -->

    services
                    .AddDbContext<ApplicationContext>(options =>
                        options.UseSqlServer(connectionString));

Here you can see All StartUp Class

    public Startup(IConfiguration configuration)
            {
                _configuration = configuration;
            }

            private readonly IConfiguration _configuration;

            public void ConfigureServices(IServiceCollection services)
            {
                services.AddOptions();

                var connectionString = _configuration.GetConnectionString("DefaultConnection");

                services
                    .AddDbContext<ApplicationContext>(options =>
                        options.UseSqlServer(connectionString));

                services.AddControllers()
                    .SetCompatibilityVersion(CompatibilityVersion.Latest)
                    .AddNewtonsoftJson(options =>
                    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

                services.AddHostedService<MigratorHostedService>();
            }

            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                app.UseCors("AllowAll");

                app.UseStaticFiles();

                app.UseRouting();
            }

Here is MigratorHostedService

    private readonly IServiceProvider _serviceProvider;
            public MigratorHostedService(IServiceProvider serviceProvider)
            {
                _serviceProvider = serviceProvider;
            }

            public async Task StartAsync(CancellationToken cancellationToken)
            {
                using (var scope = _serviceProvider.CreateScope())
                {
                    var myDbContext = scope.ServiceProvider.GetRequiredService<ApplicationContext>();

                    await myDbContext.Database.MigrateAsync();
                }
            }

            public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;

Here is Program

 private const int Port = ...;

        public static async Task Main()
        {
            var cts = new CancellationTokenSource();

            var host = Host.CreateDefaultBuilder();

            host.ConfigureWebHostDefaults(ConfigureWebHost);

            await host.Build()
                .RunAsync(cts.Token)
                .ConfigureAwait(false);
        }

        private static void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.UseUrls($"http://*:{Port}");
            builder.UseStartup<Startup>();
            builder.UseDefaultServiceProvider((context, options) =>
            {
                options.ValidateOnBuild = true;
            });
        }

As .net core 3 is new, I haven't found solution of this problem

Also my project packages:

    <Project Sdk="Microsoft.NET.Sdk.Web">

      <PropertyGroup>
        <TargetFramework>netcoreapp3.0</TargetFramework>
        <NoWarn>$(NoWarn);NU1605</NoWarn>
      </PropertyGroup>

      <ItemGroup>
        <PackageReference Include="JetBrains.Annotations" Version="2019.1.3" />
        <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0-preview-18579-0056" />
        <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0-preview.19080.1" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0">
          <PrivateAssets>all</PrivateAssets>
          <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        </PackageReference>
        <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.0.0-preview.19080.1" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.0.0-preview.19080.1" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.6" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0">
          <PrivateAssets>all</PrivateAssets>
          <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        </PackageReference>
        <PackageReference Include="Microsoft.NETCore.DotNetAppHost" Version="3.0.0" />
        <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Utils" Version="3.0.0" />
        <PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
      </ItemGroup>

    </Project>

ApplicationContext

public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)
        {

        }

Body:
after all tryings the right implementation of startup was there

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                x => x.MigrationsAssembly("CRM.API")));

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll",
                    builder =>
                    {
                        builder
                            .AllowAnyOrigin()
                            .AllowAnyMethod()
                            .AllowAnyHeader();
                        //.AllowCredentials();
                    });
            });

            services.AddControllers().AddNewtonsoftJson(options =>
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();

            app.UseRouting();

            app.UseCors("AllowAll");

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Departments}/{action=GetDepartments}/{id?}");
            });
        }

And right Program class implementation was there

public static async Task Main(string[] args)
        {
            var host = BuildWebHost(args);

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context = services.GetRequiredService<ApplicationContext>();

                    await context.Database.MigrateAsync();
                    await DbInitializer.InitializeAsync(context);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred while seeding the database.");
                }
            }

            host.Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();

Sure, this answer will help you


来源: stackexchange

问:
How to pass shinytree values to drop down input in shiny
I'm trying to create dropdown input in shiny which has hierarchical drop-down list in R shiny like below:

hierarchical drop-down list in R shiny

For now I'm able to create an shinytree where we can display the entire list, but I want display the list in dropdown instead of shinytree.

Below is my code:

```<code>library(shiny)

library(shinyTree)

# Define UI for application:

    ui <- {fluidPage(
            sidebarLayout(
              sidebarPanel(width = 3,
                 div(shinyTree("Tree",checkbox = TRUE)),
                 verbatimTextOutput("selected")
              ),
              mainPanel(width = 9)
           )
    )}

# Define server logic:
    server <- function(input, output, session){

       observe({
          df <- data.frame(
             child= c('a','b','c','d','e','f','g','h'),
             parent = c('f','f','f','g','h','i','i','i'))

          tree <- FromDataFrameNetwork(df)

          filtered_value <- as.list(tree)

          filtered_value <- filtered_value[-1]

          output$Tree <- renderTree({
            filtered_value
          })
       })
    }

# Run the application
    shinyApp(ui = ui, server = server)
</code>```

I'm looking for input in this manner: Custom-Dropdown

答:
I did a Shiny binding for the ComboTree library yesterday. It works but this is not fantastic.

File comboTreeBinding.js to put in the www subfolder:

var comboTreeBinding = new Shiny.InputBinding();

$.extend(comboTreeBinding, {
  find: function (scope) {
    return $(scope).find(".comboTree");
  },
  getValue: function (el) {
    var value = el.value.split(", ");
    var empty = value.length === 1 && value[0] === "";
    return empty ? null : value;
  },
  setValue: function(el, value) {
    $(el).setSelection(value);
  },
  subscribe: function (el, callback) {
    $(el).on("change.comboTreeBinding", function (e) {
      callback();
    });
  },
  unsubscribe: function (el) {
    $(el).off(".comboTreeBinding");
  },
  initialize: function(el) {
        var $el = $(el);
        $el.comboTree({
      source: $el.data("choices"),
      isMultiple: $el.data("multiple"),
      cascadeSelect: $el.data("cascaded"),
      collapse: true
    });
  }
});

Shiny.inputBindings.register(comboTreeBinding);
```

<p>Shiny app (put the files <strong>style.css</strong> and <strong>comboTreePlugin.js</strong> in the <strong>www</strong> subfolder):</p>

<pre class="lang-r prettyprint-override"><code>library(shiny)
library(jsonlite)

comboTreeInput <- function(inputId, width = "30%", height = "100px",
                           choices, multiple = TRUE, cascaded = TRUE){
  tags$div(style = sprintf("width: %s; height: %s;", width, height),
           tags$input(id = inputId, class = "comboTree", type = "text",
                      placeholder = "Select",
                      `data-choices` = as.character(toJSON(choices, auto_unbox = TRUE)),
                      `data-multiple` = ifelse(multiple, "true", "false"),
                      `data-cascaded` = ifelse(cascaded, "true", "false")
           )
  )
}

choices <- list(
  list(id = 1, title = "item1"),
  list(id = 2, title = "item2",
       subs = list(
         list(id = 21, title = "item2-1"),
         list(id = 22, title = "item2-2")
       )
  ),
  list(id = 3, title = "item3",
       subs = list(
         list(id = 31, title = "item3-1", isSelectable = FALSE,
              subs = list(
                list(id = 311, title = "item3-1-1"),
                list(id = 312, title = "item3-1-2")
              )
         ),
         list(id = 32, title = "item3-2")
       )
  )
)

ui <- fluidPage(
  tags$head(
    tags$link(rel = "stylesheet", href = "style.css"),
    tags$script(src = "comboTreePlugin.js"),
    tags$script(src = "comboTreeBinding.js")
  ),
  br(),
  h3("You selected:"),
  verbatimTextOutput("selections"),
  br(),
  comboTreeInput("mycombotree", choices = choices)
)

server <- function(input, output, session){

  output[["selections"]] <- renderPrint({
    input[["mycombotree"]]
  })

}

shinyApp(ui, server)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create dropdown input in shiny which has hierarchical drop-down list in R shiny like below:

hierarchical drop-down list in R shiny

For now I'm able to create an shinytree where we can display the entire list, but I want display the list in dropdown instead of shinytree.

Below is my code:

library(shiny)

library(shinyTree)

# Define UI for application:

    ui <- {fluidPage(
            sidebarLayout(
              sidebarPanel(width = 3,
                 div(shinyTree("Tree",checkbox = TRUE)),
                 verbatimTextOutput("selected")
              ),
              mainPanel(width = 9)
           )
    )}

# Define server logic:
    server <- function(input, output, session){

       observe({
          df <- data.frame(
             child= c('a','b','c','d','e','f','g','h'),
             parent = c('f','f','f','g','h','i','i','i'))

          tree <- FromDataFrameNetwork(df)

          filtered_value <- as.list(tree)

          filtered_value <- filtered_value[-1]

          output$Tree <- renderTree({
            filtered_value
          })
       })
    }

# Run the application
    shinyApp(ui = ui, server = server)

I'm looking for input in this manner: Custom-Dropdown

Body:
I did a Shiny binding for the ComboTree library yesterday. It works but this is not fantastic.

File comboTreeBinding.js to put in the www subfolder:

var comboTreeBinding = new Shiny.InputBinding();

$.extend(comboTreeBinding, {
  find: function (scope) {
    return $(scope).find(".comboTree");
  },
  getValue: function (el) {
    var value = el.value.split(", ");
    var empty = value.length === 1 && value[0] === "";
    return empty ? null : value;
  },
  setValue: function(el, value) {
    $(el).setSelection(value);
  },
  subscribe: function (el, callback) {
    $(el).on("change.comboTreeBinding", function (e) {
      callback();
    });
  },
  unsubscribe: function (el) {
    $(el).off(".comboTreeBinding");
  },
  initialize: function(el) {
        var $el = $(el);
        $el.comboTree({
      source: $el.data("choices"),
      isMultiple: $el.data("multiple"),
      cascadeSelect: $el.data("cascaded"),
      collapse: true
    });
  }
});

Shiny.inputBindings.register(comboTreeBinding);

Shiny app (put the files style.css and comboTreePlugin.js in the www subfolder):

library(shiny)
library(jsonlite)

comboTreeInput <- function(inputId, width = "30%", height = "100px",
                           choices, multiple = TRUE, cascaded = TRUE){
  tags$div(style = sprintf("width: %s; height: %s;", width, height),
           tags$input(id = inputId, class = "comboTree", type = "text",
                      placeholder = "Select",
                      `data-choices` = as.character(toJSON(choices, auto_unbox = TRUE)),
                      `data-multiple` = ifelse(multiple, "true", "false"),
                      `data-cascaded` = ifelse(cascaded, "true", "false")
           )
  )
}

choices <- list(
  list(id = 1, title = "item1"),
  list(id = 2, title = "item2",
       subs = list(
         list(id = 21, title = "item2-1"),
         list(id = 22, title = "item2-2")
       )
  ),
  list(id = 3, title = "item3",
       subs = list(
         list(id = 31, title = "item3-1", isSelectable = FALSE,
              subs = list(
                list(id = 311, title = "item3-1-1"),
                list(id = 312, title = "item3-1-2")
              )
         ),
         list(id = 32, title = "item3-2")
       )
  )
)

ui <- fluidPage(
  tags$head(
    tags$link(rel = "stylesheet", href = "style.css"),
    tags$script(src = "comboTreePlugin.js"),
    tags$script(src = "comboTreeBinding.js")
  ),
  br(),
  h3("You selected:"),
  verbatimTextOutput("selections"),
  br(),
  comboTreeInput("mycombotree", choices = choices)
)

server <- function(input, output, session){

  output[["selections"]] <- renderPrint({
    input[["mycombotree"]]
  })

}

shinyApp(ui, server)


问:
setOnMouseEntered not Working for ImageView in ListView
i have a problem with setOnMouseEntered on JavaFx for ImageViews.
I'm trying to change the brightness of ImageViews placed in a Listview with ColorAdjust. The effect itself works for ImageViews that are not in the ListView.

I guess that only the ListView triggers the setOnMouseEntered, but not the ImageViews, which is my goal.
The same problem is caused by the hover effects of the ImageViews, which are not triggered as soon as they are in a ListView.

fxml:

```<code> <ListView fx:id="cardsView" />
</code>```

java-Code:

```<code>@FXML private ListView<ImageView> cardsView;
private ObservableMap<ImageView, Card> hCards;

@FXML
public void initialize() {
  hCards= FXCollections.observableHashMap();
  cardsView.getItems().setAll(hCards.keySet());
  hCards.addListener(
    (MapChangeListener<ImageView, Card>)
        change -> {
          cardsView.getItems().removeAll(change.getKey());
          if (change.wasAdded()) {
            cardsView.getItems().add(change.getKey());
          }
        });
  }
</code>```

Later, for each of these ImageViews will be added:

```<code>private void addLightEffectOnMouseEntered(ImageView imageView) {
  imageView.setOnMouseEntered(
    t -> {
      ColorAdjust colorAdjust = new ColorAdjust();
      colorAdjust.setBrightness(0.4);
      imageView.setEffect(colorAdjust);
    });
}
</code>```

While debugging I figured out that things like css and the setOnMouseEntered are added correctly. So it seems to be somehow blocked by the ListView that the ChildNodes get the setOnMouseEntered or Hover effect instead of the ListView

答:
Your problem is basically the same as this one: Adding EventHandler To ImageView contained in a Label. All Cell specializations, including ListCell, inherit from Labeled and all their default skins inherit from LabeledSkinBase, which is the source of your problem. As a fix to a bug (see other Q&A) when an ImageView is used as the graphic of a Labeled it is set to be mouse-transparent. Since the the ImageView is mouse-transparent your MOUSE_ENTERED handler can never be invoked for obvious reasons.

If you're not aware, the default cell factory of ListView returns a ListCell implementation that, when the item is an instance of Node, sets the graphic of the cell to the item. An easy fix is to use your own ListCell implementation that wraps the ImageView in another node, such as Pane. Here's an example:

listView.setCellFactory(lv -> new ListCell<>() {

  private final Pane imageViewContainer = new Pane();

  @Override
  protected void updateItem(ImageView item, boolean empty) {
    super.updateItem(item, empty);
    if (empty || item == null) {
      imageViewContainer.getChildren().clear();
      setGraphic(null);
    } else {
      imageViewContainer.getChildren().setAll(item);
      setGraphic(imageViewContainer);
    }
  }
});
```

This will prevent the ImageView from becoming mouse-transparent.

As a side note, it's typically not a good idea to use GUI objects (e.g. ImageView) as the model item of a ListView (or any other virtualized control). In this case, it may be an even worse idea since this set-up encourages holding every Image related to your application in memory simultaneously. Depending on how many images there are, as well as how large those images are, this can easily lead to an OutOfMemoryError or at least consume an unnecessary amount of your users' RAM.

You may want to consider using Card as the model item combined with a memory-constrained cache of Image objects (see WeakReference / SoftReference, though you could also look for a third-party caching library). The Card class could hold the location of its associated image or the cache could derive the location based on the state of the Card.

You would still use an ImageView as the graphic of your ListCell, however, so you would still need to use the workaround mentioned above. What using a memory-constrained cache helps with is that, if a Card isn't being displayed in a ListCell then its associated Image possibly becomes eligible for garbage collection, thus reducing the memory demands of your application.

The cache also allows you to use the same Image everywhere in your application (the same Image can be shared between multiple ImageViews) and means you don't always load a new Image when a particular one is needed (as it could still be in memory when requested). In other words, the typical functionality provided by any cache.

Body:
i have a problem with setOnMouseEntered on JavaFx for ImageViews.
I'm trying to change the brightness of ImageViews placed in a Listview with ColorAdjust. The effect itself works for ImageViews that are not in the ListView.

I guess that only the ListView triggers the setOnMouseEntered, but not the ImageViews, which is my goal.
The same problem is caused by the hover effects of the ImageViews, which are not triggered as soon as they are in a ListView.

fxml:

 <ListView fx:id="cardsView" />

java-Code:

@FXML private ListView<ImageView> cardsView;
private ObservableMap<ImageView, Card> hCards;

@FXML
public void initialize() {
  hCards= FXCollections.observableHashMap();
  cardsView.getItems().setAll(hCards.keySet());
  hCards.addListener(
    (MapChangeListener<ImageView, Card>)
        change -> {
          cardsView.getItems().removeAll(change.getKey());
          if (change.wasAdded()) {
            cardsView.getItems().add(change.getKey());
          }
        });
  }

Later, for each of these ImageViews will be added:

private void addLightEffectOnMouseEntered(ImageView imageView) {
  imageView.setOnMouseEntered(
    t -> {
      ColorAdjust colorAdjust = new ColorAdjust();
      colorAdjust.setBrightness(0.4);
      imageView.setEffect(colorAdjust);
    });
}

While debugging I figured out that things like css and the setOnMouseEntered are added correctly. So it seems to be somehow blocked by the ListView that the ChildNodes get the setOnMouseEntered or Hover effect instead of the ListView

Body:
Your problem is basically the same as this one: Adding EventHandler To ImageView contained in a Label. All Cell specializations, including ListCell, inherit from Labeled and all their default skins inherit from LabeledSkinBase, which is the source of your problem. As a fix to a bug (see other Q&A) when an ImageView is used as the graphic of a Labeled it is set to be mouse-transparent. Since the the ImageView is mouse-transparent your MOUSE_ENTERED handler can never be invoked for obvious reasons.

If you're not aware, the default cell factory of ListView returns a ListCell implementation that, when the item is an instance of Node, sets the graphic of the cell to the item. An easy fix is to use your own ListCell implementation that wraps the ImageView in another node, such as Pane. Here's an example:

listView.setCellFactory(lv -> new ListCell<>() {

  private final Pane imageViewContainer = new Pane();

  @Override
  protected void updateItem(ImageView item, boolean empty) {
    super.updateItem(item, empty);
    if (empty || item == null) {
      imageViewContainer.getChildren().clear();
      setGraphic(null);
    } else {
      imageViewContainer.getChildren().setAll(item);
      setGraphic(imageViewContainer);
    }
  }
});

This will prevent the ImageView from becoming mouse-transparent.

As a side note, it's typically not a good idea to use GUI objects (e.g. ImageView) as the model item of a ListView (or any other virtualized control). In this case, it may be an even worse idea since this set-up encourages holding every Image related to your application in memory simultaneously. Depending on how many images there are, as well as how large those images are, this can easily lead to an OutOfMemoryError or at least consume an unnecessary amount of your users' RAM.

You may want to consider using Card as the model item combined with a memory-constrained cache of Image objects (see WeakReference / SoftReference, though you could also look for a third-party caching library). The Card class could hold the location of its associated image or the cache could derive the location based on the state of the Card.

You would still use an ImageView as the graphic of your ListCell, however, so you would still need to use the workaround mentioned above. What using a memory-constrained cache helps with is that, if a Card isn't being displayed in a ListCell then its associated Image possibly becomes eligible for garbage collection, thus reducing the memory demands of your application.

The cache also allows you to use the same Image everywhere in your application (the same Image can be shared between multiple ImageViews) and means you don't always load a new Image when a particular one is needed (as it could still be in memory when requested). In other words, the typical functionality provided by any cache.


问:
Spark tests failing when running with sbt test
We've have written unit tests for spark, in local mode with 4 threads.

When launched one by one, for example through intellij or sbt testOnly, each test runs fine.

When launched with sbt test, they fail with errors like

[info]   java.util.ServiceConfigurationError: org.apache.spark.sql.sources.DataSourceRegister: Provider org.apache.spark.sql.execution.datasources.csv.CSVFileFormat not a subtype

We notably upgraded sbt and spark versions to the latest, tried to run with fork in test := true in the build.sbt, but this didn't help.

Spark is in version 2.4.3, sbt 1.2.8 and scala in 2.12.8.

sbt config is nothing special:

```<code>libraryDependencies ++= Seq(
  Dependencies.Test.concordion,
  Dependencies.`spark-sql` exclude("org.slf4j","slf4j-log4j12"),
  Dependencies.`better-files`
)

fork in test := true

dependencyOverrides += "com.google.guava" % "guava" % "11.0.2"
dependencyOverrides += "com.fasterxml.jackson.core" % "jackson-databind" % "2.6.7.1"
</code>```

We're using a sbt project with multiple various sub projects, defined this way:

```<code>scalacOptions in ThisBuild ++= Seq(
  "-encoding", "UTF-8", // source files are in UTF-8
  "-deprecation", // warn about use of deprecated APIs
  "-Yrangepos", // use range positions for syntax trees
  "-language:postfixOps", //  enables postfix operators
  "-language:implicitConversions", // enables defining implicit methods and members
  "-language:existentials", // enables writing existential types
  "-language:reflectiveCalls", // enables reflection
  "-language:higherKinds", // allow higher kinded types without `import scala.language.higherKinds`
  "-unchecked", // warn about unchecked type parameters
  "-feature", // warn about misused language features
  /*"-Xlint",               // enable handy linter warnings
    "-Xfatal-warnings",     // turn compiler warnings into errors*/
  "-Ypartial-unification" // allow the compiler to unify type constructors of different arities
)

autoCompilerPlugins := true

addCompilerPlugin(Dependencies.`kind-projector`)
addCompilerPlugin(Dependencies.`better-monadic-for`)

// Define the root project, and make it compile all child projects
lazy val `datarepo` =
  project
    .in(file("."))
    .aggregate(
      `foo`,
      `foo-other`,
      `sparkusingproject`,
      `sparkusingproject-test`,
      `sparkusingproject-other`,
    )

// Define individual projects, the directories they reside in, and other projects they depend on
lazy val `foo` =
  project
    .in(file("foo"))
    .settings(Common.defaultSettings: _*)

lazy val `foo-other` =
  project
    .in(file("foo-other"))
    .dependsOn(`foo`)
    .settings(Common.defaultSettings: _*)

</code>```

答:
I just hit this exception in a test, and it was caused by trying to run a Spark action in a thread that was different from the thread where I started the SparkSession. You might want to disable parallelExecution in Test (this is recommended for Spark integration tests anyway).

Specifically, I was trying to execute multiple Spark actions in parallel, and I tried doing that in Scala's ExecutionContext.global thread pool. When I created a newFixedPoolExecutor instead, everything started working fine.

AFAICT this is because in DataSource.scala:610, Spark gets the thread's ContextClassLoader:

```<code>    val loader = Utils.getContextOrSparkClassLoader
</code>```

and, when running in Scala's default thread pool, the class loader does not contain the relevant classes and interfaces. When you create a new thread pool instead, it inherits the correct class loader from the current thread and works fine afterwards.

Body:
We've have written unit tests for spark, in local mode with 4 threads.

When launched one by one, for example through intellij or sbt testOnly, each test runs fine.

When launched with sbt test, they fail with errors like

[info]   java.util.ServiceConfigurationError: org.apache.spark.sql.sources.DataSourceRegister: Provider org.apache.spark.sql.execution.datasources.csv.CSVFileFormat not a subtype

We notably upgraded sbt and spark versions to the latest, tried to run with fork in test := true in the build.sbt, but this didn't help.

Spark is in version 2.4.3, sbt 1.2.8 and scala in 2.12.8.

sbt config is nothing special:

libraryDependencies ++= Seq(
  Dependencies.Test.concordion,
  Dependencies.`spark-sql` exclude("org.slf4j","slf4j-log4j12"),
  Dependencies.`better-files`
)

fork in test := true

dependencyOverrides += "com.google.guava" % "guava" % "11.0.2"
dependencyOverrides += "com.fasterxml.jackson.core" % "jackson-databind" % "2.6.7.1"

We're using a sbt project with multiple various sub projects, defined this way:

scalacOptions in ThisBuild ++= Seq(
  "-encoding", "UTF-8", // source files are in UTF-8
  "-deprecation", // warn about use of deprecated APIs
  "-Yrangepos", // use range positions for syntax trees
  "-language:postfixOps", //  enables postfix operators
  "-language:implicitConversions", // enables defining implicit methods and members
  "-language:existentials", // enables writing existential types
  "-language:reflectiveCalls", // enables reflection
  "-language:higherKinds", // allow higher kinded types without `import scala.language.higherKinds`
  "-unchecked", // warn about unchecked type parameters
  "-feature", // warn about misused language features
  /*"-Xlint",               // enable handy linter warnings
    "-Xfatal-warnings",     // turn compiler warnings into errors*/
  "-Ypartial-unification" // allow the compiler to unify type constructors of different arities
)

autoCompilerPlugins := true

addCompilerPlugin(Dependencies.`kind-projector`)
addCompilerPlugin(Dependencies.`better-monadic-for`)

// Define the root project, and make it compile all child projects
lazy val `datarepo` =
  project
    .in(file("."))
    .aggregate(
      `foo`,
      `foo-other`,
      `sparkusingproject`,
      `sparkusingproject-test`,
      `sparkusingproject-other`,
    )

// Define individual projects, the directories they reside in, and other projects they depend on
lazy val `foo` =
  project
    .in(file("foo"))
    .settings(Common.defaultSettings: _*)

lazy val `foo-other` =
  project
    .in(file("foo-other"))
    .dependsOn(`foo`)
    .settings(Common.defaultSettings: _*)

Body:
I just hit this exception in a test, and it was caused by trying to run a Spark action in a thread that was different from the thread where I started the SparkSession. You might want to disable parallelExecution in Test (this is recommended for Spark integration tests anyway).

Specifically, I was trying to execute multiple Spark actions in parallel, and I tried doing that in Scala's ExecutionContext.global thread pool. When I created a newFixedPoolExecutor instead, everything started working fine.

AFAICT this is because in DataSource.scala:610, Spark gets the thread's ContextClassLoader:

    val loader = Utils.getContextOrSparkClassLoader

and, when running in Scala's default thread pool, the class loader does not contain the relevant classes and interfaces. When you create a new thread pool instead, it inherits the correct class loader from the current thread and works fine afterwards.


问:
How do I compare a raw time in Java to now?

Possible Duplicate:

  How do I compare a raw time in Java?

For example suppose I have

```<code>String endTime = "16:30:45";
</code>```

How would I determine whether right now is before this time?  I have tried

```<code>SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss")
Date date = sdf.parse(endTime);
</code>```

However date has year 1970 and so the comparisons fail

答:
```<code>//Parse the time from String using SimpleDateFormat and set it to cal, reset other fields

    Calendar cal = Calendar.getInstance();
    cal.setTime(parsedTimeinDate);
    cal.set(Calendar.MONTH,0);
    cal.set(Calendar.YEAR,2000);
    cal.set(Calendar.DATE,1);
//reset other fields for now calendar those aren't related to time
    Calendar calNow = Calendar.getInstance();
    calNow .set(Calendar.MONTH,0);
    calNow .set(Calendar.YEAR,2000);
    calNow .set(Calendar.DATE,1);

//determine
    cal.before(calNow);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  How do I compare a raw time in Java?

For example suppose I have

String endTime = "16:30:45";

How would I determine whether right now is before this time?  I have tried

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss")
Date date = sdf.parse(endTime);

However date has year 1970 and so the comparisons fail


问:
Get the first element from the file path
I have the vector in a data frame

```<code>c("E:\\\\My Network Places.old.dat", "E:\\\\pagefile.sys", "E:\\\\Press_Dly_Diff_G_91.rbc",
"E:\\\\TV_Press_Dly_Diff_A\\Retrospect\\Dantz", "E:\\\\TV_Press_Dly_Diff_A\\Retrospect\\TV_Press_Dly_Diff_A\\1-TV_Press_Dly_Diff_A\\AA000083.rdb",
"E:\\\\TV_Press_Dly_Diff_A\\Retrospect\\TV_Press_Dly_Diff_A\\1-TV_Press_Dly_Diff_A\\AA000561.rdb"
)
</code>```

In the above the length of file paths vary from just 1 to 5.  I am trying to get each level of the file path into a column in the data frame.  I tried with the first part using the following:

```<code>library(stringr)
df1$PF <- strsplit(df1$File.Name, "\\\\"))
df1$PFolder <- df1$PF[[1]][3]
</code>```

But I am getting only the first My Network Places.old.dat for all the rows in the data frame.  How do I split the path into multiple columns based on \\ separator and save it into separate columns within the data frame.  The desired output looks like this:

```<code>File.Name         FilePath1         FilePath2       FilePath3
</code>```

The above character vector is in File.Name in the data frame.

答:
Import with a separator - "\":

```<code>library(data.table)

fread("
E:\\\\My Network Places.old.dat
E:\\\\pagefile.sys
E:\\\\Press_Dly_Diff_G_91.rbc
E:\\\\TV_Press_Dly_Diff_A\\Retrospect\\Dantz
E:\\\\TV_Press_Dly_Diff_A\\Retrospect\\TV_Press_Dly_Diff_A\\1-TV_Press_Dly_Diff_A\\AA000083.rdb
E:\\\\TV_Press_Dly_Diff_A\\Retrospect\\TV_Press_Dly_Diff_A\\1-TV_Press_Dly_Diff_A\\AA000561.rdb",
      sep = "\\", fill = TRUE, na.strings = "")

#    V1 V2                        V3         V4                  V5                    V6           V7
# 1: E: NA My Network Places.old.dat       <NA>                <NA>                  <NA>         <NA>
# 2: E: NA              pagefile.sys       <NA>                <NA>                  <NA>         <NA>
# 3: E: NA   Press_Dly_Diff_G_91.rbc       <NA>                <NA>                  <NA>         <NA>
# 4: E: NA       TV_Press_Dly_Diff_A Retrospect               Dantz                  <NA>         <NA>
# 5: E: NA       TV_Press_Dly_Diff_A Retrospect TV_Press_Dly_Diff_A 1-TV_Press_Dly_Diff_A AA000083.rdb
# 6: E: NA       TV_Press_Dly_Diff_A Retrospect TV_Press_Dly_Diff_A 1-TV_Press_Dly_Diff_A AA000561.rdb
</code>```

Body:
I have the vector in a data frame

c("E:\\\\My Network Places.old.dat", "E:\\\\pagefile.sys", "E:\\\\Press_Dly_Diff_G_91.rbc",
"E:\\\\TV_Press_Dly_Diff_A\\Retrospect\\Dantz", "E:\\\\TV_Press_Dly_Diff_A\\Retrospect\\TV_Press_Dly_Diff_A\\1-TV_Press_Dly_Diff_A\\AA000083.rdb",
"E:\\\\TV_Press_Dly_Diff_A\\Retrospect\\TV_Press_Dly_Diff_A\\1-TV_Press_Dly_Diff_A\\AA000561.rdb"
)

In the above the length of file paths vary from just 1 to 5.  I am trying to get each level of the file path into a column in the data frame.  I tried with the first part using the following:

library(stringr)
df1$PF <- strsplit(df1$File.Name, "\\\\"))
df1$PFolder <- df1$PF[[1]][3]

But I am getting only the first My Network Places.old.dat for all the rows in the data frame.  How do I split the path into multiple columns based on \\ separator and save it into separate columns within the data frame.  The desired output looks like this:

File.Name         FilePath1         FilePath2       FilePath3

The above character vector is in File.Name in the data frame.

Body:
Import with a separator - "\":

library(data.table)

fread("
E:\\\\My Network Places.old.dat
E:\\\\pagefile.sys
E:\\\\Press_Dly_Diff_G_91.rbc
E:\\\\TV_Press_Dly_Diff_A\\Retrospect\\Dantz
E:\\\\TV_Press_Dly_Diff_A\\Retrospect\\TV_Press_Dly_Diff_A\\1-TV_Press_Dly_Diff_A\\AA000083.rdb
E:\\\\TV_Press_Dly_Diff_A\\Retrospect\\TV_Press_Dly_Diff_A\\1-TV_Press_Dly_Diff_A\\AA000561.rdb",
      sep = "\\", fill = TRUE, na.strings = "")

#    V1 V2                        V3         V4                  V5                    V6           V7
# 1: E: NA My Network Places.old.dat       <NA>                <NA>                  <NA>         <NA>
# 2: E: NA              pagefile.sys       <NA>                <NA>                  <NA>         <NA>
# 3: E: NA   Press_Dly_Diff_G_91.rbc       <NA>                <NA>                  <NA>         <NA>
# 4: E: NA       TV_Press_Dly_Diff_A Retrospect               Dantz                  <NA>         <NA>
# 5: E: NA       TV_Press_Dly_Diff_A Retrospect TV_Press_Dly_Diff_A 1-TV_Press_Dly_Diff_A AA000083.rdb
# 6: E: NA       TV_Press_Dly_Diff_A Retrospect TV_Press_Dly_Diff_A 1-TV_Press_Dly_Diff_A AA000561.rdb


问:
Bearer error="invalid_token", error_description="The issuer is invalid"
I have a simple web api project, which looks like this:

```<code>[Authorize]
        [Route("Get")]
        public ActionResult<string> SayHello()
        {
            return "Hello World";
        }
</code>```

I am trying to test it with Postman.  By following the steps here: https://kevinchalet.com/2016/07/13/creating-your-own-openid-connect-server-with-asos-testing-your-authorization-server-with-postman/

1) Send the request below and receive a token as expected:

2) Attempt to send another request with the authorization token as shown below:

Why do I get a 401 (unauthorized) error? The WWW-Authenticate response header says: Bearer error="invalid_token", error_description="The issuer is invalid".  I am using .Net Core 3.1.  I have commented out the sensitive information in the screenshots.

The web api works as expected when accessed from an MVC application.

Here is the startup code:

```<code>services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = identityUrl; //identityurl is a config item
                    options.RequireHttpsMetadata = false;
                    options.ApiName = apiName;

                });
</code>```

答:
The Authority of AddIdentityServerAuthentication middleware should be the base-address of your identityserver , middleware will contact the identity server's OIDC metadata endpoint to get the public keys to validate the JWT token .

Please confirm that the Authority is the url of identity server where you issued the jwt token .

Body:
I have a simple web api project, which looks like this:

[Authorize]
        [Route("Get")]
        public ActionResult<string> SayHello()
        {
            return "Hello World";
        }

I am trying to test it with Postman.  By following the steps here: https://kevinchalet.com/2016/07/13/creating-your-own-openid-connect-server-with-asos-testing-your-authorization-server-with-postman/

1) Send the request below and receive a token as expected:

2) Attempt to send another request with the authorization token as shown below:

Why do I get a 401 (unauthorized) error? The WWW-Authenticate response header says: Bearer error="invalid_token", error_description="The issuer is invalid".  I am using .Net Core 3.1.  I have commented out the sensitive information in the screenshots.

The web api works as expected when accessed from an MVC application.

Here is the startup code:

services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = identityUrl; //identityurl is a config item
                    options.RequireHttpsMetadata = false;
                    options.ApiName = apiName;

                });


问:
WPF Combobox - changed Datasource results in empty ItemsSource
I'm doing a simple binding of a Combobox in Page:

XAML:

```<code> <ComboBox x:Name="Cmb_test"  Grid.Column="2" Grid.Row="2" HorizontalAlignment="Left"  ItemsSource="{Binding}" />
</code>```

CODE behind:

```<code>private void Page_Loaded(object sender, RoutedEventArgs e)
{
     //Binding of label works fine everytime
     My_label.Content = dt.Rows[0]["Column1"];

     Cmb_test.DataContext = dt.DefaultView;
     Cmb_test.SelectedValuePath = dt.Columns[3].ToString();
     Cmb_test.DisplayMemberPath = dt.Columns[4].ToString();

     //Just a check to see whether DataTable really has changed
     Console.WriteLine(dt.Rows.Count.ToString());
 }
</code>```

But whenever my DataTable "dt" get's changed, my Combobox doesn't display Items anymore. I know there were a lot of questions allready asked regarding this issue, but all I could found were problems associating with refreshing during run-time. In my case I close a Page and re-open It when DataTable is changed, but result is empty Combobox.

Code for closing my Page, for addition:

CODE in same Page as Combobox:

```<code>private void BtnClose_Click(object sender, RoutedEventArgs e)
{
      Cmb_test.ItemsSource = null;
      Cmb_test.DataContext = null;

      var main_window = Application.Current.MainWindow;
      var frame = (main_window as MainWindow).My_Frame;
      frame.Content = null;

}
</code>```

Code in MainWindow:

```<code>private void My_Frame_Navigated(object sender, NavigationEventArgs e)
{
     if (My_Frame.Content == null)
     {
        My_Frame.RemoveBackEntry();
     }
}
</code>```

EDIT - another attempt:

XAML:

```<code>  <Page.Resources>
        <CollectionViewSource x:Key="My_source"/>
    </Page.Resources>

  <ComboBox x:Name="Cmb_test" ItemsSource="{Binding Source={StaticResource My_source}}" DisplayMemberPath="Column1"/>
</code>```

CODE behind:

```<code> private void Page_Loaded(object sender, RoutedEventArgs e)
        {

            var combo_datasource = new CollectionViewSource();
            combo_datasource = (CollectionViewSource)this.FindResource("seznamVrstEvidenc");
            combo_datasource.Source = Tabele.dt_Sifrant.DefaultView;

        }
</code>```

What is going on here, how can I fix combobox to show It's Items everytime ?

答:
You're not binding your ComboBox to anything

```<code><ComboBox x:Name="Cmb_test" [...] ItemsSource="{Binding}" />
</code>```

You should have some sort of collection

```<code><ComboBox x:Name="Cmb_test" [...] ItemsSource="{Binding MyList}" />
</code>```

Looking at the rest of your code it seems like you're "manually binding" the ComboBox to a DataTable. You can then create a Binding programmatically that links the ComboBox ItemsSource to the DataTable DefaultView.

There is a problem though, if what you mean with "DataTable is changed" is something like

```<code>dt = new DataTable();
</code>```

or

```<code>dt = Db.GetTable();
</code>```

you will likely fall in the same problem again because the binding is done between two instances, so when a new dt is created you have to rebind it to the ComboBox.

Another way of solving the problem could be to set the ComboBox ItemsSource every time you have a new DataTable.

I hope I was helpful.

--------- UPDATE --------

Following my comment I would go with implementing INotifyPropertyChanged on the class that stores the DataTable dt.

```<code>public class ThatParticulareClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    // [...] all the other stuff

    public void MethodThatUpdateDataTable()
    {
        // Update DataTable
        NotifyPropertyChanged(nameof(dt));
    }
}
</code>```

That should work. If your changes on the DataTable object came only from the user (from the view) than you should register at the control which expose the DataTable an the ending edit event (something like DataGrid.RowEditEnding). At that point you call NotifyPropertyChanged(nameof(dt)); (Be sure that this call is from the same class that contains the DataTable dt)

Implementation

Body:
I'm doing a simple binding of a Combobox in Page:

XAML:

 <ComboBox x:Name="Cmb_test"  Grid.Column="2" Grid.Row="2" HorizontalAlignment="Left"  ItemsSource="{Binding}" />

CODE behind:

private void Page_Loaded(object sender, RoutedEventArgs e)
{
     //Binding of label works fine everytime
     My_label.Content = dt.Rows[0]["Column1"];

     Cmb_test.DataContext = dt.DefaultView;
     Cmb_test.SelectedValuePath = dt.Columns[3].ToString();
     Cmb_test.DisplayMemberPath = dt.Columns[4].ToString();

     //Just a check to see whether DataTable really has changed
     Console.WriteLine(dt.Rows.Count.ToString());
 }

But whenever my DataTable "dt" get's changed, my Combobox doesn't display Items anymore. I know there were a lot of questions allready asked regarding this issue, but all I could found were problems associating with refreshing during run-time. In my case I close a Page and re-open It when DataTable is changed, but result is empty Combobox.

Code for closing my Page, for addition:

CODE in same Page as Combobox:

private void BtnClose_Click(object sender, RoutedEventArgs e)
{
      Cmb_test.ItemsSource = null;
      Cmb_test.DataContext = null;

      var main_window = Application.Current.MainWindow;
      var frame = (main_window as MainWindow).My_Frame;
      frame.Content = null;

}

Code in MainWindow:

private void My_Frame_Navigated(object sender, NavigationEventArgs e)
{
     if (My_Frame.Content == null)
     {
        My_Frame.RemoveBackEntry();
     }
}

EDIT - another attempt:

XAML:

  <Page.Resources>
        <CollectionViewSource x:Key="My_source"/>
    </Page.Resources>

  <ComboBox x:Name="Cmb_test" ItemsSource="{Binding Source={StaticResource My_source}}" DisplayMemberPath="Column1"/>

CODE behind:

 private void Page_Loaded(object sender, RoutedEventArgs e)
        {

            var combo_datasource = new CollectionViewSource();
            combo_datasource = (CollectionViewSource)this.FindResource("seznamVrstEvidenc");
            combo_datasource.Source = Tabele.dt_Sifrant.DefaultView;

        }

What is going on here, how can I fix combobox to show It's Items everytime ?

Body:
You're not binding your ComboBox to anything

<ComboBox x:Name="Cmb_test" [...] ItemsSource="{Binding}" />

You should have some sort of collection

<ComboBox x:Name="Cmb_test" [...] ItemsSource="{Binding MyList}" />

Looking at the rest of your code it seems like you're "manually binding" the ComboBox to a DataTable. You can then create a Binding programmatically that links the ComboBox ItemsSource to the DataTable DefaultView.

There is a problem though, if what you mean with "DataTable is changed" is something like

dt = new DataTable();

or

dt = Db.GetTable();

you will likely fall in the same problem again because the binding is done between two instances, so when a new dt is created you have to rebind it to the ComboBox.

Another way of solving the problem could be to set the ComboBox ItemsSource every time you have a new DataTable.

I hope I was helpful.

--------- UPDATE --------

Following my comment I would go with implementing INotifyPropertyChanged on the class that stores the DataTable dt.

public class ThatParticulareClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    // [...] all the other stuff

    public void MethodThatUpdateDataTable()
    {
        // Update DataTable
        NotifyPropertyChanged(nameof(dt));
    }
}

That should work. If your changes on the DataTable object came only from the user (from the view) than you should register at the control which expose the DataTable an the ending edit event (something like DataGrid.RowEditEnding). At that point you call NotifyPropertyChanged(nameof(dt)); (Be sure that this call is from the same class that contains the DataTable dt)

Implementation


问:
Is it possible to parse a property from application.yml to the java class field with a different name?
Is it possible to parse a property from application.yml to the java class field with a different name?

Say I have the following application.yml file

```<code>service:
  cms:
    webClient: http://www.example.com
</code>```

and my java class is

```<code>@Getter
@Setter
@ConfigurationProperties(prefix = "service.cms")
public class CmsProperties {
  private String webClient;
}
</code>```

I would like to rename java field name CmsProperties#webClient into CmsProperties#basePath, but I must keep the original name webClient in the application.yml.

Is it possible to do it?

P.S. I am using Spring Framework if it matters for the solution.

答:
OfCourse It is possible.

Spring

When you read property from yml file, you just need to provide key while it stores in basePath

```<code>@Value("${webClient}")
private String basePath;
</code>```

Plain Java

```<code>InputStream input = new FileInputStream("path/to/config.properties")) {
Properties prop = new Properties();
prop.load(input);
String basePath = prop.getProperty("webClient")
</code>```

Hope that does resolve answer

Body:
Is it possible to parse a property from application.yml to the java class field with a different name?

Say I have the following application.yml file

service:
  cms:
    webClient: http://www.example.com

and my java class is

@Getter
@Setter
@ConfigurationProperties(prefix = "service.cms")
public class CmsProperties {
  private String webClient;
}

I would like to rename java field name CmsProperties#webClient into CmsProperties#basePath, but I must keep the original name webClient in the application.yml.

Is it possible to do it?

P.S. I am using Spring Framework if it matters for the solution.

Body:
OfCourse It is possible.

Spring

When you read property from yml file, you just need to provide key while it stores in basePath

@Value("${webClient}")
private String basePath;

Plain Java

InputStream input = new FileInputStream("path/to/config.properties")) {
Properties prop = new Properties();
prop.load(input);
String basePath = prop.getProperty("webClient")

Hope that does resolve answer


问:
Python - Count Numbers of Different Digits in String
I'm very new to Python, please help.

I can only use if else statements, no loops or anything special like that.

This program asks the user for one string.
It counts the number of different digits in the string.  for
example a11111a1a1 contains a single digit, while a1s2d1d2d1d2d1
contains 2 digits.

Examples:

```<code>% python3 countNumbers.py
enter string: qwerty
there are no digits in string: "qwerty"

% python3 countNumbers.py
enter string: asdf1sdfg
there is one digit in string: "asdf1sdfg"

% python3 countNumbers.py
enter string: as1as2as333333
there are 3 different digits in string: "as1as2as333333"

% python3 countNumbers.py
enter string: a0123456789x
there are 10 different digits in string: "a0123456789x"
</code>```

```<code>num = input("enter string: ")
count = 0

if "0" in num:
    count = count + 1
if "1" in num:
    count = count + 1
if "2" in num:
    count = count + 1
if "3" in num:
    count = count + 1
if "4" in num:
    count = count + 1
if "5" in num:
    count = count + 1
if "6" in num:
    count = count + 1
if "7" in num:
    count = count + 1
if "8" in num:
    count = count + 1
if "9" in num:
    count = count + 1

if count >= 1:
    print("there is one digit in string: ", num)
elif count >= 2:
    print("there are two digits in string: ", num)
else:
    print("there are no digits in string: ", num)

</code>```

答:
One liner without re, using plain list and str operations

```<code>x='a1s2d1d2d1d2d1'
>>> sum( i.isdigit() for i in list(set(list(x))) )
2
>>>
</code>```

Breaking it down: convert string to list and then to set and then back to list, will remove duplicates and then count the digits.

```<code>>>>
>>> l = list(set(list(x)))
>>> sum( i.isdigit() for i in l )
2
</code>```

Note: this uses loop inside one liner.

Body:
I'm very new to Python, please help.

I can only use if else statements, no loops or anything special like that.

This program asks the user for one string.
It counts the number of different digits in the string.  for
example a11111a1a1 contains a single digit, while a1s2d1d2d1d2d1
contains 2 digits.

Examples:

% python3 countNumbers.py
enter string: qwerty
there are no digits in string: "qwerty"

% python3 countNumbers.py
enter string: asdf1sdfg
there is one digit in string: "asdf1sdfg"

% python3 countNumbers.py
enter string: as1as2as333333
there are 3 different digits in string: "as1as2as333333"

% python3 countNumbers.py
enter string: a0123456789x
there are 10 different digits in string: "a0123456789x"

num = input("enter string: ")
count = 0

if "0" in num:
    count = count + 1
if "1" in num:
    count = count + 1
if "2" in num:
    count = count + 1
if "3" in num:
    count = count + 1
if "4" in num:
    count = count + 1
if "5" in num:
    count = count + 1
if "6" in num:
    count = count + 1
if "7" in num:
    count = count + 1
if "8" in num:
    count = count + 1
if "9" in num:
    count = count + 1

if count >= 1:
    print("there is one digit in string: ", num)
elif count >= 2:
    print("there are two digits in string: ", num)
else:
    print("there are no digits in string: ", num)

Body:
One liner without re, using plain list and str operations

x='a1s2d1d2d1d2d1'
>>> sum( i.isdigit() for i in list(set(list(x))) )
2
>>>

Breaking it down: convert string to list and then to set and then back to list, will remove duplicates and then count the digits.

>>>
>>> l = list(set(list(x)))
>>> sum( i.isdigit() for i in l )
2

Note: this uses loop inside one liner.


问:
$aggregation, $sum on two collections in MongoDB
Hi suppose I have these two collections

sample1 :

```<code> {
    "_id" : {
            "date" : ISODate("2020-02-11T18:30:00Z"),
            "price" : 4,
            "offer" : 0,
            "itemCode" : "A001"
            "customerId" : ObjectId("5e43de778b57693cd46859eb"),
            "sellerId" : ObjectId("5e43e5cdc11f750864f46820"),
      },
    "charges" : 168
  }
  {
    "_id" : {
            "date" : ISODate("2020-02-11T18:30:00Z"),
            "coverPrice" :5.5 ,
            "offer" : 38,
            "itemCode" : "B001"
            "customerId" : ObjectId("5e43de778b57693cd46859eb"),
            "sellerId" : ObjectId("5e43e5cdc11f750864f46820"),
    },
    "charges" : 209.5
  }
</code>```

NOTE : sample1's _id doesnot have any ObjectId().

sample2 :

```<code>        {
            "paymentReceivedOnDate" : ISODate("2020-02-12T18:30:00Z"),
             "customerId" : ObjectId("5e43de778b57693cd46859eb"),
            "sellerId" : ObjectId("5e43e5cdc11f750864f46820"),
            "amount" : 30,
         }
      {
            "paymentReceivedOnDate" : ISODate("2020-02-12T18:30:00Z"),
             "customerId" : ObjectId("5e43de778b57693cd46859eb"),
            "sellerId" : ObjectId("5e43e5cdc11f750864f46820"),
            "amount" : 160,
         }
     {
            "paymentReceivedOnDate" : ISODate("2020-02-11T18:30:00Z"),
             "customerId" : ObjectId("5e43de778b57693cd46859eb"),
            "sellerId" : ObjectId("5e43e5cdc11f750864f46820"),
            "amount" : 50,
        }
</code>```

My problem statements :

1: Firstly i need to calculate the totalCharges from sample 1 collection. against the [date,customerId,sellerId ]

2: Secondly i need to calculate totalAmount from sample 2 collection.

3: Than i need calculte the outstanding i.e [totalCharges - totalAmount].

4: lastly and most importantly i need to save the projected result into a new collection suppose "result" with the following fields-['customerId','sellerId','date','totalCharges','outstanding'(i.e: [totalCharges - totalAmount]),'totalAmount'.

答:
You can try below query :

```<code>db.sample1.aggregate([
    /** groups data & sum up charges */
    { $group: { _id: { date: '$_id.date', customerId: '$_id.customerId', sellerId: '$_id.sellerId' }, totalCharges: { $sum: '$charges' } } },
    /** finds matching docs from sample2 */
    {
        $lookup:
        {
            from: "sample2",
            let: { customerId: '$_id.customerId', sellerId: '$_id.sellerId' },
            pipeline: [
                {
                    $match:
                    {
                        $expr:
                        {
                            $and:
                                [
                                    { $eq: ["$customerId", "$$customerId"] },
                                    { $eq: ["$sellerId", "$$sellerId"] }
                                ]
                        }
                    }
                },
                { $project: { amount: 1, _id: 0 } }
            ],
            as: "TotalAmount" // TotalAmount is an array of objects, each object will have just amount field in it.
        }
    },
    /** retains only needed fields  */
    {
        $project: {
            totalCharges: 1, outstanding: {
                $subtract: ['$totalCharges', {
                    $reduce: {
                        input: '$TotalAmount',
                        initialValue: 0,
                        in: { $add: ["$$value", "$$this.amount"] }
                    }
                }]
            }, TotalAmount: {
                $reduce: {
                    input: '$TotalAmount',
                    initialValue: 0,
                    in: { $add: ["$$value", "$$this.amount"] }
                }
            }
        }
    }
])
</code>```

Test : MongoDB-Playground

Ref : aggregation-pipeline

Note : At the end of the aggregation you can have either $merge or $out stage to write aggregation results into new collection, If your MongoDB v >=4.2 then prefer $merge cause it will merge fields to existing documents/adds new documents to existing collection or if no collection is found with given name it would create new collection, But where as $out will completely replaces existing collection if provided collection name already exists or creates new collection with provided name.

Body:
Hi suppose I have these two collections

sample1 :

 {
    "_id" : {
            "date" : ISODate("2020-02-11T18:30:00Z"),
            "price" : 4,
            "offer" : 0,
            "itemCode" : "A001"
            "customerId" : ObjectId("5e43de778b57693cd46859eb"),
            "sellerId" : ObjectId("5e43e5cdc11f750864f46820"),
      },
    "charges" : 168
  }
  {
    "_id" : {
            "date" : ISODate("2020-02-11T18:30:00Z"),
            "coverPrice" :5.5 ,
            "offer" : 38,
            "itemCode" : "B001"
            "customerId" : ObjectId("5e43de778b57693cd46859eb"),
            "sellerId" : ObjectId("5e43e5cdc11f750864f46820"),
    },
    "charges" : 209.5
  }

NOTE : sample1's _id doesnot have any ObjectId().

sample2 :

        {
            "paymentReceivedOnDate" : ISODate("2020-02-12T18:30:00Z"),
             "customerId" : ObjectId("5e43de778b57693cd46859eb"),
            "sellerId" : ObjectId("5e43e5cdc11f750864f46820"),
            "amount" : 30,
         }
      {
            "paymentReceivedOnDate" : ISODate("2020-02-12T18:30:00Z"),
             "customerId" : ObjectId("5e43de778b57693cd46859eb"),
            "sellerId" : ObjectId("5e43e5cdc11f750864f46820"),
            "amount" : 160,
         }
     {
            "paymentReceivedOnDate" : ISODate("2020-02-11T18:30:00Z"),
             "customerId" : ObjectId("5e43de778b57693cd46859eb"),
            "sellerId" : ObjectId("5e43e5cdc11f750864f46820"),
            "amount" : 50,
        }

My problem statements :

1: Firstly i need to calculate the totalCharges from sample 1 collection. against the [date,customerId,sellerId ]

2: Secondly i need to calculate totalAmount from sample 2 collection.

3: Than i need calculte the outstanding i.e [totalCharges - totalAmount].

4: lastly and most importantly i need to save the projected result into a new collection suppose "result" with the following fields-['customerId','sellerId','date','totalCharges','outstanding'(i.e: [totalCharges - totalAmount]),'totalAmount'.

Body:
You can try below query :

db.sample1.aggregate([
    /** groups data & sum up charges */
    { $group: { _id: { date: '$_id.date', customerId: '$_id.customerId', sellerId: '$_id.sellerId' }, totalCharges: { $sum: '$charges' } } },
    /** finds matching docs from sample2 */
    {
        $lookup:
        {
            from: "sample2",
            let: { customerId: '$_id.customerId', sellerId: '$_id.sellerId' },
            pipeline: [
                {
                    $match:
                    {
                        $expr:
                        {
                            $and:
                                [
                                    { $eq: ["$customerId", "$$customerId"] },
                                    { $eq: ["$sellerId", "$$sellerId"] }
                                ]
                        }
                    }
                },
                { $project: { amount: 1, _id: 0 } }
            ],
            as: "TotalAmount" // TotalAmount is an array of objects, each object will have just amount field in it.
        }
    },
    /** retains only needed fields  */
    {
        $project: {
            totalCharges: 1, outstanding: {
                $subtract: ['$totalCharges', {
                    $reduce: {
                        input: '$TotalAmount',
                        initialValue: 0,
                        in: { $add: ["$$value", "$$this.amount"] }
                    }
                }]
            }, TotalAmount: {
                $reduce: {
                    input: '$TotalAmount',
                    initialValue: 0,
                    in: { $add: ["$$value", "$$this.amount"] }
                }
            }
        }
    }
])

Test : MongoDB-Playground

Ref : aggregation-pipeline

Note : At the end of the aggregation you can have either $merge or $out stage to write aggregation results into new collection, If your MongoDB v >=4.2 then prefer $merge cause it will merge fields to existing documents/adds new documents to existing collection or if no collection is found with given name it would create new collection, But where as $out will completely replaces existing collection if provided collection name already exists or creates new collection with provided name.


问:
Docker Wordpress container with custom php.ini file settings
I'm running Wordpress (and PHPMyAdmin and MySQL) in a Docker container, and I need to make a change to increase the maximum uploadable file size for PHPMyAdmin

I researched a number of solutions and found a suggestion to create a custom uploads.ini file and then include this file in the docker-compose file.

So I have this:

uploads.ini

```<code>file_uploads = On
memory_limit = 64M
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 600
</code>```

docker-compose.yml

```<code>version: '3'

services:
  # Database
  db:
    image: mysql:5.7
    volumes:
      - db_data:/var/lib/mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: wordpress
    networks:
      - wpsite
  # phpmyadmin
  phpmyadmin:
    depends_on:
      - db
    image: phpmyadmin/phpmyadmin
    restart: always
    ports:
      - '8080:80'
    environment:
      PMA_HOST: db
      MYSQL_ROOT_PASSWORD: password
    networks:
      - wpsite
  # Wordpress
  wordpress:
    depends_on:
      - db
    image: wordpress:latest
    ports:
      - '8000:80'
    restart: always
    volumes:
      - './:/var/www/html'
      - ./uploads.ini:/usr/local/etc/php/conf.d/uploads.ini
    environment:
      WORDPRESS_DB_HOST: db:3306
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: wordpress
    networks:
      - wpsite
networks:
  wpsite:
volumes:
  db_data:
</code>```

I have included the uploads.ini file in the volumes for wordpress

```<code>volumes:
      - './:/var/www/html'
      - ./uploads.ini:/usr/local/etc/php/conf.d/uploads.ini
</code>```

But sadly after running the docker-compose and opening localhost:8080 to go to PHPMyAdmin I still only have a maximum file upload size of 2m, not the 64m in my custom file

答:
You want increase the maximum uploadable file size for PHPMyAdmin, but uploads.ini you add for your wordpress container)

add volume for phpmyadmin container and you'll be happy=)

```<code># phpmyadmin
phpmyadmin:
depends_on:
  - db
image: phpmyadmin/phpmyadmin
volumes:
 - ./uploads.ini:/usr/local/etc/php/conf.d/uploads.ini
restart: always
ports:
  - '8080:80'
environment:
  PMA_HOST: db
  MYSQL_ROOT_PASSWORD: password
networks:
  - wpsite
</code>```

Body:
I'm running Wordpress (and PHPMyAdmin and MySQL) in a Docker container, and I need to make a change to increase the maximum uploadable file size for PHPMyAdmin

I researched a number of solutions and found a suggestion to create a custom uploads.ini file and then include this file in the docker-compose file.

So I have this:

uploads.ini

file_uploads = On
memory_limit = 64M
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 600

docker-compose.yml

version: '3'

services:
  # Database
  db:
    image: mysql:5.7
    volumes:
      - db_data:/var/lib/mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: wordpress
    networks:
      - wpsite
  # phpmyadmin
  phpmyadmin:
    depends_on:
      - db
    image: phpmyadmin/phpmyadmin
    restart: always
    ports:
      - '8080:80'
    environment:
      PMA_HOST: db
      MYSQL_ROOT_PASSWORD: password
    networks:
      - wpsite
  # Wordpress
  wordpress:
    depends_on:
      - db
    image: wordpress:latest
    ports:
      - '8000:80'
    restart: always
    volumes:
      - './:/var/www/html'
      - ./uploads.ini:/usr/local/etc/php/conf.d/uploads.ini
    environment:
      WORDPRESS_DB_HOST: db:3306
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: wordpress
    networks:
      - wpsite
networks:
  wpsite:
volumes:
  db_data:

I have included the uploads.ini file in the volumes for wordpress

volumes:
      - './:/var/www/html'
      - ./uploads.ini:/usr/local/etc/php/conf.d/uploads.ini

But sadly after running the docker-compose and opening localhost:8080 to go to PHPMyAdmin I still only have a maximum file upload size of 2m, not the 64m in my custom file

Body:
You want increase the maximum uploadable file size for PHPMyAdmin, but uploads.ini you add for your wordpress container)

add volume for phpmyadmin container and you'll be happy=)

# phpmyadmin
phpmyadmin:
depends_on:
  - db
image: phpmyadmin/phpmyadmin
volumes:
 - ./uploads.ini:/usr/local/etc/php/conf.d/uploads.ini
restart: always
ports:
  - '8080:80'
environment:
  PMA_HOST: db
  MYSQL_ROOT_PASSWORD: password
networks:
  - wpsite


问:
c++ memory leak when using std::string in shared memory array
I have this class

```<code>class LayoutEntry
{
  unsigned int id_;
  string name_;
  bool isInput_;
};
</code>```

The copy constructor looks like this:

```<code>LayoutEntry(const LayoutEntry &other)
        : id_(other.id_),
        name_(other.name_),
        isInput_(other.isInput_)
    {
    }
</code>```

Objects of this class are put inside a map within another class

```<code>class DataLayoutDescription
{
    unsigned int sz_;
    set<LayoutEntry, SortByOffset> impl;

    // HERE!!!
    map<unsigned int, LayoutEntry> mapById;
</code>```

The copy constructor of this class looks like this:

```<code>DataLayoutDescription::DataLayoutDescription(const DataLayoutDescription &other)
    :sz_(other.sz_), impl(other.impl), mapById(other.mapById)
{
}
</code>```

Now the question:

I Get a memory leak for each LayoutEntry when run like printed

If I remove mapById(other.mapById) in the copy constructor of DataLayoutDescription  then there is no memleak

If I remove name_(other.name_), The memory leaks are also gone

Why?

EDIT

For Testing I use BOOST::UnitTest at the end I get a memory leak dump

```<code>C:\wc\05_EAPGit\Debug>EapLibTest.exe --run-test=SharedVectorTest
Running 7 test cases...

*** No errors detected
Detected memory leaks!
Dumping objects ->
{1378} normal block at 0x005815C0, 16 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
{1377} normal block at 0x00581580, 16 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
{1376} normal block at 0x00581540, 16 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
</code>```

Possible Reason?
I persist the DataLayoutDescription in a shared memory area using this method

```<code>void DataLayoutDescription::Save(LayoutEntry *les, unsigned int maxEntries) const
{
    int n = std::max(impl.size(), maxEntries);
    int i = 0;
    for (DataLayoutDescription::iterator it = begin(); it != end(); ++it)
    {
        les[i] = *it;  // Source of memory leak here???
        ++i;
    }
}
</code>```

I dereference the iterator ant store a copy of this in the array that is located in the shared memory region. Is there something wrong? The shared memory is deleted on exit.

Furhter Trackdown
The class LayoutEntry is placed in an array within a shared memory area and contains a string. The reason for the memory leak is that the string gets resized. Thus it allocates more memory on the heap. Now I guess that this memroy will not be freed since the original memory is located in the shared memory. Could this be the reason? Next thing I will try to remove the string and replace it with an char array of fixed length.

... after several minutes

This was it. After replacing the string with a fixed array of char the memory leak dissapeared. Hope this helps someone.

答:
Assuming that when you say you have a memory leak, you mean some checker like Purify or valgrind is telling you so, the most likely scenario is that somehow you're leaking LayoutEntry objects, NOT string objects directly. I got bitten by this once and got confused because my own object was getting leaked, but the leak was tagged (by valgrind) to std::string which made it harder to find.

Alternately it may just be detecting a growth. Did you try doing a clear on your map prior to exiting?

Body:
I have this class

class LayoutEntry
{
  unsigned int id_;
  string name_;
  bool isInput_;
};

The copy constructor looks like this:

LayoutEntry(const LayoutEntry &other)
        : id_(other.id_),
        name_(other.name_),
        isInput_(other.isInput_)
    {
    }

Objects of this class are put inside a map within another class

class DataLayoutDescription
{
    unsigned int sz_;
    set<LayoutEntry, SortByOffset> impl;

    // HERE!!!
    map<unsigned int, LayoutEntry> mapById;

The copy constructor of this class looks like this:

DataLayoutDescription::DataLayoutDescription(const DataLayoutDescription &other)
    :sz_(other.sz_), impl(other.impl), mapById(other.mapById)
{
}

Now the question:

I Get a memory leak for each LayoutEntry when run like printed

If I remove mapById(other.mapById) in the copy constructor of DataLayoutDescription  then there is no memleak

If I remove name_(other.name_), The memory leaks are also gone

Why?

EDIT

For Testing I use BOOST::UnitTest at the end I get a memory leak dump

C:\wc\05_EAPGit\Debug>EapLibTest.exe --run-test=SharedVectorTest
Running 7 test cases...

*** No errors detected
Detected memory leaks!
Dumping objects ->
{1378} normal block at 0x005815C0, 16 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
{1377} normal block at 0x00581580, 16 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
{1376} normal block at 0x00581540, 16 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.

Possible Reason?
I persist the DataLayoutDescription in a shared memory area using this method

void DataLayoutDescription::Save(LayoutEntry *les, unsigned int maxEntries) const
{
    int n = std::max(impl.size(), maxEntries);
    int i = 0;
    for (DataLayoutDescription::iterator it = begin(); it != end(); ++it)
    {
        les[i] = *it;  // Source of memory leak here???
        ++i;
    }
}

I dereference the iterator ant store a copy of this in the array that is located in the shared memory region. Is there something wrong? The shared memory is deleted on exit.

Furhter Trackdown
The class LayoutEntry is placed in an array within a shared memory area and contains a string. The reason for the memory leak is that the string gets resized. Thus it allocates more memory on the heap. Now I guess that this memroy will not be freed since the original memory is located in the shared memory. Could this be the reason? Next thing I will try to remove the string and replace it with an char array of fixed length.

... after several minutes

This was it. After replacing the string with a fixed array of char the memory leak dissapeared. Hope this helps someone.


问:
How to transfer Yoast SEO plugin data into advanced custom fields
My current site used yoast plugin for show meta data. But i want to deactivate the plugin and I want to transfer all meta details in to Advanced custom fields. Any idea.</p>

答:
You can use WP All Export plugin to export whole your preferred data, then use WP All Import plugin to import as ACF fields.

URLs of plugins

https://wordpress.org/plugins/wp-all-export/

https://wordpress.org/plugins/wp-all-import/


问:
Loop through number array to construct object of index nodes in plain javascript
I have an array such as [2,5,3,1] each number represents an index number. How would I be able to construct an object path using these nodes? For example:

[2,5] would create:

```<code>myObject.conversations[i].conversations[i]
</code>```

[2,5,3,1] would create:

```<code>myObject.conversations[i].conversations[i].conversations[i].conversations[i]
</code>```

I can only use basic javascript - es6, es5 etc not allowed. I tried a for loop to construct a string which I could just keep adding to but it didn’t work.

答:
I hope that can help.</p>

```<code>let obj = 'myObject';
[2,5,3,1].forEach(i => {
  obj += `.conversations[${i}]`;
});
eval(obj);
</code>```

Body:
I have an array such as [2,5,3,1] each number represents an index number. How would I be able to construct an object path using these nodes? For example:

[2,5] would create:

myObject.conversations[i].conversations[i]

[2,5,3,1] would create:

myObject.conversations[i].conversations[i].conversations[i].conversations[i]

I can only use basic javascript - es6, es5 etc not allowed. I tried a for loop to construct a string which I could just keep adding to but it didn’t work.

Body:
I hope that can help.

let obj = 'myObject';
[2,5,3,1].forEach(i => {
  obj += `.conversations[${i}]`;
});
eval(obj);


答:
```<code>num=input()
count=0

for i in num:
    if i in '0123456789':
        count+=1

print(count)
</code>```

You can use "in" in a single line

Title: Python - Count Numbers of Different Digits in String

Body:
num=input()
count=0

for i in num:
    if i in '0123456789':
        count+=1

print(count)

You can use "in" in a single line


问:
How can i compress the MultipartFie[] size in spring boot when i deploy the spring boot project in aws elastic beanstalk.?
In this service class where can i write the file compression code and am saving the file as "Base64" format in database. The single file is uploaded in s3 bucket but when i upload the MultipartFile[] using postman in aws s3 bucket am getting the "413 Request Entity Too Large" error.How can i solve this error.

This is my service class

```<code>@Component
public class TeacherGalleryService {
    @Autowired
    TeacherGalleryRepository galleryRepo;

    private AmazonS3 amazonS3;

    @Value("${aws.access.key.id}")
    private String accessKey;

    @Value("${aws.access.key.secret}")
    private String secretKey;

    @Value("${aws.region}")
    private String region;

    @Value("${aws.s3.audio.bucket}")
    private String s3Bucket;

    @Value("${aws.endpointUrl}")
    private String endpointUrl;

    @SuppressWarnings("deprecation")
    @PostConstruct
    private void initializeAmazon() {
        System.out.println(accessKey);
        AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
        this.amazonS3 = new AmazonS3Client(credentials);
    }

    public String uploadFile(MultipartFile file) {
        String fileUrl = "";
        try {
            File myFile = convertMultiPartToFile(file);
            String fileName = generateFileName(file);
            fileUrl = endpointUrl + "/" + s3Bucket + "/" + fileName;
            uploadFileTos3bucket(fileName, myFile);
            myFile.delete();
        } catch (Exception e) {
           e.printStackTrace();
        }
        return fileUrl;
    }

    private File convertMultiPartToFile(MultipartFile file) throws IOException {
        File convFile = new File(file.getOriginalFilename());
        FileOutputStream fos = new FileOutputStream(convFile);
        fos.write(file.getBytes());
        fos.close();
        return convFile;
    }

    private String generateFileName(MultipartFile multiPart) {
        return  multiPart.getOriginalFilename().replace(" ", "_");
    }

    private void uploadFileTos3bucket(String fileName, File file) {
        amazonS3.putObject(new PutObjectRequest(s3Bucket, fileName, file)
                .withCannedAcl(CannedAccessControlList.PublicRead));
    }

    public TeacherGallery storeFile(TeacherGallery teacherGallery, MultipartFile file) {
        String fileNames = StringUtils.cleanPath(file.getOriginalFilename());
        String fileUrls = endpointUrl + "/" + s3Bucket + "/" + fileNames;
        byte[] images = null;
        try {
            images = Base64.encodeBase64(file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        teacherGallery = new TeacherGallery(images, fileNames, fileUrls, teacherGallery.getTitle());
        return galleryRepo.save(teacherGallery)
}
}
</code>```

答:
This does seem to be low size configured in Spring's servlet container. Take a look at Web properties for your Spring Boot:

You want to look into these properties

```<code>spring.servlet.multipart.max-file-size (default 1MB)
spring.servlet.multipart.max-request-size (default 10 MB)
</code>```

Body:
In this service class where can i write the file compression code and am saving the file as "Base64" format in database. The single file is uploaded in s3 bucket but when i upload the MultipartFile[] using postman in aws s3 bucket am getting the "413 Request Entity Too Large" error.How can i solve this error.

This is my service class

@Component
public class TeacherGalleryService {
    @Autowired
    TeacherGalleryRepository galleryRepo;

    private AmazonS3 amazonS3;

    @Value("${aws.access.key.id}")
    private String accessKey;

    @Value("${aws.access.key.secret}")
    private String secretKey;

    @Value("${aws.region}")
    private String region;

    @Value("${aws.s3.audio.bucket}")
    private String s3Bucket;

    @Value("${aws.endpointUrl}")
    private String endpointUrl;

    @SuppressWarnings("deprecation")
    @PostConstruct
    private void initializeAmazon() {
        System.out.println(accessKey);
        AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
        this.amazonS3 = new AmazonS3Client(credentials);
    }

    public String uploadFile(MultipartFile file) {
        String fileUrl = "";
        try {
            File myFile = convertMultiPartToFile(file);
            String fileName = generateFileName(file);
            fileUrl = endpointUrl + "/" + s3Bucket + "/" + fileName;
            uploadFileTos3bucket(fileName, myFile);
            myFile.delete();
        } catch (Exception e) {
           e.printStackTrace();
        }
        return fileUrl;
    }

    private File convertMultiPartToFile(MultipartFile file) throws IOException {
        File convFile = new File(file.getOriginalFilename());
        FileOutputStream fos = new FileOutputStream(convFile);
        fos.write(file.getBytes());
        fos.close();
        return convFile;
    }

    private String generateFileName(MultipartFile multiPart) {
        return  multiPart.getOriginalFilename().replace(" ", "_");
    }

    private void uploadFileTos3bucket(String fileName, File file) {
        amazonS3.putObject(new PutObjectRequest(s3Bucket, fileName, file)
                .withCannedAcl(CannedAccessControlList.PublicRead));
    }

    public TeacherGallery storeFile(TeacherGallery teacherGallery, MultipartFile file) {
        String fileNames = StringUtils.cleanPath(file.getOriginalFilename());
        String fileUrls = endpointUrl + "/" + s3Bucket + "/" + fileNames;
        byte[] images = null;
        try {
            images = Base64.encodeBase64(file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        teacherGallery = new TeacherGallery(images, fileNames, fileUrls, teacherGallery.getTitle());
        return galleryRepo.save(teacherGallery)
}
}

Body:
This does seem to be low size configured in Spring's servlet container. Take a look at Web properties for your Spring Boot:

You want to look into these properties

spring.servlet.multipart.max-file-size (default 1MB)
spring.servlet.multipart.max-request-size (default 10 MB)


问:
"Browse To Find Source" in Visual Studio 2010
When is "Browse To Find source" enabled in Visual Studio 2010? (see below)

In addition, I want to have it enabled so that I could browse to already-downloaded source code
files from http://referencesource.microsoft.com/.

This would be useful since Microsoft doesn't always release PDB/source code at the same time with their latest patches. So if I want to step for example into DateTime, I really don't care about the latest patches which didn't involve DateTime. I just want to browse to its code which I downloaded from http://referencesource.microsoft.com/.

After some investigations I found dia2dump which is a useful tool to view PDB file contents. (It's in C:\Program Files (x86)\Microsoft Visual Studio 10.0\DIA SDK\Samples\DIA2Dump\)

It looks like when I can't see source code for something like DateTime, using .NET Framework stepping, a mscorlib.pdb file actually gets downloaded.

But if you look inside it with dia2dump it doesn't contain source file mappings. In other words useless, because even if you could browse to the source code like my initial idea, it wouldn't work because there are no source file mappings and no start addresses of the functions, and a lot of stuff missing :(

I think the solutions here are to use .NET Reflector Pro for or keep a virtual machine at hand, with releases of the framework which have source code and then disable updates.

答:
Check out the article Step Into .NET Framework 4.0 Source Code.

If you encounter the “No Source Available” screen, try to press “Browse to Find Source” and find the file you need in the source directory. You should probably need to use files search to find it.
  This is done only once, since from now on Visual Studio remembers this location and searches there for missing source files.

I hope it's about what you are looking for.


问:
Scala Spark Task not serializable error in code
Not sure whats wrong with the code below , but its throwing

```<code>org.apache.spark.SparkException: Task not serializable
</code>```

error. Googled about the error, but couldn't resolve.

Below is the code: (Can be copy pasted and executed on community.cloud.databricks.com by creating new Scala notebook)

```<code>    import com.google.gson._
     object TweetUtils {
          case class Tweet(
               id : String,
               user : String,
               userName : String,
               text : String,
               place : String,
               country : String,
               lang : String
          )

       def parseFromJson(lines:Iterator[String]):Iterator[Tweet] = {
            val gson = new Gson
            lines.map( line => gson.fromJson(line, classOf[Tweet]))
       }

       def loadData(): RDD[Tweet] = {
           val pathToFile = "/FileStore/tables/reduced_tweets-57570.json"
           sc.textFile(pathToFile).mapPartitions(parseFromJson(_))
       }

       def tweetsByUser(): RDD[(String, Iterable[Tweet])] = {
           val tweets = loadData
           tweets.groupBy(_.user)
       }
   }

   val res = TweetUtils.tweetsByUser()
   res.collect().take(5).foreach(println)
</code>```

Below is the detailed error Message:

```<code>at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:403)
    at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:393)
    at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:162)
    at org.apache.spark.SparkContext.clean(SparkContext.scala:2548)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitions$1.apply(RDD.scala:827)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitions$1.apply(RDD.scala:826)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:392)
    at org.apache.spark.rdd.RDD.mapPartitions(RDD.scala:826)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$TweetUtils$.loadData(command-3696793732897971:22)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$TweetUtils$.tweetsByUser(command-3696793732897971:25)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:30)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:84)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:86)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:88)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:90)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw.<init>(command-3696793732897971:92)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw.<init>(command-3696793732897971:94)
</code>```

Thanks in advance,

Sri

答:
Finally, what worked is by implementing together both suggestions from " Artem Aliev" and "Partha" together. i.e. by moving "case class Tweet" outside of "TweetUtils object" and also by extending the Object "object TweetUtils extends Serializable"

Thanks to both of you.

Body:
Not sure whats wrong with the code below , but its throwing

org.apache.spark.SparkException: Task not serializable

error. Googled about the error, but couldn't resolve.

Below is the code: (Can be copy pasted and executed on community.cloud.databricks.com by creating new Scala notebook)

    import com.google.gson._
     object TweetUtils {
          case class Tweet(
               id : String,
               user : String,
               userName : String,
               text : String,
               place : String,
               country : String,
               lang : String
          )

       def parseFromJson(lines:Iterator[String]):Iterator[Tweet] = {
            val gson = new Gson
            lines.map( line => gson.fromJson(line, classOf[Tweet]))
       }

       def loadData(): RDD[Tweet] = {
           val pathToFile = "/FileStore/tables/reduced_tweets-57570.json"
           sc.textFile(pathToFile).mapPartitions(parseFromJson(_))
       }

       def tweetsByUser(): RDD[(String, Iterable[Tweet])] = {
           val tweets = loadData
           tweets.groupBy(_.user)
       }
   }

   val res = TweetUtils.tweetsByUser()
   res.collect().take(5).foreach(println)

Below is the detailed error Message:

at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:403)
    at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:393)
    at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:162)
    at org.apache.spark.SparkContext.clean(SparkContext.scala:2548)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitions$1.apply(RDD.scala:827)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitions$1.apply(RDD.scala:826)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:392)
    at org.apache.spark.rdd.RDD.mapPartitions(RDD.scala:826)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$TweetUtils$.loadData(command-3696793732897971:22)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$TweetUtils$.tweetsByUser(command-3696793732897971:25)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:30)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:84)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:86)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:88)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw$$iw.<init>(command-3696793732897971:90)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw$$iw.<init>(command-3696793732897971:92)
    at line05db6d250e4b42e2b2c1d6b97ba83df533.$read$$iw$$iw.<init>(command-3696793732897971:94)

Thanks in advance,

Sri