问:
How to bind TextField and ProgressBar in JavaFx
I'm trying to Use reactive bindings to bind the value of alcoholPercentageField to the progress property of alcoholBar.
The progress bar will "full" when alcoholic content is set to 20 % and empty when the alcoholic content is 0

My Code-

```<code>    public void start(Stage stage) throws Exception {
    stage.setTitle("Mead calculator");

    // Creating the fields and components
    TextField waterAmountField = new TextField();

    TextField alcoholPercentageField = new TextField();

    TextField sugarAmountField = new TextField();
    Label meadTotalAmount = new Label();
    Label assessmentLabel = new Label("");
    //assessmentLabel.textProperty().bind(alcoholPercentageField.textProperty());

    //Conditional Binding Error

    assessmentLabel.textProperty().bind(Bindings.when((alcoholPercentageField.textProperty().lessThan(5))).then("Smart").otherwise("Bad"));

    ProgressBar alcoholBar = new ProgressBar();

    //Error is here
    alcoholBar.progressProperty().bind(alcoholPercentageField.textProperty() * 5);
</code>```

Rest of the Code: some visual things

```<code>GridPane grid = new GridPane();
    grid.setAlignment(Pos.CENTER);
    grid.setHgap(10);
    grid.setVgap(10);
    grid.setPadding(new Insets(25, 25, 25, 25));
    var columnOneConstraints = new ColumnConstraints(150, 150, Double.MAX_VALUE);
    columnOneConstraints.setHalignment(HPos.RIGHT);
    var columnTwoConstrains = new ColumnConstraints(200,200, Double.MAX_VALUE);
    columnTwoConstrains.setHgrow(Priority.SOMETIMES);
    grid.getColumnConstraints().addAll(columnOneConstraints, columnTwoConstrains);
    alcoholBar.setMaxWidth(Double.MAX_VALUE);
    GridPane.setColumnSpan(alcoholBar, 2);
    GridPane.setHalignment(assessmentLabel, HPos.RIGHT);
    sugarAmountField.setDisable(true);

    grid.add(new Label("Water (l):"), 0, 0);
    grid.add(waterAmountField, 1, 0);

    grid.add(new Label("Vol-%:"), 0, 1);
    grid.add(alcoholPercentageField, 1, 1);

    grid.add(new Label("Sugar (kg):"),  0, 2);
    grid.add(sugarAmountField, 1, 2);

    grid.add(new Label("Lemons: "), 0, 3);
    grid.add(new Label("To taste"), 1, 3);

    grid.add(new Label("Mead total (kg):"), 0, 4);
    grid.add(meadTotalAmount, 1, 4);

    grid.add(alcoholBar, 0, 5);
    grid.add(assessmentLabel, 1, 6);
    // Okay, layout creation stops here

    // And of course set the scene and show the stage as always
    stage.setScene(new Scene(grid, 500, 400));
    stage.show();
}
</code>```

}

答:
You need to create some additional Property and Binding objects.

First, create properties for your TextField alcoholPercentageField. Then, you'll bind them using a StringConverter to convert the text entered into doubles.

Finally, use bindBidirectional to propagate and lastly bind it with progressBar by dividing 20 ( The progress bar will be "full" when alcoholic content is set to 20 %)

Code Will be like this-

```<code>    // Properties used for bindings
    DoubleProperty alcoholPercent = new SimpleDoubleProperty();

    //Setup the converters to get the input from the textfields
    StringConverter<? extends Number> converter = new DoubleStringConverter();

    Bindings.bindBidirectional(alcoholPercentageField.textProperty(), alcoholPercent, (StringConverter<Number>) converter);
    alcoholBar.progressProperty().bind(alcoholPercent.divide(20));
</code>```

For Conditional Binding, check this Conditional Binding

Code would be like this-

```<code>    assessmentLabel.textProperty().bind(Bindings.when(alcoholPercent.lessThan(5)).then("Smart").otherwise("Bad"));
    assessmentLabel.textFillProperty().bind(Bindings.when(alcoholPercent.lessThan(5)).then(Color.GREEN).otherwise(Color.RED));
</code>```

Body:
I'm trying to Use reactive bindings to bind the value of alcoholPercentageField to the progress property of alcoholBar.
The progress bar will "full" when alcoholic content is set to 20 % and empty when the alcoholic content is 0

My Code-

    public void start(Stage stage) throws Exception {
    stage.setTitle("Mead calculator");

    // Creating the fields and components
    TextField waterAmountField = new TextField();

    TextField alcoholPercentageField = new TextField();

    TextField sugarAmountField = new TextField();
    Label meadTotalAmount = new Label();
    Label assessmentLabel = new Label("");
    //assessmentLabel.textProperty().bind(alcoholPercentageField.textProperty());

    //Conditional Binding Error

    assessmentLabel.textProperty().bind(Bindings.when((alcoholPercentageField.textProperty().lessThan(5))).then("Smart").otherwise("Bad"));

    ProgressBar alcoholBar = new ProgressBar();

    //Error is here
    alcoholBar.progressProperty().bind(alcoholPercentageField.textProperty() * 5);

Rest of the Code: some visual things

GridPane grid = new GridPane();
    grid.setAlignment(Pos.CENTER);
    grid.setHgap(10);
    grid.setVgap(10);
    grid.setPadding(new Insets(25, 25, 25, 25));
    var columnOneConstraints = new ColumnConstraints(150, 150, Double.MAX_VALUE);
    columnOneConstraints.setHalignment(HPos.RIGHT);
    var columnTwoConstrains = new ColumnConstraints(200,200, Double.MAX_VALUE);
    columnTwoConstrains.setHgrow(Priority.SOMETIMES);
    grid.getColumnConstraints().addAll(columnOneConstraints, columnTwoConstrains);
    alcoholBar.setMaxWidth(Double.MAX_VALUE);
    GridPane.setColumnSpan(alcoholBar, 2);
    GridPane.setHalignment(assessmentLabel, HPos.RIGHT);
    sugarAmountField.setDisable(true);

    grid.add(new Label("Water (l):"), 0, 0);
    grid.add(waterAmountField, 1, 0);

    grid.add(new Label("Vol-%:"), 0, 1);
    grid.add(alcoholPercentageField, 1, 1);

    grid.add(new Label("Sugar (kg):"),  0, 2);
    grid.add(sugarAmountField, 1, 2);

    grid.add(new Label("Lemons: "), 0, 3);
    grid.add(new Label("To taste"), 1, 3);

    grid.add(new Label("Mead total (kg):"), 0, 4);
    grid.add(meadTotalAmount, 1, 4);

    grid.add(alcoholBar, 0, 5);
    grid.add(assessmentLabel, 1, 6);
    // Okay, layout creation stops here

    // And of course set the scene and show the stage as always
    stage.setScene(new Scene(grid, 500, 400));
    stage.show();
}

}

Body:
You need to create some additional Property and Binding objects.

First, create properties for your TextField alcoholPercentageField. Then, you'll bind them using a StringConverter to convert the text entered into doubles.

Finally, use bindBidirectional to propagate and lastly bind it with progressBar by dividing 20 ( The progress bar will be "full" when alcoholic content is set to 20 %)

Code Will be like this-

    // Properties used for bindings
    DoubleProperty alcoholPercent = new SimpleDoubleProperty();

    //Setup the converters to get the input from the textfields
    StringConverter<? extends Number> converter = new DoubleStringConverter();

    Bindings.bindBidirectional(alcoholPercentageField.textProperty(), alcoholPercent, (StringConverter<Number>) converter);
    alcoholBar.progressProperty().bind(alcoholPercent.divide(20));

For Conditional Binding, check this Conditional Binding

Code would be like this-

    assessmentLabel.textProperty().bind(Bindings.when(alcoholPercent.lessThan(5)).then("Smart").otherwise("Bad"));
    assessmentLabel.textFillProperty().bind(Bindings.when(alcoholPercent.lessThan(5)).then(Color.GREEN).otherwise(Color.RED));


来源: stackexchange

问:
Looping through a nested list and summing all elements of each internal list in python
My problem is as follows: I have a list of lists named 'All_slips.' I would like to loop through each of the lists within the list and sum all of its elements, and then append these sums to a new list called 'Summed_list.' As such my desired output/solution would be a 'Summed_list' = [10,16,19]. A minimum reproducible program is provided below:

```<code>All_slips = [[1,2,3,4],[1,3,5,7],[1,2,7,9]]
Summed_list = []

for j in All_slips[j][] :
    counter = 0
    for i in All_slips[j][i] :
        counter += i
    Summed_list.insert(len(Summed_list),counter)

print (Summed_list)
</code>```

I am new to python and i obtain a syntax error on line 4: 'for j in All_slips[j][]:'. What is the proper syntax to achieve what I stated above - I could not find another post that described this problem. Thanks in advance for your help.

答:
```<code>summed_list = []
for sublist in All_slips:
    summed_list.append(sum(sublist))
</code>```

That's all. You can also employ a list comprehension.

```<code>summed_list = [sum(sublist) for sublist in All_slips]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My problem is as follows: I have a list of lists named 'All_slips.' I would like to loop through each of the lists within the list and sum all of its elements, and then append these sums to a new list called 'Summed_list.' As such my desired output/solution would be a 'Summed_list' = [10,16,19]. A minimum reproducible program is provided below:

All_slips = [[1,2,3,4],[1,3,5,7],[1,2,7,9]]
Summed_list = []

for j in All_slips[j][] :
    counter = 0
    for i in All_slips[j][i] :
        counter += i
    Summed_list.insert(len(Summed_list),counter)

print (Summed_list)

I am new to python and i obtain a syntax error on line 4: 'for j in All_slips[j][]:'. What is the proper syntax to achieve what I stated above - I could not find another post that described this problem. Thanks in advance for your help.

Body:
summed_list = []
for sublist in All_slips:
    summed_list.append(sum(sublist))

That's all. You can also employ a list comprehension.

summed_list = [sum(sublist) for sublist in All_slips]


问:
How to get output of a code script as a python exception message?
I have the code below. When i run it get an error :

*

```<code>STDOUT:
[librpc/rpc/dcerpc_connect.c:337:dcerpc_pipe_connect_ncacn_ip_tcp_recv()] failed NT status (c00000b5) in dcerpc_pipe_connect_ncacn_ip_tcp_recv
[librpc/rpc/dcerpc_connect.c:828:dcerpc_pipe_connect_b_recv()] failed NT status (c00000b5) in dcerpc_pipe_connect_b_recv
[wmi/wmic.c:196:main()] ERROR: Login to remote object.

  STDERR:
NTSTATUS: NT_STATUS_IO_TIMEOUT - NT_STATUS_IO_TIMEOUT
</code>```

I want to get this error message in my exception. And then, i use linux logger and save it into my db. How can i get this output as an exception message?

```<code>#!/usr/bin/python3
#!/usr/bin/python

import wmi_client_wrapper as wmi

try:
  wmic = wmi.WmiClientWrapper(username="Administrator",password="Abc",host="192.168.1.2",)
  output = wmic.query("SELECT * FROM Win32_Processor")
  print(output)
except:
  print("An exception occurred")
</code>```

答:
Use only one shebang.

You can catch the exception and it contains the message.

#!/usr/bin/python3

import wmi_client_wrapper as wmi

try:
  wmic = wmi.WmiClientWrapper(username="Administrator",password="Abc",host="192.168.1.2",)
  output = wmic.query("SELECT * FROM Win32_Processor")
  print(output)
except Exception as e:
  print("An exception occurred:", e)
```

Body:
I have the code below. When i run it get an error :

*

STDOUT:
[librpc/rpc/dcerpc_connect.c:337:dcerpc_pipe_connect_ncacn_ip_tcp_recv()] failed NT status (c00000b5) in dcerpc_pipe_connect_ncacn_ip_tcp_recv
[librpc/rpc/dcerpc_connect.c:828:dcerpc_pipe_connect_b_recv()] failed NT status (c00000b5) in dcerpc_pipe_connect_b_recv
[wmi/wmic.c:196:main()] ERROR: Login to remote object.

  STDERR:
NTSTATUS: NT_STATUS_IO_TIMEOUT - NT_STATUS_IO_TIMEOUT

I want to get this error message in my exception. And then, i use linux logger and save it into my db. How can i get this output as an exception message?

#!/usr/bin/python3
#!/usr/bin/python

import wmi_client_wrapper as wmi

try:
  wmic = wmi.WmiClientWrapper(username="Administrator",password="Abc",host="192.168.1.2",)
  output = wmic.query("SELECT * FROM Win32_Processor")
  print(output)
except:
  print("An exception occurred")


问:
Can't load develop for windows option in android studio with flutter
I have downloaded the newest sdk of flutter, (2.10) and connected it to android studio.
However, when creating a new flutter project android studio doesn't offer me the develop for windows option as a clickable option.
What do?</p>

答:
Hi there you need to add the config to flutter using the following command(s) from your terminal.

```<code>flutter config --enable-windows-desktop
flutter config --enable-linux-desktop
flutter config --enable-macos-desktop
</code>```

Once you have done this restart Android Studio.

https://docs.flutter.dev/desktop

Body:
Hi there you need to add the config to flutter using the following command(s) from your terminal.

flutter config --enable-windows-desktop
flutter config --enable-linux-desktop
flutter config --enable-macos-desktop

Once you have done this restart Android Studio.

https://docs.flutter.dev/desktop


问:
nhibernate manytomany query
I am new to nhibernate and trying to create a query on a database with manytomany links between items and categories.

I have a database with 3 tables : items, categories and a lookup table categoryitem like this:

categorys - primary key categoryId

items - primary key itemId

categoryItem - categoryId column and itemId column

I want a query returning items for a particular category and have tried this and think i am along the right lines:

```<code>public IList<Item> GetItemsForCategory(Category category)
        {

//detached criteria

DetachedCriteria itemIdsCriteria = DetachedCriteria.For(typeof(Category))
                .SetProjection(Projections.Distinct(Projections.Property("Item.Id")))
                .Add(Restrictions.Eq("Category.Id", category.Id));

                 criteria.Add(Subqueries.PropertyIn("Id", itemIdsCriteria));

            return criteria.List<Item>() as List<Item>;

}
</code>```

I only have business objects for category and item.
how do i create a repository method to find items for a particular category?

答:
I assume that your classes look like this:

```<code>class Item
{
  // id and stuff
  IList<Category> Categories { get; private set; }
}

class Category
{
  // id and stuff
}
</code>```

query (HQL)

```<code>session.CreateQuery(@"select i
from Item i
  inner join i.Categories c
where
  c = :category")
.SetEntity("category", category)
</code>```

Criteria

```<code>session
  .CreateCriteria(typeof(Item))
  .CreateCriteria("Categories", "c")
  .Add(Restrictions.Eq("c.Id", category.Id))
</code>```

ContentLicense: CC BY-SA 3.0

Title: nhibernate manytomany query

Body:
I am new to nhibernate and trying to create a query on a database with manytomany links between items and categories.

I have a database with 3 tables : items, categories and a lookup table categoryitem like this:

categorys - primary key categoryId

items - primary key itemId

categoryItem - categoryId column and itemId column

I want a query returning items for a particular category and have tried this and think i am along the right lines:

public IList<Item> GetItemsForCategory(Category category)
        {

//detached criteria

DetachedCriteria itemIdsCriteria = DetachedCriteria.For(typeof(Category))
                .SetProjection(Projections.Distinct(Projections.Property("Item.Id")))
                .Add(Restrictions.Eq("Category.Id", category.Id));

                 criteria.Add(Subqueries.PropertyIn("Id", itemIdsCriteria));

            return criteria.List<Item>() as List<Item>;

}

I only have business objects for category and item.
how do i create a repository method to find items for a particular category?

Body:
I assume that your classes look like this:

class Item
{
  // id and stuff
  IList<Category> Categories { get; private set; }
}

class Category
{
  // id and stuff
}

query (HQL)

session.CreateQuery(@"select i
from Item i
  inner join i.Categories c
where
  c = :category")
.SetEntity("category", category)

Criteria

session
  .CreateCriteria(typeof(Item))
  .CreateCriteria("Categories", "c")
  .Add(Restrictions.Eq("c.Id", category.Id))


问:
Same code does not work in venv despite installing dependencies from same requirements.txt
I am developing a web application and trying to migrate from Spyder to VS Code.
It was working with the default interpreter, so I created a new venv but when I start the server it does not work with the same code that was working without the venv.
Error description:

```<code>File "C:\Users\User\Desktop\Flask\app.py", line 77, in index
measurement_mx = rs.all()
AttributeError: 'ResultProxy' object has no attribute 'all'
</code>```

I installed exactly the same dependencies with pip install -r requirements.txt.

Can you help me what the solution could be, I could not find this problem unfortunately.

Relevant code snippet:

```<code>@app.route('/', methods=['POST', 'GET'])
def index():
    with engine.connect() as con:
        rs = con.execute(SQL_string)
        measurement_mx = rs.all() #this is the error line
        measurement_list = []
        for row in measurement_mx:
            measurement_list.append(row._data)
        measurement_list = transpose(measurement_list)
    return render_template('index.html', measurement_list=measurement_list )

</code>```

Thank you in advance!

答:
Welcome to StackOverflow!

The issue could be that your requirements.txt file may specify what packages to install, but not their exact version, so could you please:

paste the content of your requirements file?

check the packages versions between your two virtual environments?

Some thoughts:

requirements.txt file may constrain packages versions

the way to exactly reproduce an environment would be to install from a lock file, see for instance this discussion on pip.lock file)

Now, concerning your exact issue: ResultProxy is not an object from flask but from SQLAlchemy, which SQLAchemy v1.4 replaced:

class sqlalchemy.engine.Result(cursor_metadata)

Represent a set of database results.

New in version 1.4: The Result object provides a completely updated usage model and calling facade for SQLAlchemy Core and SQLAlchemy ORM. In Core, it forms the basis of the CursorResult object which replaces the previous ResultProxy interface. When using the ORM, a higher level object called ChunkedIteratorResult is normally used.

(emphasis mine)

Which means you can:

either fix SQLAlchemy version in your requirements.txt file,

or update your code to cope with current SQLAlchemy syntax.

Body:
I am developing a web application and trying to migrate from Spyder to VS Code.
It was working with the default interpreter, so I created a new venv but when I start the server it does not work with the same code that was working without the venv.
Error description:

File "C:\Users\User\Desktop\Flask\app.py", line 77, in index
measurement_mx = rs.all()
AttributeError: 'ResultProxy' object has no attribute 'all'

I installed exactly the same dependencies with pip install -r requirements.txt.

Can you help me what the solution could be, I could not find this problem unfortunately.

Relevant code snippet:

@app.route('/', methods=['POST', 'GET'])
def index():
    with engine.connect() as con:
        rs = con.execute(SQL_string)
        measurement_mx = rs.all() #this is the error line
        measurement_list = []
        for row in measurement_mx:
            measurement_list.append(row._data)
        measurement_list = transpose(measurement_list)
    return render_template('index.html', measurement_list=measurement_list )

Thank you in advance!


问:
Sass and node-sass not working with react app
I am trying to use Sass in my react app.

I am aware node-sass is now deprecated and only version 4 and below of node-sass work with node. However, even when I install node-sass@4.14.1 npm doesn't allow me to install saying there is an error tar@2.2.2

So i install normal sass and normal sass asks me to install node-sass ...

So i go around in circles like a headless chicken. Neither node-sass or normal sass working for me.

答: Yes normal sass is dart sass. I installed but had issues on a project. I updated tar to version 6 and it still wouldn't work. Then I did it on a new project and it worked.</p>


问:
How do I return the user to my TWA when pressing on a media notification?
I'm building an Android app that wraps my Progressive Web App as a Trusted Web Activity. (I'm following guidelines from Google's sample project.)

When the user plays audio in the app, a media notification appears on the device. I'm using the web Media Session API to customise the content of this notification.

If running the PWA in a normal web browser, once the notification appears, pressing it returns the user to the relevant browser tab. (If the phone is locked, the user is prompted to unlock.)

If the media notification is triggered from the TWA, pressing on it does nothing. (Other functionality such as play/pause works as expected.)

The Media Session API is fairly limited in scope. MediaSession action types do not include an action to focus the app.

```<code>navigator.mediaSession.setActionHandler('pause', () => {
            audioElement.pause();
            navigator.mediaSession.playbackState = 'paused';
        });

        navigator.mediaSession.setActionHandler('play', () => {
            audioElement.play();
            navigator.mediaSession.playbackState = 'playing';
        });

navigator.mediaSession.metadata = new MediaMetadata({
            title: 'App',
            artist: 'Name',
            artwork: [
                { src: '/android-chrome-192x192.png?v=47rE43RRzB', sizes: '192x192', type: 'image/png' },
                { src: '/android-chrome-512x512.png?v=47rE43RRzB', sizes: '512x512', type: 'image/png' },
            ],
        });
</code>```

When the media notification is trigged from the TWA, I expect the same functionality as when it is triggered from a web browser such as Chrome.

That includes the returning the user to the TWA (or prompting the user to unlock the device) when the notification is pressed anywhere except the play/pause control.

Everything else works except this aspect.

答: This was the default action in pwa and web, whenever someone clicks on notification media control, its takes to the website or pwa, but in twa its broken, its taking to the chrome browser but not focusing the app or website. I already raised ticket for the same on github</p>

Body:
I'm building an Android app that wraps my Progressive Web App as a Trusted Web Activity. (I'm following guidelines from Google's sample project.)

When the user plays audio in the app, a media notification appears on the device. I'm using the web Media Session API to customise the content of this notification.

If running the PWA in a normal web browser, once the notification appears, pressing it returns the user to the relevant browser tab. (If the phone is locked, the user is prompted to unlock.)

If the media notification is triggered from the TWA, pressing on it does nothing. (Other functionality such as play/pause works as expected.)

The Media Session API is fairly limited in scope. MediaSession action types do not include an action to focus the app.

navigator.mediaSession.setActionHandler('pause', () => {
            audioElement.pause();
            navigator.mediaSession.playbackState = 'paused';
        });

        navigator.mediaSession.setActionHandler('play', () => {
            audioElement.play();
            navigator.mediaSession.playbackState = 'playing';
        });

navigator.mediaSession.metadata = new MediaMetadata({
            title: 'App',
            artist: 'Name',
            artwork: [
                { src: '/android-chrome-192x192.png?v=47rE43RRzB', sizes: '192x192', type: 'image/png' },
                { src: '/android-chrome-512x512.png?v=47rE43RRzB', sizes: '512x512', type: 'image/png' },
            ],
        });

When the media notification is trigged from the TWA, I expect the same functionality as when it is triggered from a web browser such as Chrome.

That includes the returning the user to the TWA (or prompting the user to unlock the device) when the notification is pressed anywhere except the play/pause control.

Everything else works except this aspect.


问:
Dialog with transparent background in Android
How do I remove the black background from a dialog box in Android. The pic shows the problem.

```<code>final Dialog dialog = new Dialog(Screen1.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.themechanger);
</code>```

答:
In my case, nothing was working to apply a transparent background.

Only I used in my dialog onStart():

```<code>dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
</code>```

But it was not taking any effect. I checked styles.xml, nothing linked to my problem.

Finally, when I was checking how my dialog is gets created I found that the navigation component was creating the dialog whenever I request the dialog fragment.

There In XML of navgraph.xml, I defined the dialog fragment as a fragment so, It was created as a fragment instead of a dialog. Changing that fragment to dialog made everything fall in place.

BTW: You cannot modify from fragment to dialog in the GUI of the navigation editor. You should change by hand in code.

This might be one of a cause when some effect on a dialog is not reflected in runtime.

Body:
How do I remove the black background from a dialog box in Android. The pic shows the problem.

final Dialog dialog = new Dialog(Screen1.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.themechanger);

Body:
In my case, nothing was working to apply a transparent background.

Only I used in my dialog onStart():

dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

But it was not taking any effect. I checked styles.xml, nothing linked to my problem.

Finally, when I was checking how my dialog is gets created I found that the navigation component was creating the dialog whenever I request the dialog fragment.

There In XML of navgraph.xml, I defined the dialog fragment as a fragment so, It was created as a fragment instead of a dialog. Changing that fragment to dialog made everything fall in place.

BTW: You cannot modify from fragment to dialog in the GUI of the navigation editor. You should change by hand in code.

This might be one of a cause when some effect on a dialog is not reflected in runtime.


问:
How to declare a variable to get an output as a Sub parameter using Jacob
I am using Jacob to call VBA COM interfaces in software.
I need to call a Sub that has an output parameter, that is not of canonical type (int, String, etc.) but of some dedicated interface declared in .tlb that are brought with this software.
Here is the

```<code>Sub GetMaterialOnBody (Body iBody, Material oMaterial)
</code>```

So I tried many declarations and initializations for the output parameter material in the call, I get various errors and cannot seem to find the proper way to do.

```<code>Variant material = new Variant (null, false);
Dispatch.invoke(materialManager.getDispatch(), "GetMaterialOnBody", Dispatch.Method, new Object[] {hybridBody, material}, new int[1]);
</code>```

but got

```<code>com.jacob.com.ComFailException: A COM exception has been encountered:
At Invoke of: GetMaterialOnBody
Description: Type mismatch.
</code>```

Then I tried to call .getDispatch() on material

```<code>Variant material = new Variant (null, false);
Dispatch.invoke(materialManager.getDispatch(), "GetMaterialOnBody", Dispatch.Method, new Object[] {hybridBody, material.getDispatch()}, new int[1]);
</code>```

but got

```<code>java.lang.IllegalStateException: getDispatch() only legal on Variants of type VariantDispatch, not 0
</code>```

So I tried

```<code>Variant material = new Variant (null, false);
material.putNothing();
Dispatch.invoke(materialManager.getDispatch(), "GetMaterialOnBody", Dispatch.Method, new Object[] {hybridBody, material.getDispatch()}, new int[1]);
</code>```

but got

```<code>com.jacob.com.ComFailException: putObject failed
at com.jacob.com.Variant.putVariantDispatch(Native Method) ~[jacob-1.14.3.jar:na]
at com.jacob.com.Variant.putDispatch(Variant.java:1341) ~[jacob-1.14.3.jar:na]
</code>```

I tried different solutions, including using Ref, etc.
I am a bit lost on how exactly we have to initialize a variant/dispatch to pass as an output parameter in a Sub.

Does anyone have any clue on how to do that? The closes resources I found were handling String/Integer and not object.

This old question might be related (but obviously no answer): https://community.oracle.com/tech/developers/discussion/1548970/jacob-out-parameters-refs-in-jni

I have open a question on the jacob github
https://github.com/freemansoft/jacob-project/issues/23

Also I emailed the owner of the project on github and he said the project was dormant for some time already. As all the code is available I will take the time to compile and debug the native (C++) side in order to debug my case. I will update that question then.

答:
if that is output parameter, shouldn't it be 'ByRef' ?

```<code>Sub GetMaterialOnBody (Body iBody, ByRef Material oMaterial)
</code>```

In your case probably GetMaterialOnBody sub is expected to fill in internals of oMaterial object, not to set reference to it? Then just create an empty Material object  and pass to the sub

Body:
I am using Jacob to call VBA COM interfaces in software.
I need to call a Sub that has an output parameter, that is not of canonical type (int, String, etc.) but of some dedicated interface declared in .tlb that are brought with this software.
Here is the

Sub GetMaterialOnBody (Body iBody, Material oMaterial)

So I tried many declarations and initializations for the output parameter material in the call, I get various errors and cannot seem to find the proper way to do.

Variant material = new Variant (null, false);
Dispatch.invoke(materialManager.getDispatch(), "GetMaterialOnBody", Dispatch.Method, new Object[] {hybridBody, material}, new int[1]);

but got

com.jacob.com.ComFailException: A COM exception has been encountered:
At Invoke of: GetMaterialOnBody
Description: Type mismatch.

Then I tried to call .getDispatch() on material

Variant material = new Variant (null, false);
Dispatch.invoke(materialManager.getDispatch(), "GetMaterialOnBody", Dispatch.Method, new Object[] {hybridBody, material.getDispatch()}, new int[1]);

but got

java.lang.IllegalStateException: getDispatch() only legal on Variants of type VariantDispatch, not 0

So I tried

Variant material = new Variant (null, false);
material.putNothing();
Dispatch.invoke(materialManager.getDispatch(), "GetMaterialOnBody", Dispatch.Method, new Object[] {hybridBody, material.getDispatch()}, new int[1]);

but got

com.jacob.com.ComFailException: putObject failed
at com.jacob.com.Variant.putVariantDispatch(Native Method) ~[jacob-1.14.3.jar:na]
at com.jacob.com.Variant.putDispatch(Variant.java:1341) ~[jacob-1.14.3.jar:na]

I tried different solutions, including using Ref, etc.
I am a bit lost on how exactly we have to initialize a variant/dispatch to pass as an output parameter in a Sub.

Does anyone have any clue on how to do that? The closes resources I found were handling String/Integer and not object.

This old question might be related (but obviously no answer): https://community.oracle.com/tech/developers/discussion/1548970/jacob-out-parameters-refs-in-jni

I have open a question on the jacob github
https://github.com/freemansoft/jacob-project/issues/23

Also I emailed the owner of the project on github and he said the project was dormant for some time already. As all the code is available I will take the time to compile and debug the native (C++) side in order to debug my case. I will update that question then.

Body:
if that is output parameter, shouldn't it be 'ByRef' ?

Sub GetMaterialOnBody (Body iBody, ByRef Material oMaterial)

In your case probably GetMaterialOnBody sub is expected to fill in internals of oMaterial object, not to set reference to it? Then just create an empty Material object  and pass to the sub


问:
Pushing data in keys into a single array only values
Such data is coming from Laravel to Ajax. How do I push the values inside the keys into a single array without the keys.

```<code>$get_session = session()->get('cart.products');
return response($get_session);
</code>```

Data returned to Ajax.

```<code>data1: {
1234543: {id: 1, title: 'Product Title1', description: 'Product Descrition1'}
3453234: {id: 2, title: 'Product Title2', description: 'Product Descrition2'}
4564234: {id: 3, title: 'Product Title3', description: 'Product Descrition3'}
}

data2: {
4643345: {id: 4, title: 'Product Title4', description: 'Product Descrition4'}
8679673: {id: 5, title: 'Product Title5', description: 'Product Descrition5'}
2344565: {id: 6, title: 'Product Title6', description: 'Product Descrition6'}
}
</code>```

this is what i want to do

```<code>[
1234543: {id: 1, title: 'Product Title1', description: 'Product Descrition1'}
3453234: {id: 2, title: 'Product Title2', description: 'Product Descrition2'}
4564234: {id: 3, title: 'Product Title3', description: 'Product Descrition3'}
4643345: {id: 4, title: 'Product Title4', description: 'Product Descrition4'}
8679673: {id: 5, title: 'Product Title5', description: 'Product Descrition5'}
2344565: {id: 6, title: 'Product Title6', description: 'Product Descrition6'}
]
</code>```

How can I do it with Laravel or jquery? Thanks everyone.

答:
try this</p>
```<code>return response()->json([$get_session['data1']]);
</code>```

Body:
Such data is coming from Laravel to Ajax. How do I push the values inside the keys into a single array without the keys.

$get_session = session()->get('cart.products');
return response($get_session);

Data returned to Ajax.

data1: {
1234543: {id: 1, title: 'Product Title1', description: 'Product Descrition1'}
3453234: {id: 2, title: 'Product Title2', description: 'Product Descrition2'}
4564234: {id: 3, title: 'Product Title3', description: 'Product Descrition3'}
}

data2: {
4643345: {id: 4, title: 'Product Title4', description: 'Product Descrition4'}
8679673: {id: 5, title: 'Product Title5', description: 'Product Descrition5'}
2344565: {id: 6, title: 'Product Title6', description: 'Product Descrition6'}
}

this is what i want to do

[
1234543: {id: 1, title: 'Product Title1', description: 'Product Descrition1'}
3453234: {id: 2, title: 'Product Title2', description: 'Product Descrition2'}
4564234: {id: 3, title: 'Product Title3', description: 'Product Descrition3'}
4643345: {id: 4, title: 'Product Title4', description: 'Product Descrition4'}
8679673: {id: 5, title: 'Product Title5', description: 'Product Descrition5'}
2344565: {id: 6, title: 'Product Title6', description: 'Product Descrition6'}
]

How can I do it with Laravel or jquery? Thanks everyone.

Body:
try this

return response()->json([$get_session['data1']]);


问:
SpEL with @Query in spring data elasticsearch
im running a query on ES but the number of params are increasing (due to business reasons).

According to the doc in spring data elastic search you can use @Query with ordered parameters like ?0, ?1 and so on for parameters given in the signature of the method but this approach seems a bit uncomfortable

Is it possible to make a query like :#{#myParam.myPropOfMyParam} in other words use SpEL to access argument properties?

and not end with a method with a bunch of parameters like

@Query("match.... ?0,.. ?1, ?2")
Page<Doc> findBy(String arg1, String arg2, String arg3, Pageable pageable)
```
<p>and to be more like spring-data-jpa uses</p>
<pre class="lang-java prettyprint-override"><code>

public interface CompanyDocRepo extends ElasticsearchRepository<CompanyDoc, UUID> {

    @Query(value =
            "{\n" +
                    "  \"multi_match\": {\n" +
                    "    \"query\": \"#{#keyword['somevalue']}\",\n" +
                    "    \"fields\": [\n" +
                    "      \"name\",\n" +
                    "      \"description\",\n" +
                    "      \"city\",\n" +
                    "      \"department\",\n" +
                    "      \"sectors.sector.descriptionSector\",\n" +
                    "      \"sectors.sector.description\",\n" +
                    "      \"sectors.sector.name\",\n" +
                    "      \"interests.name\"\n" +
                    "    ]\n" +
                    "  }\n" +
                    "}\n")
    Page<CompanyDoc> findByKeyword(@Param("keyword") Map<String,String> keyword, Pageable pageable);

}

</code>```

or if there are other ways to make a query without leave a side spring data interfaces?

答: This is currently not possible. You might want to create an issue for this at https://github.com/spring-projects/spring-data-elasticsearch/issues</p>

Body:
im running a query on ES but the number of params are increasing (due to business reasons).

According to the doc in spring data elastic search you can use @Query with ordered parameters like ?0, ?1 and so on for parameters given in the signature of the method but this approach seems a bit uncomfortable

Is it possible to make a query like :#{#myParam.myPropOfMyParam} in other words use SpEL to access argument properties?

and not end with a method with a bunch of parameters like

@Query("match.... ?0,.. ?1, ?2")
Page<Doc> findBy(String arg1, String arg2, String arg3, Pageable pageable)

and to be more like spring-data-jpa uses

public interface CompanyDocRepo extends ElasticsearchRepository<CompanyDoc, UUID> {

    @Query(value =
            "{\n" +
                    "  \"multi_match\": {\n" +
                    "    \"query\": \"#{#keyword['somevalue']}\",\n" +
                    "    \"fields\": [\n" +
                    "      \"name\",\n" +
                    "      \"description\",\n" +
                    "      \"city\",\n" +
                    "      \"department\",\n" +
                    "      \"sectors.sector.descriptionSector\",\n" +
                    "      \"sectors.sector.description\",\n" +
                    "      \"sectors.sector.name\",\n" +
                    "      \"interests.name\"\n" +
                    "    ]\n" +
                    "  }\n" +
                    "}\n")
    Page<CompanyDoc> findByKeyword(@Param("keyword") Map<String,String> keyword, Pageable pageable);

}

or if there are other ways to make a query without leave a side spring data interfaces?


问:
Issue in opening a word document(.doc- Microsoft word 97- 2003 document) which is trying to connect with some network drive while opening
We are trying to convert a .doc file to .docx using c# code. Now, while opening the MS word application, the .doc file is taking more than 20 mins to open as it trying to connect to some network path to find some template.

Is there any way we can open that .doc file without letting it connect with network drive using Microsoft technologies.enter image description here

答:
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article.

Instead, you may consider using any third-party components designed for the server-side execution. The Open XML SDK can be considered if you deal with open XML documents only, see Welcome to the Open XML SDK 2.5 for Office for more information.


问:
How to iteratively apply a function (pdf_text()) across pdf files in a folder in R?
I have a large folder of pdf documents. I am trying to extract the text from each document iteratively (such that the only input is the folder pathway). It seems one can approach this with a imap/map and a for loop. Below is an attempt mapping a function onto a vector in which all files in the folder reside.

```<code>files <- list.files(path = "foldername", pattern = "*.pdf")

text_vector = c()

df <- files %>% map(function(x) {
    text <- pdf_text(x))
    text_vector <- append(text)})

</code>```

I welcome alternative methods to the same end of extracting the text across all files in a folder.

答:
Here's a more concise way of assigning your pdf text to a single vector using map_chr:

```<code>files <- list.files(path = "foldername", pattern = "*.pdf")

text_vector <- map_chr(files, ~ pdf_text(.))
</code>```

Body:
I have a large folder of pdf documents. I am trying to extract the text from each document iteratively (such that the only input is the folder pathway). It seems one can approach this with a imap/map and a for loop. Below is an attempt mapping a function onto a vector in which all files in the folder reside.

files <- list.files(path = "foldername", pattern = "*.pdf")

text_vector = c()

df <- files %>% map(function(x) {
    text <- pdf_text(x))
    text_vector <- append(text)})

I welcome alternative methods to the same end of extracting the text across all files in a folder.

Body:
Here's a more concise way of assigning your pdf text to a single vector using map_chr:

files <- list.files(path = "foldername", pattern = "*.pdf")

text_vector <- map_chr(files, ~ pdf_text(.))


问:
Change to custom background when a cell is highlighted
How can I change the background of a custom cell when a it is selected ?

Thanks, Niels

答:
You need to subclass UITableViewCell, and override the following methods:

```<code>- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated;
- (void)setSelected:(BOOL)selected animated:(BOOL)animated;
</code>```

You can change the cell's background image there.

The cell's selectionStyle property allows for some very basic customization, too.

Body:
You need to subclass UITableViewCell, and override the following methods:

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated;
- (void)setSelected:(BOOL)selected animated:(BOOL)animated;

You can change the cell's background image there.

The cell's selectionStyle property allows for some very basic customization, too.


问:
KeyError:'image_path' while executing Google Vision API using python
I am trying to extract text data from images using Google Cloud Vision API. My Initial starting point was here After Enabling Vision API and Creating service account,generating json file, I created a script by referring this example.

Here's my code

```<code>from google.cloud import vision
from google.cloud.vision_v1 import types
import os

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'generated_after_creating_sec_key.json'
image_path = 'images\\image_1.png'
vision_client = vision.ImageAnnotatorClient()
print(vision_client)
image = types.Image()
image.source.image_path = image_path

response = vision_client.text_detection(image=image)
for text in response.text_annotations:
    print(text.description)
</code>```

The only difference between the example shown in google page and my code is that the image uploaded in the example is on gcloud while mine happens to be on local storage.

Here's the complete stacktrace.

```<code><google.cloud.vision_v1.ImageAnnotatorClient object at 0x000001DF861D7970>
Traceback (most recent call last):
  File "text_detection.py", line 10, in <module>
    image.source.image_path = image_path
  File "C:\Users\user\ProjectFolder\ProjName\venv\lib\site-packages\proto\message.py", line 677, in __setattr__
    pb_type = self._meta.fields[key].pb_type
KeyError: 'image_path'
</code>```

What is the root cause of this error? Please help!

答:
According to the Google Cloud Vision docs, you should use
image.source.image_uri instead.

Body:
I am trying to extract text data from images using Google Cloud Vision API. My Initial starting point was here After Enabling Vision API and Creating service account,generating json file, I created a script by referring this example.

Here's my code

from google.cloud import vision
from google.cloud.vision_v1 import types
import os

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'generated_after_creating_sec_key.json'
image_path = 'images\\image_1.png'
vision_client = vision.ImageAnnotatorClient()
print(vision_client)
image = types.Image()
image.source.image_path = image_path

response = vision_client.text_detection(image=image)
for text in response.text_annotations:
    print(text.description)

The only difference between the example shown in google page and my code is that the image uploaded in the example is on gcloud while mine happens to be on local storage.

Here's the complete stacktrace.

<google.cloud.vision_v1.ImageAnnotatorClient object at 0x000001DF861D7970>
Traceback (most recent call last):
  File "text_detection.py", line 10, in <module>
    image.source.image_path = image_path
  File "C:\Users\user\ProjectFolder\ProjName\venv\lib\site-packages\proto\message.py", line 677, in __setattr__
    pb_type = self._meta.fields[key].pb_type
KeyError: 'image_path'

What is the root cause of this error? Please help!


问:
OpenCV BackgroundSubtractorMOG2 algorithm crashes when executed as part of my Swift UI app
I'm creating a Swift UI application to process images on a device and use the OpenCV library, specifically the BackgroundSubtractor algorithm. I was able to follow the OpenCV iOS guide and perform basic image operations, like take an image, convert to Matrix, make it gray or perform bitwise operations with OpenCV functions but when I try to use the BackgroundSubtractor.apply method, the app crashes with EXC_BAD_ACCESS error:

Thread 1: EXC_BAD_ACCESS (code=2, address=0x10455aa40)

Here is my code:

```<code>+ (UIImage *)toMyGreatImage:(UIImage *)source {

    Mat sourceMat = [OpenCVWrapper _matFrom:source];
    Mat result;

    BackgroundSubtractor *backSub = createBackgroundSubtractorMOG2();
    Mat mask;
    backSub->apply(sourceMat, mask); // crashes here
    return [OpenCVWrapper _imageFrom:mask];
}
</code>```

Just to compare, my other function works perfectly fine with the same source image:

```<code>+ (UIImage *)toGray:(UIImage *)source {
    return [OpenCVWrapper _imageFrom:[OpenCVWrapper _grayFrom:[OpenCVWrapper _matFrom:source]]];
}
</code>```

I have also tested the background subtractor code in python and it works as expected. What did I miss in my iOS setup?

答:
you need a "smart pointer" to capture your newly created BackgroundSubtractor instance (not a "raw" one), else it will self-destruct, and crash when you call a method on an invalid pointer:

```<code>cv::Ptr<BackgroundSubtractor> backSub = createBackgroundSubtractorMOG2();
</code>```

(note, that cv::Ptr is just an alias for std::shared_ptr nowadays)

(also, tutorial)

Body:
I'm creating a Swift UI application to process images on a device and use the OpenCV library, specifically the BackgroundSubtractor algorithm. I was able to follow the OpenCV iOS guide and perform basic image operations, like take an image, convert to Matrix, make it gray or perform bitwise operations with OpenCV functions but when I try to use the BackgroundSubtractor.apply method, the app crashes with EXC_BAD_ACCESS error:

Thread 1: EXC_BAD_ACCESS (code=2, address=0x10455aa40)

Here is my code:

+ (UIImage *)toMyGreatImage:(UIImage *)source {

    Mat sourceMat = [OpenCVWrapper _matFrom:source];
    Mat result;

    BackgroundSubtractor *backSub = createBackgroundSubtractorMOG2();
    Mat mask;
    backSub->apply(sourceMat, mask); // crashes here
    return [OpenCVWrapper _imageFrom:mask];
}

Just to compare, my other function works perfectly fine with the same source image:

+ (UIImage *)toGray:(UIImage *)source {
    return [OpenCVWrapper _imageFrom:[OpenCVWrapper _grayFrom:[OpenCVWrapper _matFrom:source]]];
}

I have also tested the background subtractor code in python and it works as expected. What did I miss in my iOS setup?

Body:
you need a "smart pointer" to capture your newly created BackgroundSubtractor instance (not a "raw" one), else it will self-destruct, and crash when you call a method on an invalid pointer:

cv::Ptr<BackgroundSubtractor> backSub = createBackgroundSubtractorMOG2();

(note, that cv::Ptr is just an alias for std::shared_ptr nowadays)

(also, tutorial)


问:
What is the difference between AWS Elastic MapReduce and AWS Kinesis Data Analytics?
I'm executing a Flink Job with this tools.
I think both can do exactly the same with the proper configuration. Does Kinesis Data Analytics do something that EMR can not do or vice versa?

Amazon Kinesis Data Analytics is the easiest way to analyze streaming data, gain actionable insights, and respond to your business and customer needs in real time.

Amazon Elastic Map Reduce provides a managed Hadoop framework that makes it easy, fast, and cost-effective to process vast amounts of data across dynamically scalable Amazon EC2 instances. You can also run other popular distributed frameworks such as Apache Spark, HBase, Presto, and Flink in EMR.

答: I will say one major difference between the two is that Kinesis does not provide a hosted Hadoop service unlike Elastic MapReduce (now EMR)</p>


问:
Asp.Net Core - appsettings.json Dictionary<string, Value> property mapping is not working in Azure environment
I have gone through a couple of similar questions in SO but both are not working as expected in the Azure environment.

I have the following appsettings.json configuration

```<code>  {
"Luis": {
    "SubDomain": {
        "AreaOne": {
            "AppIds": {
                "Us": "12345678",
                "India": "567890"
            },
            "APIKey": "xyz123",
            "HostName": "www.example.com"
        },
          "AreaTwo": {
            "AppIds": {
                "Us": "12345679",
                "India": "887890"
            },
            "APIKey": "xyz456",
            "HostName": "www.exampleareatwo.com"
        }
    }
}
}
</code>```

We are trying to bind it to the following object

```<code>public class Luis
{
    public Dictionary<string,SubDomain> SubDomainLuis { get; set; }
}
public class SubDomain
{

    public Dictionary<string, string> AppIds { get; set; }
    public string APIKey { get; set; }
    public string HostName { get; set; }
}
</code>```

We are getting the proper result in the local environment but after hosting the azure app service it shows as null value.

This is the constructor code:

The LuisConfig.SubDomainLuis is always returning a null value in the azure environment.

```<code>var LuisConfig = new Luis();
ConfigurationBinder.Bind(configuration.GetSection(nameof(Luis)), LuisConfig);
</code>```

Startup class:

```<code>var config = new Luis();
        Configuration.Bind("Luis", config);
        services.AddSingleton(config);
</code>```

The directory is always copying the settings file.

These are the questions I have already referred.

Dictionary issue

appsettings mapping

Configuration binding doesn't work

答:
As @ChristianHeld mentioned in the comment the issue is related to the environment appsettings.json. We forget to add environment variable details in the azure configuration. So that is the reason it always points to appsettings.json instead of appsettings.Local.json or appsettings.Dev.json.

ASPNETCORE_ENVIRONMENT is the environment key and value you can add as UAT, DEV, Prod, etc.

Azure AppService -> Configuration

Body:
I have gone through a couple of similar questions in SO but both are not working as expected in the Azure environment.

I have the following appsettings.json configuration

  {
"Luis": {
    "SubDomain": {
        "AreaOne": {
            "AppIds": {
                "Us": "12345678",
                "India": "567890"
            },
            "APIKey": "xyz123",
            "HostName": "www.example.com"
        },
          "AreaTwo": {
            "AppIds": {
                "Us": "12345679",
                "India": "887890"
            },
            "APIKey": "xyz456",
            "HostName": "www.exampleareatwo.com"
        }
    }
}
}

We are trying to bind it to the following object

public class Luis
{
    public Dictionary<string,SubDomain> SubDomainLuis { get; set; }
}
public class SubDomain
{

    public Dictionary<string, string> AppIds { get; set; }
    public string APIKey { get; set; }
    public string HostName { get; set; }
}

We are getting the proper result in the local environment but after hosting the azure app service it shows as null value.

This is the constructor code:

The LuisConfig.SubDomainLuis is always returning a null value in the azure environment.

var LuisConfig = new Luis();
ConfigurationBinder.Bind(configuration.GetSection(nameof(Luis)), LuisConfig);

Startup class:

var config = new Luis();
        Configuration.Bind("Luis", config);
        services.AddSingleton(config);

The directory is always copying the settings file.

These are the questions I have already referred.

Dictionary issue

appsettings mapping

Configuration binding doesn't work


问:
How do I port code for Borland C++ builder to Linux?
I have source code for a Windows DLL that is written in C++ and uses Visual Component Library. Now my task is to port that to Linux, but I don't have source code for the VCL itself, or any kind of documentation (and I have never worked with Borland C++; in my Windows days I used MFC).

This should not be all that hard, since my DLL does not have any GUI: as far as I can see, it mostly uses VCL for multithreading. I ran into a class that inherits from TThread and that is where I got stuck. I did some search on the Internet, but found no documentation for VCL so far. I would like to avoid buying a book on Borland C++ Builder, because I don't have time to wait for it to arrive from the Amazon. I cannot consider buying the package for Windows, because at work I only have a Linux box.

Any suggestions?

答: Many years ago, Borland released a version of their IDE for linux, marketed as Kylix. I'm not sure if it is still supported, but that might be the path of least resistance, for you.</p>

OwnerDisplayName: ajanicij

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: veefu


问:
Debugging JavaScript in IE7
I need to debug JavaScript in Internet Explorer 7.

Unfortunately, its default debugger doesn't provide me with much information. It tells me the page that the error showed up on (not the specific script) and gives me a line number.  I don't know if that is related to my problem.

It'd be nice if it could narrow down the error to a line number on a specific script (like Firebug can).

Is there an addon to debug JavaScript in IE7 like Firebug does in Firefox?

Thank you!

See also:

Does IE7 have a “developer mode” or plugin like Firefox/Chrome/Safari?

OwnerDisplayName: alex

Title: Debugging JavaScript in IE7

Body:
FireBug Lite:
http://getfirebug.com/firebuglite


问:
How to make my button only show the div on its group when I click it
Currently when I click the 1st button both hidden divs are showing. My goal is when I click the 1st button it only shows the hidden div on its group. And if I click the 2nd button it only shows the hidden div on its group.

Can anyone help me with how to achieve it?

$(document).ready(function () {
    $(".btn").on("click", function () {
        $(".hidden").addClass("active");
    });

    $(".closed").on("click", function (){
        $(".hidden").removeClass("active")
    })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn {
  background: blue;
  color: #ffffff;
  font-weight: 600;
  padding: 20px;
}

.hidden {
  width: 100px;
  height: 100px;
  background: yellow;
  display: none;
}

.hidden.active {
  display: block;
}</code>```

Show

Click to hide

Show

Click to hide

```

答:
Your code

```<code>$(".hidden").addClass("active");
</code>```

selects all .hidden elements (hence your issue).

Within the click event you need to use this to refer to the element being clicked and then use relative DOM navigation to find the element you do want.

In your case it's the next sibling, so .next() will suffice for show, but hide/close will need to find its parent .hidden

$(document).ready(function () {
    $(".show").on("click", function () {
        $(this).next().addClass("active");
    });

    $(".close").on("click", function (){
        $(this).closest(".hidden").removeClass("active")
    })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.show {
  background: blue;
  color: #ffffff;
  font-weight: 600;
  padding: 20px;
}

.hidden {
  width: 100px;
  height: 100px;
  background: yellow;
  display: none;
}

.hidden.active {
  display: block;
}

.close { background-color:#ccc; }</code>```

Show

Click to hide

Show

Click to hide

```

Body:
Currently when I click the 1st button both hidden divs are showing. My goal is when I click the 1st button it only shows the hidden div on its group. And if I click the 2nd button it only shows the hidden div on its group.

Can anyone help me with how to achieve it?

$(document).ready(function () {
    $(".btn").on("click", function () {
        $(".hidden").addClass("active");
    });

    $(".closed").on("click", function (){
        $(".hidden").removeClass("active")
    })
})

.btn {
  background: blue;
  color: #ffffff;
  font-weight: 600;
  padding: 20px;
}

.hidden {
  width: 100px;
  height: 100px;
  background: yellow;
  display: none;
}

.hidden.active {
  display: block;
}

Show

Click to hide

Show

Click to hide

Body:
Your code

$(".hidden").addClass("active");

selects all .hidden elements (hence your issue).

Within the click event you need to use this to refer to the element being clicked and then use relative DOM navigation to find the element you do want.

In your case it's the next sibling, so .next() will suffice for show, but hide/close will need to find its parent .hidden

$(document).ready(function () {
    $(".show").on("click", function () {
        $(this).next().addClass("active");
    });

    $(".close").on("click", function (){
        $(this).closest(".hidden").removeClass("active")
    })
})

.show {
  background: blue;
  color: #ffffff;
  font-weight: 600;
  padding: 20px;
}

.hidden {
  width: 100px;
  height: 100px;
  background: yellow;
  display: none;
}

.hidden.active {
  display: block;
}

.close { background-color:#ccc; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="con">
      <div class="show">Show</div>
      <div class="hidden">
        <div class="close">Click to hide</div>
      </div>
  </div>
</div>

<br>

<div class="container">
  <div class="con">
      <div class="show">Show</div>
      <div class="hidden">
        <div class="close">Click to hide</div>
      </div>
  </div>
</div>


问:
SQL CASE WHEN a is NULL
I have 3 columns all contain email addresses

```<code>email
alt_email
main_email
</code>```

I wanted to do case when email is null then alt_email
when alt_email is null then email and when both are null then main_email end as all_emails.

I am not getting the correct answer as the total count for all_emails is way 90% less than the total all customers.

TIA

答:
As @sparky mentioned, this is a job for COALESCE:

SELECT COALESCE(email, alt_email, main_email) AS all_email FROM ...
```

it gets the first non-null value from the columns mentioned, in that order.

See docs for SqlServer, but the same syntax applies to other DBMS's as well.

Title: SQL CASE WHEN a is NULL

Body:
I have 3 columns all contain email addresses

email
alt_email
main_email

I wanted to do case when email is null then alt_email
when alt_email is null then email and when both are null then main_email end as all_emails.

I am not getting the correct answer as the total count for all_emails is way 90% less than the total all customers.

TIA

Body:
As @sparky mentioned, this is a job for COALESCE:

SELECT COALESCE(email, alt_email, main_email) AS all_email FROM ...

it gets the first non-null value from the columns mentioned, in that order.

See docs for SqlServer, but the same syntax applies to other DBMS's as well.


问:
Problems with inverse_transform scaled predictions and y_test in multi-step, multi-variate LSTM
I have built a multi-step, multi-variate LSTM model to predict the target variable 5 days into the future with 5 days of look-back. The model runs smooth (even though it has to be further improved), but I cannot correctly invert the transformation applied, once I get my predictions.
I have seen on the web that there are many ways to pre-process and transform data. I decided to follow these steps:

Data fetching and cleaning

```<code>df = yfinance.download(['^GSPC', '^GDAXI', 'CL=F', 'AAPL'], period='5y', interval='1d')['Adj Close'];
df.dropna(axis=0, inplace=True)
df.describe()
</code>```

Data set table

Split the data set into train and test

```<code>size = int(len(df) * 0.80)
df_train = df.iloc[:size]
df_test = df.iloc[size:]
</code>```

Scaled train and test sets separately with MinMaxScaler()

```<code>scaler = MinMaxScaler(feature_range=(0,1))
df_train_sc = scaler.fit_transform(df_train)
df_test_sc = scaler.transform(df_test)
</code>```

Creation of 3D X and y time-series compatible with the LSTM model

I borrowed the following function from this article

```<code>def create_X_Y(ts: np.array, lag=1, n_ahead=1, target_index=0) -> tuple:
    """
    A method to create X and Y matrix from a time series array for the training of
    deep learning models
    """
    # Extracting the number of features that are passed from the array
    n_features = ts.shape[1]

    # Creating placeholder lists
    X, Y = [], []

    if len(ts) - lag <= 0:
        X.append(ts)
    else:
        for i in range(len(ts) - lag - n_ahead):
            Y.append(ts[(i + lag):(i + lag + n_ahead), target_index])
            X.append(ts[i:(i + lag)])

    X, Y = np.array(X), np.array(Y)

    # Reshaping the X array to an RNN input shape
    X = np.reshape(X, (X.shape[0], lag, n_features))

    return X, Y

#In this example let's assume that the first column (AAPL) is the target variable.

trainX,trainY = create_X_Y(df_train_sc,lag=5, n_ahead=5, target_index=0)
testX,testY = create_X_Y(df_test_sc,lag=5, n_ahead=5, target_index=0)
</code>```

Model creation

```<code>def build_model(optimizer):
    grid_model = Sequential()
    grid_model.add(LSTM(64,activation='tanh', return_sequences=True,input_shape=(trainX.shape[1],trainX.shape[2])))
    grid_model.add(LSTM(64,activation='tanh', return_sequences=True))
    grid_model.add(LSTM(64,activation='tanh'))
    grid_model.add(Dropout(0.2))
    grid_model.add(Dense(trainY.shape[1]))
    grid_model.compile(loss = 'mse',optimizer = optimizer)
    return grid_model

grid_model = KerasRegressor(build_fn=build_model,verbose=1,validation_data=(testX,testY))
parameters = {'batch_size' : [12,24],
              'epochs' : [8,30],
              'optimizer' : ['adam','Adadelta'] }
grid_search  = GridSearchCV(estimator = grid_model,
                            param_grid = parameters,
                            cv = 3)

grid_search = grid_search.fit(trainX,trainY)
grid_search.best_params_
my_model = grid_search.best_estimator_.model

</code>```

Get predictions

```<code>yhat = my_model.predict(testX)
</code>```

Invert transformation of predictions and actual values

Here my problems begin, because I am not sure which way to go. I have read many tutorials, but it seems that those authors prefer to apply MinMaxScaler() on the entire dataset before splitting the data into train and test. I do not agree on this, because, otherwise, training data will be incorrectly scaled with information we should not use (i.e. the test set). So, I followed my approach, but I am stucked here.

I found this possible solution on another post, but it's not working for me:

```<code># invert scaling for forecast
pred_scaler = MinMaxScaler(feature_range=(0, 1)).fit(df_test.values[:,0].reshape(-1, 1))
inv_yhat = pred_scaler.inverse_transform(yhat)
# invert scaling for actual
inv_y = pred_scaler.inverse_transform(testY)
</code>```

In fact, when I double check the last values of the target from my original data set they don't match with the inverted scaled version of the testY.

Can someone please help me on this? Many thanks in advance for your support!

答: Two things could be mentioned here. First, you cannot inverse transform something you did not see. This happens because you use two different scalers. The NN will predict values in the range of Scaler 1, where it is not said that this lies within the range of Scaler 2 (scaled on test data). Second, the best practice is to fit your scaler on the training set and use the same scaler (only transform) on the test data as well. Now, you should be able to reverse transform your test results. Third if scaling wents off, because the test set has completely different values - e.g. happens with live streaming data, it is up to you to deal with it, e.g. the min-max scaler will produce values > 1.0.</p>

Body:
I have built a multi-step, multi-variate LSTM model to predict the target variable 5 days into the future with 5 days of look-back. The model runs smooth (even though it has to be further improved), but I cannot correctly invert the transformation applied, once I get my predictions.
I have seen on the web that there are many ways to pre-process and transform data. I decided to follow these steps:

Data fetching and cleaning

df = yfinance.download(['^GSPC', '^GDAXI', 'CL=F', 'AAPL'], period='5y', interval='1d')['Adj Close'];
df.dropna(axis=0, inplace=True)
df.describe()

Data set table

Split the data set into train and test

size = int(len(df) * 0.80)
df_train = df.iloc[:size]
df_test = df.iloc[size:]

Scaled train and test sets separately with MinMaxScaler()

scaler = MinMaxScaler(feature_range=(0,1))
df_train_sc = scaler.fit_transform(df_train)
df_test_sc = scaler.transform(df_test)

Creation of 3D X and y time-series compatible with the LSTM model

I borrowed the following function from this article

def create_X_Y(ts: np.array, lag=1, n_ahead=1, target_index=0) -> tuple:
    """
    A method to create X and Y matrix from a time series array for the training of
    deep learning models
    """
    # Extracting the number of features that are passed from the array
    n_features = ts.shape[1]

    # Creating placeholder lists
    X, Y = [], []

    if len(ts) - lag <= 0:
        X.append(ts)
    else:
        for i in range(len(ts) - lag - n_ahead):
            Y.append(ts[(i + lag):(i + lag + n_ahead), target_index])
            X.append(ts[i:(i + lag)])

    X, Y = np.array(X), np.array(Y)

    # Reshaping the X array to an RNN input shape
    X = np.reshape(X, (X.shape[0], lag, n_features))

    return X, Y

#In this example let's assume that the first column (AAPL) is the target variable.

trainX,trainY = create_X_Y(df_train_sc,lag=5, n_ahead=5, target_index=0)
testX,testY = create_X_Y(df_test_sc,lag=5, n_ahead=5, target_index=0)

Model creation

def build_model(optimizer):
    grid_model = Sequential()
    grid_model.add(LSTM(64,activation='tanh', return_sequences=True,input_shape=(trainX.shape[1],trainX.shape[2])))
    grid_model.add(LSTM(64,activation='tanh', return_sequences=True))
    grid_model.add(LSTM(64,activation='tanh'))
    grid_model.add(Dropout(0.2))
    grid_model.add(Dense(trainY.shape[1]))
    grid_model.compile(loss = 'mse',optimizer = optimizer)
    return grid_model

grid_model = KerasRegressor(build_fn=build_model,verbose=1,validation_data=(testX,testY))
parameters = {'batch_size' : [12,24],
              'epochs' : [8,30],
              'optimizer' : ['adam','Adadelta'] }
grid_search  = GridSearchCV(estimator = grid_model,
                            param_grid = parameters,
                            cv = 3)

grid_search = grid_search.fit(trainX,trainY)
grid_search.best_params_
my_model = grid_search.best_estimator_.model

Get predictions

yhat = my_model.predict(testX)

Invert transformation of predictions and actual values

Here my problems begin, because I am not sure which way to go. I have read many tutorials, but it seems that those authors prefer to apply MinMaxScaler() on the entire dataset before splitting the data into train and test. I do not agree on this, because, otherwise, training data will be incorrectly scaled with information we should not use (i.e. the test set). So, I followed my approach, but I am stucked here.

I found this possible solution on another post, but it's not working for me:

# invert scaling for forecast
pred_scaler = MinMaxScaler(feature_range=(0, 1)).fit(df_test.values[:,0].reshape(-1, 1))
inv_yhat = pred_scaler.inverse_transform(yhat)
# invert scaling for actual
inv_y = pred_scaler.inverse_transform(testY)

In fact, when I double check the last values of the target from my original data set they don't match with the inverted scaled version of the testY.

Can someone please help me on this? Many thanks in advance for your support!


问:
Cant use BigInt in TS project regardless of es2020
I have simple TS project where this is my tsconfig.json

```<code>{
  "compilerOptions": {
    "target": "es2020",
    "lib": ["es2020"],
  }
}
</code>```

And I have one file, script.ts with following code inside

BigInt(2);

Unfortunatelly, when I execute tsc script.ts, I receive this error:
Cannot find name 'BigInt'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.

Why is that happening? Isn't my library set to correct version?

答:
BigInt is relativele new feature in Typescript, So in order to use it you have to specify target: esnext in your tsconfig.json

In your code you can create BigInt with n suffix, like this:

```<code>const bigIntNumber = 1n
</code>```

Body:
I have simple TS project where this is my tsconfig.json

{
  "compilerOptions": {
    "target": "es2020",
    "lib": ["es2020"],
  }
}

And I have one file, script.ts with following code inside

BigInt(2);

Unfortunatelly, when I execute tsc script.ts, I receive this error:
Cannot find name 'BigInt'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.

Why is that happening? Isn't my library set to correct version?

Body:
BigInt is relativele new feature in Typescript, So in order to use it you have to specify target: esnext in your tsconfig.json

In your code you can create BigInt with n suffix, like this:

const bigIntNumber = 1n


问:
The text contained in the tag is equal to a specific text and does not contain only the specific text
Here is my probleme:
I have two tags.

```<code><div class='twoLink'
<a class='link' <div> microsoft word </div></a>
<a class='link' <div> word </div></a>
</div>
</code>```

My goal is to click on the tag containing only the word "word" and not "microsoft word".

so I did this :

```<code>element = 'word'
linkWord = WebDriverWait(driver, timeout=5).until(EC.element_to_be_clickable(
         (By.XPATH,"//a[contains(@class, 'link')]/div[contains(text(), '"+ element +"')]")))
         driver.execute_script("arguments[0].click();", linkWord )
</code>```

But this method makes me click on the tag containing "word" and not equal to "word", so the tag I click is the first one and not the second one as I would have liked.

I would have to find a method to check an equality but I didn't find one.

What can I do about it please ?

答:
Here is a way you can assert if the word is present.
I noticed that you are using contains because there is a space preceding the word word in element DOM, but contains is fetching the microsoft word since it contains word in in it. So, the below approach works. I have added asserts in a conditional statement to be clear, but you can actually reduce it to one line assert x == 'word', "not the right word"

```<code>x = driver.find_element(By.XPATH, "//div[@class='twoLink']//following-sibling::a").text
print(x)
if x == 'word':
    print("True")
    assert True
else:
    print("False")
    assert False
</code>```

Output:

```<code>word
True

Process finished with exit code 0
</code>```

This also works:

```<code>//a[@class='link' and text()=' word ']
</code>```

One more strategy would be to use normalize. Please research on that if you would like to use it.
Here is the normalized-space locator. This would find you your element:

```<code>//a[normalize-space(text()='word')]
</code>```

Body:
Here is my probleme:
I have two tags.

<div class='twoLink'
<a class='link'
 microsoft word

<a class='link'
 word

My goal is to click on the tag containing only the word "word" and not "microsoft word".

so I did this :

element = 'word'
linkWord = WebDriverWait(driver, timeout=5).until(EC.element_to_be_clickable(
         (By.XPATH,"//a[contains(@class, 'link')]/div[contains(text(), '"+ element +"')]")))
         driver.execute_script("arguments[0].click();", linkWord )

But this method makes me click on the tag containing "word" and not equal to "word", so the tag I click is the first one and not the second one as I would have liked.

I would have to find a method to check an equality but I didn't find one.

What can I do about it please ?

Body:
Here is a way you can assert if the word is present.
I noticed that you are using contains because there is a space preceding the word word in element DOM, but contains is fetching the microsoft word since it contains word in in it. So, the below approach works. I have added asserts in a conditional statement to be clear, but you can actually reduce it to one line assert x == 'word', "not the right word"

x = driver.find_element(By.XPATH, "//div[@class='twoLink']//following-sibling::a").text
print(x)
if x == 'word':
    print("True")
    assert True
else:
    print("False")
    assert False

Output:

word
True

Process finished with exit code 0

This also works:

//a[@class='link' and text()=' word ']

One more strategy would be to use normalize. Please research on that if you would like to use it.
Here is the normalized-space locator. This would find you your element:

//a[normalize-space(text()='word')]


问:
Set view as percentage of width in portrait and percentage of height in landscape, in interface builder using autolayout
I am creating a launch screen that has a centered image. I want the image to be 0.7 of the width in portrait orientation and 0.7 of the height in landscape orientation, so the image is the same size in both orientations, but relative to device size. It would be smaller on iPhones and larger on iPads, while supporting both orientations on iPad.

I can do one of those constraints but not both. For example, if I make it 0.7 of the width in portrait then it looks good in portrait but then oversized in landscape, and vice versa.

How do I create such autolayout purely in interface builder? (I'm assuming launch screens must only use IB.)

答:
To make this work requires adding the equal widths constraints (per @Saumya Gautam's answer - welcome to SO!) but requires a little more tweaking to give the results.

Create equal width constraints to desired percentage (image to super view).

Update constraints: set one of them to "less than or equal" relation and set the other at a priority less than the first, e.g. 900.

Create aspect ratio (1:1) constraint on image.

Constraints:

Result, in portrait:

In landscape:


问:
PHP/PEAR - Retain trailing zeros when creating spreadsheets
I'm using the PHP PEAR package to generate excel spreadsheets. I have data of type double with trailing zeros that need to be retained. How can I preserve this data without having the Worksheet::writeNumber function truncate the zeros? I've tried changing the format string in the pack function but no luck yet.</p>

答:
Add a ' before it, e.g.

```<code>"'" . $number
</code>```

Body:
Add a ' before it, e.g.

"'" . $number


问:
Looping through a nested list and summing all elements of each internal list in python
My problem is as follows: I have a list of lists named 'All_slips.' I would like to loop through each of the lists within the list and sum all of its elements, and then append these sums to a new list called 'Summed_list.' As such my desired output/solution would be a 'Summed_list' = [10,16,19]. A minimum reproducible program is provided below:

```<code>All_slips = [[1,2,3,4],[1,3,5,7],[1,2,7,9]]
Summed_list = []

for j in All_slips[j][] :
    counter = 0
    for i in All_slips[j][i] :
        counter += i
    Summed_list.insert(len(Summed_list),counter)

print (Summed_list)
</code>```

I am new to python and i obtain a syntax error on line 4: 'for j in All_slips[j][]:'. What is the proper syntax to achieve what I stated above - I could not find another post that described this problem. Thanks in advance for your help.

答:
Take a look at the docs for an introduction to for loops.

A typical for loop in python has a for item in iterable type of syntax and you can access the members of the iterable using the variable item within the loop.

In your case, if you want to maintain the two loops-

```<code>for inner_list in All_slips:
    inner_sum = 0
    for element in inner_list:
        inner_sum = inner_sum + element
    summmed_list.append(inner_sum)
</code>```

Of course, you don't really have to maintain the two loops as sum is a built in function in python -

```<code>for inner_list in All_slips:
    inner_sum = sum(inner_list)
    summed_list.append(inner_sum)
</code>```

You can take it a step further by using a list comprehension -

```<code>summed_list = [sum(inner_list) for inner_list in All_slips]
</code>```

Body:
My problem is as follows: I have a list of lists named 'All_slips.' I would like to loop through each of the lists within the list and sum all of its elements, and then append these sums to a new list called 'Summed_list.' As such my desired output/solution would be a 'Summed_list' = [10,16,19]. A minimum reproducible program is provided below:

All_slips = [[1,2,3,4],[1,3,5,7],[1,2,7,9]]
Summed_list = []

for j in All_slips[j][] :
    counter = 0
    for i in All_slips[j][i] :
        counter += i
    Summed_list.insert(len(Summed_list),counter)

print (Summed_list)

I am new to python and i obtain a syntax error on line 4: 'for j in All_slips[j][]:'. What is the proper syntax to achieve what I stated above - I could not find another post that described this problem. Thanks in advance for your help.

Body:
Take a look at the docs for an introduction to for loops.

A typical for loop in python has a for item in iterable type of syntax and you can access the members of the iterable using the variable item within the loop.

In your case, if you want to maintain the two loops-

for inner_list in All_slips:
    inner_sum = 0
    for element in inner_list:
        inner_sum = inner_sum + element
    summmed_list.append(inner_sum)

Of course, you don't really have to maintain the two loops as sum is a built in function in python -

for inner_list in All_slips:
    inner_sum = sum(inner_list)
    summed_list.append(inner_sum)

You can take it a step further by using a list comprehension -

summed_list = [sum(inner_list) for inner_list in All_slips]


问:
Get Unique records from two hive tables
I have two hive table's. And both tables have one column column. There are some few rows which value is same in both tables
Now my requirement is join the two tables and exclude the common records from second table based on common column.

For example,
Table a:

Name.   City.    Country

Devid.    Hyd.    Ind

Steve.    London.  UK

John.     Bangalore.  Ind

Table B

Name.     City.     Country

Xxxx.     Xxxxx.      Ind

Yyyyy.      Yyyy.      US

Zzzz.      Zzzzz.      UK

Now my required output is

Name.   City.     Country

Devid.    Hyd.    Ind

Steve.    London.  UK

John.     Bangalore.  Ind

Yyyyy.      Yyyy.      US

I tried following logic

```<code>Select a.* From A a union
Select t.* From (
Select c.* From table B b right join table A c on
b.country = c.coubtry
Where b.id is null) t;
</code>```

This query not completing, keep on running. Any workaround needed?
Please help me out guys.

答:
Try the below code:</p>
```<code>SELECT * FROM A
UNION
SELECT * FROM B
WHERE Country NOT IN
(SELECT DISTINCT Country FROM A)
</code>```

Title: Get Unique records from two hive tables

Body:
I have two hive table's. And both tables have one column column. There are some few rows which value is same in both tables
Now my requirement is join the two tables and exclude the common records from second table based on common column.

For example,
Table a:

Name.   City.    Country

Devid.    Hyd.    Ind

Steve.    London.  UK

John.     Bangalore.  Ind

Table B

Name.     City.     Country

Xxxx.     Xxxxx.      Ind

Yyyyy.      Yyyy.      US

Zzzz.      Zzzzz.      UK

Now my required output is

Name.   City.     Country

Devid.    Hyd.    Ind

Steve.    London.  UK

John.     Bangalore.  Ind

Yyyyy.      Yyyy.      US

I tried following logic

Select a.* From A a union
Select t.* From (
Select c.* From table B b right join table A c on
b.country = c.coubtry
Where b.id is null) t;

This query not completing, keep on running. Any workaround needed?
Please help me out guys.

Body:
Try the below code:

SELECT * FROM A
UNION
SELECT * FROM B
WHERE Country NOT IN
(SELECT DISTINCT Country FROM A)


问:
How to use jQuery in global imported functions without jQuery.ready
my code in JS is getting very large right now and so I wanted to outsource sections to other files, for clarity.

In my main file I use

```<code>jQuery(document).ready(function ($) {

    $.getScript("/wp-content/plugins/file2.js",function(){
        console.log("loaded 2");
    });
    $.getScript("/wp-content/plugins/file3.js",function(){
        console.log("loaded 3");
    });
</code>```

This works.
In file 2 and 3 I use jQuery with functions like:

```<code>function getData(){
$.("#foo").on("click", function(){});
}
</code>```

So I am getting the error

```<code>$ is undefined
</code>```

because I do not declare $.
But if I wrap around the $.ready function I can't access the functions inside file 2 which are used by the other files.

How can I 'declare' the $ separately without loosing the global scope of the function. Or is there even a better way?
I only include in html:

```<code><script src="/wp-content/plugins/file1.js" type="text/javascript"></script>
</code>```

Thanks for helping!

答:
A copy of jQuery is assigned to $ by default.

It will only be undefined if you:

Overwrite it

Mask it

Call $.noConflict()

… so don't do any of those.

Body:
my code in JS is getting very large right now and so I wanted to outsource sections to other files, for clarity.

In my main file I use

jQuery(document).ready(function ($) {

    $.getScript("/wp-content/plugins/file2.js",function(){
        console.log("loaded 2");
    });
    $.getScript("/wp-content/plugins/file3.js",function(){
        console.log("loaded 3");
    });

This works.
In file 2 and 3 I use jQuery with functions like:

function getData(){
$.("#foo").on("click", function(){});
}

So I am getting the error

$ is undefined

because I do not declare $.
But if I wrap around the $.ready function I can't access the functions inside file 2 which are used by the other files.

How can I 'declare' the $ separately without loosing the global scope of the function. Or is there even a better way?
I only include in html:

Thanks for helping!


答:
Using ROW_NUMBER:

WITH cte AS (
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Date DESC) rn
    FROM yourTable t
)

SELECT Name, Rating, Date
FROM cte
WHERE rn = 1;
```

Title: Group by name and return row with most recent date

Body:
Suppose you have the following data:

+-------+--------+------------+
| Name  | Rating |    Date    |
+-------+--------+------------+
| Alice |    4.5 | 01/01/2022 |
| Alice |      4 | 14/12/2021 |
| Alice |      4 | 16/05/2021 |
| Mary  |      5 | 05/01/2022 |
| Mary  |      4 | 31/01/2022 |
| Bob   |    3.5 | 03/02/2022 |
+-------+--------+------------+

What would be the best way to group by name and return the row with the most recent date in Snowflake (ANSI SQL)? Expected output:

+-------+--------+------------+
| Name  | Rating |    Date    |
+-------+--------+------------+
| Alice |    4.5 | 01/01/2022 |
| Mary  |      4 | 31/01/2022 |
| Bob   |    3.5 | 03/02/2022 |
+-------+--------+------------+


问:
Accessing the Extended ASCII Character Set from 0xF000 to 0xF0FF using ncursesw in Raspbian Linux
I'm writing an application for the non-GUI text terminal in Raspian Linux in C++ using the ncursesw library.  I found out by accident that if you print anything with mvwaddch using A_ALTCHARSET (e.g. mvwaddch(stdscr, 1, 1, A_ALTCHARSET | 65);), then the entire Extended ASCII character set (0 - 255) becomes available to mvadd_wch starting from index 0xF000.

It doesn't look like 0xF000 is an official mapping for the UTF-8 locale that my terminal is configured for.  Somehow the ncursesw library triggers the system to load up these characters.

How is this done?  Is there a way to load up this character set without first writing junk data using A_ALTCHARSET?

It may be enough for my purposes to use a mvwaddch(stdscr, 0, 0, A_ALTCHARSET); to print a null character when the program initializes.  But I would still like to know what is happening behind the scenes here.

For reference, this is the character set I am referring to:

答:
ncurses has to support certain terminal descriptions which send "8-bit" codes for the alternate character set feature.  The Linux console happens to be a commonly-used case.  There's a few places in the source-code which you would find helpful to understand, e.g., in the update-code.

```<code>/*
 * If the character falls into any of these special cases, do
 * not force the result to a blank:
 *
 * a) it is printable (this works around a bug in wcwidth()).
 * b) use_legacy_coding() has been called to modify the treatment
 *    of codes 128-255.
 * c) the acs_map[] has been initialized to allow codes 0-31
 *    to be rendered.  This supports Linux console's "PC"
 *    characters.  Codes 128-255 are allowed though this is
 *    not checked.
 */
</code>```

The Linux console has no special knowledge of PC-character sets (the console_codes manual page mentions only UTF-8 and ISO-8859-1), but the showconsolefont command uses a Linux ioctl to allow it to print a table of 256 codes, which depending upon the font which has been loaded, will match some PC code-page (see my answer to Why does showconsolefont have different output in tmux?).

Body:
ncurses has to support certain terminal descriptions which send "8-bit" codes for the alternate character set feature.  The Linux console happens to be a commonly-used case.  There's a few places in the source-code which you would find helpful to understand, e.g., in the update-code.

/*
 * If the character falls into any of these special cases, do
 * not force the result to a blank:
 *
 * a) it is printable (this works around a bug in wcwidth()).
 * b) use_legacy_coding() has been called to modify the treatment
 *    of codes 128-255.
 * c) the acs_map[] has been initialized to allow codes 0-31
 *    to be rendered.  This supports Linux console's "PC"
 *    characters.  Codes 128-255 are allowed though this is
 *    not checked.
 */

The Linux console has no special knowledge of PC-character sets (the console_codes manual page mentions only UTF-8 and ISO-8859-1), but the showconsolefont command uses a Linux ioctl to allow it to print a table of 256 codes, which depending upon the font which has been loaded, will match some PC code-page (see my answer to Why does showconsolefont have different output in tmux?).


问:
What do people mean when they talk about serialization in Unity?
I hear people talking about serializing variables among things in their unity projects and quite don't understand it. I see them using

```<code>[SerializeField]
</code>```

and don't know why or what it does.

答:
Any values set in the Unity inspector for any public fields or private/protected fields that use the attribute [SerializeField] are saved with the current scene file.

If you open up a Unity.scene file you will find a hierarchy of data that matches the scene hierarchy along with lists of what script or component classes are attached to that game object and what the field values of those classes/components should be.

When loading a level in Unity, the scene file is deserialized meaning that a program walks the data structure creating game objects. It then creates component and script class instances attached to those components and initializes them with the serialized data in the scene file. After that you end up with a level more or less the same as it was when saved in the unity editor.

In addition to your own Monobehaviour scripts having this ability, all the default unity components work this way. Transform uses serialized Vector3s for position, rotation and scale. MeshFilter components serialize a reference to a mesh asset and the MeshRenderer component references Materials that are used by the GPU to draw the mesh etc etc.

In short, serialisation is a process by which computers transform data so that it can be written to a file (or sent across a network via a protocol stream) and then later transformed back into the original set of objects it was to begin with (or as close as matters).

Body:
I hear people talking about serializing variables among things in their unity projects and quite don't understand it. I see them using

[SerializeField]

and don't know why or what it does.


问:
React app fetch() response is empty although API endpoint returns data when sending a GET request from somewhere else
This is what my API call looks like:

```<code>export async function getTasks(): Promise<Task[]> {
  if (process.env.NODE_ENV === "test") {
    return new Promise<Task[]>((resolve) =>
      setTimeout(() => resolve(DefaultTasksArray), 1500)
    );
  } else {
    return (await fetch("/api/tasks").then(
      (response) => response.json
    )) as unknown as Task[];
  }
}
</code>```

GET action in the controller in the API

```<code>[HttpGet]
async public Task<IActionResult> Get()
{
    var tasks = await _service.GetAsync();

    return Ok(tasks);
}
</code>```

The service in the API

```<code>private readonly IMongoCollection<TaskObject> _tasksCollection;

public TaskService(IOptions<TaskManagerDbSettings> taskManagerDbSettings)
{
    var mongoClient = new MongoClient(taskManagerDbSettings.Value.ConnectionString);
    var mongoDatabase = mongoClient.GetDatabase(taskManagerDbSettings.Value.DatabaseName);
    _tasksCollection = mongoDatabase.GetCollection<TaskObject>(taskManagerDbSettings.Value.TasksCollectionName);
}

async public Task<List<TaskObject>> GetAsync() =>
    await _tasksCollection.Find(_ => true).ToListAsync();
</code>```

When I send a GET request in Postman or in a browser, I get a JSON object like:

```<code>[
  {
    *data*
  },
  {
    *data*
  },
  ...
]
</code>```

But the fetch() returns an empty response. What might be the cause?
I don't see any errors in the browser when I open the app.

upd:
I see the response in the Network tab in the browser, it has code 200 and all the data. But in the app itself the response is empty.

答:
The json property on the response from the fetch API is a function which you are mean to call.

```<code>(response) => response.json
</code>```

should be

```<code>(response) => response.json()
</code>```

Body:
This is what my API call looks like:

export async function getTasks(): Promise<Task[]> {
  if (process.env.NODE_ENV === "test") {
    return new Promise<Task[]>((resolve) =>
      setTimeout(() => resolve(DefaultTasksArray), 1500)
    );
  } else {
    return (await fetch("/api/tasks").then(
      (response) => response.json
    )) as unknown as Task[];
  }
}

GET action in the controller in the API

[HttpGet]
async public Task<IActionResult> Get()
{
    var tasks = await _service.GetAsync();

    return Ok(tasks);
}

The service in the API

private readonly IMongoCollection<TaskObject> _tasksCollection;

public TaskService(IOptions<TaskManagerDbSettings> taskManagerDbSettings)
{
    var mongoClient = new MongoClient(taskManagerDbSettings.Value.ConnectionString);
    var mongoDatabase = mongoClient.GetDatabase(taskManagerDbSettings.Value.DatabaseName);
    _tasksCollection = mongoDatabase.GetCollection<TaskObject>(taskManagerDbSettings.Value.TasksCollectionName);
}

async public Task<List<TaskObject>> GetAsync() =>
    await _tasksCollection.Find(_ => true).ToListAsync();

When I send a GET request in Postman or in a browser, I get a JSON object like:

[
  {
    *data*
  },
  {
    *data*
  },
  ...
]

But the fetch() returns an empty response. What might be the cause?
I don't see any errors in the browser when I open the app.

upd:
I see the response in the Network tab in the browser, it has code 200 and all the data. But in the app itself the response is empty.

Body:
The json property on the response from the fetch API is a function which you are mean to call.

(response) => response.json

should be

(response) => response.json()


问:
Why can't I create an array of automatic variables?
In C++0x (ohh! read C++11), we have automatic type inference. One thing which made me curious was that I can't create an array of auto variables. For example:

```<code>auto A[] = {1, 2, 3, 4}; // Error!
</code>```

Any ideas why this might have been disallowed?

答:
auto deduces every brace-enclosed initializer list to a std::initializer_list<T>. (See §7.1.6.4.6 including the example).
Unfortunately you cannot initialize an array or even std::array from a std::initializer_list once you have obtained it, but you can use a std::vector.

```<code>#include <vector>
#include <array>
#include <initializer_list>

int main()
{
  auto x = {1,2,3};
  std::array<int, 3> foo1 = x; // won't work for whatever reason
  std::vector<int> foo2 = x; // works as expected
  return 0;
}
</code>```

Of course this defeats the whole purpose of what you are trying to do.

I tried writing a work around called make_array but had to realize that this cannot ever work as the size of an initializer_list isn't part of its template arguments and so you only instantiate one make_array template for each T. This sucks.

```<code>template<typename T>
auto make_array(const std::initializer_list<T>& x)
     -> std::array<T, x.size()> { } // maaah
</code>```

Well, apparently you can go for the variadic-template hack mentioned here How do I initialize a member array with an initializer_list?

Body:
In C++0x (ohh! read C++11), we have automatic type inference. One thing which made me curious was that I can't create an array of auto variables. For example:

auto A[] = {1, 2, 3, 4}; // Error!

Any ideas why this might have been disallowed?

Body:
auto deduces every brace-enclosed initializer list to a std::initializer_list<T>. (See §7.1.6.4.6 including the example).
Unfortunately you cannot initialize an array or even std::array from a std::initializer_list once you have obtained it, but you can use a std::vector.

#include <vector>
#include <array>
#include <initializer_list>

int main()
{
  auto x = {1,2,3};
  std::array<int, 3> foo1 = x; // won't work for whatever reason
  std::vector<int> foo2 = x; // works as expected
  return 0;
}

Of course this defeats the whole purpose of what you are trying to do.

I tried writing a work around called make_array but had to realize that this cannot ever work as the size of an initializer_list isn't part of its template arguments and so you only instantiate one make_array template for each T. This sucks.

template<typename T>
auto make_array(const std::initializer_list<T>& x)
     -> std::array<T, x.size()> { } // maaah

Well, apparently you can go for the variadic-template hack mentioned here How do I initialize a member array with an initializer_list?