问:
How to generate OptionParser require arguments
The code below works, but I am manually raising argument errors for the required arguments using fetch, when I want to build the required arguments into the native OptionParser sytax for required parameters:

```<code># ocra script.rb -- --type=value
options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: example.rb [options]"

  opts.on("--type [TYPE]",String, [:gl, :time], "Select Exception file type (gl, time)") do |t|
    options["type"] = t
  end

  opts.on("--company [TYPE]",String, [:jaxon, :doric], "Select Company (jaxon, doric)") do |t|
    options["company"] = t
  end

end.parse!

opts = {}
opts['type'] = options.fetch('type') do
  raise ArgumentError,"no 'type' option specified  as a parameter (gl or time)"
end

opts['company'] = options.fetch('company') do
  raise ArgumentError,"no 'company' option specified  as a parameter (doric or jaxon)"
end
</code>```

答:
Faced with the same situation, I ended up with an option like this. If not all of my mandatory options are provided, output the user-friendly help text generated by OptionParser based on my defined options. Feels cleaner than throwing an exception and printing a stack trace to the user.

```<code>options = {}
option_parser = OptionParser.new do |opts|
  opts.banner = "Usage: #{$0} --data-dir DATA_DIR [options]"

  # A non-mandatory option
  opts.on('-p', '--port PORT', Integer, 'Override port number') do |v|
    options[:port] = v
  end

  # My mandatory option
  opts.on('-d', '--data-dir DATA_DIR', '[Mandatory] Specify the path to the data dir.') do |d|
    options[:data_dir] = d
  end
end

option_parser.parse!

if options[:data_dir].nil?
  puts option_parser.help
  exit 1
end
</code>```

Body:
The code below works, but I am manually raising argument errors for the required arguments using fetch, when I want to build the required arguments into the native OptionParser sytax for required parameters:

# ocra script.rb -- --type=value
options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: example.rb [options]"

  opts.on("--type [TYPE]",String, [:gl, :time], "Select Exception file type (gl, time)") do |t|
    options["type"] = t
  end

  opts.on("--company [TYPE]",String, [:jaxon, :doric], "Select Company (jaxon, doric)") do |t|
    options["company"] = t
  end

end.parse!

opts = {}
opts['type'] = options.fetch('type') do
  raise ArgumentError,"no 'type' option specified  as a parameter (gl or time)"
end

opts['company'] = options.fetch('company') do
  raise ArgumentError,"no 'company' option specified  as a parameter (doric or jaxon)"
end

Body:
Faced with the same situation, I ended up with an option like this. If not all of my mandatory options are provided, output the user-friendly help text generated by OptionParser based on my defined options. Feels cleaner than throwing an exception and printing a stack trace to the user.

options = {}
option_parser = OptionParser.new do |opts|
  opts.banner = "Usage: #{$0} --data-dir DATA_DIR [options]"

  # A non-mandatory option
  opts.on('-p', '--port PORT', Integer, 'Override port number') do |v|
    options[:port] = v
  end

  # My mandatory option
  opts.on('-d', '--data-dir DATA_DIR', '[Mandatory] Specify the path to the data dir.') do |d|
    options[:data_dir] = d
  end
end

option_parser.parse!

if options[:data_dir].nil?
  puts option_parser.help
  exit 1
end


来源: stackexchange

问:
Execute python script on user's computer (web application)
I'm developing a web application (PHP) where I need to get user's windows ID (to auth the user with LDAP). I've found that with python I can easily get it with the following script :

```<code>import os
print(os.getenv('username'))
</code>```

Which return 'firestname.lastname'

The problem is that, when I call it in my application with :

```<code>$python = "C:\Python3.8\python.exe";
$pyscript = "C:\wamp64\www\Dashboard\Content\python\simple.py";
$cmd = "$python $pyscript";
exec($cmd, $output);
</code>```

I got my computer name : 'MY-COMPUTER$'

I guess the script is running on my local webserver (wamp64). So my question is :

1) Can I execute this script on the user's computer ? And if I can, shall I have python installed on their PC ?
2) Do you have any other solution ?

Thanks !

答:
Do you need the username of a user authenticated to a windows domain controller of a company for SingleSignOn?

If so, you should look into ntlm authentication and GSSAPI.

Which webserver software are you using?

ContentLicense: CC BY-SA 4.0

Body:
I'm developing a web application (PHP) where I need to get user's windows ID (to auth the user with LDAP). I've found that with python I can easily get it with the following script :

import os
print(os.getenv('username'))

Which return 'firestname.lastname'

The problem is that, when I call it in my application with :

$python = "C:\Python3.8\python.exe";
$pyscript = "C:\wamp64\www\Dashboard\Content\python\simple.py";
$cmd = "$python $pyscript";
exec($cmd, $output);

I got my computer name : 'MY-COMPUTER$'

I guess the script is running on my local webserver (wamp64). So my question is :

1) Can I execute this script on the user's computer ? And if I can, shall I have python installed on their PC ?
2) Do you have any other solution ?

Thanks !


问:
Access violation closing the last ODBC connection (Win64 only)
I am trying to fix a problem without success related to multiple (two or more) ODBC connections with Microsoft Access driver on Windows x64 (both Windows 10 and 7). In particular, when the last connection is closed (the second one in the example), an access violation occurs (in Mso30win32client.dll module). This problem does not appear if the code is built for x86 (win32) target. I tried different compilers (C++ Builder 10.2, Visual C 2019, MingW64 4.5.3) without success. I am using the MS Access ODBC driveris installed with Office 2016 (all updates are installed) whose version is 16.00.4951.1000 (ACEODBC.DLL). If I change the data source making multiple connections with MySQL driver, the code works perfectly for both 32- and 64-bit targets.

Here is the code:

```<code>#include <windows.h>
#include <stdio.h>
#include <sql.h>
#include <sqlext.h>

#ifdef _WIN64
const TCHAR * DsnSource1 = TEXT("Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
                                "Dbq=..\\..\\Ligands.mdb");

const TCHAR * DsnSource2 = TEXT("Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
                                "Dbq=..\\..\\Pockets.mdb");
#else

const TCHAR * DsnSource1 = TEXT("Driver={Microsoft Access Driver (*.mdb)};"
                                "Dbq=..\\..\\Ligands.mdb");

const TCHAR * DsnSource2 = TEXT("Driver={Microsoft Access Driver (*.mdb)};"
                                "Dbq=..\\..\\Pockets.mdb");
#endif

int main(int argc, char *argv[])
{
  SQLRETURN         Res;
  HDBC              hDBC1, hDBC2;
  HENV              hEnv;

  Res = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv);
  Res = SQLSetEnvAttr(hEnv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);

  Res = SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &hDBC1);
  Res = SQLDriverConnect(hDBC1, NULL, (SQLTCHAR *)DsnSource1, SQL_NTS,
                         NULL, 0, NULL, SQL_DRIVER_NOPROMPT);

  Res = SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &hDBC2);
  Res = SQLDriverConnect(hDBC2, NULL, (SQLTCHAR *)DsnSource2, SQL_NTS,
                         NULL, 0, NULL, SQL_DRIVER_NOPROMPT);

  Res = SQLDisconnect(hDBC1);
  Res = SQLFreeHandle(SQL_HANDLE_DBC, hDBC1);

  Res = SQLDisconnect(hDBC2);  /* <- Access violation */
  Res = SQLFreeHandle(SQL_HANDLE_DBC, hDBC2);

  Res = SQLFreeHandle(SQL_HANDLE_ENV, hEnv);

 return 0;
}
</code>```

I don't understand were is the problem. Any suggestion is appreciated and thank you in advance.

答:
We are experiencing the same problem here using exactly this driver version and Win64.
It is working now when setting "Threads=1" within the connection string, i.e. the dsn will be: </p>

```<code>const TCHAR * DsnSource1 = TEXT("Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
                                "Dbq=..\\..\\Ligands.mdb;Threads=1");
</code>```

Body:
I am trying to fix a problem without success related to multiple (two or more) ODBC connections with Microsoft Access driver on Windows x64 (both Windows 10 and 7). In particular, when the last connection is closed (the second one in the example), an access violation occurs (in Mso30win32client.dll module). This problem does not appear if the code is built for x86 (win32) target. I tried different compilers (C++ Builder 10.2, Visual C 2019, MingW64 4.5.3) without success. I am using the MS Access ODBC driveris installed with Office 2016 (all updates are installed) whose version is 16.00.4951.1000 (ACEODBC.DLL). If I change the data source making multiple connections with MySQL driver, the code works perfectly for both 32- and 64-bit targets.

Here is the code:

#include <windows.h>
#include <stdio.h>
#include <sql.h>
#include <sqlext.h>

#ifdef _WIN64
const TCHAR * DsnSource1 = TEXT("Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
                                "Dbq=..\\..\\Ligands.mdb");

const TCHAR * DsnSource2 = TEXT("Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
                                "Dbq=..\\..\\Pockets.mdb");
#else

const TCHAR * DsnSource1 = TEXT("Driver={Microsoft Access Driver (*.mdb)};"
                                "Dbq=..\\..\\Ligands.mdb");

const TCHAR * DsnSource2 = TEXT("Driver={Microsoft Access Driver (*.mdb)};"
                                "Dbq=..\\..\\Pockets.mdb");
#endif

int main(int argc, char *argv[])
{
  SQLRETURN         Res;
  HDBC              hDBC1, hDBC2;
  HENV              hEnv;

  Res = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv);
  Res = SQLSetEnvAttr(hEnv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);

  Res = SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &hDBC1);
  Res = SQLDriverConnect(hDBC1, NULL, (SQLTCHAR *)DsnSource1, SQL_NTS,
                         NULL, 0, NULL, SQL_DRIVER_NOPROMPT);

  Res = SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &hDBC2);
  Res = SQLDriverConnect(hDBC2, NULL, (SQLTCHAR *)DsnSource2, SQL_NTS,
                         NULL, 0, NULL, SQL_DRIVER_NOPROMPT);

  Res = SQLDisconnect(hDBC1);
  Res = SQLFreeHandle(SQL_HANDLE_DBC, hDBC1);

  Res = SQLDisconnect(hDBC2);  /* <- Access violation */
  Res = SQLFreeHandle(SQL_HANDLE_DBC, hDBC2);

  Res = SQLFreeHandle(SQL_HANDLE_ENV, hEnv);

 return 0;
}

I don't understand were is the problem. Any suggestion is appreciated and thank you in advance.

Body:
We are experiencing the same problem here using exactly this driver version and Win64.
It is working now when setting "Threads=1" within the connection string, i.e. the dsn will be:

const TCHAR * DsnSource1 = TEXT("Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
                                "Dbq=..\\..\\Ligands.mdb;Threads=1");


问:
Software for browsing classes in a C/C++ project
I have seen that some developers have a graphical representation of all their classes in an image file which comes with their project. How can I myself create these graphics?

Basically they show what classes exist in a file and how these files relate to each other.

Thanks

答: It might be Doxygen, a software that generates documentation with dependancy graphs.</p>

ContentLicense: CC BY-SA 3.0


问:
ADFS 2016: Can not redirect to login page after logout
I'm using OpenID Connect and OAuth 2.0 to authenticate and authorize users directly against AD FS 4.0. I added my Angular + ASP.NET Core app as Native and Wep API application to Application groups, provided list of Redirect URI for Native app.

When users logout from application they don't redirect to login page. I checked answer ADFS 2016 oAuth not redirecting to login page after logout but in my case id_token_hint and post_Logout_Redirect_Uri are specified:

```<code>GET https://<server-name>/adfs/ls/?wa=wsignoutcleanup1.0&id_token_hint=<current_Id_Token>&post_logout_redirect_uri=http://localhost:5000 HTTP/1.1
</code>```

http:/localhost:5000 is added to list of Redirect URI in native aplication properties. Also no error or warning can be found in adfs logs with enabled tracing.

May I missed something when settings some adfs properties?

答:
As described here you could try using the Open ID Connect Frontchannel Logout mechanism which is supported by ADFS.

Go to https://server-name/adfs/.well-known/openid-configuration and check if frontend logout mechanism is supported by verifying that following entries are present:

```<code>end_session_endpoint: "https://<server-name>/adfs/oauth2/logout",
...
frontchannel_logout_supported: true,
frontchannel_logout_session_supported: true,
</code>```

Thereafter you add a logout uri to your server/native app in adfs by executing:

```<code> Set-AdfsServerApplication -TargetIdentifier <id> -LogoutUri http://localhost:5000/logout
</code>```

Finally you can logout by calling:

```<code>https://<server-name>/adfs/oauth2/logout?id_token_hint=XXXXX&post_logout_redirect_uri=http://localhost:5080
</code>```

Body:
I'm using OpenID Connect and OAuth 2.0 to authenticate and authorize users directly against AD FS 4.0. I added my Angular + ASP.NET Core app as Native and Wep API application to Application groups, provided list of Redirect URI for Native app.

When users logout from application they don't redirect to login page. I checked answer ADFS 2016 oAuth not redirecting to login page after logout but in my case id_token_hint and post_Logout_Redirect_Uri are specified:

GET https://<server-name>/adfs/ls/?wa=wsignoutcleanup1.0&id_token_hint=<current_Id_Token>&post_logout_redirect_uri=http://localhost:5000 HTTP/1.1

http:/localhost:5000 is added to list of Redirect URI in native aplication properties. Also no error or warning can be found in adfs logs with enabled tracing.

May I missed something when settings some adfs properties?

Body:
As described here you could try using the Open ID Connect Frontchannel Logout mechanism which is supported by ADFS.

Go to https://server-name/adfs/.well-known/openid-configuration and check if frontend logout mechanism is supported by verifying that following entries are present:

end_session_endpoint: "https://<server-name>/adfs/oauth2/logout",
...
frontchannel_logout_supported: true,
frontchannel_logout_session_supported: true,

Thereafter you add a logout uri to your server/native app in adfs by executing:

 Set-AdfsServerApplication -TargetIdentifier <id> -LogoutUri http://localhost:5000/logout

Finally you can logout by calling:

https://<server-name>/adfs/oauth2/logout?id_token_hint=XXXXX&post_logout_redirect_uri=http://localhost:5080


问:
Two API's both using JWT authentication. How to authenticate between the two?
I have two rest API's using a Bearer  auth header to a authenticate.

This works perfectly for the front-end of both systems, they call the auth endpoint, obtain a token and attach it for the duration of the session.

I need to be able to communicate between the two APIs, however, there's the problem that the JWT token expires after a set period of time, so I can't just store that token and attach it as a header.

What's the best way to manage authorization between the two systems?

答:
I eventually came up with a solution. I create an account for each system on it's counterpart. I then store these login details in a settings.local.json file, along with the API url for the other system.

When one system wants to communicate with the other, we first call the authenticate endpoint with the authentication details we have in the settings file, store the token returned and then call the endpoint we desire to call.

Essentially, exactly as you would as if it were the front-end.


问:
Why are graph DBs faster then RDBs for graph traversals?

I've read several articles (like this) stating that graph DBs are inherently faster then RDBs when running graph traversal algorithms because of the index-free adjacency. However, I'm having trouble understanding the theoretical justification for it. It seems to me that if you construct a hash-indexed adjacency tables, you should reach the same complexity performance.

For example, finding the friends of a person (given the person id) using an RDB with 2 tables: people and friendships

1) Locating the friends: O(m) - where m is the number of friends.

2) For each friend Id, locating in people: O(1)

Total: O(m)

In a graph DB, this should be the same, no?

答:
No, queries are executed differently in RDBMS than in a graph database.

The example you gave is finding a friend of a given person, which is a one-hop query (in graph terms) and is quite easy in both kinds of databases.

However, if you want to perform an n-hop query (n > 3), in RDBMS you can use subquery or join and the performance would be dependent on your optimizer.

Below is an example:

Assume that we have tables class with fields id (PRIMARY KEY) and name, student with fields id (PRIMARY KEY), name and class_id.

In order to find the class name whose id is 2, and the corresponding students, we need to join between two tables table class and student

```<code>SELECT c.name as c_name, s.name as s_name
  FROM class as c
    LEFT JOIN student as s
      ON c.id = s.class_id
        WHERE c.id = 2;
</code>```

Explain the query:
  Query explained in table

The whole student table will be scanned in order to find class_id=2.

Of course we can create an index on student class_id column.

table of the index

It reads the student_class index to get the pointers to the physical
  rows and then read the records as it is a non clustered index.

In graph database, data are modeled as nodes and connections.

graph database model

To find the class name whose id is 2, and the corresponding students,
   just get the class node and traverse in backwards direction on select
   connections. And avoid the join index lookup performance problem.

If you want to find the shortest path and all possible paths between two points (but you don't know how many hops there are for the query), then there would be much trouble using RDBMS. The query would be quite long. LDBC has some nice cases using SQL, GQL (Cypher) and SparQL respectively. Unfortunately I haven't found the runtime differences among the different languages.

It is difficult to do graph computing like LPA (Label Propagation Algorithm) and Page Rank algorithm with RDBMS. But would be much easier to do so in some(most) Graph DBMS

Body:
No, queries are executed differently in RDBMS than in a graph database.

The example you gave is finding a friend of a given person, which is a one-hop query (in graph terms) and is quite easy in both kinds of databases.

However, if you want to perform an n-hop query (n > 3), in RDBMS you can use subquery or join and the performance would be dependent on your optimizer.

Below is an example:

Assume that we have tables class with fields id (PRIMARY KEY) and name, student with fields id (PRIMARY KEY), name and class_id.

In order to find the class name whose id is 2, and the corresponding students, we need to join between two tables table class and student

SELECT c.name as c_name, s.name as s_name
  FROM class as c
    LEFT JOIN student as s
      ON c.id = s.class_id
        WHERE c.id = 2;

Explain the query:
  Query explained in table

The whole student table will be scanned in order to find class_id=2.

Of course we can create an index on student class_id column.

table of the index

It reads the student_class index to get the pointers to the physical
  rows and then read the records as it is a non clustered index.

In graph database, data are modeled as nodes and connections.

graph database model

To find the class name whose id is 2, and the corresponding students,
   just get the class node and traverse in backwards direction on select
   connections. And avoid the join index lookup performance problem.

If you want to find the shortest path and all possible paths between two points (but you don't know how many hops there are for the query), then there would be much trouble using RDBMS. The query would be quite long. LDBC has some nice cases using SQL, GQL (Cypher) and SparQL respectively. Unfortunately I haven't found the runtime differences among the different languages.

It is difficult to do graph computing like LPA (Label Propagation Algorithm) and Page Rank algorithm with RDBMS. But would be much easier to do so in some(most) Graph DBMS


问:
Task :app:transformNativeLibsWithMergeJniLibsForDebug FAILED
I am working with react native and every time I build a new project it seems to work on my device , but whenever I try to restart it It is giving me 1 or more errors

I have tried looking for solutions on github but none of them are clear I will post the entire error message here.

react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 855 file(s) to forward-jetify. Using 4 workers...
info Starting JS server...
info Installing the app...
Starting a Gradle Daemon (subsequent builds will be faster)

Task :app:transformNativeLibsWithMergeJniLibsForDebug FAILED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.4.1/userguide/command_line_interface.html#sec:command_line_warnings
24 actionable tasks: 2 executed, 22 up-to-date

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:transformNativeLibsWithMergeJniLibsForDebug'.

Could not read path 'C:\REACT_NATIVE\AwesomeProject2\android\app\build\intermediates\transforms\mergeJniLibs\debug\0\lib\arm64-v8a'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 57s

error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:transformNativeLibsWithMergeJniLibsForDebug'.

Could not read path 'C:\REACT_NATIVE\AwesomeProject2\android\app\build\intermediates\transforms\mergeJniLibs\debug\0\lib\arm64-v8a'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 57s

```<code>at checkExecSyncError (child_process.js:623:11)
at execFileSync (child_process.js:641:15)
at runOnAllDevices (C:\REACT_NATIVE\AwesomeProject2\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:75:39)
at buildAndRun (C:\REACT_NATIVE\AwesomeProject2\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:169:41)
at C:\REACT_NATIVE\AwesomeProject2\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:135:12
at processTicksAndRejections (internal/process/task_queues.js:85:5)
at async Command.handleAction (C:\REACT_NATIVE\AwesomeProject2\node_modules\react-native\node_modules\@react-native-community\cli\build\cliEntry.js:160:7)
</code>```

答:
Clean project working for me

A react-native Project is about one XCode Project and one Android Project. (pure js code no need to do clean)

So what are you need would be

Clean XCode Project with

```<code>$ cd ios
$ xcodebuild clean
$ cd .. && react-native run-ios
</code>```

And then clean Android Project with

```<code>$ cd android
$ ./gradlew clean
$ cd .. && react-native run-android
</code>```

You can simply write a batch file for it.

Body:
I am working with react native and every time I build a new project it seems to work on my device , but whenever I try to restart it It is giving me 1 or more errors

I have tried looking for solutions on github but none of them are clear I will post the entire error message here.

react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 855 file(s) to forward-jetify. Using 4 workers...
info Starting JS server...
info Installing the app...
Starting a Gradle Daemon (subsequent builds will be faster)

Task :app:transformNativeLibsWithMergeJniLibsForDebug FAILED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.4.1/userguide/command_line_interface.html#sec:command_line_warnings
24 actionable tasks: 2 executed, 22 up-to-date

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:transformNativeLibsWithMergeJniLibsForDebug'.

Could not read path 'C:\REACT_NATIVE\AwesomeProject2\android\app\build\intermediates\transforms\mergeJniLibs\debug\0\lib\arm64-v8a'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 57s

error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:transformNativeLibsWithMergeJniLibsForDebug'.

Could not read path 'C:\REACT_NATIVE\AwesomeProject2\android\app\build\intermediates\transforms\mergeJniLibs\debug\0\lib\arm64-v8a'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 57s

at checkExecSyncError (child_process.js:623:11)
at execFileSync (child_process.js:641:15)
at runOnAllDevices (C:\REACT_NATIVE\AwesomeProject2\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:75:39)
at buildAndRun (C:\REACT_NATIVE\AwesomeProject2\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:169:41)
at C:\REACT_NATIVE\AwesomeProject2\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:135:12
at processTicksAndRejections (internal/process/task_queues.js:85:5)
at async Command.handleAction (C:\REACT_NATIVE\AwesomeProject2\node_modules\react-native\node_modules\@react-native-community\cli\build\cliEntry.js:160:7)

Body:
Clean project working for me

A react-native Project is about one XCode Project and one Android Project. (pure js code no need to do clean)

So what are you need would be

Clean XCode Project with

$ cd ios
$ xcodebuild clean
$ cd .. && react-native run-ios

And then clean Android Project with

$ cd android
$ ./gradlew clean
$ cd .. && react-native run-android

You can simply write a batch file for it.


问:
How Can I implement in OOP?
```<code>// A is the core class

class A{
   public $lang;
   function sayhi($name){echo "Hi".$name;}
   function speak(){echo "Can Speak".$this->lang;}
}

class B {

  function TODO(){
       echo  " Go to work ";
  }
}
</code>```

I DID for now like this:

```<code>class C extends B {

    function TODO(){
    //more implement here

    $a = new A();// here I created an instance.
        // do  any  actions for A
    $a->sayhi("Newbie");
    }

}
</code>```

BUT I  want to class B have all the construct  of class A?

so when I DO on  class C (just something like this)

```<code>class C extends B {

    function TODO(){
    //more implement here
     // I wish I can
       sayhi("Newbie");
    }

}
</code>```

Anybody could tell me how can implement this?

答:
don't know php that good, but are you searching for this...

```<code>class A {
}

class B extends A{
}

class C extends B{
}
</code>```

or did i miss something?

Title: How Can I implement in OOP?

Body:
// A is the core class

class A{
   public $lang;
   function sayhi($name){echo "Hi".$name;}
   function speak(){echo "Can Speak".$this->lang;}
}

class B {

  function TODO(){
       echo  " Go to work ";
  }
}

I DID for now like this:

class C extends B {

    function TODO(){
    //more implement here

    $a = new A();// here I created an instance.
        // do  any  actions for A
    $a->sayhi("Newbie");
    }

}

BUT I  want to class B have all the construct  of class A?

so when I DO on  class C (just something like this)

class C extends B {

    function TODO(){
    //more implement here
     // I wish I can
       sayhi("Newbie");
    }

}

Anybody could tell me how can implement this?

Body:
don't know php that good, but are you searching for this...

class A {
}

class B extends A{
}

class C extends B{
}

or did i miss something?


问:
SQL join in Laravel, how to?
Help me please, with JOINS, learning SQL and joins are painful :(

I have table: categories with column name: Name, ID

I have table: sub_categories with column name: ID

I have table: provider_services with column name: category_id & subcategory_id

When I do in laravel view blade {{$provider->providerServices()->where("status",1)->count()}}

I will receive: 2

It means, that provider, has 2 services with category_id 2, 3 and subcategory_id 4,8

Question:
How can I join this data to table categories and grab the category Name using cat_id & subcat_id?

Category_id 2 is - Painting

Category_id 3 is - Plumbing

SubCategory_id is - Aqua

SubCategory_id 8 is - Test

So, as A result I need to have something: Painting and Aqua, Plumbing and Test

Thank you very much!

答:
Inner Join Clause

The query builder may also be used to write join statements. To perform a basic "inner join", you may use the join method on a query builder instance. The first argument passed to the join method is the name of the table you need to join to, while the remaining arguments specify the column constraints for the join. You can even join to multiple tables in a single query:

```<code>$users = DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->select('users.*', 'contacts.phone', 'orders.price')
            ->get();
</code>```

Source: https://laravel.com/docs/5.8/queries#joins

The above example can easily be changed to work for you.
The join function for is made the following:

```<code>->join('table', 'column1', '=', 'column2')
</code>```

Title: SQL join in Laravel, how to?

Body:
Inner Join Clause

The query builder may also be used to write join statements. To perform a basic "inner join", you may use the join method on a query builder instance. The first argument passed to the join method is the name of the table you need to join to, while the remaining arguments specify the column constraints for the join. You can even join to multiple tables in a single query:

$users = DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->select('users.*', 'contacts.phone', 'orders.price')
            ->get();

Source: https://laravel.com/docs/5.8/queries#joins

The above example can easily be changed to work for you.
The join function for is made the following:

->join('table', 'column1', '=', 'column2')


问:
Anyway to split files to diff folder?
I have over 100,000 files in a folder name: A, all are picture files either jpeg, or jpg extension with random file names, like abc.jpg, xcc.jpg, bbb.jpeg

Is there any way to move the all the 100k files to folder in the following structure:

Any order of the images don't matter, just need 5000 pic in each folder under B

```<code>Folder B -> Folder 1 (5000 of the jpg files)
            Folder 2 (next 5000 of the jpg files)
            .
            Folder n (last 5000 remaining of files)
</code>```

Batch files or powershell doesn't matter as long run in windows or cmd, I just can't think of any way to spilt files to 5000 per folder.

Any help is appreciated... Thanks

答:
One simple approach for your scenario would be to use Select-Object to create batches of files and a counter variable $i to create folder names corresponding to the batch number.

```<code>$i = 1
while (($files = Get-ChildItem *.jpg, *.jpeg).Count -gt 0)
{
    $folderPath = ".\Folder $i"
    New-Item -Type Directory $folderPath
    $files | Select-Object -First 5000 | Move-Item -Destination $folderPath
    $i += 1
}
</code>```

See the question, that @Matthew posted in the comments for several alternative ways to tackle this type of problem.

Note: I am assuming, that you do not already have subfolders with the name "Folder 1", "Folder 2", and so on...

Title: Anyway to split files to diff folder?

Body:
I have over 100,000 files in a folder name: A, all are picture files either jpeg, or jpg extension with random file names, like abc.jpg, xcc.jpg, bbb.jpeg

Is there any way to move the all the 100k files to folder in the following structure:

Any order of the images don't matter, just need 5000 pic in each folder under B

Folder B -> Folder 1 (5000 of the jpg files)
            Folder 2 (next 5000 of the jpg files)
            .
            Folder n (last 5000 remaining of files)

Batch files or powershell doesn't matter as long run in windows or cmd, I just can't think of any way to spilt files to 5000 per folder.

Any help is appreciated... Thanks

Body:
One simple approach for your scenario would be to use Select-Object to create batches of files and a counter variable $i to create folder names corresponding to the batch number.

$i = 1
while (($files = Get-ChildItem *.jpg, *.jpeg).Count -gt 0)
{
    $folderPath = ".\Folder $i"
    New-Item -Type Directory $folderPath
    $files | Select-Object -First 5000 | Move-Item -Destination $folderPath
    $i += 1
}

See the question, that @Matthew posted in the comments for several alternative ways to tackle this type of problem.

Note: I am assuming, that you do not already have subfolders with the name "Folder 1", "Folder 2", and so on...


问:
Trimmed mean in Python
I'm trying to calculate the trimmed mean of a list with a manual function in python but I don't know how I have to adjust my formula.

I want that you can give the function an alpha parameter, e.g. 0.1 (to cut 10% outliers).

My code so far (0.1 is in this case the alpha value):

```<code>lst[5,30,29,15,25,5,13,28,24,29] #for alpha=0.1 the list need to be adjusted --> lst[5,13,15,24,25,28,29,29]

def tmean(lst):
  s= sorted(lst)
  k= 0.1*len(lst)
  trimmed_mean= (1/(len(lst)-(2*k)))*sum(len(lst)-k)
  print(trimmed_mean)
</code>```

The trimmed_mean with alpha= 0.1 should be 21, but I don't know how I need to adjust my code.

Thanks.

答:
```<code>lst = [5,30,29,15,25,5,13,28,24,29]

def tmean(lst, alpha):
    s = sorted(lst)
    # Caclculate number of elements to trim from the beginning and end
    a = round(alpha * len(lst)
    # Check if alpha can actually remove any elements and if not return straight mean
    if a == 0:
        return sum(lst) / len(lst)
    # Remove trimmed elements from the list
    trimmed_list = s[a:-a]
    # Check if there is a list left after trimming
    if len(trimmed_list) == 0:
        return
    # Calculate average on the new list
    trimmed_ave = sum(trimmed_list)/len(trimmed_list)
    print(trimmed_ave)
    return trimmed_ave

tmean(lst, 0.1)
</code>```

Obviously some of the above stages could be combined for more concise code, but have split into separate lines for ease of explanation

Title: Trimmed mean in Python

Body:
I'm trying to calculate the trimmed mean of a list with a manual function in python but I don't know how I have to adjust my formula.

I want that you can give the function an alpha parameter, e.g. 0.1 (to cut 10% outliers).

My code so far (0.1 is in this case the alpha value):

lst[5,30,29,15,25,5,13,28,24,29] #for alpha=0.1 the list need to be adjusted --> lst[5,13,15,24,25,28,29,29]

def tmean(lst):
  s= sorted(lst)
  k= 0.1*len(lst)
  trimmed_mean= (1/(len(lst)-(2*k)))*sum(len(lst)-k)
  print(trimmed_mean)

The trimmed_mean with alpha= 0.1 should be 21, but I don't know how I need to adjust my code.

Thanks.

Body:
lst = [5,30,29,15,25,5,13,28,24,29]

def tmean(lst, alpha):
    s = sorted(lst)
    # Caclculate number of elements to trim from the beginning and end
    a = round(alpha * len(lst)
    # Check if alpha can actually remove any elements and if not return straight mean
    if a == 0:
        return sum(lst) / len(lst)
    # Remove trimmed elements from the list
    trimmed_list = s[a:-a]
    # Check if there is a list left after trimming
    if len(trimmed_list) == 0:
        return
    # Calculate average on the new list
    trimmed_ave = sum(trimmed_list)/len(trimmed_list)
    print(trimmed_ave)
    return trimmed_ave

tmean(lst, 0.1)

Obviously some of the above stages could be combined for more concise code, but have split into separate lines for ease of explanation


问:
Pandas merging rows with same values based on multiple columns
I have a sample dataset like this

Col1 Col2 Col3

A 1,2,3 A123

A 4,5 A456

A 1,2,3 A456

A 4,5 A123

I just want to merge the Col2 and Col3  into single row based on the unique Col1.

Expected Result:

Col1    Col2    Col3

A   1,2,3,4,5   A123,A456

I referred some solutions and tried with the following. But it only appends single column.

```<code>df.groupby(df.columns.difference(['Col3']).tolist())\
                 .Col3.apply(pd.Series.unique).reset_index()
</code>```

答:
Drop duplicates with subsets Col1 and 3

groupby Col1

Then aggregate, using the string concatenate method

```<code>(df.drop_duplicates(['Col1','Col3'])
.groupby('Col1')
.agg(Col2 = ('Col2',lambda x: x.str.cat(sep=',')),
     Col3 = ('Col3', lambda x: x.str.cat(sep=','))
     )
.reset_index()
 )

    Col1    Col2    Col3
0   A   1,2,3,4,5   A123,A456
</code>```

Body:
I have a sample dataset like this

Col1 Col2 Col3

A 1,2,3 A123

A 4,5 A456

A 1,2,3 A456

A 4,5 A123

I just want to merge the Col2 and Col3  into single row based on the unique Col1.

Expected Result:

Col1    Col2    Col3

A   1,2,3,4,5   A123,A456

I referred some solutions and tried with the following. But it only appends single column.

df.groupby(df.columns.difference(['Col3']).tolist())\
                 .Col3.apply(pd.Series.unique).reset_index()

Body:
Drop duplicates with subsets Col1 and 3

groupby Col1

Then aggregate, using the string concatenate method

(df.drop_duplicates(['Col1','Col3'])
.groupby('Col1')
.agg(Col2 = ('Col2',lambda x: x.str.cat(sep=',')),
     Col3 = ('Col3', lambda x: x.str.cat(sep=','))
     )
.reset_index()
 )

    Col1    Col2    Col3
0   A   1,2,3,4,5   A123,A456


问:
Can we perform some action whenever crash occurs in android
I want to perform implicit logout of my app when ever my app gets crash. So that when user does login again so that he will be having fresh data instead of incomplete data that was caused by my crash.</p>

答:
You can register your Thread.UncaughtExceptionHandler on each thread that can crash. This will allow you to add some extra steps before crash is reported to Android. But be careful, because if your code throws another exception during those steps, you will never receive crash report to your Android Market account.

Basically, keep code inside your uncaught exception handler as simple as possible.

Here is an example:

```<code>public class MyUncaughtExceptionHandler implements UncaughtExceptionHandler {
    private final UncaughtExceptionHandler defaultHandler;

    MyUncaughtExceptionHandler(){
        defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    }

    public void uncaughtException(Thread t, Throwable e) {
        //TODO: add your custom code here
        defaultHandler.uncaughtException(t,e);
    }
}
</code>```

Body:
You can register your Thread.UncaughtExceptionHandler on each thread that can crash. This will allow you to add some extra steps before crash is reported to Android. But be careful, because if your code throws another exception during those steps, you will never receive crash report to your Android Market account.

Basically, keep code inside your uncaught exception handler as simple as possible.

Here is an example:

public class MyUncaughtExceptionHandler implements UncaughtExceptionHandler {
    private final UncaughtExceptionHandler defaultHandler;

    MyUncaughtExceptionHandler(){
        defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    }

    public void uncaughtException(Thread t, Throwable e) {
        //TODO: add your custom code here
        defaultHandler.uncaughtException(t,e);
    }
}


问:
Nth salary in SQL
I'm trying to understand below query, how its working.

```<code>SELECT *
FROM Employee Emp1
WHERE (N-1) = (
               SELECT COUNT(DISTINCT(Emp2.Salary))
               FROM Employee Emp2
               WHERE Emp2.Salary > Emp1.Salary
               )
</code>```

Lets say I have 5 distinct salaries and want to get 3rd largest salary. So Inner query will run first and then outer query ?

I'm getting confused how its being done in sql engine. Curious to know. Becasue if its 3rd largest then 3-1 = 2, so that 2 needs to be matched with inner count as well. How inner count is being operated.

Can anyone explain the how its working .. ?

答:
The subquery is correlated subquery, so it conceptually executes once for each row in the outer query (database optimizations left apart).. What it does is count how many employees have a salary greater than the one on the row in the outer query: if there are 2 employee with a higher salary, then you know that the employee on the current row in the outer query has the third highest salary.

Another way to phrase this is to use row_number() for this:

```<code>select *
from (
    select
        e.*,
        row_number() over(order by salary desc) rn
    from employee e
) t
where rn = 3
</code>```

Depending on how you want to handle duplicates, dense_rank() might also be an option.

Title: Nth salary in SQL

Body:
I'm trying to understand below query, how its working.

SELECT *
FROM Employee Emp1
WHERE (N-1) = (
               SELECT COUNT(DISTINCT(Emp2.Salary))
               FROM Employee Emp2
               WHERE Emp2.Salary > Emp1.Salary
               )

Lets say I have 5 distinct salaries and want to get 3rd largest salary. So Inner query will run first and then outer query ?

I'm getting confused how its being done in sql engine. Curious to know. Becasue if its 3rd largest then 3-1 = 2, so that 2 needs to be matched with inner count as well. How inner count is being operated.

Can anyone explain the how its working .. ?

Body:
The subquery is correlated subquery, so it conceptually executes once for each row in the outer query (database optimizations left apart).. What it does is count how many employees have a salary greater than the one on the row in the outer query: if there are 2 employee with a higher salary, then you know that the employee on the current row in the outer query has the third highest salary.

Another way to phrase this is to use row_number() for this:

select *
from (
    select
        e.*,
        row_number() over(order by salary desc) rn
    from employee e
) t
where rn = 3

Depending on how you want to handle duplicates, dense_rank() might also be an option.


问:
Some react routes don't work on refresh or manual url
I've read all the available questions here at StackOverflow or any other platform. I understand that every time a url is entered it first hits the backend. But how is that possible when backend and frontend work on different ports?

Here is my server:

```<code>app.use(cors())

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

connectDB()

const PORT = process.env.PORT || 5000;
const server = app.listen(PORT, () => console.log(`Server running on port ${PORT}`))

const socketio = require('socket.io')
const io = socketio(server)
const questions = require('./api/questions')(io)

app.use('/api/users', users)
app.use('/api/posts', posts)
app.use('/api/questions', questions)

express.static(path.resolve(__dirname, '/client/public'));

app.get('/*', (req, res) => {
    res.sendFile(__dirname + '/client/public/index.html'), err => console.log(err)
})
</code>```

I do have a route that redirects to my index.html if no route is matched, however when I enter a url it never reaches the backend route.

It works fine using postman. Frontend react app runs on port 3000, backend runs on port 5000. I don't get any errors or what so ever on page refresh. It does'nt load the routes it should in the front end.

EDIT: it reaches the route but doesnt render the index.html page, I checked the directory,it should be working, i dont know wth is wrong

答:
This problem because react has its own server and by default put the localhost@5000 as a prefix on any request (proxy) so you can solve it by put.

```<code>"proxy": "http://localhost@serverport"  // in the package.json file on the react
</code>```

then restart your front server more than one time then try your requests.

Body:
I've read all the available questions here at StackOverflow or any other platform. I understand that every time a url is entered it first hits the backend. But how is that possible when backend and frontend work on different ports?

Here is my server:

app.use(cors())

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

connectDB()

const PORT = process.env.PORT || 5000;
const server = app.listen(PORT, () => console.log(`Server running on port ${PORT}`))

const socketio = require('socket.io')
const io = socketio(server)
const questions = require('./api/questions')(io)

app.use('/api/users', users)
app.use('/api/posts', posts)
app.use('/api/questions', questions)

express.static(path.resolve(__dirname, '/client/public'));

app.get('/*', (req, res) => {
    res.sendFile(__dirname + '/client/public/index.html'), err => console.log(err)
})

I do have a route that redirects to my index.html if no route is matched, however when I enter a url it never reaches the backend route.

It works fine using postman. Frontend react app runs on port 3000, backend runs on port 5000. I don't get any errors or what so ever on page refresh. It does'nt load the routes it should in the front end.

EDIT: it reaches the route but doesnt render the index.html page, I checked the directory,it should be working, i dont know wth is wrong

Body:
This problem because react has its own server and by default put the localhost@5000 as a prefix on any request (proxy) so you can solve it by put.

"proxy": "http://localhost@serverport"  // in the package.json file on the react

then restart your front server more than one time then try your requests.


问:
$injector:modulerr error in IE 11 Using AngularJS
I've developed an AngularJS App and it works on Firefox,Opera,Safari, Edge, and Chrome but it won't work on IE 11.

Here is the specific error message I get in opening the app in IE 11:

[$injector:modulerr] Failed to instantiate module TicketSystemApp due
  to: Error: [$injector:modulerr] Failed to instantiate module
  TicketSystemControllers due to: Error: [$injector:nomod] Module
  'TicketSystemControllers' is not available! You either misspelled the
  module name or forgot to load it.

It seems like my module app is not loading.

Here is my entire script load:

```<code>  <script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
<!-- Angular js -->
<script src= "js/angular.min.js"></script>
<script src="https://code.angularjs.org/1.5.0/angular-route.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-animate.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-aria.min.js"></script>
<!-- Angular Material Library -->
<script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.0.7/angular-material.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-messages.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src = "js/ui-bootstrap-tpls-1.2.1.js"></script>
<script src="bower_components/angular-bootstrap-lightbox/dist/angular-bootstrap-lightbox.js"></script>
<script src="js/angular-ui-router.js"></script>
<script src="js/md-data-table.min.js"></script>
<script src="js/toArrayFilter.js"></script>
<!-- auto-scroll module  -->
<script src="bower_components/angular-scroll-glue/src/scrollglue.js"></script>

<script src = "js/app.js"></script>
<!-- Controllers -->
<script src = "js/controllers.js"></script>
<script src ="js/globalFunctions.js"></script>
<!-- Custom File Upload Angular -->
<script src="js/ng-file-upload-shim.min.js"></script> <!-- for no html5 browsers support -->
<script src="js/ng-file-upload.min.js"></script>
<!-- FACTORY -->
<script src = "js/authInterceptor.js"></script>

<!-- Services -->
<script src="js/auth.js"></script>
<script src="js/session.js"></script>

<!-- loading bar -->
<script  src="bower_components/angular-loading-bar/build/loading-bar.min.js"></script>
</code>```

I have this in as my html tag:

```<code><html lang="en" ng-app="TicketSystemApp" xmlns:ng="http://angularjs.org" class="ng-app:TicketSystemApp" id="ng-app">
</code>```

And I do have this in my head tag:

```<code>  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
</code>```

I have tried manually bootstrapping but I just get the same error message twice.

Here is my app.js(Just the initialization):

```<code>    var TicketSystemApp = angular.module('TicketSystemApp',[
    'ngRoute',
    'TicketSystemControllers',
  'angular-loading-bar',
    'ngAnimate',
    'ui.router',
    'ui.bootstrap',
  'ngMaterial',
  'md.data.table',
  'angular-toArrayFilter'
]);
</code>```

Here is my controller.js(just the initialization).  I use this to module to contain all controllers:

```<code>var TicketSystemControllers = angular.module('TicketSystemControllers',[
    'ngRoute',
    'ui.router',
    'ui.bootstrap',
    'angular-loading-bar',
    'ngAnimate',
    'ngMaterial',
    'ngMessages',
    'ngFileUpload',
    'md.data.table',
    'bootstrapLightbox',
    'luegg.directives'

    ]);
</code>```

答:
In my case it was using const val = something.
When I changed it to var val = something, the error was gone.

Body:
I've developed an AngularJS App and it works on Firefox,Opera,Safari, Edge, and Chrome but it won't work on IE 11.

Here is the specific error message I get in opening the app in IE 11:

[$injector:modulerr] Failed to instantiate module TicketSystemApp due
  to: Error: [$injector:modulerr] Failed to instantiate module
  TicketSystemControllers due to: Error: [$injector:nomod] Module
  'TicketSystemControllers' is not available! You either misspelled the
  module name or forgot to load it.

It seems like my module app is not loading.

Here is my entire script load:

I have this in as my html tag:

And I do have this in my head tag:

  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

I have tried manually bootstrapping but I just get the same error message twice.

Here is my app.js(Just the initialization):

    var TicketSystemApp = angular.module('TicketSystemApp',[
    'ngRoute',
    'TicketSystemControllers',
  'angular-loading-bar',
    'ngAnimate',
    'ui.router',
    'ui.bootstrap',
  'ngMaterial',
  'md.data.table',
  'angular-toArrayFilter'
]);

Here is my controller.js(just the initialization).  I use this to module to contain all controllers:

var TicketSystemControllers = angular.module('TicketSystemControllers',[
    'ngRoute',
    'ui.router',
    'ui.bootstrap',
    'angular-loading-bar',
    'ngAnimate',
    'ngMaterial',
    'ngMessages',
    'ngFileUpload',
    'md.data.table',
    'bootstrapLightbox',
    'luegg.directives'

    ]);


问:
Continuously submitting Runnable tasks to ExecutorService until work is done, getting java.util.concurrent.RejectedExecutionException
My multi-threaded class is supposed to carry out three operations – operation1, operation2, and operation3 – on a number of objects of the class ClassA, where each type of operation is dependant on the earlier operation. For this, I have tried to implement the producer-consumer pattern using a number of BlockingQueues and an ExecutorService.

```<code>final ExecutorService executor = ForkJoinPool.commonPool();
final BlockingQueue<ClassA> operationOneQueue = new ArrayBlockingQueue<>(NO_OF_CLASS_A_OBJECTS);
final BlockingQueue<ClassA> operationTwoQueue = new ArrayBlockingQueue<>(NO_OF_CLASS_A_OBJECTS);
final BlockingQueue<ClassA> operationThreeQueue = new ArrayBlockingQueue<>(NO_OF_CLASS_A_OBJECTS);
final BlockingQueue<ClassA> resultQueue = new ArrayBlockingQueue<>(NO_OF_CLASS_A_OBJECTS);
</code>```

The operations are implemented like this:

```<code>void doOperationOne() throws InterruptedException {
    ClassA objectA = operationOneQueue.take();
    objectA.operationOne();
    operationTwoQueue.put(objectA);
}
</code>```

where each type of operation has its own corresponding method, with its "own" in-queue and out-queue. Each operation method calls the appropriate method on the ClassA object. The method doOperationThree puts ClassA objects in the resultQueue, meaning they have been completely processed.

First, I fill the operationOneQueue with all ClassA objects that are to be operated on. Then, I try to assign executable tasks to the ExecutorService like this:

```<code>    while (resultQueue.size() < NO_OF_CLASS_A_OBJECTS) {
        executor.execute(() -> {
            try {
                doOperationOne();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        executor.execute(() -> {
            try {
                doOperationTwo();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        executor.execute(() -> {
            try {
                doOperationThree();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
    }
    executor.shutdown();
</code>```

Running my program, I get a java.util.concurrent.RejectedExecutionException.

```<code>    Operation1: ClassA object 0
    Operation2: ClassA object 0
    Operation1: ClassA object 1
    Operation3: ClassA object 0
    ....
    Operation1: ClassA object 46
    Operation2: ClassA object 45
    Operation3: ClassA object 45
    Exception in thread "main" java.util.concurrent.RejectedExecutionException: Queue capacity exceeded
at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.growArray(ForkJoinPool.java:912)
at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.lockedPush(ForkJoinPool.java:867)
at java.base/java.util.concurrent.ForkJoinPool.externalPush(ForkJoinPool.java:1911)
at java.base/java.util.concurrent.ForkJoinPool.externalSubmit(ForkJoinPool.java:1930)
at java.base/java.util.concurrent.ForkJoinPool.execute(ForkJoinPool.java:2462)
at concurrent.operations.Program1.main(Program1.java:96)
</code>```

What am I doing wrong? How can I achieve this without over-saturating the thread pool?

Edit: Full disclosure – this is homework with some requirements. 1. I must use ForkJoinPool.commonPool() and must not set the number of threads myself, 2. I must use the consumer-producer pattern, and 3. I must not modify ClassA.

答:
I really like doing concurrent stuff, so I did try writing it. I did use CompletableFuture which a) does run in the ForkJoinPool.commonPool by default and b) makes the actual processing really easy:

```<code>while (true) {
    final ClassA nextOperation = queue.take();
    CompletableFuture.runAsync(nextOperation::operationOne)
        .thenRun(nextOperation::operationTwo)
        .thenRun(nextOperation::operationThree)
        .thenRun(() -> resultQueue.add(nextOperation));
}
</code>```

This will take ClassA objects from the queue and execute all their operations concurrently, but in order.

You did leave out where the tasks are coming from, and whether you need the consumer to terminate. Generally you don't want to, and it does make matters a bit more complicated.

```<code>private static final int COUNT = 10;
private static final Random RANDOM = new Random();

public static void main(String[] args) throws ExecutionException, InterruptedException {
    BlockingQueue<ClassA> runnables = new ArrayBlockingQueue<>(COUNT);
    BlockingQueue<ClassA> finished = new ArrayBlockingQueue<>(COUNT);

    // start producer
    ExecutorService createTaskExecutor = Executors.newSingleThreadExecutor();
    createTaskExecutor.submit(() -> fillQueue(runnables));
    // wait for all consumer tasks to finish
    while (finished.size() != COUNT) {
        try {
            // we need to poll instead of waiting forever
            // because the last tasks might still be running
            // while there are no others to add anymore
            // so we need to check again if all have finished in the meantime
            final ClassA nextOperation = runnables.poll(2, TimeUnit.SECONDS);
            if (nextOperation != null) {
                CompletableFuture.runAsync(nextOperation::operationOne)
                        .thenRun(nextOperation::operationTwo)
                        .thenRun(nextOperation::operationThree)
                        .thenRun(() -> finished.add(nextOperation));
            }
        } catch (InterruptedException e) {
            System.err.println("exception while retrieving next operation");
            // we will actually need to terminate now, or probably never will
            throw e;
        }
    }
    System.out.printf("finished tasks (%d):%n", finished.size());
    for (ClassA classA : finished) {
        System.out.printf("finished task %d%n", classA.designator);
    }
    createTaskExecutor.shutdown();
}

private static void fillQueue(BlockingQueue<ClassA> runnables) {
    // start thread filling the queue at random
    for (int i = 0; i < COUNT; i++) {
        runnables.add(new ClassA(i));
        try {
            Thread.sleep(RANDOM.nextInt(1_000));
        } catch (InterruptedException e) {
            System.err.println("failed to add runnable");
        }
    }
}
</code>```

Since you didn't provide ClassA, I used this one. It contains an identifier so you can track which is running at what time.

```<code>class ClassA {
    private static final Random RANDOM = new Random();
    public final int designator;

    public ClassA(int i) {
        designator = i;
    }

    public void operationOne() {
        System.out.printf("%d: operation 1%n", designator);
        sleep();
    }

    public void operationTwo() {
        System.out.printf("%d: operation 2%n", designator);
        sleep();
    }

    public void operationThree() {
        System.out.printf("%d: operation 3%n", designator);
        sleep();
    }

    private static void sleep() {
        try {
            Thread.sleep(RANDOM.nextInt(5_000));
        } catch (InterruptedException e) {
            System.err.println("interrupted while executing task");
        }
    }
}
</code>```

Body:
My multi-threaded class is supposed to carry out three operations – operation1, operation2, and operation3 – on a number of objects of the class ClassA, where each type of operation is dependant on the earlier operation. For this, I have tried to implement the producer-consumer pattern using a number of BlockingQueues and an ExecutorService.

final ExecutorService executor = ForkJoinPool.commonPool();
final BlockingQueue<ClassA> operationOneQueue = new ArrayBlockingQueue<>(NO_OF_CLASS_A_OBJECTS);
final BlockingQueue<ClassA> operationTwoQueue = new ArrayBlockingQueue<>(NO_OF_CLASS_A_OBJECTS);
final BlockingQueue<ClassA> operationThreeQueue = new ArrayBlockingQueue<>(NO_OF_CLASS_A_OBJECTS);
final BlockingQueue<ClassA> resultQueue = new ArrayBlockingQueue<>(NO_OF_CLASS_A_OBJECTS);

The operations are implemented like this:

void doOperationOne() throws InterruptedException {
    ClassA objectA = operationOneQueue.take();
    objectA.operationOne();
    operationTwoQueue.put(objectA);
}

where each type of operation has its own corresponding method, with its "own" in-queue and out-queue. Each operation method calls the appropriate method on the ClassA object. The method doOperationThree puts ClassA objects in the resultQueue, meaning they have been completely processed.

First, I fill the operationOneQueue with all ClassA objects that are to be operated on. Then, I try to assign executable tasks to the ExecutorService like this:

    while (resultQueue.size() < NO_OF_CLASS_A_OBJECTS) {
        executor.execute(() -> {
            try {
                doOperationOne();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        executor.execute(() -> {
            try {
                doOperationTwo();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        executor.execute(() -> {
            try {
                doOperationThree();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
    }
    executor.shutdown();

Running my program, I get a java.util.concurrent.RejectedExecutionException.

    Operation1: ClassA object 0
    Operation2: ClassA object 0
    Operation1: ClassA object 1
    Operation3: ClassA object 0
    ....
    Operation1: ClassA object 46
    Operation2: ClassA object 45
    Operation3: ClassA object 45
    Exception in thread "main" java.util.concurrent.RejectedExecutionException: Queue capacity exceeded
at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.growArray(ForkJoinPool.java:912)
at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.lockedPush(ForkJoinPool.java:867)
at java.base/java.util.concurrent.ForkJoinPool.externalPush(ForkJoinPool.java:1911)
at java.base/java.util.concurrent.ForkJoinPool.externalSubmit(ForkJoinPool.java:1930)
at java.base/java.util.concurrent.ForkJoinPool.execute(ForkJoinPool.java:2462)
at concurrent.operations.Program1.main(Program1.java:96)

What am I doing wrong? How can I achieve this without over-saturating the thread pool?

Edit: Full disclosure – this is homework with some requirements. 1. I must use ForkJoinPool.commonPool() and must not set the number of threads myself, 2. I must use the consumer-producer pattern, and 3. I must not modify ClassA.

Body:
I really like doing concurrent stuff, so I did try writing it. I did use CompletableFuture which a) does run in the ForkJoinPool.commonPool by default and b) makes the actual processing really easy:

while (true) {
    final ClassA nextOperation = queue.take();
    CompletableFuture.runAsync(nextOperation::operationOne)
        .thenRun(nextOperation::operationTwo)
        .thenRun(nextOperation::operationThree)
        .thenRun(() -> resultQueue.add(nextOperation));
}

This will take ClassA objects from the queue and execute all their operations concurrently, but in order.

You did leave out where the tasks are coming from, and whether you need the consumer to terminate. Generally you don't want to, and it does make matters a bit more complicated.

private static final int COUNT = 10;
private static final Random RANDOM = new Random();

public static void main(String[] args) throws ExecutionException, InterruptedException {
    BlockingQueue<ClassA> runnables = new ArrayBlockingQueue<>(COUNT);
    BlockingQueue<ClassA> finished = new ArrayBlockingQueue<>(COUNT);

    // start producer
    ExecutorService createTaskExecutor = Executors.newSingleThreadExecutor();
    createTaskExecutor.submit(() -> fillQueue(runnables));
    // wait for all consumer tasks to finish
    while (finished.size() != COUNT) {
        try {
            // we need to poll instead of waiting forever
            // because the last tasks might still be running
            // while there are no others to add anymore
            // so we need to check again if all have finished in the meantime
            final ClassA nextOperation = runnables.poll(2, TimeUnit.SECONDS);
            if (nextOperation != null) {
                CompletableFuture.runAsync(nextOperation::operationOne)
                        .thenRun(nextOperation::operationTwo)
                        .thenRun(nextOperation::operationThree)
                        .thenRun(() -> finished.add(nextOperation));
            }
        } catch (InterruptedException e) {
            System.err.println("exception while retrieving next operation");
            // we will actually need to terminate now, or probably never will
            throw e;
        }
    }
    System.out.printf("finished tasks (%d):%n", finished.size());
    for (ClassA classA : finished) {
        System.out.printf("finished task %d%n", classA.designator);
    }
    createTaskExecutor.shutdown();
}

private static void fillQueue(BlockingQueue<ClassA> runnables) {
    // start thread filling the queue at random
    for (int i = 0; i < COUNT; i++) {
        runnables.add(new ClassA(i));
        try {
            Thread.sleep(RANDOM.nextInt(1_000));
        } catch (InterruptedException e) {
            System.err.println("failed to add runnable");
        }
    }
}

Since you didn't provide ClassA, I used this one. It contains an identifier so you can track which is running at what time.

class ClassA {
    private static final Random RANDOM = new Random();
    public final int designator;

    public ClassA(int i) {
        designator = i;
    }

    public void operationOne() {
        System.out.printf("%d: operation 1%n", designator);
        sleep();
    }

    public void operationTwo() {
        System.out.printf("%d: operation 2%n", designator);
        sleep();
    }

    public void operationThree() {
        System.out.printf("%d: operation 3%n", designator);
        sleep();
    }

    private static void sleep() {
        try {
            Thread.sleep(RANDOM.nextInt(5_000));
        } catch (InterruptedException e) {
            System.err.println("interrupted while executing task");
        }
    }
}


问:
how to get returned value from stored function in PDO?
I have this code :

```<code>include("connect.php");
// Call database function
$p = 100;
$sth = $conn->prepare('SELECT ISPPRO.USERPKG.GET_USER(:bind1, :bind3) AS v FROM DUAL');
$sth->bindParam(":bind1", $p, PDO::PARAM_INT);
$sth->bindParam(":bind3", $p, PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r( $result);
echo "<br>```";
print_r($conn->errorInfo());
echo "```";
</code>```

The ISPPRO.USERPKG.GET_USER returns 1 or 0;

How I can get it??

Thanks in advance.

EDIT:

I changed the above code and I am getting this error:

```<code>OCIStmtExecute: ORA-00904: "ISPPRO"."USERPKG"."GET_USER": invalid identifier
</code>```

答:
Do you have execute permission on the package?

User ISPPRO should run the command

```<code>GRANT EXECUTE ON userpkg TO <your_user>;
</code>```

An easy way to check if you've been granted execute on this package is to run this command:

```<code>SELECT privilege
  FROM all_tab_privs
 WHERE table_schema = 'ISPPRO'
   AND table_name = 'USERPKG';
</code>```

You should get a row with EXECUTE as the privilege.

Body:
I have this code :

include("connect.php");
// Call database function
$p = 100;
$sth = $conn->prepare('SELECT ISPPRO.USERPKG.GET_USER(:bind1, :bind3) AS v FROM DUAL');
$sth->bindParam(":bind1", $p, PDO::PARAM_INT);
$sth->bindParam(":bind3", $p, PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r( $result);
echo "

";
print_r($conn->errorInfo());
echo "
";

The ISPPRO.USERPKG.GET_USER returns 1 or 0;

How I can get it??

Thanks in advance.

EDIT:

I changed the above code and I am getting this error:

OCIStmtExecute: ORA-00904: "ISPPRO"."USERPKG"."GET_USER": invalid identifier

Body:
Do you have execute permission on the package?

User ISPPRO should run the command

GRANT EXECUTE ON userpkg TO <your_user>;

An easy way to check if you've been granted execute on this package is to run this command:

SELECT privilege
  FROM all_tab_privs
 WHERE table_schema = 'ISPPRO'
   AND table_name = 'USERPKG';

You should get a row with EXECUTE as the privilege.


问:
Python pandas - Divide a column in dataframe1 with a column in dataframe2 based on another column in dataframe1
Dateframe1

```<code>df = pd.DataFrame(SQL_Query, columns=[ X,Y . . . . Currency,Amount]

Index         X             Y  ...         Currency          Amount
0             74            1  ...         USD               100
1             75            1  ...         EUR               5000
2             76            1  ...         AUD               300
3             79            1  ...         EUR               750

[1411137 rows x 162 columns]
</code>```

A large SQL query so I avoid writing out all columns.

```<code>df1=pd.read_excel(r`FX_EUR.xlsx)

Index       Currency      FX
0             AUD      1.61350
1             BGN      1.95580
2             BRL      4.51450
3             CAD      1.45830
4             CHF      1.09280
</code>```

So what would I like to achieve is to make a lookup in DF1 to see which Currency is used then divide the "DF1 Amount" column with "DF2 FX" column and to this for all rows in DF1. Either by making a third DF3 or by creating a new column i DF1 called Amount_EUR.

Any ideas on how to write this code?

答:
You can use a map to apply the transformation -

```<code>import pandas as pd
df = pd.DataFrame({"Currency": ['USD', 'EUR', 'AUD', 'EUR'], "Amount": [100, 5000, 300, 750]})

df1 = pd.DataFrame({"Currency": ["AUD", "BGN", "BRL", "CAD", "EUR"], "FX": [1.6, 1.9, 4.5, 1.5, 1.1]})
df1 = df1.set_index("Currency")

df['FX'] = df['Currency'].map(df1.FX)
df['FX_Adj_Amt'] = df['Amount'].div(df['FX'])

df
#  Currency  Amount   Fx   FX_Adj_Amt
#0      USD     100  NaN          NaN
#1      EUR    5000  1.1  4545.454545
#2      AUD     300  1.6   187.500000
#3      EUR     750  1.1   681.818182
</code>```

Body:
Dateframe1

df = pd.DataFrame(SQL_Query, columns=[ X,Y . . . . Currency,Amount]

Index         X             Y  ...         Currency          Amount
0             74            1  ...         USD               100
1             75            1  ...         EUR               5000
2             76            1  ...         AUD               300
3             79            1  ...         EUR               750

[1411137 rows x 162 columns]

A large SQL query so I avoid writing out all columns.

df1=pd.read_excel(r`FX_EUR.xlsx)

Index       Currency      FX
0             AUD      1.61350
1             BGN      1.95580
2             BRL      4.51450
3             CAD      1.45830
4             CHF      1.09280

So what would I like to achieve is to make a lookup in DF1 to see which Currency is used then divide the "DF1 Amount" column with "DF2 FX" column and to this for all rows in DF1. Either by making a third DF3 or by creating a new column i DF1 called Amount_EUR.

Any ideas on how to write this code?

Body:
You can use a map to apply the transformation -

import pandas as pd
df = pd.DataFrame({"Currency": ['USD', 'EUR', 'AUD', 'EUR'], "Amount": [100, 5000, 300, 750]})

df1 = pd.DataFrame({"Currency": ["AUD", "BGN", "BRL", "CAD", "EUR"], "FX": [1.6, 1.9, 4.5, 1.5, 1.1]})
df1 = df1.set_index("Currency")

df['FX'] = df['Currency'].map(df1.FX)
df['FX_Adj_Amt'] = df['Amount'].div(df['FX'])

df
#  Currency  Amount   Fx   FX_Adj_Amt
#0      USD     100  NaN          NaN
#1      EUR    5000  1.1  4545.454545
#2      AUD     300  1.6   187.500000
#3      EUR     750  1.1   681.818182


问:
the following code is about rotating a sorted arrray by some value d
my code is not working it is producing unexpected results.the code is about array rotation by using  a temp array . function "rotate" rotates the array , while function printArray prints the array .in the main function both functions are called. then there is cout with "hello". the overall output if "ellolloloohello". why am i getting this output.thanks

```<code> #include<iostream>
 using namespace std;

 void rotate(int arr[],int d, int n){
int temp[d];
for(int i =0;i<d;i++){
    temp[i]=arr[i];

}
for(int i = 0;i<n-d;i++){
    arr[i] = arr[i+d];
}
for(int i =0 ;i < d;i++)
{
    temp[i]= arr[n-d+i];

}

}
void printArray(int arr[],int size){
for(int i =0;i<size;i++)
{

    cout<<arr[i]+" " ;
}
}
int main()
{

int arr[10] = {0,1,2,3,4,5,6,7,8,9};
rotate(arr,3,10);
printArray(arr,10);
cout <<"hello";
}
;
</code>```

the output is "ellolloloohello" instead of "hello". whats happening here?????

答:
Change cout<<arr[i]+" " ; to cout << arr[i] << ' ';

And please use std::vector. int arr[d] is no c++ :(

Body:
my code is not working it is producing unexpected results.the code is about array rotation by using  a temp array . function "rotate" rotates the array , while function printArray prints the array .in the main function both functions are called. then there is cout with "hello". the overall output if "ellolloloohello". why am i getting this output.thanks

 #include<iostream>
 using namespace std;

 void rotate(int arr[],int d, int n){
int temp[d];
for(int i =0;i<d;i++){
    temp[i]=arr[i];

}
for(int i = 0;i<n-d;i++){
    arr[i] = arr[i+d];
}
for(int i =0 ;i < d;i++)
{
    temp[i]= arr[n-d+i];

}

}
void printArray(int arr[],int size){
for(int i =0;i<size;i++)
{

    cout<<arr[i]+" " ;
}
}
int main()
{

int arr[10] = {0,1,2,3,4,5,6,7,8,9};
rotate(arr,3,10);
printArray(arr,10);
cout <<"hello";
}
;

the output is "ellolloloohello" instead of "hello". whats happening here?????


问:
Displaying conditional Fields in HTML&JS twice
I have a list of many elements. When i have click a button I want to display next list. Until here, it's all good. When i have repeat this procedure for the newly opened list, the code didn't work. Why?

//here open the first list

$("#product").change(function() { //product is id from first list
  var selected = $("#product").val();
  $('p').hide(); //p represents Paragraph.
  $('#' + selected).show();

});

$(document).ready(function() {
  $('p').hide();
});

//here, i want to repeat same code for next list, but didn t work...

$("#1").change(function() { //1 is id from second list
  var selected = $("#1").val();
  $('p').hide(); //p represents Paragraph.
  $('#' + selected).show();

});

$(document).ready(function() {
  $('p').hide(); //p represents Paragraph.
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="product" name="faculty" required="">
  <option value="">-- Choose--</option>

  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>

<p id="1">
  <select id="1" name="domeniul_mate_info" required="">

    <option value="">-- Choose--</option>
    <option value="info">Info</option>
    <option value="math">Math</option>

  </select>

</p>

<p id="info">
  <select name="info" required="">

    <option value="">-- Choose--</option>
    <option value="info1">info1</option>
    <option value="info2">info2</option>

  </select>

</p></code>```

答:
The reason is you are using duplicate selector id 1 for both
 element and  element. You can only use unique selector identifier. I have updated your code, please find code below and let me know if any issue.

const product = [1, 2, 3];
const productDropDown1Relation = {
  1: ['info', 'math'],
  2: ['history', 'geography'],
  3: ['science', 'sport'],
}
const dropDown1DropDown2Relation = {
  info: ['info1', 'info2'],
  math: ['math1', 'math2'],
  history: ['history1', 'history2'],
  geography: ['geography1', 'geography2'],
  science: ['science1', 'science2'],
  sport: ['sport1', 'sport2'],
}

$(document).ready(function() {

  $("#dropdown2, #dropdown3").hide();
  const optionString = buildOptions(product);
  $("#product").html(optionString);

  $("#product").change(function() {
    debugger;
    const selected = $("#product").val();
    const optinString = buildOptions(productDropDown1Relation[selected]);
    $('#dropdown2').html(optinString);
    $('#dropdown2').show();
  });

  $("#dropdown2").change(function() {
    const selected = $("#dropdown2").val();
    const optinString = buildOptions(dropDown1DropDown2Relation[selected]);
    $('#dropdown3').html(optinString);
    $('#dropdown3').show();
  });
});

function buildOptions(arr) {
  let optionString = `<option value=''>--Choose--</option>`;
  for (const element of arr) {
    optionString += `<option value='${element}'>${element}</option>`;
  }
  return optionString;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="product" name="faculty" required="">
</select>

<select id="dropdown2" name="dropdown2" required="">
</select>

<select id="dropdown3" name="dropdown3" required="">
</select></code>```

Body:
I have a list of many elements. When i have click a button I want to display next list. Until here, it's all good. When i have repeat this procedure for the newly opened list, the code didn't work. Why?

//here open the first list

$("#product").change(function() { //product is id from first list
  var selected = $("#product").val();
  $('p').hide(); //p represents Paragraph.
  $('#' + selected).show();

});

$(document).ready(function() {
  $('p').hide();
});

//here, i want to repeat same code for next list, but didn t work...

$("#1").change(function() { //1 is id from second list
  var selected = $("#1").val();
  $('p').hide(); //p represents Paragraph.
  $('#' + selected).show();

});

$(document).ready(function() {
  $('p').hide(); //p represents Paragraph.
});

<select id="product" name="faculty" required="">
  <option value="">-- Choose--</option>

  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>

  <select id="1" name="domeniul_mate_info" required="">

    <option value="">-- Choose--</option>
    <option value="info">Info</option>
    <option value="math">Math</option>

  </select>

  <select name="info" required="">

    <option value="">-- Choose--</option>
    <option value="info1">info1</option>
    <option value="info2">info2</option>

  </select>

Body:
The reason is you are using duplicate selector id 1 for both
 element and  element. You can only use unique selector identifier. I have updated your code, please find code below and let me know if any issue.

const product = [1, 2, 3];
const productDropDown1Relation = {
  1: ['info', 'math'],
  2: ['history', 'geography'],
  3: ['science', 'sport'],
}
const dropDown1DropDown2Relation = {
  info: ['info1', 'info2'],
  math: ['math1', 'math2'],
  history: ['history1', 'history2'],
  geography: ['geography1', 'geography2'],
  science: ['science1', 'science2'],
  sport: ['sport1', 'sport2'],
}

$(document).ready(function() {

  $("#dropdown2, #dropdown3").hide();
  const optionString = buildOptions(product);
  $("#product").html(optionString);

  $("#product").change(function() {
    debugger;
    const selected = $("#product").val();
    const optinString = buildOptions(productDropDown1Relation[selected]);
    $('#dropdown2').html(optinString);
    $('#dropdown2').show();
  });

  $("#dropdown2").change(function() {
    const selected = $("#dropdown2").val();
    const optinString = buildOptions(dropDown1DropDown2Relation[selected]);
    $('#dropdown3').html(optinString);
    $('#dropdown3').show();
  });
});

function buildOptions(arr) {
  let optionString = `<option value=''>--Choose--</option>`;
  for (const element of arr) {
    optionString += `<option value='${element}'>${element}</option>`;
  }
  return optionString;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="product" name="faculty" required="">
</select>

<select id="dropdown2" name="dropdown2" required="">
</select>

<select id="dropdown3" name="dropdown3" required="">
</select>


问:
How to refresh an ag-grid when a change occurs inside a custom Cell Renderer component?
Inside my grid, I have this column:

```<code>  {
      headerName: "Generic/Specific",
      field: "genericspecific",
      id: "6",
      cellRenderer:'genericSpecificCellRenderersComponent',
      cellStyle: params => {
        const colors: string[] = ["red", "orange"];
        const genericSpecific: string[] = ["Generic", "Specific"];
        return {
          "background-color": colors[genericSpecific.indexOf(this.selectedOptions[params.node.id])]
        };
      }
    }
</code>```

As you can see, it has a custom Cell Renderer. Here's its definition:

```<code> @Component({
  selector: "app-generic-specific-renderers",
  template: `
    <hr />
    <select class="form-control" id='0' (change)="updateChosenValue($event.target); refresh(params)">
      <option >{{ selectedOptions[params.node.id] }}</option>
      <option >Specific</option>
      <option >Generic</option>
    </select>
    <hr />
  `
})
export class GenericSpecificCellRenderersComponent implements OnInit {
  updateChosenValue(event) {
    if (event.value==='Specific'){
      this.selectedOptions[this.params.node.id]='Specific'
    }
    else if (event.value==='Generic'){
      this.selectedOptions[this.params.node.id]='Generic'
     }
    }
  selectedOptions:string[]=[];
  constructor(private controlAssessmentData: ControlAssessmentService) {
    this.controlAssessmentData.currentSelectedOptions.subscribe(
      receivedSelectedOptions =>
        (this.selectedOptions = receivedSelectedOptions)
    );
  }
  ngOnInit() {}
  public params: any;
  public gridApi:any;

  // called on init
  agInit(params: any): void {
    this.params = params;
    this.gridApi= params.api;
  }
  // called when the cell is refreshed
  refresh(params: any): boolean {
    this.params = params;
    this.gridApi.refreshCells()
    console.log('this.params: ', this.params);
    return true;
  }
}
</code>```

I wanted to refresh the grid everytime the user chooses an option from the dropDown list.

I thought my code should work, because I used the same logic when refreshing the grid where it was defined.

However, it didn't.

Any idea why?  And maybe how I can solve it?

Thank you!

答:
Refresh on Component Renderer 'mycomponentRenderer' is called for example:

```<code> const rowNode = this.gridApi.getDisplayedRowAtIndex(1);
 rowNode.setDataValue('mycolumn', 'myvalue');
 this.gridApi.refreshCells({ columns: ['mycolumn'] });
</code>```

and "mycolumn" have to put in the columnDefs during columns configuration in "field" property.

html:

```<code>html: <ag-grid-angular
        [rowData]="items"
        [columnDefs]="columnDefs"
        [defaultColDef]="defaultColDef"
        (gridReady)="onGridReady($event)"
        [frameworkComponents]="frameworkComponents">
</ag-grid-angular>
</code>```

ts:

```<code> this.columnDef[0] = {
            field: 'mycolumn',
            headerName: 'mycolumnHeader',
            cellRenderer: 'mycomponentRenderer',
}
</code>```

Body:
Inside my grid, I have this column:

  {
      headerName: "Generic/Specific",
      field: "genericspecific",
      id: "6",
      cellRenderer:'genericSpecificCellRenderersComponent',
      cellStyle: params => {
        const colors: string[] = ["red", "orange"];
        const genericSpecific: string[] = ["Generic", "Specific"];
        return {
          "background-color": colors[genericSpecific.indexOf(this.selectedOptions[params.node.id])]
        };
      }
    }

As you can see, it has a custom Cell Renderer. Here's its definition:

 @Component({
  selector: "app-generic-specific-renderers",
  template: `

    <select class="form-control" id='0' (change)="updateChosenValue($event.target); refresh(params)">
      <option >{{ selectedOptions[params.node.id] }}</option>
      <option >Specific</option>
      <option >Generic</option>
    </select>

  `
})
export class GenericSpecificCellRenderersComponent implements OnInit {
  updateChosenValue(event) {
    if (event.value==='Specific'){
      this.selectedOptions[this.params.node.id]='Specific'
    }
    else if (event.value==='Generic'){
      this.selectedOptions[this.params.node.id]='Generic'
     }
    }
  selectedOptions:string[]=[];
  constructor(private controlAssessmentData: ControlAssessmentService) {
    this.controlAssessmentData.currentSelectedOptions.subscribe(
      receivedSelectedOptions =>
        (this.selectedOptions = receivedSelectedOptions)
    );
  }
  ngOnInit() {}
  public params: any;
  public gridApi:any;

  // called on init
  agInit(params: any): void {
    this.params = params;
    this.gridApi= params.api;
  }
  // called when the cell is refreshed
  refresh(params: any): boolean {
    this.params = params;
    this.gridApi.refreshCells()
    console.log('this.params: ', this.params);
    return true;
  }
}

I wanted to refresh the grid everytime the user chooses an option from the dropDown list.

I thought my code should work, because I used the same logic when refreshing the grid where it was defined.

However, it didn't.

Any idea why?  And maybe how I can solve it?

Thank you!

Body:
Refresh on Component Renderer 'mycomponentRenderer' is called for example:

 const rowNode = this.gridApi.getDisplayedRowAtIndex(1);
 rowNode.setDataValue('mycolumn', 'myvalue');
 this.gridApi.refreshCells({ columns: ['mycolumn'] });

and "mycolumn" have to put in the columnDefs during columns configuration in "field" property.

html:

html: <ag-grid-angular
        [rowData]="items"
        [columnDefs]="columnDefs"
        [defaultColDef]="defaultColDef"
        (gridReady)="onGridReady($event)"
        [frameworkComponents]="frameworkComponents">
</ag-grid-angular>

ts:

 this.columnDef[0] = {
            field: 'mycolumn',
            headerName: 'mycolumnHeader',
            cellRenderer: 'mycomponentRenderer',
}