问:
Neo4j-shell not working on Mac Community edition 3.3.0
I'm new to Neo4j and have installed the Community Edition (3.3.0).  I'm working through tutorials that reference neo4j-shell.  However, every time I try to run it I get:

```<code>-bash: /usr/local/bin/neo4j-shell: No such file or directory
</code>```

I tried to run the Desktop version and use its terminal, but get the same thing.  I even installed it with Homebrew (have since uninstalled) and it seemed to respond but could not connect to anything even when I used the appropriate switches.  I've also tried things I've found searching here and within the Google Group to no avail.

Could anyone please let me know how to get this running with Community Edition, or if not possible, please let me know how to otherwise.  I'm running on a Mac and installed using the .dmg file.

Thanks in advance for your help.

Greg

答: You should be using cypher-shell with the new versions of Neo4j. (3.x +)  Make sure to update your ./conf/neo4j.conf file and look for dbms.shell.enabled which will be commented out by default.  Remove the # so it says dbms.shell.enabled=true</p>

Body:
I'm new to Neo4j and have installed the Community Edition (3.3.0).  I'm working through tutorials that reference neo4j-shell.  However, every time I try to run it I get:

-bash: /usr/local/bin/neo4j-shell: No such file or directory

I tried to run the Desktop version and use its terminal, but get the same thing.  I even installed it with Homebrew (have since uninstalled) and it seemed to respond but could not connect to anything even when I used the appropriate switches.  I've also tried things I've found searching here and within the Google Group to no avail.

Could anyone please let me know how to get this running with Community Edition, or if not possible, please let me know how to otherwise.  I'm running on a Mac and installed using the .dmg file.

Thanks in advance for your help.

Greg


来源: stackexchange

问:
error with \t in last step of while loop (c++)
I'm trying to perfect an aligned multiplication table. All is good, but the \t kinda falters in the very last step of the loop. It inserts double the space intended only in this step and I don't know why.

```<code>int main()
{
    int N;
    cin >> N;
    int i = 1;
    while (i<=N)
    {
        int j = 1;
        while (j<=N)
        {
            cout << "(" << i << "x";
            cout << j << ")";
            cout << "=" << i*j;
            j++;
            cout << "\t\t";
        }

        i++;
        cout << "\n";
    }
        system("pause");
        return 0;
    }
</code>```

The output:

答:
This seems to solve your problem

```<code>#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
   int N;
   cin >> N;
   int i = 1;
   while (i<=N)
   {
       int j = 1;
       while (j<=N)
       {
           cout << "(" << i << "x" << j << ")" << "=" << i*j;
           if (i*j < 10) cout << "\t\t";
           else cout << "\t";
           j++;
       }

       i++;
       cout << endl;
   }
   system("pause");
   return 0;
}
</code>```

Your problem doesn't only occur in the last iteration. It occurs after the first 2-digit result (eg. try running your code for N = 5). Because of the existence of one more digit in the result (in your example because of (4x3)=12) the following operation to be printed in that line is pushed one \t to the right.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to perfect an aligned multiplication table. All is good, but the \t kinda falters in the very last step of the loop. It inserts double the space intended only in this step and I don't know why.

int main()
{
    int N;
    cin >> N;
    int i = 1;
    while (i<=N)
    {
        int j = 1;
        while (j<=N)
        {
            cout << "(" << i << "x";
            cout << j << ")";
            cout << "=" << i*j;
            j++;
            cout << "\t\t";
        }

        i++;
        cout << "\n";
    }
        system("pause");
        return 0;
    }

The output:

Body:
This seems to solve your problem

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
   int N;
   cin >> N;
   int i = 1;
   while (i<=N)
   {
       int j = 1;
       while (j<=N)
       {
           cout << "(" << i << "x" << j << ")" << "=" << i*j;
           if (i*j < 10) cout << "\t\t";
           else cout << "\t";
           j++;
       }

       i++;
       cout << endl;
   }
   system("pause");
   return 0;
}

Your problem doesn't only occur in the last iteration. It occurs after the first 2-digit result (eg. try running your code for N = 5). Because of the existence of one more digit in the result (in your example because of (4x3)=12) the following operation to be printed in that line is pushed one \t to the right.


问:
How to avoid circular dependency with Dagger 2?
I have the following Module :

```<code>@Module
class HomeModule(private val context: Context) {

    @Provides
    fun provideContext() = context

    @Provides
    fun provideHomeUi(): HomeUi {
        return HomeUi()
    }

    @Provides
    @Singleton
    fun provideHomePresenter(homeUi: HomeUi): HomePresenter {
        return HomePresenter(homeUi)
    }
}
</code>```

Those injected fields in HomeUi.kt

```<code>@Inject lateinit var context: Context
@Inject lateinit var presenter: HomePresenter
</code>```

And this one in HomePresenter.kt

```<code>@Inject lateinit var context: Context
</code>```

Here my Deps Component

```<code>@Singleton
@Component(modules = arrayOf(
        NetworkModule::class,
        HomeModule::class
))
interface Deps {
    fun inject(homePresenter: HomePresenter)
    fun inject(homeActivity: HomeActivity)
    fun inject(homeUi: HomeUi)
}
</code>```

I am using Dagger 2.10 but a StackOverflowError is thrown. I am looking for a way to avoid my circular dependency.

Note : This is my HomeUi which is infinitely instantiate.

答:
It seems like you'd be calling field injection on HomeUi from within your presenters constructor, thus triggering an infinite loop since neither object can finish being constructed without the other (?). This looks like a really bad approach and you should try to move your dependencies into the objects constructors instead of creating half-finished objects.

Use field injection primarily for objects that you can't create yourself, e.g. with Android framework types. IMHO inject(homeActivity: HomeActivity) should be the only method of your component.

Cyclic dependencies are hard to manage and there is no perfect solution, but you can try things like switching to Provider<HomePresenter> to delay the dependency and be able to resolve it this way.

The following should do what you intended, and please note how I'm using constructor injection instead of having 2 additional methods in the module.

```<code>@Singleton
@Component(modules = arrayOf(
    NetworkModule::class,
    HomeModule::class
))
interface Deps {
  fun inject(homeActivity: HomeActivity)
}

@Module
class HomeModule(private val context: Context) {

  @Provides
  fun provideContext() = context

}

@Singleton
class HomeUi @Inject constructor(presenter : Provider<HomePresenter>, context : Context)
{
  // use with presenter.get()
}

@Singleton
class HomePresenter @Inject constructor(homeUi : HomeUi)
</code>```

Please note that using a Provider<T> is the cheapest way to resolve a cyclic dependency that I know of, but it might not be suited for every situation.

Body:
I have the following Module :

@Module
class HomeModule(private val context: Context) {

    @Provides
    fun provideContext() = context

    @Provides
    fun provideHomeUi(): HomeUi {
        return HomeUi()
    }

    @Provides
    @Singleton
    fun provideHomePresenter(homeUi: HomeUi): HomePresenter {
        return HomePresenter(homeUi)
    }
}

Those injected fields in HomeUi.kt

@Inject lateinit var context: Context
@Inject lateinit var presenter: HomePresenter

And this one in HomePresenter.kt

@Inject lateinit var context: Context

Here my Deps Component

@Singleton
@Component(modules = arrayOf(
        NetworkModule::class,
        HomeModule::class
))
interface Deps {
    fun inject(homePresenter: HomePresenter)
    fun inject(homeActivity: HomeActivity)
    fun inject(homeUi: HomeUi)
}

I am using Dagger 2.10 but a StackOverflowError is thrown. I am looking for a way to avoid my circular dependency.

Note : This is my HomeUi which is infinitely instantiate.

Body:
It seems like you'd be calling field injection on HomeUi from within your presenters constructor, thus triggering an infinite loop since neither object can finish being constructed without the other (?). This looks like a really bad approach and you should try to move your dependencies into the objects constructors instead of creating half-finished objects.

Use field injection primarily for objects that you can't create yourself, e.g. with Android framework types. IMHO inject(homeActivity: HomeActivity) should be the only method of your component.

Cyclic dependencies are hard to manage and there is no perfect solution, but you can try things like switching to Provider<HomePresenter> to delay the dependency and be able to resolve it this way.

The following should do what you intended, and please note how I'm using constructor injection instead of having 2 additional methods in the module.

@Singleton
@Component(modules = arrayOf(
    NetworkModule::class,
    HomeModule::class
))
interface Deps {
  fun inject(homeActivity: HomeActivity)
}

@Module
class HomeModule(private val context: Context) {

  @Provides
  fun provideContext() = context

}

@Singleton
class HomeUi @Inject constructor(presenter : Provider<HomePresenter>, context : Context)
{
  // use with presenter.get()
}

@Singleton
class HomePresenter @Inject constructor(homeUi : HomeUi)

Please note that using a Provider<T> is the cheapest way to resolve a cyclic dependency that I know of, but it might not be suited for every situation.


问:
Compile Error : ( Warning: Control Reaches End of Non-Void Function [-Wreturn-type] )
When I try to compile my code using this:g++ -Wall -std=c++11 -o test10 program10.cpp This occurs:

```<code>program10.cpp: In function 'int getInt(std::string)':
program10.cpp:76:1: warning: control reaches end of non-void function [-Wreturn-type]
</code>```

Here is the code:

```<code>int getInt(string str) {
    string bin[] = {"11000", "00011", "00101", "00110", "01001",
                    "01010", "01100", "10001", "10010", "10100"};
    for (int i = 0; i < 10; i++) {
        if (str.compare(bin[i]) == 0) {
            return i;
        }
    }
}
</code>```

答:
Your warning was explained concisely by the compiler. The code is only reaching your return statement when one of the strings in the bin array is found. This is one of the many reasons you should prefer a single exit point (makes for better readability, won't cause this warning, and easier to debug).  You should also prefer passing non-POD types as reference for function arguments.

```<code>int getInt(string & str)
{
    int ret(-1); // bias to error
    string bin[] = {"11000", "00011", "00101", "00110", "01001",
        "01010", "01100", "10001", "10010", "10100"};
    for (int i = 0; i < 10; i++) {
        if (str.compare(bin[i]) == 0) {
            ret = i; // success!
        }
    }
    return ret;
}
</code>```

Body:
When I try to compile my code using this:g++ -Wall -std=c++11 -o test10 program10.cpp This occurs:

program10.cpp: In function 'int getInt(std::string)':
program10.cpp:76:1: warning: control reaches end of non-void function [-Wreturn-type]

Here is the code:

int getInt(string str) {
    string bin[] = {"11000", "00011", "00101", "00110", "01001",
                    "01010", "01100", "10001", "10010", "10100"};
    for (int i = 0; i < 10; i++) {
        if (str.compare(bin[i]) == 0) {
            return i;
        }
    }
}

Body:
Your warning was explained concisely by the compiler. The code is only reaching your return statement when one of the strings in the bin array is found. This is one of the many reasons you should prefer a single exit point (makes for better readability, won't cause this warning, and easier to debug).  You should also prefer passing non-POD types as reference for function arguments.

int getInt(string & str)
{
    int ret(-1); // bias to error
    string bin[] = {"11000", "00011", "00101", "00110", "01001",
        "01010", "01100", "10001", "10010", "10100"};
    for (int i = 0; i < 10; i++) {
        if (str.compare(bin[i]) == 0) {
            ret = i; // success!
        }
    }
    return ret;
}


问:
Installing .net core on ubuntu
I downloaded .net core file and got it in the form of tar.gz
I then extracted in to a particular folder. Inside it, when I double click on dotnet file (to maybe install it), nothing happens!

Please help.
I need it to run Visual studio code

答:
Installing the .NET Core SDK and runtime on an ubuntu machine can be quite daunting if you don't have much experience with Linux distributions.

But the steps are outlined on the official .NET Core website (which is available here https://www.microsoft.com/net/learn/get-started/linuxubuntu) quite well, in my opinion.

side note: I know that a lot of Linux set up can be daunting and seem like a dark art to folks who are new to it.

Depending on which version of Ubuntu you have, you'll need to run slightly different steps. I run Unbuntu 17.04, for instance, so the commands that I would run in the terminal (which is the Command Prompt if you're from a Windows background) are:

```<code>curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
sudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg
</code>```

This will install Microsoft's secure key into your system and allow your system to install their packages.

```<code>sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-zesty-prod zesty main" > /etc/apt/sources.list.d/dotnetdev.list'
</code>```

This adds the package list for Microsoft's builds of .NET Core to the list of sources that your Ubuntu installation can install packages and application from. It's also the only step which appears to be different depending on which version of Ubuntu you are running.

```<code>sudo apt-get update
sudo apt-get install dotnet-sdk-2.0.2
</code>```

The first command here tells Ubuntu's package manager (apt-get) to update it's list of available packages (from the list we just updated).

The second command here is the important one, it's the one which installs the .NET Core SDK onto your computer.

Once this has completed (it might take a while), you can run commands like:

```<code>dotnet new console -o myApp
</code>```

Which will create a Console Application project called myApp in a directory called myApp.

From there you can open the project with any IDE which supports .NET Core. I'd recommend either Visual Studio Code with the C# extension by OmniSharp, or Rider by Jet Brains (there is a cost to this though, as it is not a free IDE).

Tiny bit of self promotion here, but  I've written about getting it all set up before, in case you're interested in reading about it - here is a link to it. It's from 2016, so some of the version numbers will have changed. But most of the information is the same.

Note to moderators, admins and community members

I do not mind at all, if the final paragraph of my answer is edited out. I just thought that it would be a useful resource to include. I'll leave it to the community to decide, but I wanted to be up front about it being self-promotion as it linked to a blog that I run. Apologies if this breaks the rules or guidelines.

Title: Installing .net core on ubuntu

Body:
Installing the .NET Core SDK and runtime on an ubuntu machine can be quite daunting if you don't have much experience with Linux distributions.

But the steps are outlined on the official .NET Core website (which is available here https://www.microsoft.com/net/learn/get-started/linuxubuntu) quite well, in my opinion.

side note: I know that a lot of Linux set up can be daunting and seem like a dark art to folks who are new to it.

Depending on which version of Ubuntu you have, you'll need to run slightly different steps. I run Unbuntu 17.04, for instance, so the commands that I would run in the terminal (which is the Command Prompt if you're from a Windows background) are:

curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
sudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg

This will install Microsoft's secure key into your system and allow your system to install their packages.

sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-zesty-prod zesty main" > /etc/apt/sources.list.d/dotnetdev.list'

This adds the package list for Microsoft's builds of .NET Core to the list of sources that your Ubuntu installation can install packages and application from. It's also the only step which appears to be different depending on which version of Ubuntu you are running.

sudo apt-get update
sudo apt-get install dotnet-sdk-2.0.2

The first command here tells Ubuntu's package manager (apt-get) to update it's list of available packages (from the list we just updated).

The second command here is the important one, it's the one which installs the .NET Core SDK onto your computer.

Once this has completed (it might take a while), you can run commands like:

dotnet new console -o myApp

Which will create a Console Application project called myApp in a directory called myApp.

From there you can open the project with any IDE which supports .NET Core. I'd recommend either Visual Studio Code with the C# extension by OmniSharp, or Rider by Jet Brains (there is a cost to this though, as it is not a free IDE).

Tiny bit of self promotion here, but  I've written about getting it all set up before, in case you're interested in reading about it - here is a link to it. It's from 2016, so some of the version numbers will have changed. But most of the information is the same.

Note to moderators, admins and community members

I do not mind at all, if the final paragraph of my answer is edited out. I just thought that it would be a useful resource to include. I'll leave it to the community to decide, but I wanted to be up front about it being self-promotion as it linked to a blog that I run. Apologies if this breaks the rules or guidelines.


问:
Automatic web-page refresh using xdotool - not sending key after window focus
Given:

I have Firefox with the [Firefox Page Title] page open on my Ubuntu computer.

Here is my command:

```<code>xdotool search "[Firefox Page Title]" windowactivate --sync key --clearmodifiers ctrl+r
</code>```

Documentation:

xdotool website with documentation/examples is here.

Example straight from the xdotool website:

```<code># As of version 2.20100623, you can do this simpler version of above:
xdotool search "Mozilla Firefox" windowactivate --sync key --clearmodifiers ctrl+l
</code>```

Notes:

I'm using xdotool version 2.20110530.1.

The command correctly focuses my screen to whatever window title I choose, but it doesn't send the ctrl+r key to the window, as the website doesn't refresh. I receive no error messages from the command. (Refresh shortcut in Firefox is ctrl+r)

Wanted Behavior:

The command will hopefully (when it works) be applied to a web server statistics page that is open 24/7 on my server computer, I'd like it to refresh the page automatically so I can view new traffic to my website without me having to do anything.

EDIT: I'm open to using other applications that can provide this functionality, if you know of something else that's easy/similar, please provide it as an answer! If I can't get this working I'll default to the next best thing.

答:
```<code>xdotool search --onlyvisible --classname Navigator windowactivate --sync key F5
</code>```

runing arch linux

Body:
Given:

I have Firefox with the [Firefox Page Title] page open on my Ubuntu computer.

Here is my command:

xdotool search "[Firefox Page Title]" windowactivate --sync key --clearmodifiers ctrl+r

Documentation:

xdotool website with documentation/examples is here.

Example straight from the xdotool website:

# As of version 2.20100623, you can do this simpler version of above:
xdotool search "Mozilla Firefox" windowactivate --sync key --clearmodifiers ctrl+l

Notes:

I'm using xdotool version 2.20110530.1.

The command correctly focuses my screen to whatever window title I choose, but it doesn't send the ctrl+r key to the window, as the website doesn't refresh. I receive no error messages from the command. (Refresh shortcut in Firefox is ctrl+r)

Wanted Behavior:

The command will hopefully (when it works) be applied to a web server statistics page that is open 24/7 on my server computer, I'd like it to refresh the page automatically so I can view new traffic to my website without me having to do anything.

EDIT: I'm open to using other applications that can provide this functionality, if you know of something else that's easy/similar, please provide it as an answer! If I can't get this working I'll default to the next best thing.

Body:
xdotool search --onlyvisible --classname Navigator windowactivate --sync key F5

runing arch linux


问:
Error Package file was not signed corrctly
I am trying to learn how to put apps out in the market and I made a quick JS-Light (Flashlight) app with Esclipe-IDE. I did and export of a signed package and uploaded to the market.  it downloads and then I get the following error

Error Package file was not signed corrctly

答:
If you've been testing your application on your phone, the application package on your phone has been signed with a different debug key, whereas the package you uploaded to the Market is signed with your own key.

In order for an application to be replaced with a new version of it, the keys have to match. An ordinary user will have no trouble downloading your app and installing it.

ContentLicense: CC BY-SA 2.5


问:
Oracle logs filled with "java.lang.Throwable: No Error"?
I have enabled JDBC logging for my Oracle connection. I would like the log to only contain the text of executed queries, but it is filled with the below error.

Any suggestions for what may be causing this trace, how I can fix it, and/or how I can limit my logging to the text of executed queries?

```<code>java.lang.Throwable: No Error
  at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1624)
  at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:4347)
  at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:4426)
  at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:4733)
  at sun.reflect.GeneratedMethodAccessor47.invoke(Unknown Source)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:606)
  at oracle.ucp.jdbc.proxy.PreparedStatementProxyFactory.invoke(PreparedStatementProxyFactory.java:125)
  at com.sun.proxy.$Proxy60.executeQuery(Unknown Source)
  at com.me.MyClass.doQuery(MyClass.java:56)
  at org.apache.jsp.jsp.secure.b2f.b2flogin_jsp._jspService(b2flogin_jsp.java:686)
  at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
  at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
  at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
  at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
  at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
  at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
  at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
  at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
  at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
  at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
  at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
  at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
  at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
  at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
  at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
  at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1539)
  at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1495)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
  at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
  at java.lang.Thread.run(Thread.java:745)
</code>```

My OraceLog.properties

```<code>oracle.jdbc.level=CONFIG
oracle.jdbc.handlers=java.util.logging.FileHandler
java.util.logging.FileHandler.level=CONFIG
java.util.logging.FileHandler.count=1
java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter

java.util.logging.FileHandler.pattern = /tmp/jdbc.log
</code>```

Edit

After using the JDBC logging a bit for debugging my applications, I have found the trace is useful, as it indicates code locations of SQL statements. And it can be easily filtered out with regex like:

tail -f /tmp/jdbc.log | grep -v 'java.lang.*\|.at.’

答:
This seems to be a known side-effect of tracing SQL statements (.level=CONFIG and finer).  It is discussed in the comments on  Enabling Oracle JDBC Driver Debug.  The last post there was in 2012.

There does not seem to be a way to disable the stack trace.

Body:
I have enabled JDBC logging for my Oracle connection. I would like the log to only contain the text of executed queries, but it is filled with the below error.

Any suggestions for what may be causing this trace, how I can fix it, and/or how I can limit my logging to the text of executed queries?

java.lang.Throwable: No Error
  at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1624)
  at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:4347)
  at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:4426)
  at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:4733)
  at sun.reflect.GeneratedMethodAccessor47.invoke(Unknown Source)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:606)
  at oracle.ucp.jdbc.proxy.PreparedStatementProxyFactory.invoke(PreparedStatementProxyFactory.java:125)
  at com.sun.proxy.$Proxy60.executeQuery(Unknown Source)
  at com.me.MyClass.doQuery(MyClass.java:56)
  at org.apache.jsp.jsp.secure.b2f.b2flogin_jsp._jspService(b2flogin_jsp.java:686)
  at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
  at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
  at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
  at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
  at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
  at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
  at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
  at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
  at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
  at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
  at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
  at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
  at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
  at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
  at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
  at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1539)
  at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1495)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
  at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
  at java.lang.Thread.run(Thread.java:745)

My OraceLog.properties

oracle.jdbc.level=CONFIG
oracle.jdbc.handlers=java.util.logging.FileHandler
java.util.logging.FileHandler.level=CONFIG
java.util.logging.FileHandler.count=1
java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter

java.util.logging.FileHandler.pattern = /tmp/jdbc.log

Edit

After using the JDBC logging a bit for debugging my applications, I have found the trace is useful, as it indicates code locations of SQL statements. And it can be easily filtered out with regex like:

tail -f /tmp/jdbc.log | grep -v 'java.lang.*\|.at.’


问:
Javascript: Changing "document.body.onresize" does not take hold without "console.log"
I'm writing a website with a canvas in it. The website has a script that runs successfully on every refresh except for a line at the end. When the script ends with:

```<code>document.body.onresize = function() {viewport.resizeCanvas()}
</code>```

"document.body.onresize" is unchanged. (I double-checked in Chrome's javascript console: Entering "document.body.onresize" returns "undefined".)

However, when the script ends with:

```<code>document.body.onresize = function() {viewport.resizeCanvas()}
console.log(document.body.onresize)
</code>```

"document.body.onresize" does change. The function works exactly as it should.

I can't explain why these two functionally identical pieces of code have different results. Can anyone help?

Edit: As far as I can tell, "document.body" is referring to the correct "document.body". When I call console.log(document.body) just before I assign document.body.onresize, the correct HTML is printed.

Edit 2: A solution (sort of)

When I substituted "window" for "document" the viewport's "resizeCanvas" function was called without fail every time I resized the window.

Why does "window" work while "document" only works if you call "console.log" first? Not a clue.

答:
```<code><script>
    function body_OnResize() {
      alert('resize');
    }
</script>

<body onresize="body_OnResize()"></body>
</code>```

Body:
I'm writing a website with a canvas in it. The website has a script that runs successfully on every refresh except for a line at the end. When the script ends with:

document.body.onresize = function() {viewport.resizeCanvas()}

"document.body.onresize" is unchanged. (I double-checked in Chrome's javascript console: Entering "document.body.onresize" returns "undefined".)

However, when the script ends with:

document.body.onresize = function() {viewport.resizeCanvas()}
console.log(document.body.onresize)

"document.body.onresize" does change. The function works exactly as it should.

I can't explain why these two functionally identical pieces of code have different results. Can anyone help?

Edit: As far as I can tell, "document.body" is referring to the correct "document.body". When I call console.log(document.body) just before I assign document.body.onresize, the correct HTML is printed.

Edit 2: A solution (sort of)

When I substituted "window" for "document" the viewport's "resizeCanvas" function was called without fail every time I resized the window.

Why does "window" work while "document" only works if you call "console.log" first? Not a clue.


问:
ArangoDB AQL FILTER graph for matching edge attributes
I have one words collection and one word_relations edge collection. Words have relationships to other words, like synonym, hasPart, partOf, hasType, typeOf, etc.

I am trying to figure out how to FILTER an AQL graph query so that all paths are followed, but paths with more than one edge contain identical edge attribute of relation_type.

E.g., I want this result (all returned paths, whether one or many, contain a single relation_type attribute value):

```<code>[
  {
    "edges": [
      {
        "_from": "library/parent",
        "_to": "library/organism",
        "relation_type": "typeOf"
      }
    ],
    "vertices": [
      {
        "_key": "parent",
        "word": "parent"
      },
      {
        "_key": "organism",
        "word": "organism"
      }
    ]
  },
  {
    "edges": [
      {
        "_from": "library/parent",
        "_to": "library/organism",
        "relation_type": "typeOf"
      },
      {
        "_from": "library/organism",
        "_to": "library/scheme",
        "relation_type": "typeOf"
      }
    ],
    "vertices": [
      {
        "_key": "parent",
        "word": "parent"
      },
      {
        "_key": "organism",
        "word": "organism"
      },
      {
        "_key": "scheme",
        "word": "scheme"
      }
    ]
  },
  {
    "edges": [
      {
        "_from": "library/parent",
        "_to": "library/stepparent",
        "relation_type": "hasType"
      },
      {
        "_from": "library/stepparent",
        "_to": "library/stepmother",
        "relation_type": "hasType"
      }
    ],
    "vertices": [
      {
        "_key": "parent",
        "word": "parent"
      },
      {
        "_key": "stepparent",
        "word": "stepparent"
      },
      {
        "_key": "stepmother",
        "word": "stepmother"
      }
    ]
  }
]
</code>```

NOT this result (the relation_type attribute value changes within one path):

```<code>[
  {
    "edges": [
      {
        "_from": "library/parent",
        "_to": "library/organism",
        "relation_type": "typeOf"
      }
    ],
    "vertices": [
      {
        "_key": "parent",
        "word": "parent"
      },
      {
        "_key": "organism",
        "word": "organism"
      }
    ]
  },
  {
    "edges": [
      {
        "_from": "library/parent",
        "_to": "library/organism",
        "relation_type": "typeOf"
      },
      {
        "_from": "library/organism",
        "_to": "library/zygote",
        "relation_type": "hasCategories"
      }
    ],
    "vertices": [
      {
        "_key": "parent",
        "word": "parent"
      },
      {
        "_key": "organism",
        "word": "organism"
      },
      {
        "_key": "zygote",
        "word": "zygote"
      }
    ]
  },
  {
    "edges": [
      {
        "_from": "library/parent",
        "_to": "library/family_unit",
        "relation_type": "memberOf"
      },
      {
        "_from": "library/family_unit",
        "_to": "library/sibling",
        "relation_type": "hasMembers"
      }
    ],
    "vertices": [
      {
        "_key": "parent",
        "word": "parent"
      },
      {
        "_key": "family_unit",
        "word": "family unit"
      },
      {
        "_key": "sibling",
        "word": "sibling"
      }
    ]
  },
]
</code>```

There are many different kinds of relation_type attribute values. I do not want to filter to a specific value, I don't care what the initial value is, I just want all follow-on attribute values to be the same as the first.

The AQL to get the second (undesirable) result looks like:

```<code>FOR v, e, p IN 1..2 OUTBOUND 'words/parent' word_relations
  RETURN p
</code>```

I have tried a few different filters, none of which work:

0 results:

```<code>FOR v, e, p IN 1..2 OUTBOUND 'library/parent' library_relations
  FILTER p.edges[*].relation_type ALL == p.edges[*].relation_type
  RETURN p
</code>```

Only returns 2 paths, b/c the FILTER requires the second to exist:

```<code>FOR v, e, p IN 1..2 OUTBOUND 'library/parent' library_relations
  FILTER p.edges[0].relation_type == p.edges[1].relation_type
  RETURN p
</code>```

Thanks for your help!

答:
The following could be used for larger values of MAX as well:

```<code>FOR v, e, p IN 1..2 OUTBOUND 'library/parent' library_relations
  FILTER p.edges[*].relation_type ALL == e.relation_type
  RETURN p
</code>```

Unfortunately, the AQL optimizer is tragically impaired at the moment (see https://github.com/arangodb/arangodb/issues/3979#issuecomment-350686061), so most likely you would have to work around its limitation, e.g. by prepending the above with:

```<code>FOR tmpV, tmpE  IN 1..1 OUTBOUND 'library/parent’ library_relations
</code>```

and then using tmpE.relation_type instead of e.relation_type.

Body:
I have one words collection and one word_relations edge collection. Words have relationships to other words, like synonym, hasPart, partOf, hasType, typeOf, etc.

I am trying to figure out how to FILTER an AQL graph query so that all paths are followed, but paths with more than one edge contain identical edge attribute of relation_type.

E.g., I want this result (all returned paths, whether one or many, contain a single relation_type attribute value):

[
  {
    "edges": [
      {
        "_from": "library/parent",
        "_to": "library/organism",
        "relation_type": "typeOf"
      }
    ],
    "vertices": [
      {
        "_key": "parent",
        "word": "parent"
      },
      {
        "_key": "organism",
        "word": "organism"
      }
    ]
  },
  {
    "edges": [
      {
        "_from": "library/parent",
        "_to": "library/organism",
        "relation_type": "typeOf"
      },
      {
        "_from": "library/organism",
        "_to": "library/scheme",
        "relation_type": "typeOf"
      }
    ],
    "vertices": [
      {
        "_key": "parent",
        "word": "parent"
      },
      {
        "_key": "organism",
        "word": "organism"
      },
      {
        "_key": "scheme",
        "word": "scheme"
      }
    ]
  },
  {
    "edges": [
      {
        "_from": "library/parent",
        "_to": "library/stepparent",
        "relation_type": "hasType"
      },
      {
        "_from": "library/stepparent",
        "_to": "library/stepmother",
        "relation_type": "hasType"
      }
    ],
    "vertices": [
      {
        "_key": "parent",
        "word": "parent"
      },
      {
        "_key": "stepparent",
        "word": "stepparent"
      },
      {
        "_key": "stepmother",
        "word": "stepmother"
      }
    ]
  }
]

NOT this result (the relation_type attribute value changes within one path):

[
  {
    "edges": [
      {
        "_from": "library/parent",
        "_to": "library/organism",
        "relation_type": "typeOf"
      }
    ],
    "vertices": [
      {
        "_key": "parent",
        "word": "parent"
      },
      {
        "_key": "organism",
        "word": "organism"
      }
    ]
  },
  {
    "edges": [
      {
        "_from": "library/parent",
        "_to": "library/organism",
        "relation_type": "typeOf"
      },
      {
        "_from": "library/organism",
        "_to": "library/zygote",
        "relation_type": "hasCategories"
      }
    ],
    "vertices": [
      {
        "_key": "parent",
        "word": "parent"
      },
      {
        "_key": "organism",
        "word": "organism"
      },
      {
        "_key": "zygote",
        "word": "zygote"
      }
    ]
  },
  {
    "edges": [
      {
        "_from": "library/parent",
        "_to": "library/family_unit",
        "relation_type": "memberOf"
      },
      {
        "_from": "library/family_unit",
        "_to": "library/sibling",
        "relation_type": "hasMembers"
      }
    ],
    "vertices": [
      {
        "_key": "parent",
        "word": "parent"
      },
      {
        "_key": "family_unit",
        "word": "family unit"
      },
      {
        "_key": "sibling",
        "word": "sibling"
      }
    ]
  },
]

There are many different kinds of relation_type attribute values. I do not want to filter to a specific value, I don't care what the initial value is, I just want all follow-on attribute values to be the same as the first.

The AQL to get the second (undesirable) result looks like:

FOR v, e, p IN 1..2 OUTBOUND 'words/parent' word_relations
  RETURN p

I have tried a few different filters, none of which work:

0 results:

FOR v, e, p IN 1..2 OUTBOUND 'library/parent' library_relations
  FILTER p.edges[*].relation_type ALL == p.edges[*].relation_type
  RETURN p

Only returns 2 paths, b/c the FILTER requires the second to exist:

FOR v, e, p IN 1..2 OUTBOUND 'library/parent' library_relations
  FILTER p.edges[0].relation_type == p.edges[1].relation_type
  RETURN p

Thanks for your help!

Body:
The following could be used for larger values of MAX as well:

FOR v, e, p IN 1..2 OUTBOUND 'library/parent' library_relations
  FILTER p.edges[*].relation_type ALL == e.relation_type
  RETURN p

Unfortunately, the AQL optimizer is tragically impaired at the moment (see https://github.com/arangodb/arangodb/issues/3979#issuecomment-350686061), so most likely you would have to work around its limitation, e.g. by prepending the above with:

FOR tmpV, tmpE  IN 1..1 OUTBOUND 'library/parent’ library_relations

and then using tmpE.relation_type instead of e.relation_type.


问:
ArrayIndexOufOfBoundsException
Hello I wanted to create a multiple quiz app, but when the app is at the last question, it stops suddenly. I want it to show a dialog where it counts the final score, then go back to main.

This is the error

```<code>12-07 22:38:17.997 29516-29516/com.example.ancaalexandra.proiectandroidd E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.ancaalexandra.proiectandroidd, PID: 29516
                                                                                java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
                                                                                at com.example.ancaalexandra.proiectandroidd.QuestionsBD.getQuestion(QuestionsBD.java:27)
                                                                                at com.example.ancaalexandra.proiectandroidd.BazeDeDate1Activity.updateQuestion(BazeDeDate1Activity.java:150)
                                                                                at com.example.ancaalexandra.proiectandroidd.BazeDeDate1Activity.access$400(BazeDeDate1Activity.java:19)
                                                                                at com.example.ancaalexandra.proiectandroidd.BazeDeDate1Activity$1.onClick(BazeDeDate1Activity.java:78)
                                                                                at android.view.View.performClick(View.java:6261)
                                                                                at android.widget.TextView.performClick(TextView.java:11185)
                                                                                at android.view.View$PerformClick.run(View.java:23752)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
</code>```

This is QuestionsBD class, where i create the questions and their answers:

```<code>class QuestionsBD {

private String bdquestions[]= {
        "Componenta de date dintr-un SBD poate contine: ",
        "In arhitectura unui SBD pe niveluri, viziunea programatorului corespunde: ",
        "Arhitectura pe componente a unui sistem de  baze de date contine:"};

private String bdChoices[][]={
        {"Sistemul de operare","Sistemul de coduri","Dictionarul distribuit","Fisierele anexe"},
        {"Nivelul fizic","Nivelul SO","Nivelul logic","Nivelul SGBD"},
        {"Datele","Fisierele","Software-ul de comunicatie","Programe de comunicatie"}
};

private String bdCorrectAns[]={"Fisierele anexe", "Nivelul logic","Datele"};

public String getQuestion(int a)
{
    String question= bdquestions[a];
    return question;
}

public String getChoice0(int a)
{
    String choice0=bdChoices[a][0];
    return choice0;
}

public String getChoice1(int a)
{
    String choice1=bdChoices[a][1];
    return choice1;
}

public String getChoice2(int a)
{
    String choice2=bdChoices[a][2];
    return choice2;
}

public String getChoice3(int a)
{
    String choice3=bdChoices[a][3];
    return choice3;
}

public String getCorrectAnswer(int a)
{
    String answer=bdCorrectAns[a];
    return answer;
}

public int getNrQuestions()
{
    int nrquestions=bdquestions.length;
    return nrquestions;
    }
}
</code>```

And this is the activity where are shown the questions:

```<code>public class BazeDeDate1Activity  extends AppCompatActivity implements View.OnClickListener {

    private QuestionsBD questBd = new QuestionsBD();

    private TextView scoreTW;
    private TextView questionsTW;
    private Button choice0;
    private Button choice1;
    private Button choice2;
    private Button choice3;
    private Button choiceQuit;
    private ImageView numberPhoto;

    private String answer;
    private int scoreInit = 0;
    private int questionNumber = 0;
    private String quit = "quit";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_baze_de_date1);

        View v = findViewById(R.id.buttonBD1quit);
        v.setOnClickListener(this);

        /*AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Scor final: " + scoreInit);
        builder.setTitle("Felicitari!!");

        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int idok) {

            }
        });

        AlertDialog dialog = builder.create();
*/
        scoreTW = (TextView) findViewById(R.id.textViewScorObtinut);
        questionsTW = (TextView) findViewById(R.id.textViewIntrebare1BD);
        choice0 = (Button) findViewById(R.id.buttonBD1r1);
        choice1 = (Button) findViewById(R.id.buttonBD1r2);
        choice2 = (Button) findViewById(R.id.buttonBD1r3);
        choice3 = (Button) findViewById(R.id.buttonBD1r4);
        choiceQuit = (Button) findViewById(R.id.buttonBD1quit);
        numberPhoto = (ImageView) findViewById(R.id.imageViewONE);

        //updateQuestion();

        choice0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (choice0.getText() == answer) {
                    scoreInit = scoreInit + 1;
                    updateScore(scoreInit);
                    Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show();

                    updateQuestion();

                } else {
                    Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show();

                        updateQuestion();

                }
            }
        });

        choice1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (choice1.getText() == answer) {
                    scoreInit = scoreInit + 1;
                    updateScore(scoreInit);
                    Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show();
                        updateQuestion();

                } else {
                    Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show();
                    updateQuestion();
                }

            }
        });

        choice2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (choice2.getText() == answer) {
                    scoreInit = scoreInit + 1;
                    updateScore(scoreInit);
                    Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show();

                } else {
                    Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show();

                }
            }
        });

        choice3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (choice3.getText() == answer) {
                    scoreInit = scoreInit + 1;
                    updateScore(scoreInit);
                    Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show();

                } else {
                    Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show();

                }
            }
        });

    }

    private void updateQuestion()
    {
        questionsTW.setText(questBd.getQuestion(questionNumber));
        choice0.setText(questBd.getChoice0(questionNumber));
        choice1.setText(questBd.getChoice1(questionNumber));
        choice2.setText(questBd.getChoice2(questionNumber));

        answer=questBd.getCorrectAnswer(questionNumber);
        questionNumber++;
    }

    private void updateScore(int point)
    {
        scoreTW.setText(""+scoreInit);
    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.buttonBD1quit)
        {
            Intent intent=new Intent(this,BeginActivity.class);
            this.startActivity(intent);
        }
    }
}
</code>```

答:
You are calling String getQuestion(int a) with a value of 3 when 3 is the hardcoded size of the bdquestions array. There are multiple ways this could be solved but the fundamental issue is your application design, using hardcoded datasets and a codebase that has an expectation of the hardcoded data being there. You can check if the number is < 3 but that will just hide the problem instead of fixing it.

For starters, you should have a data type for your questions/answers:

```<code>public class Question {

    public Question(String question, int answerIndex, String... answers) {
        this.question = question;
        this.correctAnswerIndex = answerIndex;
        this.answers.addAll(Arrays.asList(answers));
    }

    private String question;

    private List<String> answers = new ArrayList<>();

    private int correctAnswerIndex = 0;

    private String getQuestion() {
        return question;
    }

    private List<String> getAnswers() {
        return answers;
    }

    private String getCorrectAnswer() {
        if(answers.size() > correctAnswerIndex) {
            return answers.get(correctAnswerIndex);
        }
        return null;
    }
}
</code>```

From there, you can access it directly (and safely) by iterating through the possible answers with a for loop, getting the answer in a non-hardcoded fashion, and so forth. The biggest part of making an application that is protected against crashes or undefined behavior is designing it carefully so that error states are difficult to create.

Title: ArrayIndexOufOfBoundsException

Body:
Hello I wanted to create a multiple quiz app, but when the app is at the last question, it stops suddenly. I want it to show a dialog where it counts the final score, then go back to main.

This is the error

12-07 22:38:17.997 29516-29516/com.example.ancaalexandra.proiectandroidd E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.ancaalexandra.proiectandroidd, PID: 29516
                                                                                java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
                                                                                at com.example.ancaalexandra.proiectandroidd.QuestionsBD.getQuestion(QuestionsBD.java:27)
                                                                                at com.example.ancaalexandra.proiectandroidd.BazeDeDate1Activity.updateQuestion(BazeDeDate1Activity.java:150)
                                                                                at com.example.ancaalexandra.proiectandroidd.BazeDeDate1Activity.access$400(BazeDeDate1Activity.java:19)
                                                                                at com.example.ancaalexandra.proiectandroidd.BazeDeDate1Activity$1.onClick(BazeDeDate1Activity.java:78)
                                                                                at android.view.View.performClick(View.java:6261)
                                                                                at android.widget.TextView.performClick(TextView.java:11185)
                                                                                at android.view.View$PerformClick.run(View.java:23752)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

This is QuestionsBD class, where i create the questions and their answers:

class QuestionsBD {

private String bdquestions[]= {
        "Componenta de date dintr-un SBD poate contine: ",
        "In arhitectura unui SBD pe niveluri, viziunea programatorului corespunde: ",
        "Arhitectura pe componente a unui sistem de  baze de date contine:"};

private String bdChoices[][]={
        {"Sistemul de operare","Sistemul de coduri","Dictionarul distribuit","Fisierele anexe"},
        {"Nivelul fizic","Nivelul SO","Nivelul logic","Nivelul SGBD"},
        {"Datele","Fisierele","Software-ul de comunicatie","Programe de comunicatie"}
};

private String bdCorrectAns[]={"Fisierele anexe", "Nivelul logic","Datele"};

public String getQuestion(int a)
{
    String question= bdquestions[a];
    return question;
}

public String getChoice0(int a)
{
    String choice0=bdChoices[a][0];
    return choice0;
}

public String getChoice1(int a)
{
    String choice1=bdChoices[a][1];
    return choice1;
}

public String getChoice2(int a)
{
    String choice2=bdChoices[a][2];
    return choice2;
}

public String getChoice3(int a)
{
    String choice3=bdChoices[a][3];
    return choice3;
}

public String getCorrectAnswer(int a)
{
    String answer=bdCorrectAns[a];
    return answer;
}

public int getNrQuestions()
{
    int nrquestions=bdquestions.length;
    return nrquestions;
    }
}

And this is the activity where are shown the questions:

public class BazeDeDate1Activity  extends AppCompatActivity implements View.OnClickListener {

    private QuestionsBD questBd = new QuestionsBD();

    private TextView scoreTW;
    private TextView questionsTW;
    private Button choice0;
    private Button choice1;
    private Button choice2;
    private Button choice3;
    private Button choiceQuit;
    private ImageView numberPhoto;

    private String answer;
    private int scoreInit = 0;
    private int questionNumber = 0;
    private String quit = "quit";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_baze_de_date1);

        View v = findViewById(R.id.buttonBD1quit);
        v.setOnClickListener(this);

        /*AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Scor final: " + scoreInit);
        builder.setTitle("Felicitari!!");

        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int idok) {

            }
        });

        AlertDialog dialog = builder.create();
*/
        scoreTW = (TextView) findViewById(R.id.textViewScorObtinut);
        questionsTW = (TextView) findViewById(R.id.textViewIntrebare1BD);
        choice0 = (Button) findViewById(R.id.buttonBD1r1);
        choice1 = (Button) findViewById(R.id.buttonBD1r2);
        choice2 = (Button) findViewById(R.id.buttonBD1r3);
        choice3 = (Button) findViewById(R.id.buttonBD1r4);
        choiceQuit = (Button) findViewById(R.id.buttonBD1quit);
        numberPhoto = (ImageView) findViewById(R.id.imageViewONE);

        //updateQuestion();

        choice0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (choice0.getText() == answer) {
                    scoreInit = scoreInit + 1;
                    updateScore(scoreInit);
                    Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show();

                    updateQuestion();

                } else {
                    Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show();

                        updateQuestion();

                }
            }
        });

        choice1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (choice1.getText() == answer) {
                    scoreInit = scoreInit + 1;
                    updateScore(scoreInit);
                    Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show();
                        updateQuestion();

                } else {
                    Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show();
                    updateQuestion();
                }

            }
        });

        choice2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (choice2.getText() == answer) {
                    scoreInit = scoreInit + 1;
                    updateScore(scoreInit);
                    Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show();

                } else {
                    Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show();

                }
            }
        });

        choice3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (choice3.getText() == answer) {
                    scoreInit = scoreInit + 1;
                    updateScore(scoreInit);
                    Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show();

                } else {
                    Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show();

                }
            }
        });

    }

    private void updateQuestion()
    {
        questionsTW.setText(questBd.getQuestion(questionNumber));
        choice0.setText(questBd.getChoice0(questionNumber));
        choice1.setText(questBd.getChoice1(questionNumber));
        choice2.setText(questBd.getChoice2(questionNumber));

        answer=questBd.getCorrectAnswer(questionNumber);
        questionNumber++;
    }

    private void updateScore(int point)
    {
        scoreTW.setText(""+scoreInit);
    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.buttonBD1quit)
        {
            Intent intent=new Intent(this,BeginActivity.class);
            this.startActivity(intent);
        }
    }
}

Body:
You are calling String getQuestion(int a) with a value of 3 when 3 is the hardcoded size of the bdquestions array. There are multiple ways this could be solved but the fundamental issue is your application design, using hardcoded datasets and a codebase that has an expectation of the hardcoded data being there. You can check if the number is < 3 but that will just hide the problem instead of fixing it.

For starters, you should have a data type for your questions/answers:

public class Question {

    public Question(String question, int answerIndex, String... answers) {
        this.question = question;
        this.correctAnswerIndex = answerIndex;
        this.answers.addAll(Arrays.asList(answers));
    }

    private String question;

    private List<String> answers = new ArrayList<>();

    private int correctAnswerIndex = 0;

    private String getQuestion() {
        return question;
    }

    private List<String> getAnswers() {
        return answers;
    }

    private String getCorrectAnswer() {
        if(answers.size() > correctAnswerIndex) {
            return answers.get(correctAnswerIndex);
        }
        return null;
    }
}

From there, you can access it directly (and safely) by iterating through the possible answers with a for loop, getting the answer in a non-hardcoded fashion, and so forth. The biggest part of making an application that is protected against crashes or undefined behavior is designing it carefully so that error states are difficult to create.


问:
How can I display progress bar as table row background?
I have a table like this:

```<code>th1    th2    th3    th4    th5    th6
td1    td2    td3    td4    td5    td6
td1    td2    td3    td4    td5    td6
</code>```

New table rows are added with a form above that runs a background process to calculate all the data in each td. The process can take 10-60 seconds.

Rather than a separate column that displays progress, I'd like to shade the background of the entire tr as it corresponds to the % completion of the calculation process.

For example:

```<code>th1    th2    th3    th4    th5    th6
$ 1    $ 2    $ 3    $ 4    $ 5    $ 6   [100% done, 100% of row shaded light green]
$ -    $ -    $ -    $ -    $ -    $ -   [ 40% done,  40% of row shaded light green]
</code>```

Background only:

```<code>th1    th2    th3    th4    th5    th6
||||||||||||||||||||||||||||||||||||||   [100% done, 100% of row shaded light green]
|||||||||||||||                          [ 40% done,  40% of row shaded light green]
|||||||||                                [ 25% done,  25% of row shaded light green]
||||                                     [ 10% done,  10% of row shaded light green]
</code>```

What do you recommend?

Here's some general markup:

```<code><table>
    <thead>
        <tr><th>th1</th><th>th2</th><th>th3</th><th>th4</th><th>th5</th><th>th6</th></tr>
    </thead>
    <tbody>
        <tr data-progress="100"><td>$1</td><td>$2</td><td>$3</td><td>$4</td><td>$5</td><td>$6</td></tr>
        <tr data-progress="40"><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>
        <tr data-progress="25"><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>
        <tr data-progress="10"><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>
    </tbody>
</table>
</code>```

答:
In case anyone is still looking for an elegant solution, you can style your tr. For a progress bar of 40%, I'd use:

Example: https://codepen.io/drspa44/pen/rYEzWj

Body:
I have a table like this:

th1    th2    th3    th4    th5    th6
td1    td2    td3    td4    td5    td6
td1    td2    td3    td4    td5    td6

New table rows are added with a form above that runs a background process to calculate all the data in each td. The process can take 10-60 seconds.

Rather than a separate column that displays progress, I'd like to shade the background of the entire tr as it corresponds to the % completion of the calculation process.

For example:

th1    th2    th3    th4    th5    th6
$ 1    $ 2    $ 3    $ 4    $ 5    $ 6   [100% done, 100% of row shaded light green]
$ -    $ -    $ -    $ -    $ -    $ -   [ 40% done,  40% of row shaded light green]

Background only:

th1    th2    th3    th4    th5    th6
||||||||||||||||||||||||||||||||||||||   [100% done, 100% of row shaded light green]
|||||||||||||||                          [ 40% done,  40% of row shaded light green]
|||||||||                                [ 25% done,  25% of row shaded light green]
||||                                     [ 10% done,  10% of row shaded light green]

What do you recommend?

Here's some general markup:

th1	th2	th3	th4	th5	th6

$1	$2	$3	$4	$5	$6

-	-	-	-	-	-

-	-	-	-	-	-

-	-	-	-	-	-

Body:
In case anyone is still looking for an elegant solution, you can style your tr. For a progress bar of 40%, I'd use:

<tr style="background-image: linear-gradient(to right,lightgrey 40%,white 40%)">

Example: https://codepen.io/drspa44/pen/rYEzWj


问:
2 Dimensional Arrays.Why do I have to declare size of Columns in C
I want to ask a question about 2D arrays in C .First Let me explain what I want to do.

I am trying to read names into a 2D array till user enters 0 and from that array I want to randomly pick an name. Now I have couple of questions.

Why do I have to declare the size of arr? I want to do it like char arr[][50] the reason that am asking this is because I took a semester of C before my current semester and I remember my tutor said something like you don't have to declare size of column as long as you declare a row size.

```<code>#include <stdio.h>

void main(){
    char arr[50][50];
    int i;
    for(i= 0 ; i < 50; i++){
        scanf("%s",&arr[i]);
    }
}
</code>```

I just found that I was missing braces after if inside for code gives no error at the moment but entering 0 from the keyboard does not executes the proccess.

```<code>#include <stdio.h>

void main(){
    char arr[0][50];
    int i;
    for(i= 0 ; i < 50; i++){
        scanf("%49s", arr[i]);
        if(arr[i]== 0){
            arr[i][0] = '\0';
            break;}

    }
}
</code>```

Also I want to read names in a function but couldn't figure out how to pass the arr[50][50] to a function So I can read names in that function.

I am trying to work with ANSI C

答:
When you create something in a program, you need to know how big it is. The computer has to decide what memory it is going to store the thing in, so it has to know how much memory it needs. So, when you define an array, you must include all the sizes. So, in char arr[50][50];, both of the dimension lengths are needed.

When you pass an array to a function, the function does not always need to know how big the array is. It only needs to know where the array is and where its parts are. Once you tell the function where the array is and what the parts are, the function has the information it needs (because it can calculate how big each part is from knowing what type they are).

In C, we could have said, when you pass an array to a function, declare the type (so the function understands the parts the array is made of) and pass the address of the array. Instead, they did something slightly different. They decided, when you pass an array to a function, you declare the type and pass the address of the first element. (On a lot of computer processors, these two addresses are the same thing at the machine language level. But there can be differences.)

So, when you pass this array arr to a function, you are supposed to pass &arr[0], which is the address of the first element of arr. (Note that arr is an array of 50 arrays of 50 char. So its elements are arrays of 50 char. In contrast, &arr[0][0] is the address of the first element of the first element of arr.)

That would work fine. Everybody could pass &arr[0] or whatever the first element of their array is. But the creators of C decided to make it look simpler and to look like you were passing the array. They made a rule that if you use arr in a typical expression, the compiler would automatically convert it to &arr[0] for you. So you can write MyFunction(arr), and it is just like you wrote MyFunction(&arr[0]).

Next, what does the array look like in the function declaration? Since you are passing a pointer to the first element of the array, you ought to declare that as char (*arr)[50], which is a pointer to an array of 50 char. However, again, the creators of C wanted to make this look better, so they said, in a function declaration, you can declare a parameter as char arr[50][50], and the compiler will automatically adjust it to be char (*arr)[50]. Whenever you declare a function parameter to be an array, the compiler automatically adjusts the declared type to be a pointer to an element. (This adjustment only occurs for the first dimension.)

So, when you pass an array to a function, the function actually receives a pointer to the first element. Then, if it ever wants to find the element with index n, all it has to do is add the size of n elements to the address of the first element. So the function has all the information it needs to locate array elements. It does not need to know the total size. If you write arr[3][4] in the function, the function starts with the address you passed. Then it calculates where element 3 is, which is 3 times the size of an element. An element of arr is an array of 50 char, so its size is 50. So arr[3] is at the start address plus 150 bytes. Then it calculates where element 4 of that array is, which is 4 times the size of an element. An element of arr[3] is a char, so its size is 1. So arr[3][4] is at the start address plus 150 bytes plus 4 bytes.

Since a function does not actually need to know the total size of the array, you are allowed to declare a function parameter with char arr[][50], leaving out the length of the first dimension. The compiler would just discard that length anyway when it adjusts the parameter to char (*)[50].

Body:
I want to ask a question about 2D arrays in C .First Let me explain what I want to do.

I am trying to read names into a 2D array till user enters 0 and from that array I want to randomly pick an name. Now I have couple of questions.

Why do I have to declare the size of arr? I want to do it like char arr[][50] the reason that am asking this is because I took a semester of C before my current semester and I remember my tutor said something like you don't have to declare size of column as long as you declare a row size.

#include <stdio.h>

void main(){
    char arr[50][50];
    int i;
    for(i= 0 ; i < 50; i++){
        scanf("%s",&arr[i]);
    }
}

I just found that I was missing braces after if inside for code gives no error at the moment but entering 0 from the keyboard does not executes the proccess.

#include <stdio.h>

void main(){
    char arr[0][50];
    int i;
    for(i= 0 ; i < 50; i++){
        scanf("%49s", arr[i]);
        if(arr[i]== 0){
            arr[i][0] = '\0';
            break;}

    }
}

Also I want to read names in a function but couldn't figure out how to pass the arr[50][50] to a function So I can read names in that function.

I am trying to work with ANSI C


问:
How install and use library android
I would like to use librares in android studio I import module and I don't know what to do later.
There's librares https://github.com/feicien/android-auto-update
https://github.com/mitmel/AppUpdateChecker

How make this working ? Instructions there are a bit weak.

答:
This is a very popular question, you could easily find an answer to this everywhere, for instance:

How do I add a library project to Android Studio?

Adding external library in Android studio

Long story short:

Try this:

File > Project Structure > Dependencies Tab > Add module dependency (scope = compile)

Where the module dependency is the project library android folder

Title: How install and use library android


问:
delete doesn't free memory at the end of a function
I'm nearing my wits end with this. I have searched for hours for a solution to this, but I haven't found something that solves my problem.

So I want to code a neuronal network and I have written extensive code for it and which I have checked and debugged so far. I tried evolving my network over multiple generations but although it does execute it gives me a double free or corruption error. I have traced the error with valgrind to this function

```<code>bool mutate_a_neuron(Neuron* neuron, int numberofneurons, int numberofinputs){

    int num_e = 3*NUM_I+3;
    bool* element_already_mutated = new bool[num_e];  //line 91
    //bool element_already_mutated[15]; //Workaround :(
    for(int i =0; i<num_e; i++){
        element_already_mutated[i]=false;
    }

    int number_of_elements = (int) neuron->numberofelementstomutate;
    unsigned short will_it_be_mutated = rand() % USHRT_MAX ;

    if(  neuron->mutationrate > will_it_be_mutated ){

        for(int i = 0; i<number_of_elements; i++){

            int elementtomutate = rand() % num_e;   //choose random element
            if(element_already_mutated[elementtomutate]){//check if mutated
                i--;
                continue;
            }

            if( mutate_element(neuron, elementtomutate, numberofneurons, numberofinputs) ){//mutate stuff
                element_already_mutated[elementtomutate]=true;
            } else {
                printf("Something went wrong while mutating an element or takes_input was false\n"); //die if error
            }
        }

        return true;
    }

    delete [] element_already_mutated; //line 120

    return false;
}
</code>```

Valgrind gives me a mismatched free()/delete/delete[] error at where element_already_mutated gets initialized and free'd. The funky thing is, if I comment the dynamic allocation out and just initialize my "workaround" which is just a normal static array, I get no memory leaks and everything gets deallocated correctly. NUM_I is defined as 4 in the header as:

```<code>#define NUM_I 4
</code>```

Valgrind error:

```<code>==1887== 15,023,190 bytes in 1,001,546 blocks are definitely lost in loss record 1 of 1
==1887==    at 0x4C2C93F: operator new[](unsigned long) (vg_replace_malloc.c:423)
==1887==    by 0x10A461: mutate_a_neuron(Neuron*, int, int) (n.cpp:91)
==1887==    (here follow more functions, which call mutate_a_neuron)
</code>```

Can someone tell me what I'm doing wrong? I don't think I'm deallocating incorrectly but I have no idea where the error might be otherwise.

答:
Given the function you did show, the simplest way to avoid the memory leak (if this function is indeed the only one leaking memory) is to use std::vector.

```<code>#include <vector>

bool mutate_a_neuron(Neuron* neuron, int numberofneurons, int numberofinputs){
    int num_e = 3*NUM_I+3;
    std::vector<bool> element_already_mutated(num_e);
    int number_of_elements = (int) neuron->numberofelementstomutate;
    unsigned short will_it_be_mutated = rand() % USHRT_MAX ;
    //...
    // rest of your code
    //
    // delete [] element_already_mutated is no longer needed
    return false;
}
</code>```

1) The initialization of the vector elements to false is automatically done on construction of the vector, thus the for loop that initialized the boolean array to false is no longer needed.

2) The call to delete [] element_already_mutated; must be removed, since element_already_mutated is no longer a pointer.  In addition, vector will automatically deallocate memory it has allocated, thus another reason to remove the delete [].

3) The return true; statement you had no longer will cause an issue, since if the mutate_a_neuron function returns for any reason, the vector<bool> will be destroyed, thus removing any chance of a memory leak.

4) Since the code that uses vector makes accesses using [], the rest of the code does not need to be changed, since std::vector overloads operator [] to act as an array.

Body:
I'm nearing my wits end with this. I have searched for hours for a solution to this, but I haven't found something that solves my problem.

So I want to code a neuronal network and I have written extensive code for it and which I have checked and debugged so far. I tried evolving my network over multiple generations but although it does execute it gives me a double free or corruption error. I have traced the error with valgrind to this function

bool mutate_a_neuron(Neuron* neuron, int numberofneurons, int numberofinputs){

    int num_e = 3*NUM_I+3;
    bool* element_already_mutated = new bool[num_e];  //line 91
    //bool element_already_mutated[15]; //Workaround :(
    for(int i =0; i<num_e; i++){
        element_already_mutated[i]=false;
    }

    int number_of_elements = (int) neuron->numberofelementstomutate;
    unsigned short will_it_be_mutated = rand() % USHRT_MAX ;

    if(  neuron->mutationrate > will_it_be_mutated ){

        for(int i = 0; i<number_of_elements; i++){

            int elementtomutate = rand() % num_e;   //choose random element
            if(element_already_mutated[elementtomutate]){//check if mutated
                i--;
                continue;
            }

            if( mutate_element(neuron, elementtomutate, numberofneurons, numberofinputs) ){//mutate stuff
                element_already_mutated[elementtomutate]=true;
            } else {
                printf("Something went wrong while mutating an element or takes_input was false\n"); //die if error
            }
        }

        return true;
    }

    delete [] element_already_mutated; //line 120

    return false;
}

Valgrind gives me a mismatched free()/delete/delete[] error at where element_already_mutated gets initialized and free'd. The funky thing is, if I comment the dynamic allocation out and just initialize my "workaround" which is just a normal static array, I get no memory leaks and everything gets deallocated correctly. NUM_I is defined as 4 in the header as:

#define NUM_I 4

Valgrind error:

==1887== 15,023,190 bytes in 1,001,546 blocks are definitely lost in loss record 1 of 1
==1887==    at 0x4C2C93F: operator new[](unsigned long) (vg_replace_malloc.c:423)
==1887==    by 0x10A461: mutate_a_neuron(Neuron*, int, int) (n.cpp:91)
==1887==    (here follow more functions, which call mutate_a_neuron)

Can someone tell me what I'm doing wrong? I don't think I'm deallocating incorrectly but I have no idea where the error might be otherwise.

Body:
Given the function you did show, the simplest way to avoid the memory leak (if this function is indeed the only one leaking memory) is to use std::vector.

#include <vector>

bool mutate_a_neuron(Neuron* neuron, int numberofneurons, int numberofinputs){
    int num_e = 3*NUM_I+3;
    std::vector<bool> element_already_mutated(num_e);
    int number_of_elements = (int) neuron->numberofelementstomutate;
    unsigned short will_it_be_mutated = rand() % USHRT_MAX ;
    //...
    // rest of your code
    //
    // delete [] element_already_mutated is no longer needed
    return false;
}

1) The initialization of the vector elements to false is automatically done on construction of the vector, thus the for loop that initialized the boolean array to false is no longer needed.

2) The call to delete [] element_already_mutated; must be removed, since element_already_mutated is no longer a pointer.  In addition, vector will automatically deallocate memory it has allocated, thus another reason to remove the delete [].

3) The return true; statement you had no longer will cause an issue, since if the mutate_a_neuron function returns for any reason, the vector<bool> will be destroyed, thus removing any chance of a memory leak.

4) Since the code that uses vector makes accesses using [], the rest of the code does not need to be changed, since std::vector overloads operator [] to act as an array.


问:
verify (bitwise) if a value matches multiple specific flags of an enum
I would like to check if a value corresponds to a set of flags (from an enum or object alike).

Right now, I have come up with the following function in javascript (praise the snippet :3):

function hasFlags(flags, value) {
    let s = flags.reduce((sum, v) => sum += v, 0);

    return (s & value) === s
}

FLAGS = {
    STEP_0: 1 << 0,
    STEP_1: 1 << 1,
    STEP_2: 1 << 2,
    STEP_3: 1 << 3,
    STEP_4: 1 << 4,
    STEP_5: 1 << 5,
    STEP_6: 1 << 6,
    STEP_7: 1 << 7
}

const needed = [
    FLAGS.STEP_2,
    FLAGS.STEP_3,
    FLAGS.STEP_6,
]

console.log(hasFlags(needed, 4));                  // false
console.log(hasFlags(needed, 8));                  // false
console.log(hasFlags(needed, 64));                 // false
console.log(hasFlags(needed, 4 + 8));              // false
console.log(hasFlags(needed, 4 + 64));             // false
console.log(hasFlags(needed, 8 + 64));             // false
console.log(hasFlags(needed, 4 + 8 + 64));         // true
console.log(hasFlags(needed, 4 + 8 + 64 + 1));     // true
console.log(hasFlags(needed, 4 + 8 + 64 + 2));     // true
console.log(hasFlags(needed, 4 + 8 + 64 + 1 + 2)); // true
// etc...```
</div>
</div>
</p>

<p>In python the function would look like this:</p>

```def hasFlags(flags, value):
    s = sum(flags)
    return (s & value) == s

print hasFlags((4,8,64), 4)  # False
print hasFlags((4,8,64), 4+8+64)  # True
# ...
```

Is there a better way (that is, more idiomatic ... or more pythonic) to do this same verification?

Edit: Solutions in both python and javascript are appreciated, but I am  especially looking for an algorithm (whatever the language), as I've searched a lot across the web and never found any, while it seems to me that it's a common problem.

答:
You could check with Array#every, which exit if a condition is wrong.

const
    hasFlags = (flags, value) => flags.every(flag => flag & value),
    FLAGS = {
        STEP_0: 1 << 0,
        STEP_1: 1 << 1,
        STEP_2: 1 << 2,
        STEP_3: 1 << 3,
        STEP_4: 1 << 4,
        STEP_5: 1 << 5,
        STEP_6: 1 << 6,
        STEP_7: 1 << 7
    },
    needed = [
        FLAGS.STEP_2,
        FLAGS.STEP_3,
        FLAGS.STEP_6,
    ];

console.log(hasFlags(needed, 4));                  // false
console.log(hasFlags(needed, 8));                  // false
console.log(hasFlags(needed, 64));                 // false
console.log(hasFlags(needed, 4 + 8));              // false
console.log(hasFlags(needed, 4 + 64));             // false
console.log(hasFlags(needed, 8 + 64));             // false
console.log(hasFlags(needed, 4 + 8 + 64));         // true
console.log(hasFlags(needed, 4 + 8 + 64 + 1));     // true
console.log(hasFlags(needed, 4 + 8 + 64 + 2));     // true
console.log(hasFlags(needed, 4 + 8 + 64 + 1 + 2)); // true```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I would like to check if a value corresponds to a set of flags (from an enum or object alike).

Right now, I have come up with the following function in javascript (praise the snippet :3):

function hasFlags(flags, value) {
    let s = flags.reduce((sum, v) => sum += v, 0);

    return (s & value) === s
}

FLAGS = {
    STEP_0: 1 << 0,
    STEP_1: 1 << 1,
    STEP_2: 1 << 2,
    STEP_3: 1 << 3,
    STEP_4: 1 << 4,
    STEP_5: 1 << 5,
    STEP_6: 1 << 6,
    STEP_7: 1 << 7
}

const needed = [
    FLAGS.STEP_2,
    FLAGS.STEP_3,
    FLAGS.STEP_6,
]

console.log(hasFlags(needed, 4));                  // false
console.log(hasFlags(needed, 8));                  // false
console.log(hasFlags(needed, 64));                 // false
console.log(hasFlags(needed, 4 + 8));              // false
console.log(hasFlags(needed, 4 + 64));             // false
console.log(hasFlags(needed, 8 + 64));             // false
console.log(hasFlags(needed, 4 + 8 + 64));         // true
console.log(hasFlags(needed, 4 + 8 + 64 + 1));     // true
console.log(hasFlags(needed, 4 + 8 + 64 + 2));     // true
console.log(hasFlags(needed, 4 + 8 + 64 + 1 + 2)); // true
// etc...

In python the function would look like this:

def hasFlags(flags, value):
    s = sum(flags)
    return (s & value) == s

print hasFlags((4,8,64), 4)  # False
print hasFlags((4,8,64), 4+8+64)  # True
# ...

Is there a better way (that is, more idiomatic ... or more pythonic) to do this same verification?

Edit: Solutions in both python and javascript are appreciated, but I am  especially looking for an algorithm (whatever the language), as I've searched a lot across the web and never found any, while it seems to me that it's a common problem.

Body:
You could check with Array#every, which exit if a condition is wrong.

const
    hasFlags = (flags, value) => flags.every(flag => flag & value),
    FLAGS = {
        STEP_0: 1 << 0,
        STEP_1: 1 << 1,
        STEP_2: 1 << 2,
        STEP_3: 1 << 3,
        STEP_4: 1 << 4,
        STEP_5: 1 << 5,
        STEP_6: 1 << 6,
        STEP_7: 1 << 7
    },
    needed = [
        FLAGS.STEP_2,
        FLAGS.STEP_3,
        FLAGS.STEP_6,
    ];

console.log(hasFlags(needed, 4));                  // false
console.log(hasFlags(needed, 8));                  // false
console.log(hasFlags(needed, 64));                 // false
console.log(hasFlags(needed, 4 + 8));              // false
console.log(hasFlags(needed, 4 + 64));             // false
console.log(hasFlags(needed, 8 + 64));             // false
console.log(hasFlags(needed, 4 + 8 + 64));         // true
console.log(hasFlags(needed, 4 + 8 + 64 + 1));     // true
console.log(hasFlags(needed, 4 + 8 + 64 + 2));     // true
console.log(hasFlags(needed, 4 + 8 + 64 + 1 + 2)); // true

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Unable to create AWS UserPool login on a single page app
Im building a single page app that uses AWS UserPools to manage the user login/credentials.

As I want to use further services after login so the projected flow is;

UserPool-> FederatedIdentity -> API Gateway

Reading the docs at: https://github.com/aws/amazon-cognito-auth-js
I loaded:

```<code><!-- AWS JS -->
<script src="js/aws-cognito-sdk.min.js"></script>
<script src="js/amazon-cognito-identity.min.js"></script>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.162.0.min.js"></script>
</code>```

When I go to run the usecase 4 code - the page errors with:

```<code>aws-cognito-sdk.js:11972:42
</code>```

Console log:

```<code>callListeners
aws-cognito-sdk.js:11972:42
emit
aws-cognito-sdk.js:11944:4
emitEvent
aws-cognito-sdk.js:11571:4
a
aws-cognito-sdk.js:11300:4
[52]</d.prototype.runTo
aws-cognito-sdk.js:13172:2
[52]</d.prototype.runTo/<
aws-cognito-sdk.js:13184:4
a/<
aws-cognito-sdk.js:11316:8
emitEvent/<
aws-cognito-sdk.js:11573:6
callListeners
aws-cognito-sdk.js:11980:4
emit
aws-cognito-sdk.js:11944:4
emitEvent
aws-cognito-sdk.js:11571:4
a
aws-cognito-sdk.js:11300:4
[52]</d.prototype.runTo
aws-cognito-sdk.js:13172:2
[52]</d.prototype.runTo/<
aws-cognito-sdk.js:13184:4
a/<
aws-cognito-sdk.js:11316:8
emitEvent/<
aws-cognito-sdk.js:11573:6
callListeners
aws-cognito-sdk.js:11980:4
emit
aws-cognito-sdk.js:11944:4
emitEvent
aws-cognito-sdk.js:11571:4
a
aws-cognito-sdk.js:11300:4
[52]</d.prototype.runTo
aws-cognito-sdk.js:13172:2
[52]</d.prototype.runTo/<
aws-cognito-sdk.js:13184:4
a/<
aws-cognito-sdk.js:11316:8
emitEvent/<
aws-cognito-sdk.js:11573:6
callListeners
aws-cognito-sdk.js:11980:4
emit
aws-cognito-sdk.js:11944:4
emitEvent
aws-cognito-sdk.js:11571:4
a
aws-cognito-sdk.js:11300:4
[52]</d.prototype.runTo
aws-cognito-sdk.js:13172:2
[52]</d.prototype.runTo/<
aws-cognito-sdk.js:13184:4
a/<
aws-cognito-sdk.js:11316:8
emitEvent/<
aws-cognito-sdk.js:11573:6
callListeners
aws-cognito-sdk.js:11980:4
f
aws-cognito-sdk.js:11960:6
c/<
aws-cognito-sdk.js:9255:10
[60]</d.prototype.emit
aws-cognito-sdk.js:15537:8
finishRequest
aws-cognito-sdk.js:9730:4
handleRequest/<
aws-cognito-sdk.js:9655:8
</code>```

Here is a copy of my modified sample code:

```<code>var authenticationData = {
        Username : 'mytestusername',
        Password : 'mytestpassword',
    };
    var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
    var poolData = {
        UserPoolId : 'us-east-1_777', // Your user pool id here
        ClientId : 'myclientidfromuserpools' // Your client id here
    };
    var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
    var userData = {
        Username : 'mytestusername',
        Pool : userPool
    };
    var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function (result) {
            console.log('access token + ' + result.getAccessToken().getJwtToken());

        //POTENTIAL: Region needs to be set if not already set previously elsewhere.
        AWS.config.region = 'us-east-1';

        AWS.config.credentials = new AWS.CognitoIdentityCredentials({
            IdentityPoolId : 'us-east-1:myfederatedID', // your identity pool id here
            Logins : {
                // Change the key below according to the specific region your user pool is in.
                'cognito-idp.us-east-1.amazonaws.com/us-east-myfederatedID' : result.getIdToken().getJwtToken()
            }
        });

        //refreshes credentials using AWS.CognitoIdentity.getCredentialsForIdentity()
        AWS.config.credentials.refresh((error) => {
            if (error) {
                 console.error(error);
            } else {
                 // Instantiate aws sdk service objects now that the credentials have been updated.
                 // example: var s3 = new AWS.S3();
                 console.log('Successfully logged!');
            }
        });
    },

    onFailure: function(err) {
        alert(err);
    },

});
</code>```

I dont understand whats going with AWS JS to be able to figure out how to fix.
Im trying to keep the login inside the SinglePageApp rather than use the AWS hosted and redirects.
Where am I going wrong?

答: You can try to use the unminified versions of the scripts available in the same repos and Google Chrome developer tools to get a more descriptive error. </p>

Body:
Im building a single page app that uses AWS UserPools to manage the user login/credentials.

As I want to use further services after login so the projected flow is;

UserPool-> FederatedIdentity -> API Gateway

Reading the docs at: https://github.com/aws/amazon-cognito-auth-js
I loaded:

When I go to run the usecase 4 code - the page errors with:

aws-cognito-sdk.js:11972:42

Console log:

callListeners
aws-cognito-sdk.js:11972:42
emit
aws-cognito-sdk.js:11944:4
emitEvent
aws-cognito-sdk.js:11571:4
a
aws-cognito-sdk.js:11300:4
[52]</d.prototype.runTo
aws-cognito-sdk.js:13172:2
[52]</d.prototype.runTo/<
aws-cognito-sdk.js:13184:4
a/<
aws-cognito-sdk.js:11316:8
emitEvent/<
aws-cognito-sdk.js:11573:6
callListeners
aws-cognito-sdk.js:11980:4
emit
aws-cognito-sdk.js:11944:4
emitEvent
aws-cognito-sdk.js:11571:4
a
aws-cognito-sdk.js:11300:4
[52]</d.prototype.runTo
aws-cognito-sdk.js:13172:2
[52]</d.prototype.runTo/<
aws-cognito-sdk.js:13184:4
a/<
aws-cognito-sdk.js:11316:8
emitEvent/<
aws-cognito-sdk.js:11573:6
callListeners
aws-cognito-sdk.js:11980:4
emit
aws-cognito-sdk.js:11944:4
emitEvent
aws-cognito-sdk.js:11571:4
a
aws-cognito-sdk.js:11300:4
[52]</d.prototype.runTo
aws-cognito-sdk.js:13172:2
[52]</d.prototype.runTo/<
aws-cognito-sdk.js:13184:4
a/<
aws-cognito-sdk.js:11316:8
emitEvent/<
aws-cognito-sdk.js:11573:6
callListeners
aws-cognito-sdk.js:11980:4
emit
aws-cognito-sdk.js:11944:4
emitEvent
aws-cognito-sdk.js:11571:4
a
aws-cognito-sdk.js:11300:4
[52]</d.prototype.runTo
aws-cognito-sdk.js:13172:2
[52]</d.prototype.runTo/<
aws-cognito-sdk.js:13184:4
a/<
aws-cognito-sdk.js:11316:8
emitEvent/<
aws-cognito-sdk.js:11573:6
callListeners
aws-cognito-sdk.js:11980:4
f
aws-cognito-sdk.js:11960:6
c/<
aws-cognito-sdk.js:9255:10
[60]</d.prototype.emit
aws-cognito-sdk.js:15537:8
finishRequest
aws-cognito-sdk.js:9730:4
handleRequest/<
aws-cognito-sdk.js:9655:8

Here is a copy of my modified sample code:

var authenticationData = {
        Username : 'mytestusername',
        Password : 'mytestpassword',
    };
    var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
    var poolData = {
        UserPoolId : 'us-east-1_777', // Your user pool id here
        ClientId : 'myclientidfromuserpools' // Your client id here
    };
    var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
    var userData = {
        Username : 'mytestusername',
        Pool : userPool
    };
    var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function (result) {
            console.log('access token + ' + result.getAccessToken().getJwtToken());

        //POTENTIAL: Region needs to be set if not already set previously elsewhere.
        AWS.config.region = 'us-east-1';

        AWS.config.credentials = new AWS.CognitoIdentityCredentials({
            IdentityPoolId : 'us-east-1:myfederatedID', // your identity pool id here
            Logins : {
                // Change the key below according to the specific region your user pool is in.
                'cognito-idp.us-east-1.amazonaws.com/us-east-myfederatedID' : result.getIdToken().getJwtToken()
            }
        });

        //refreshes credentials using AWS.CognitoIdentity.getCredentialsForIdentity()
        AWS.config.credentials.refresh((error) => {
            if (error) {
                 console.error(error);
            } else {
                 // Instantiate aws sdk service objects now that the credentials have been updated.
                 // example: var s3 = new AWS.S3();
                 console.log('Successfully logged!');
            }
        });
    },

    onFailure: function(err) {
        alert(err);
    },

});

I dont understand whats going with AWS JS to be able to figure out how to fix.
Im trying to keep the login inside the SinglePageApp rather than use the AWS hosted and redirects.
Where am I going wrong?


问:
Is there a way to submit multiple forms to insert data in specific column?
I have this form, but I need to use it for more users.
ex for user_id=1 to submit 1 form for user_id=2 to submit another form,
can you guys help?

The database table has a column u_userid where 1 = admin 2,3,4,5,6,7 is normal user, each user has more columns which I need to update data from database.

```<code><?php
if( $_SESSION['user_id'] == '1' || $_SESSION['user_id'] == '7' )
{
    echo '<hr class="mx-3 my-0">
            <div class="callout callout-warning m-0 py-3">
              <div>
                <strong>Sas Andreea</strong>
              </div>
              <small class="text-muted mr-3"><i class="icon-calendar"></i>Salariu Lunar:</small>
              <small class="text-muted"><i class="icon-location-pin"></i><input type="text"  name="salariulunar" value="' . $row[
  'salariulunar'] . '"  maxlength="4" size="4"> lei
              <br /> Data contract: <input type="text"  name="datacontractului"  maxlength="10" size="7" value="' . $row['datacontractului'] . ' ">
              <br /> Datorie: <input type="text"  name="datorie" value="' . $row['datorie'] . '"   maxlength="4" size="4"> Lei
              <br /> Salariu in avans: <input type="text" value="' . $row['salariuavans'] . ' " name="salariuavans"  maxlength="4" size="4"> Lei
              <br /> Zile de concediu luate: <input  type="text" value="' . $row['zileconcediu'] . '"  name="zileconcediu"  maxlength="2" size="2"> Zile
              </small>
            </div>';
}
?>
<!-- Sfarsit angajat -->
<?php
if( $_SESSION['user_id'] == '1' )
{
    echo '<button type="submit" name="submit" class="btn btn-sm btn-primary"><i class="fa fa-dot-circle-o" ></i> Modifica</button>';
}
?>
</form>
</code>```

答:
You can fix it by making the If statement like this...
      If($_SESSION['user_id'] == '2')

    {

Use the update feature and then add a ‘where user_id = 1’ in the end of your statement

ContentLicense: CC BY-SA 4.0

Body:
I have this form, but I need to use it for more users.
ex for user_id=1 to submit 1 form for user_id=2 to submit another form,
can you guys help?

The database table has a column u_userid where 1 = admin 2,3,4,5,6,7 is normal user, each user has more columns which I need to update data from database.

<?php
if( $_SESSION['user_id'] == '1' || $_SESSION['user_id'] == '7' )
{
    echo '

                Sas Andreea

              Salariu Lunar:
              <input type="text"  name="salariulunar" value="' . $row[
  'salariulunar'] . '"  maxlength="4" size="4"> lei

 Data contract: <input type="text"  name="datacontractului"  maxlength="10" size="7" value="' . $row['datacontractului'] . ' ">

 Datorie: <input type="text"  name="datorie" value="' . $row['datorie'] . '"   maxlength="4" size="4"> Lei

 Salariu in avans: <input type="text" value="' . $row['salariuavans'] . ' " name="salariuavans"  maxlength="4" size="4"> Lei

 Zile de concediu luate: <input  type="text" value="' . $row['zileconcediu'] . '"  name="zileconcediu"  maxlength="2" size="2"> Zile

';
}
?>

<?php
if( $_SESSION['user_id'] == '1' )
{
    echo '<button type="submit" name="submit" class="btn btn-sm btn-primary"> Modifica</button>';
}
?>
</form>