问:
Windows: Child Process with Redirected Input and Output
I'm trying to create a Child Process with Redirected Input and Output (as described here - http://msdn.microsoft.com/en-us/library/ms682499(VS.85).aspx).

For the people that don't want to bother reading the source code on that page, the author is using anonymous pipes to redirect the child's input and output. The parent process writes to the child process's input and reads from the child process's output.

In that code however, the program is closing the pipes after reading and writing (in WriteToPipe and ReadFromPipe), so actually the program just reads a file, dumps it on the child process input stream and then reads the child process response.

Now, what I'm looking for is a code where we will not close the pipes, but we will continuously post requests and read the child process response (in contrast to making just 1 request).

I've tried several modifications to the source code given on the link posted above, but no matter what I try, the program always hangs when calling ReadFile() in the ReadFromPipe() function (it probably waits for the child to quit - but as I said I like to get the child response, and then send other requests to it).

Any ideas on how I can get over this?

Update:

Can anyone at least tell me whether using the .NET Process class with RedirectStandardInput and RedirectStandardOutput is a good option?

答:
Yes - the .Net Process class redirects the standard input / output of the child process with anonymous pipes in a very similar way to the linked sample if you use RedirectStandardInput and RedirectStandardOutput, so this is probably a fairly good option.

As for why ReadFile is hanging - it sounds like this function is waiting for the child process to either send some data back, or to close the pipe.  If you want to continuously post requests to the child process then you need to either:

Know exactly when it is appropriate to read so that you are not left waiting / blocked for the child process (so for example you only read immediately after a request has been sent).  This strategy is very risky as there is always a chance that the child process doesn't behave as expected and you are left waiting on the child process indefinitely.

Have a dedicated thread for reading - if you have a dedicated thread for reading then it doesn't matter that the thread may wait indefinitely for the child process as your other threads are still able to send requests and operate as normal.  This method is more complex than the first option, however when done properly is far more robust.  The only other drawback to this approach is that it requires you have an additional read thread for each child process, meaning that it doesn't scale very well if you need to communicate with a large number of child processes.

Use asynchronous IO - It is possible to call the ReadFile function in a way such that it always immediately returns, however notifies you when a read has completed (I'm a little fuzzy on the exact details on how this works as I'm more used to C#).  This is know as Asynchronous IO and is the most versatile of these 3 methods as it allows you to communicate with many child processes without needing a dedicated thread for each one.  The tradeoff however is that it is also the most complex to do correctly (at least in my opinion).


来源: stackexchange

问:
Homebrew Warning: Xcode is installed to a directory with a space in the name
I just wiped and reinstalled OSX 10.7.5, I'm attempting to set up Homebrew but receive the following warning.

I've seen this blog post on someone having the same problem, but didn't see a link/illustration to his solution included. Any help on how to correct and remove this warning will be well received.

Here is the output from which gcc && echo $PATH?

答:
I ended up needing to do both the things suggested in other responses here; neither one alone would have fixed the problem in my case. I had originally installed Xcode to a subdirectory under Applications, with a space in the directory name. Here's how I fixed it:

1) In Finder I moved Xcode from the folder it was in to the main Applications folder. (I chose to try dragging it, not uninstalling and reinstalling, because I didn't want to wait for it to download again--it's a big file and takes a long time to download.) But when I tried running brew doctor again I got a new error, this time saying that
"xcrun: error: active developer path ([the previous path to Xcode.app]) does not exist, use xcode-select --switch path/to/Xcode.app to specify the Xcode that you wish to use for command line developer tools (or see man xcode-select)"

2) So I followed its directions and ran sudo xcode-select --switch /Applications/Xcode.app to tell it the new location. Success!

(One other thing I did to clean up: I had forgotten that dragging Xcode.app from its subdirectory to the main Applications folder would copy it instead of moving it, so afterward I had two copies. I deleted the one in the subdirectory, since Xcode is currently over 9GB and I wanted the space back.)

ContentLicense: CC BY-SA 3.0


问:
Unable to use OAUTH2 Django
I'm following this tutorial https://django-oauth-toolkit.readthedocs.io/en/latest/tutorial/tutorial_01.html, and unfortunately I'm stuck in this part

"Point your browser to //localhost:8000/o/applications/ and add an Application instance"

unfortunately when I go to that URL, I get the following error and redirected to

"localhost:8000/accounts/login/?next=/o/applications/"

and page not found error, is there something I'm doing wrong?

答:
The guide doesn't mention it but you need an authenticated session before you can access that page.  Add the following steps:

Create a user:

```<code>python manage.py createsuperuser
</code>```

Start up the django server:

```<code>python manage.py runserver
</code>```

Get a validated session by logging into the admin page with the admin account that you just created:

```<code>http://localhost:8000/admin
</code>```

Then navigate to the page the guide references:

```<code>http://localhost:8000/o/applications/
</code>```

Title: Unable to use OAUTH2 Django

Body:
The guide doesn't mention it but you need an authenticated session before you can access that page.  Add the following steps:

Create a user:

python manage.py createsuperuser

Start up the django server:

python manage.py runserver

Get a validated session by logging into the admin page with the admin account that you just created:

http://localhost:8000/admin

Then navigate to the page the guide references:

http://localhost:8000/o/applications/


问:
objective-c Fbric crashlytics "Hmmm, seems like your kit isn't activating."
trying to install Fabric Crashlytics on my Cordova project

I followed all the steps and installing all rquired steps with building the project , but at the final step i got stuck there without any action

here is my AppDelegate.h

```<code>#import "AppDelegate.h"
#import <Fabric/Fabric.h>
#import <Crashlytics/Crashlytics.h>

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[Fabric with:@[[Crashlytics class]]];
return YES;
}
@end
</code>```

after I build the project it's stuck there without any action

^^ this screen waits for 1 minute then it's cahnged to

I checked the info.plist and seems good without any problem

答: Mike from Fabric here. We don't have support for Cordova based projects. We need to see a build and run of your app with Fabric enabled. I'd recommend a clean, build and run with Fabric enabled on a device to see if that helps.</p>

Body:
trying to install Fabric Crashlytics on my Cordova project

I followed all the steps and installing all rquired steps with building the project , but at the final step i got stuck there without any action

here is my AppDelegate.h

#import "AppDelegate.h"
#import <Fabric/Fabric.h>
#import <Crashlytics/Crashlytics.h>

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[Fabric with:@[[Crashlytics class]]];
return YES;
}
@end

after I build the project it's stuck there without any action

^^ this screen waits for 1 minute then it's cahnged to

I checked the info.plist and seems good without any problem


问:
Django create static and template directories when using startproject/startapp
Is it possible to modify Django so the templates and static directories (including any subdirectories for existing apps) are created automatically?

I also want the settings.py to be updated to reflect any changes. That is, to have the lines:

```<code>STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

TEMPLATES = [
    {
        ...
        'DIRS': [os.path.join(BASE_DIR, 'templates').replace('\\', '/')],
        ...
    },
]
</code>```

and possibly a flag when running ./manage.py startapp to add the appname to INSTALLED_APPS. I find I'm writing the same boilerplate code for each project and I feel like it could be easily streamlined.

Of course there might be a good reason why these things have been left out of Django. I assume that it's because the locations of those directories are only convention and they want to allow devs to easily move them if needed, but I've never needed to do this.

Ideally I'm looking for a fork of Django that would do this, so I wouldn't have to maintain it myself. I'm using Ubuntu, so I think I could alias the command to do those things, but I don't want to spend time doing that if someone else has already done it better.

答:
Take a look at --template in the startproject documentation.
https://docs.djangoproject.com/en/1.11/ref/django-admin/#startproject</p>

Body:
Is it possible to modify Django so the templates and static directories (including any subdirectories for existing apps) are created automatically?

I also want the settings.py to be updated to reflect any changes. That is, to have the lines:

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

TEMPLATES = [
    {
        ...
        'DIRS': [os.path.join(BASE_DIR, 'templates').replace('\\', '/')],
        ...
    },
]

and possibly a flag when running ./manage.py startapp to add the appname to INSTALLED_APPS. I find I'm writing the same boilerplate code for each project and I feel like it could be easily streamlined.

Of course there might be a good reason why these things have been left out of Django. I assume that it's because the locations of those directories are only convention and they want to allow devs to easily move them if needed, but I've never needed to do this.

Ideally I'm looking for a fork of Django that would do this, so I wouldn't have to maintain it myself. I'm using Ubuntu, so I think I could alias the command to do those things, but I don't want to spend time doing that if someone else has already done it better.


问:
Angular $http.get fails when application contains token?
I have been trying to search about this problem to no avail I will explain the situation.

I have an angular app that can authentication usin jwt tokens which stores token in the header. When I am logged in to the app and I attempt to consume an external api(musicbrainz) I recieve a error 400.

If I am not logged in the request does work most of the time, sometimes I get 503 or 400 not quite sure if its something api related but essentially logged out request to api works.

I am assuming its related to x-access-token being set and my app using an http interceptor to detect token.

How can I get a api request while having the token in the header? Cheers guys

答:
You would need to be selective about when to apply the Authorization header (or whatever header you're using).

I suggest using some customised config logic in your interceptor, like this

```<code>request: function(config) {
  if (!config.external) {
    config.headers.Authorization = 'Bearer '  + whatever
  }
  return config
}
</code>```

Then, in your requests to an external API, simply add the following config

```<code>$http.get('http://musicbrainz.api', {
  external: true
})
</code>```

An alternative would be to check the config.url and only apply the Authorization header to the appropriate services.

Body:
You would need to be selective about when to apply the Authorization header (or whatever header you're using).

I suggest using some customised config logic in your interceptor, like this

request: function(config) {
  if (!config.external) {
    config.headers.Authorization = 'Bearer '  + whatever
  }
  return config
}

Then, in your requests to an external API, simply add the following config

$http.get('http://musicbrainz.api', {
  external: true
})

An alternative would be to check the config.url and only apply the Authorization header to the appropriate services.


问:
Google Sheet formula for cumulative sum with condition
I have a Google Sheet with the following layout:

```<code>  Number |  Counted?  |  Cumulative Total
    4    |     Y      |         4
    2    |            |         6
    9    |     Y      |        15
   ...   |    ...     |        ...
</code>```

The first cell in the Cumulative Total column is populated with this formula:

```<code>=ArrayFormula((SUMIF(ROW(C2:C1000),"<="&ROW(C2:1000),C2:C1000)
</code>```

However this counts all rows in the 'Number' column. How can I make the Cumulative Total only count rows where the Counted? cell is Y?

答:
Try this in C2 and copy down:

```<code>= N(C1) + A2 * (B2 = "Y")
</code>```

Update

Doesn't seem to work with SUMIFS, but there is a very slow matrix multiplication alternative:

```<code>=ArrayFormula(MMult((Row(2:1000)>=Transpose(Row(2:1000)))*Transpose(A2:A1000*(B2:B1000="Y")), Row(2:1000)^0))
</code>```

Body:
I have a Google Sheet with the following layout:

  Number |  Counted?  |  Cumulative Total
    4    |     Y      |         4
    2    |            |         6
    9    |     Y      |        15
   ...   |    ...     |        ...

The first cell in the Cumulative Total column is populated with this formula:

=ArrayFormula((SUMIF(ROW(C2:C1000),"<="&ROW(C2:1000),C2:C1000)

However this counts all rows in the 'Number' column. How can I make the Cumulative Total only count rows where the Counted? cell is Y?

Body:
Try this in C2 and copy down:

= N(C1) + A2 * (B2 = "Y")

Update

Doesn't seem to work with SUMIFS, but there is a very slow matrix multiplication alternative:

=ArrayFormula(MMult((Row(2:1000)>=Transpose(Row(2:1000)))*Transpose(A2:A1000*(B2:B1000="Y")), Row(2:1000)^0))


问:
error in Fragment while try using findViewById
I get an error when I use findViewById in Fragment.

How can I solve it?

```<code>public class Discover extends Fragment {

private static final String TAG = "Discover";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.fragment_discover, container, false);
    Log.d(TAG, "onCreate: starting.");
    setupBottomNavigationView();
    return root;
}

private void setupBottomNavigationView(){

    Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
    BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomNavViewBar);
    BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);

}

public void onResume(){
    super.onResume();

    // Set title bar
    ((LandingPage) getActivity())
            .setActionBarTitle("Discover Photos");

   }

  }
}
</code>```

答:
You have to use the root view for using findViewById:

Assuming this view id.bottomNavViewBar exist in this layout layout.fragment_discoveror included:

```<code>public class Discover extends Fragment {
View root;

private static final String TAG = "Discover";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
// Inflate the layout for this fragment
root = inflater.inflate(R.layout.fragment_discover, container, false);
Log.d(TAG, "onCreate: starting.");
setupBottomNavigationView();
return root;
}

private void setupBottomNavigationView(){
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) root.findViewById(R.id.bottomNavViewBar);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);

}

public void onResume(){
super.onResume();

// Set title bar
((LandingPage) getActivity())
        .setActionBarTitle("Discover Photos");

    }

  }
}
</code>```

Now whenever you need to use findViewById, you can use the root view like this:

```<code>root.findViewById(R.id.yourview)
</code>```

Body:
I get an error when I use findViewById in Fragment.

How can I solve it?

public class Discover extends Fragment {

private static final String TAG = "Discover";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.fragment_discover, container, false);
    Log.d(TAG, "onCreate: starting.");
    setupBottomNavigationView();
    return root;
}

private void setupBottomNavigationView(){

    Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
    BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomNavViewBar);
    BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);

}

public void onResume(){
    super.onResume();

    // Set title bar
    ((LandingPage) getActivity())
            .setActionBarTitle("Discover Photos");

   }

  }
}

Body:
You have to use the root view for using findViewById:

Assuming this view id.bottomNavViewBar exist in this layout layout.fragment_discoveror included:

public class Discover extends Fragment {
View root;

private static final String TAG = "Discover";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
// Inflate the layout for this fragment
root = inflater.inflate(R.layout.fragment_discover, container, false);
Log.d(TAG, "onCreate: starting.");
setupBottomNavigationView();
return root;
}

private void setupBottomNavigationView(){
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) root.findViewById(R.id.bottomNavViewBar);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);

}

public void onResume(){
super.onResume();

// Set title bar
((LandingPage) getActivity())
        .setActionBarTitle("Discover Photos");

    }

  }
}

Now whenever you need to use findViewById, you can use the root view like this:

root.findViewById(R.id.yourview)


问:
CCCallFunc usage in cocos2dx
I am getting warning on this line stating that method actionWithTarget is deprecated.
Can any one tell which alternative method can be used in cocos2dx

```<code>CCCallFunc *callBackfunc = CCCallFunc::actionWithTarget(this,
                           callfunc_selector(GamePlay::startTrumphetAnimation));
</code>```

Thanks

答:
If you are using COCOS2DX-3.0 or 3.14v

```<code>runAction( CallFunc::create([=]() { startTrumphetAnimation() }));
</code>```

But you should write this line inside any method of GamePlay Class.

Title: CCCallFunc usage in cocos2dx

Body:
I am getting warning on this line stating that method actionWithTarget is deprecated.
Can any one tell which alternative method can be used in cocos2dx

CCCallFunc *callBackfunc = CCCallFunc::actionWithTarget(this,
                           callfunc_selector(GamePlay::startTrumphetAnimation));

Thanks

Body:
If you are using COCOS2DX-3.0 or 3.14v

runAction( CallFunc::create([=]() { startTrumphetAnimation() }));

But you should write this line inside any method of GamePlay Class.


问:
app-debuk.apk stopped working
I'm new to Android programming and it's my first project with Gradle. In the past I used Maven for Java. So I made an application with Android studio and if I click on Run and select my phone it'll build and install the apk to my phone then opens itself and works fine.

So I would like to share my progress with one of my friend, so I clicked on Make Project, and it generated an app-debug.apk in /app/build/outputs/apk/app-debug.apk but if I try that to install my Application Force Close itself after launch with a text: "Unfortunately the app stopped working".

Here is my build.gradle (Module:app):

and my build.gradle (Project: Autosiskola):

the error code:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.androidports.autosiskola/com.androidports.autosiskola.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.androidports.autosiskola.MainActivity" on path: DexPathList[[zip file "/data/app/com.androidports.autosiskola-1/base.apk"],nativeLibraryDirectories=[/data/app/com.androidports.autosiskola-1/lib/arm64, /vendor/lib64, /system/lib64]]

My Main Activity:

```<code>    package com.androidports.autosiskola;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

import android.widget.Toast;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MainActivity extends AppCompatActivity {

EditText username, password;
Button login;
ProgressBar progressBar;

Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;

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

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    username = (EditText) findViewById(R.id.txtUsername);
    password = (EditText) findViewById(R.id.txtPassword);

    login = (Button) findViewById(R.id.btnLogin);

    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    progressBar.setVisibility(View.GONE);

    conn = DBConnect.Connector();

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (username.toString().trim().isEmpty() && password.toString().isEmpty()) {
                Toast.makeText(MainActivity.this, "Nincs felhasználónév / jelszó megadva!", Toast.LENGTH_SHORT).show();
            } else {
                switch (v.getId()) {
                    case R.id.btnLogin:
                        new doMySQL().execute();
                        break;
                }
            }
        }
    });
}

public class doMySQL extends AsyncTask<Void, Void, String> {

    final String uname = username.getText().toString();
    final String passwd = password.getText().toString();
    String getUsername = null;
    String getPassword = null;
    String getPermission = null;
    String resValue = "undone";
    int exists = 0;

    protected void onPreExecute() {
        progressBar.setVisibility(View.VISIBLE);
    }

    protected String doInBackground(Void... params) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        conn = DBConnect.Connector();

        try {
            pst = conn.prepareStatement("SELECT username FROM userList WHERE username=?");
            pst.setString(1, String.valueOf(uname));
            rs = pst.executeQuery();
            if (rs.next()) {
                getUsername = rs.getString(1);
            }
            pst = conn.prepareStatement("SELECT username FROM userList WHERE username=?");
            pst.setString(1, String.valueOf(uname));
            rs = pst.executeQuery();
            if (rs.wasNull()) {
                Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
                resValue = "undone";
            }

            pst = conn.prepareStatement("SELECT password FROM userList WHERE username=?");
            pst.setString(1, String.valueOf(uname));
            rs = pst.executeQuery();
            if (rs.next()) {
                getPassword = rs.getString(1);
            }
            pst = conn.prepareStatement("SELECT password FROM userList WHERE username=?");
            pst.setString(1, String.valueOf(uname));
            rs = pst.executeQuery();
            if (rs.wasNull()) {
                Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
                resValue = "undone";
            }

            pst = conn.prepareStatement("SELECT username FROM userList WHERE username=? AND password=?");
            pst.setString(1, String.valueOf(uname));
            pst.setString(2, String.valueOf(passwd));
            rs = pst.executeQuery();
            if (rs.next()) {
                exists = 1;
            }
            pst = conn.prepareStatement("SELECT username FROM userList WHERE username=? AND password=?");
            pst.setString(1, String.valueOf(uname));
            pst.setString(2, String.valueOf(passwd));
            if (rs.wasNull()) {
                Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
                exists = 0;
                resValue = "undone";
            }

            if (exists == 1) {
                pst = conn.prepareStatement("SELECT permission FROM userList WHERE username=?");
                pst.setString(1, String.valueOf(uname));
                rs = pst.executeQuery();
                while (rs.next()) {
                    getPermission = rs.getString(1);
                    resValue = "Done";
                }
            }

        } catch (SQLException e) {
            Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
        }

        return resValue;
    }

    protected void onPostExecute(String result) {
        if ("Done".equals(result)) {
            progressBar.setVisibility(View.GONE);
            if ("teacher".equals(getPermission)) {
                Intent openTeacher = new Intent(MainActivity.this, TeacherLogin.class);
                progressBar.setVisibility(View.GONE);
                startActivity(openTeacher);
            } else if ("student".equals(getPermission)) {
                Intent openStudent = new Intent(MainActivity.this, StudentLogin.class);
                progressBar.setVisibility(View.GONE);
                startActivity(openStudent);
            }
        } else if ("undone".equals(result)) {
            Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
            progressBar.setVisibility(View.GONE);
        }
    }
}
</code>```

}

The app works when I install it with the Run command on USB, but if I want to install app-debug.apk it didn't work.

I have a mysql-connector-java dependency inside my lib folder, that's all.

答:
You can't copy file outputs/apk/app-debug.apk to run in Android device that not worked for me too. When I am trying to install app-debug.apk which crashed. I am trying to sign app first and choosing debug.

To do that:

Build -> Generate Signed APK

Filling the blank if you havent key store path, create new one. https://developer.android.com/studio/publish/app-signing.html

Choose build type is debug and choose both V1 and V2

Wait until finish.

Title: app-debuk.apk stopped working

Body:
I'm new to Android programming and it's my first project with Gradle. In the past I used Maven for Java. So I made an application with Android studio and if I click on Run and select my phone it'll build and install the apk to my phone then opens itself and works fine.

So I would like to share my progress with one of my friend, so I clicked on Make Project, and it generated an app-debug.apk in /app/build/outputs/apk/app-debug.apk but if I try that to install my Application Force Close itself after launch with a text: "Unfortunately the app stopped working".

Here is my build.gradle (Module:app):

and my build.gradle (Project: Autosiskola):

the error code:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.androidports.autosiskola/com.androidports.autosiskola.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.androidports.autosiskola.MainActivity" on path: DexPathList[[zip file "/data/app/com.androidports.autosiskola-1/base.apk"],nativeLibraryDirectories=[/data/app/com.androidports.autosiskola-1/lib/arm64, /vendor/lib64, /system/lib64]]

My Main Activity:

    package com.androidports.autosiskola;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

import android.widget.Toast;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MainActivity extends AppCompatActivity {

EditText username, password;
Button login;
ProgressBar progressBar;

Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;

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

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    username = (EditText) findViewById(R.id.txtUsername);
    password = (EditText) findViewById(R.id.txtPassword);

    login = (Button) findViewById(R.id.btnLogin);

    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    progressBar.setVisibility(View.GONE);

    conn = DBConnect.Connector();

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (username.toString().trim().isEmpty() && password.toString().isEmpty()) {
                Toast.makeText(MainActivity.this, "Nincs felhasználónév / jelszó megadva!", Toast.LENGTH_SHORT).show();
            } else {
                switch (v.getId()) {
                    case R.id.btnLogin:
                        new doMySQL().execute();
                        break;
                }
            }
        }
    });
}

public class doMySQL extends AsyncTask<Void, Void, String> {

    final String uname = username.getText().toString();
    final String passwd = password.getText().toString();
    String getUsername = null;
    String getPassword = null;
    String getPermission = null;
    String resValue = "undone";
    int exists = 0;

    protected void onPreExecute() {
        progressBar.setVisibility(View.VISIBLE);
    }

    protected String doInBackground(Void... params) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        conn = DBConnect.Connector();

        try {
            pst = conn.prepareStatement("SELECT username FROM userList WHERE username=?");
            pst.setString(1, String.valueOf(uname));
            rs = pst.executeQuery();
            if (rs.next()) {
                getUsername = rs.getString(1);
            }
            pst = conn.prepareStatement("SELECT username FROM userList WHERE username=?");
            pst.setString(1, String.valueOf(uname));
            rs = pst.executeQuery();
            if (rs.wasNull()) {
                Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
                resValue = "undone";
            }

            pst = conn.prepareStatement("SELECT password FROM userList WHERE username=?");
            pst.setString(1, String.valueOf(uname));
            rs = pst.executeQuery();
            if (rs.next()) {
                getPassword = rs.getString(1);
            }
            pst = conn.prepareStatement("SELECT password FROM userList WHERE username=?");
            pst.setString(1, String.valueOf(uname));
            rs = pst.executeQuery();
            if (rs.wasNull()) {
                Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
                resValue = "undone";
            }

            pst = conn.prepareStatement("SELECT username FROM userList WHERE username=? AND password=?");
            pst.setString(1, String.valueOf(uname));
            pst.setString(2, String.valueOf(passwd));
            rs = pst.executeQuery();
            if (rs.next()) {
                exists = 1;
            }
            pst = conn.prepareStatement("SELECT username FROM userList WHERE username=? AND password=?");
            pst.setString(1, String.valueOf(uname));
            pst.setString(2, String.valueOf(passwd));
            if (rs.wasNull()) {
                Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
                exists = 0;
                resValue = "undone";
            }

            if (exists == 1) {
                pst = conn.prepareStatement("SELECT permission FROM userList WHERE username=?");
                pst.setString(1, String.valueOf(uname));
                rs = pst.executeQuery();
                while (rs.next()) {
                    getPermission = rs.getString(1);
                    resValue = "Done";
                }
            }

        } catch (SQLException e) {
            Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
        }

        return resValue;
    }

    protected void onPostExecute(String result) {
        if ("Done".equals(result)) {
            progressBar.setVisibility(View.GONE);
            if ("teacher".equals(getPermission)) {
                Intent openTeacher = new Intent(MainActivity.this, TeacherLogin.class);
                progressBar.setVisibility(View.GONE);
                startActivity(openTeacher);
            } else if ("student".equals(getPermission)) {
                Intent openStudent = new Intent(MainActivity.this, StudentLogin.class);
                progressBar.setVisibility(View.GONE);
                startActivity(openStudent);
            }
        } else if ("undone".equals(result)) {
            Toast.makeText(MainActivity.this, "Hibás felhasználónév / jelszó!", Toast.LENGTH_SHORT).show();
            progressBar.setVisibility(View.GONE);
        }
    }
}

}

The app works when I install it with the Run command on USB, but if I want to install app-debug.apk it didn't work.

I have a mysql-connector-java dependency inside my lib folder, that's all.


问:
Problems navigating to another component(and page) on click using 'this.props.router.push'
I want to navigate to another page when an image is clicked in a separate component. Using this.props.router.push should work to achieve this. However I get this error when the image is clicked Uncaught TypeError: Cannot read property 'props' of null. This is the component I have the image that has the on click function :

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { addCart } from '../../actions';
import { withRouter } from 'react-router';
import ProductPage from '

import Shirt from './camodye.jpeg';
import Tape from './Tape.png';
import RegularHat from './regularhat.jpg';

export class WebShop extends Component {
    constructor(props){
        super(props);
        this.state = {value: 'medium', cartData: {} };
        this.handleClick = this.handleClick.bind(this);
        this.change = this.change.bind(this);
    }

    handleClick() {
        let cart = {price:0,item:"userselection",size:this.state.value};
        this.props.onCartAdd(cart);
    }

    change(e){
        this.setState({value: e.target.value})
    }

    itemSelection(){
        let userOrder = {price:0,item:"",size:""};
        let userItem = "";
        if (userItem == "shirt1") {
           let itemPrice = 20.00;
        }
    }

    goProductPage() {
        this.props.router.push({ProductPage});
    }

    render() {
        console.log('aa');
        return (
            <div className='Webshop' id='Webshop'>
                <ul id="Productlist">
                    <div className='Product'>
                      <img src={Shirt} onClick={this.goProductPage}></img>
                      <button onClick={this.handleClick} className="addit">Add to cart</button>
                      <select id="size" onChange={this.change} value={this.state.value}>
                        <option value="medium">Medium</option>
                        <option value="large">Large</option>
                        <option value="x-large">X-large</option>
                      </select>
                    </div>
                    <div className='Product'>
                      <img src={RegularHat}></img>
                      <button onClick={this.handleClick} className="addit">Add to cart</button>
                      <select id="size" onChange={this.change} value={this.state.value}>
                        <option value="medium">Medium</option>
                        <option value="large">Large</option>
                        <option value="x-large">X-large</option>
                      </select>
                    </div>
                    <div className='Product'>
                      <img src={Tape}></img>
                      <button onClick={this.handleClick} className="addit">Add to cart</button>
                      <select id="size" onChange={this.change} value={this.state.value}>
                        <option value="medium">Medium</option>
                        <option value="large">Large</option>
                        <option value="x-large">X-large</option>
                      </select>
                    </div>
                </ul>
            </div>
        );
    }
}
</code>```

This is my productpage.js that has the ProductPage component:

```<code>import React, { Component } from 'react';

export default class ProductPage extends  Component {
    render() {
        return (
            <div className= "ProductPage" id="ProductPage">
            </div>
        );
    }

}
</code>```

Why I'm I getting this error? Is this the best way to do what I want?

答:
You need to bind this to your goProductPage method in constructor:</p>

```<code>constructor(props){
    super(props);
    this.goProductPage = this.goProductPage.bind(this);
}
</code>```

Body:
I want to navigate to another page when an image is clicked in a separate component. Using this.props.router.push should work to achieve this. However I get this error when the image is clicked Uncaught TypeError: Cannot read property 'props' of null. This is the component I have the image that has the on click function :

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { addCart } from '../../actions';
import { withRouter } from 'react-router';
import ProductPage from '

import Shirt from './camodye.jpeg';
import Tape from './Tape.png';
import RegularHat from './regularhat.jpg';

export class WebShop extends Component {
    constructor(props){
        super(props);
        this.state = {value: 'medium', cartData: {} };
        this.handleClick = this.handleClick.bind(this);
        this.change = this.change.bind(this);
    }

    handleClick() {
        let cart = {price:0,item:"userselection",size:this.state.value};
        this.props.onCartAdd(cart);
    }

    change(e){
        this.setState({value: e.target.value})
    }

    itemSelection(){
        let userOrder = {price:0,item:"",size:""};
        let userItem = "";
        if (userItem == "shirt1") {
           let itemPrice = 20.00;
        }
    }

    goProductPage() {
        this.props.router.push({ProductPage});
    }

    render() {
        console.log('aa');
        return (

                      <button onClick={this.handleClick} className="addit">Add to cart</button>
                      <select id="size" onChange={this.change} value={this.state.value}>
                        <option value="medium">Medium</option>
                        <option value="large">Large</option>
                        <option value="x-large">X-large</option>
                      </select>

                      <button onClick={this.handleClick} className="addit">Add to cart</button>
                      <select id="size" onChange={this.change} value={this.state.value}>
                        <option value="medium">Medium</option>
                        <option value="large">Large</option>
                        <option value="x-large">X-large</option>
                      </select>

                      <button onClick={this.handleClick} className="addit">Add to cart</button>
                      <select id="size" onChange={this.change} value={this.state.value}>
                        <option value="medium">Medium</option>
                        <option value="large">Large</option>
                        <option value="x-large">X-large</option>
                      </select>

        );
    }
}

This is my productpage.js that has the ProductPage component:

import React, { Component } from 'react';

export default class ProductPage extends  Component {
    render() {
        return (

        );
    }

}

Why I'm I getting this error? Is this the best way to do what I want?

Body:
You need to bind this to your goProductPage method in constructor:

constructor(props){
    super(props);
    this.goProductPage = this.goProductPage.bind(this);
}


问:
R: Conditionally replacing values based on column pre-fixes and suffixes
I have two data frames. Data frame A has many observations/rows, an ID for each observation, and many additional columns. For a subset of observations X, the values for a set of columns are missing/NA. Data frame B contains a subset of the observations in X (which can be matched across data frames using the ID) and variables with identical names as in data frame A, but containing values to replace the missing values in the set of columns with missing/NA.

My code below (using a join operation) merely adds columns rather than replacing missing values. For each of the additional variables (let's name them W) in B, the resulting table produces W.x and W.y.

```<code>library(dplyr)

foo <- data.frame(id = seq(1:6), x = c(NA, NA, NA, 1, 3, 8), z = seq_along(10:15))
bar <- data.frame(id = seq(1:2), x = c(10, 9))
dplyr::left_join(x = foo, y = bar, by = "id")
</code>```

I am trying to replace the missing values in A using the values in B based on the ID, but do so in an efficient manner since I have many columns and many rows. My goal is this:

```<code>  id   x z
1  1  10 1
2  2   9 2
3  3  NA 3
4  4   1 4
5  5   3 5
6  6   8 6
</code>```

One thought was to use ifelse() after joining, but typing out ifelse() functions for all of the variables is not feasible. Is there a way to do this simply without the database join or is there a way to apply a function across all columns ending in .x to replace the values in .x with the value in .y if the value in .x is missing?

答:
EDIT

Updating the answer taking @alistaire 's example dataframe.

We can extend the same answer given below using mapply so that it can handle multiple columns for both foo and bar.

Finding out common columns between two dataframes and sorting them so they are in the same order.

```<code>vars <- sort(intersect(names(foo), names(bar))[-1])
foo[vars] <- mapply(function(x, y) {
             ind = is.na(x)
             replace(x, ind, y[match(foo$id[ind], bar$id)])
             }, foo[vars], bar[vars])

foo
#  id  x y z
#1  1 10 1 1
#2  2  9 2 2
#3  3 NA 3 3
#4  4  1 4 4
#5  5  3 5 5
#6  6  8 6 6
</code>```

Original Answer

I think this does what you are looking for :

```<code>foo[-1] <- sapply(foo[-1], function(x) {
    ind = is.na(x)
    replace(x, ind, bar$x[match(foo$id[ind], bar$id)])
})

foo
#  id  x z
#1  1 10 1
#2  2  9 2
#3  3 NA 3
#4  4  1 4
#5  5  3 5
#6  6  8 6
</code>```

For every column (except id) we find the missing value in foo and replace it with corresponding values from bar.

Body:
I have two data frames. Data frame A has many observations/rows, an ID for each observation, and many additional columns. For a subset of observations X, the values for a set of columns are missing/NA. Data frame B contains a subset of the observations in X (which can be matched across data frames using the ID) and variables with identical names as in data frame A, but containing values to replace the missing values in the set of columns with missing/NA.

My code below (using a join operation) merely adds columns rather than replacing missing values. For each of the additional variables (let's name them W) in B, the resulting table produces W.x and W.y.

library(dplyr)

foo <- data.frame(id = seq(1:6), x = c(NA, NA, NA, 1, 3, 8), z = seq_along(10:15))
bar <- data.frame(id = seq(1:2), x = c(10, 9))
dplyr::left_join(x = foo, y = bar, by = "id")

I am trying to replace the missing values in A using the values in B based on the ID, but do so in an efficient manner since I have many columns and many rows. My goal is this:

  id   x z
1  1  10 1
2  2   9 2
3  3  NA 3
4  4   1 4
5  5   3 5
6  6   8 6

One thought was to use ifelse() after joining, but typing out ifelse() functions for all of the variables is not feasible. Is there a way to do this simply without the database join or is there a way to apply a function across all columns ending in .x to replace the values in .x with the value in .y if the value in .x is missing?

Body:
EDIT

Updating the answer taking @alistaire 's example dataframe.

We can extend the same answer given below using mapply so that it can handle multiple columns for both foo and bar.

Finding out common columns between two dataframes and sorting them so they are in the same order.

vars <- sort(intersect(names(foo), names(bar))[-1])
foo[vars] <- mapply(function(x, y) {
             ind = is.na(x)
             replace(x, ind, y[match(foo$id[ind], bar$id)])
             }, foo[vars], bar[vars])

foo
#  id  x y z
#1  1 10 1 1
#2  2  9 2 2
#3  3 NA 3 3
#4  4  1 4 4
#5  5  3 5 5
#6  6  8 6 6

Original Answer

I think this does what you are looking for :

foo[-1] <- sapply(foo[-1], function(x) {
    ind = is.na(x)
    replace(x, ind, bar$x[match(foo$id[ind], bar$id)])
})

foo
#  id  x z
#1  1 10 1
#2  2  9 2
#3  3 NA 3
#4  4  1 4
#5  5  3 5
#6  6  8 6

For every column (except id) we find the missing value in foo and replace it with corresponding values from bar.


问:
Web Audio API creating a Peak Meter with AnalyserNode
What is the correct way to implement a Peak Meter like those in Logic Pro with the Web Audio API AnalyserNode?

I know AnalyserNode.getFloatFrequencyData() returns decibel values, but how do you combine those values to get the one to be displayed in the meter? Do you just take the maximum value like in the following code sample (where analyserData comes from getFloatFrequencyData():

```<code>let peak = -Infinity;
for (let i = 0; i < analyserData.length; i++) {
  const x = analyserData[i];
  if (x > peak) {
    peak = x;
  }
}
</code>```

Inspecting some output from just taking the max makes it look like this is not the correct approach. Am I wrong?

Alternatively, would it be a better idea to use a ScriptProcessorNode instead? How would that approach differ?

答:
Do you just take the maximum value

For a peak meter, yes.  For a VU meter, there's all sorts of considerations in measuring the power, as well as the ballistics of an analog meter.  There's also RMS power metering.

In digital land, you'll find a peak meter to be most useful for many tasks, and by far the easiest to compute.

A peak for any given set of samples is the highest absolute value in the set.  First though, you need that set of samples.  If you call getFloatFrequencyData(), you're not getting sample values, you're getting the spectrum.  What you want instead is getFloatTimeDomainData().  This data is a low resolution representation of the samples.  That is, you might have 4096 samples in your window, but your analyser might be configured with 256 buckets... so those 4096 samples will be resampled down to 256 samples.  This is generally acceptable for a metering task.

From there, it's just Math.max(-Math.min(samples), Math.max(samples)) to get the max of the absolute value.

Suppose you wanted a higher resolution peak meter.  For that, you need all the raw samples you can get.  That's where a ScriptProcessorNode comes in handy.  You get access to the actual sample data.

Basically, for this task, AnalyserNode is much faster, but slightly lower resolution.  ScriptProcessorNode is much slower, but slightly higher resolution.

ContentLicense: CC BY-SA 4.0

Body:
What is the correct way to implement a Peak Meter like those in Logic Pro with the Web Audio API AnalyserNode?

I know AnalyserNode.getFloatFrequencyData() returns decibel values, but how do you combine those values to get the one to be displayed in the meter? Do you just take the maximum value like in the following code sample (where analyserData comes from getFloatFrequencyData():

let peak = -Infinity;
for (let i = 0; i < analyserData.length; i++) {
  const x = analyserData[i];
  if (x > peak) {
    peak = x;
  }
}

Inspecting some output from just taking the max makes it look like this is not the correct approach. Am I wrong?

Alternatively, would it be a better idea to use a ScriptProcessorNode instead? How would that approach differ?


问:
PHP: How to pass Bearer Token in GET/POST Call to Azure API?
I've made a call to https://login.windows.net/common/oauth2/token and received something like this in response:

```<code>{
    "token_type": "Bearer",
    "scope": "Directory.Read.All User.Read",
    "expires_in": "3600",
    "ext_expires_in": "0",
    "resource": "https://graph.windows.net",
    "access_token": {{really_long_token_1}},
    "refresh_token": {{really_long_token_2}},
    "id_token": {{really_long_token_3}}
}
</code>```

I have a website hosted on HostGator that's trying to access an API I have located on Azure.

What is the correct form of a GET call to my API hosted on Azure? Here's what I have so far:

```<code>$url = 'https://myappservice.azurewebsites.net/api/getValues';

$options = array(
    'http' => array(
        'header' => array(
            'x-ms-version: 2017-06-02',
            'Authorization: Bearer {{really_long_token_1}}'
         ),
        'method' => 'GET'
     )
);

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

$var_dump($result);
</code>```

I end up getting 500 Server Errors while making this call.

答:
The 500 is Internal Error which indicates the server encountered an unexpected condition which prevented it from fulfilling the request.

It should not be relative to the authentication/authorization, please check whether there is code can cause this exception. Or you can just replace the code with a very easy code sample without any complex business logic just return the values.

Body:
I've made a call to https://login.windows.net/common/oauth2/token and received something like this in response:

{
    "token_type": "Bearer",
    "scope": "Directory.Read.All User.Read",
    "expires_in": "3600",
    "ext_expires_in": "0",
    "resource": "https://graph.windows.net",
    "access_token": {{really_long_token_1}},
    "refresh_token": {{really_long_token_2}},
    "id_token": {{really_long_token_3}}
}

I have a website hosted on HostGator that's trying to access an API I have located on Azure.

What is the correct form of a GET call to my API hosted on Azure? Here's what I have so far:

$url = 'https://myappservice.azurewebsites.net/api/getValues';

$options = array(
    'http' => array(
        'header' => array(
            'x-ms-version: 2017-06-02',
            'Authorization: Bearer {{really_long_token_1}}'
         ),
        'method' => 'GET'
     )
);

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

$var_dump($result);

I end up getting 500 Server Errors while making this call.


问:
Regenerate CRSF token codeigniter on submit Ajax
Hi I am looking for the process of regeneration of csrf token in codeigniter when ever a form is submitted using ajax. I want the token to be regenerated without page refresh. Is there any way to do that.</p>

答:
if it's not on session then you controller will be like this

```<code>public function save_date() // or whatever function you like
{
 $regen_token = $this->security->get_csrf_hash();
 $data = array(
      "data" => $this->input->post('datas'),
 );
 $insert = $this->w_m->save($data);
 echo json_encode(array("regen_token" => $regen_token));
}
</code>```

in your ajax will be look like this:

```<code>$.ajax({
 url: "your url",
 type: "POST",
 data: { your data },
 dataType: "JSON",
 success: function(data)
 {
  $("name or id of your csrf").val(JSON.stringify(data.regen_token)).trigger("change"); // this will be the function that every post you'll request and it automatically change the value of your csrf without refreshing the page.
 },
 error: function(errorThrown)
 {
   console.log(errorThrown);
 }
});
</code>```

Body:
if it's not on session then you controller will be like this

public function save_date() // or whatever function you like
{
 $regen_token = $this->security->get_csrf_hash();
 $data = array(
      "data" => $this->input->post('datas'),
 );
 $insert = $this->w_m->save($data);
 echo json_encode(array("regen_token" => $regen_token));
}

in your ajax will be look like this:

$.ajax({
 url: "your url",
 type: "POST",
 data: { your data },
 dataType: "JSON",
 success: function(data)
 {
  $("name or id of your csrf").val(JSON.stringify(data.regen_token)).trigger("change"); // this will be the function that every post you'll request and it automatically change the value of your csrf without refreshing the page.
 },
 error: function(errorThrown)
 {
   console.log(errorThrown);
 }
});


问:
Can not get music to play on my music player app
I am trying to make a music player app for my school project.

When I run the app everything thing works, except for the fact that when I click on a song it does not play.

Please help me with a detailed explanation so i can fix the app.

Here is the code:

```<code>import UIKit
import AVFoundation

var songs:[String] = []
var audioPlayer = AVAudioPlayer()

class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var myTabelView: UITableView!

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return songs.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        cell.textLabel?.text = songs[indexPath.row]
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {

        do
        {
            if let audioPath = Bundle.main.path(forResource: songs[indexPath.row], ofType: ".mp3") {
                try audioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath) as URL)
            }
        } catch {
            print(error.localizedDescription)
        }
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        gettingSongName()
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func gettingSongName()  // Get the names of all the songs
    {
         let folderUrl = URL(fileURLWithPath: Bundle.main.resourcePath!)

        do
        {
            let songPath = try FileManager.default.contentsOfDirectory(at: folderUrl, includingPropertiesForKeys: nil, options: .skipsHiddenFiles) // Axcess all of the song files

            for song in songPath
            {
                var mySong = song.absoluteString

                if mySong.contains(".mp3")
                {
                    let findString = mySong.components(separatedBy: "/")
                    mySong = (findString[findString.count-1])
                    mySong = mySong.replacingOccurrences(of: "%20", with: " ")
                    mySong = mySong.replacingOccurrences(of: ".mp3", with: " ")
                    songs.append(mySong)

                }
            }

            myTabelView.reloadData()
        }
        catch
        {

        }

    }

}
</code>```

答:
you are just initializing the audioPlayer without asking it to play, try adding this in your didSelectRow do block after the after the audioPlayer init </p>

```<code>audioPlayer.prepareToPlay()
audioPlayer.volume = 1.0
audioPlayer.play()
audioPlayer.delegate = self
</code>```

Body:
I am trying to make a music player app for my school project.

When I run the app everything thing works, except for the fact that when I click on a song it does not play.

Please help me with a detailed explanation so i can fix the app.

Here is the code:

import UIKit
import AVFoundation

var songs:[String] = []
var audioPlayer = AVAudioPlayer()

class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var myTabelView: UITableView!

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return songs.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        cell.textLabel?.text = songs[indexPath.row]
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {

        do
        {
            if let audioPath = Bundle.main.path(forResource: songs[indexPath.row], ofType: ".mp3") {
                try audioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath) as URL)
            }
        } catch {
            print(error.localizedDescription)
        }
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        gettingSongName()
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func gettingSongName()  // Get the names of all the songs
    {
         let folderUrl = URL(fileURLWithPath: Bundle.main.resourcePath!)

        do
        {
            let songPath = try FileManager.default.contentsOfDirectory(at: folderUrl, includingPropertiesForKeys: nil, options: .skipsHiddenFiles) // Axcess all of the song files

            for song in songPath
            {
                var mySong = song.absoluteString

                if mySong.contains(".mp3")
                {
                    let findString = mySong.components(separatedBy: "/")
                    mySong = (findString[findString.count-1])
                    mySong = mySong.replacingOccurrences(of: "%20", with: " ")
                    mySong = mySong.replacingOccurrences(of: ".mp3", with: " ")
                    songs.append(mySong)

                }
            }

            myTabelView.reloadData()
        }
        catch
        {

        }

    }

}

Body:
you are just initializing the audioPlayer without asking it to play, try adding this in your didSelectRow do block after the after the audioPlayer init

audioPlayer.prepareToPlay()
audioPlayer.volume = 1.0
audioPlayer.play()
audioPlayer.delegate = self


问:
How do I suppress any error condition in a sql server login trigger
I have a sql server login trigger to audit logins.

I want to suppress any errors being returned from it, as an error prevents login.

How do I do that?

Here's my trigger code

```<code>CREATE TRIGGER [trigLogon_Audit]
ON ALL SERVER
FOR LOGON
AS
    BEGIN
        IF (IS_MEMBER('dbo') = 1) RETURN;
        INSERT INTO Tracking.dbo.Activity (moment, name) VALUES (GETDATE(), ORIGINAL_LOGIN());

    END;
GO

ENABLE TRIGGER [trigLogon_Audit] ON ALL SERVER
GO
</code>```

答:
You can swallow the error silently using try/catch</p>

```<code>CREATE TRIGGER [trigLogon_Audit]
ON ALL SERVER
FOR LOGON
AS
SET NOCOUNT ON
BEGIN TRY
    IF (IS_MEMBER('dbo') = 1) RETURN;
    INSERT INTO Tracking.dbo.Activity (moment, name) VALUES (GETDATE(), ORIGINAL_LOGIN());
END TRY
BEGIN CATCH
   --Do nothing
END CATCH
GO
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a sql server login trigger to audit logins.

I want to suppress any errors being returned from it, as an error prevents login.

How do I do that?

Here's my trigger code

CREATE TRIGGER [trigLogon_Audit]
ON ALL SERVER
FOR LOGON
AS
    BEGIN
        IF (IS_MEMBER('dbo') = 1) RETURN;
        INSERT INTO Tracking.dbo.Activity (moment, name) VALUES (GETDATE(), ORIGINAL_LOGIN());

    END;
GO

ENABLE TRIGGER [trigLogon_Audit] ON ALL SERVER
GO

Body:
You can swallow the error silently using try/catch

CREATE TRIGGER [trigLogon_Audit]
ON ALL SERVER
FOR LOGON
AS
SET NOCOUNT ON
BEGIN TRY
    IF (IS_MEMBER('dbo') = 1) RETURN;
    INSERT INTO Tracking.dbo.Activity (moment, name) VALUES (GETDATE(), ORIGINAL_LOGIN());
END TRY
BEGIN CATCH
   --Do nothing
END CATCH
GO


问:
Updating php mysql_query() to prepared statement
according to some older tutorials i created a formular that stores some information into a mysql DB with mysql_query().
But now i've read some posts, that say one shouldn't use mysql_query() any longer so i've tried to "translate" my old code.
But afterwards it doesn't work anylonger and no new entries are stored in my DB.
Can you help please?

```<code><?php
    require '../db/connect.php';

    if ($mysqli->connect_error) {
      echo "Fehler bei der Verbindung: " . mysqli_connect_error();
      exit();
    }

    $flightDate = $_POST['flightDate'];
    $planeID = $_POST['planeID'];
    $planeType = $_POST['planeType'];
    $pilot = $_POST['pilot'];
    $passengers = $_POST['passengers'];

/*
    $sql = "INSERT INTO `flights`
                (`flightDate`, `planeID`,`planeType`, `pilot`, `passengers`)
            VALUES(
                '" .$flightDate. "',
                '" .$planeID. "',
                '" .$planeType. "',
                '" .$pilot. "',
                '" .$passengers. "'
            )";
    mysql_query( $sql ) or die(mysql_error());
*/

    // prepared statement
    if($stmt = $mysqli->prepare("INSERT INTO flights
                                        (flightDate, planeID,planeType, pilot, passengers)
                                VALUES (?, ?, ?, ?, ?)")) {
      $stmt->bind_param("sssss", $flightDate, $planeID, $planeType, $pilot, $passengers);
      $stmt->execute();
      echo "Anzahl der veränderten Datensätze : " . $stmt->affected_rows;
      $stmt->close();
    }

    $mysqli->close();
</code>```

Seems like there is something wrong with my variables. If i call the php file directly in the browser i get a lot of error messages:

```<code>Notice: Undefined index: flightDate in C:\xampp\htdocs\phptomysql\try_2\ajax\addFlight.php on line 9

Notice: Undefined index: planeID in C:\xampp\htdocs\phptomysql\try_2\ajax\addFlight.php on line 10

Notice: Undefined index: planeType in C:\xampp\htdocs\phptomysql\try_2\ajax\addFlight.php on line 11

Notice: Undefined index: pilot in C:\xampp\htdocs\phptomysql\try_2\ajax\addFlight.php on line 12

Notice: Undefined index: passengers in C:\xampp\htdocs\phptomysql\try_2\ajax\addFlight.php on line 13
Anzahl der veränderten Datensätze : -1
</code>```

I'm using the following jquery function to pass the values from my form to the php:

```<code>//add flight to db
$('#flightSubmit').on('click', function(){
    var flightDate = ($.datepicker.formatDate("yy-mm-dd", $('#flightDateInput').datepicker("getDate")));
    var planeID = $('input#planeIDInput').val();
    var planeType = $('input#planeTypeInput').val();
    var pilot = $('input#pilotInput').val();
    var passengers = $('input#passengersInput').val();
    $.post('ajax/addFlight.php', {flightDate: flightDate, planeID: planeID, planeType: planeType, pilot: pilot, passengers: passengers}, function(data){
        });
});
</code>```

答: You have a mixture of mysql_* calls and mysqli_* calls.  This will not work.  Fix that first.

Body:
according to some older tutorials i created a formular that stores some information into a mysql DB with mysql_query().
But now i've read some posts, that say one shouldn't use mysql_query() any longer so i've tried to "translate" my old code.
But afterwards it doesn't work anylonger and no new entries are stored in my DB.
Can you help please?

<?php
    require '../db/connect.php';

    if ($mysqli->connect_error) {
      echo "Fehler bei der Verbindung: " . mysqli_connect_error();
      exit();
    }

    $flightDate = $_POST['flightDate'];
    $planeID = $_POST['planeID'];
    $planeType = $_POST['planeType'];
    $pilot = $_POST['pilot'];
    $passengers = $_POST['passengers'];

/*
    $sql = "INSERT INTO `flights`
                (`flightDate`, `planeID`,`planeType`, `pilot`, `passengers`)
            VALUES(
                '" .$flightDate. "',
                '" .$planeID. "',
                '" .$planeType. "',
                '" .$pilot. "',
                '" .$passengers. "'
            )";
    mysql_query( $sql ) or die(mysql_error());
*/

    // prepared statement
    if($stmt = $mysqli->prepare("INSERT INTO flights
                                        (flightDate, planeID,planeType, pilot, passengers)
                                VALUES (?, ?, ?, ?, ?)")) {
      $stmt->bind_param("sssss", $flightDate, $planeID, $planeType, $pilot, $passengers);
      $stmt->execute();
      echo "Anzahl der veränderten Datensätze : " . $stmt->affected_rows;
      $stmt->close();
    }

    $mysqli->close();

Seems like there is something wrong with my variables. If i call the php file directly in the browser i get a lot of error messages:

Notice: Undefined index: flightDate in C:\xampp\htdocs\phptomysql\try_2\ajax\addFlight.php on line 9

Notice: Undefined index: planeID in C:\xampp\htdocs\phptomysql\try_2\ajax\addFlight.php on line 10

Notice: Undefined index: planeType in C:\xampp\htdocs\phptomysql\try_2\ajax\addFlight.php on line 11

Notice: Undefined index: pilot in C:\xampp\htdocs\phptomysql\try_2\ajax\addFlight.php on line 12

Notice: Undefined index: passengers in C:\xampp\htdocs\phptomysql\try_2\ajax\addFlight.php on line 13
Anzahl der veränderten Datensätze : -1

I'm using the following jquery function to pass the values from my form to the php:

//add flight to db
$('#flightSubmit').on('click', function(){
    var flightDate = ($.datepicker.formatDate("yy-mm-dd", $('#flightDateInput').datepicker("getDate")));
    var planeID = $('input#planeIDInput').val();
    var planeType = $('input#planeTypeInput').val();
    var pilot = $('input#pilotInput').val();
    var passengers = $('input#passengersInput').val();
    $.post('ajax/addFlight.php', {flightDate: flightDate, planeID: planeID, planeType: planeType, pilot: pilot, passengers: passengers}, function(data){
        });
});


问:
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property
I need to make onetomany relationship but this error appears
mappedBy reference an unknown target entity property
this is parent Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property

```<code>package com.dating.model;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="question")
public class PsyQuestions {

    @Id
    @GenericGenerator(name="autoGen" ,strategy="increment")
    @GeneratedValue(generator="autoGen")
    @Column(name="questionid")
    private long psyQuestionId;
    @Column(name="questiontext")
    private String question;

    @OneToMany(fetch = FetchType.LAZY,mappedBy="question")
    private List<PsyOptions> productlist=new ArrayList<PsyOptions>();

    public PsyQuestions() {
        super();
    }

    public List<PsyOptions> getProductlist() {
        return productlist;
    }

    public void setProductlist(List<PsyOptions> productlist) {
        this.productlist = productlist;
    }

    public long getPsyQuestionId() {
        return psyQuestionId;
    }
    public void setPsyQuestionId(long psyQuestionId) {
        this.psyQuestionId = psyQuestionId;
    }
    public String getQuestion() {
        return question;
    }
    public void setQuestion(String question) {
        this.question = question;
    }
}
</code>```

and this child class

```<code>package com.dating.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="option")
public class PsyOptions {

    @Id
    @GenericGenerator(name="autoGen" ,strategy="increment")
    @GeneratedValue(generator="autoGen")
    @Column(name="optionid")
    private long psyOptionId;
    @Column(name="optiontext")
    private String optionText;

    @JoinColumn(name = "questionid")
    @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
    PsyQuestions psyQuestions;

    public PsyOptions() {
        super();
    }

    public PsyQuestions getPsyQuestions() {
        return psyQuestions;
    }

    public void setPsyQuestions(PsyQuestions psyQuestions) {
        this.psyQuestions = psyQuestions;
    }

    public long getPsyOptionId() {
        return psyOptionId;
    }
    public void setPsyOptionId(long psyOptionId) {
        this.psyOptionId = psyOptionId;
    }
    public String getOptionText() {
        return optionText;
    }
    public void setOptionText(String optionText) {
        this.optionText = optionText;
    }

}
</code>```

答:
Not sure if this is going to help anyone, it was a simple mistake caused this error on my config. Without realising I have had two different packages containing domain class files. Mapped member was in the other package while the application was only scanning single package path.

It was hard to figure out as they were different only by a single character e.g. org.abc.core.domains and org.abcs.core.domains.

Added other package to database @configuration scanners resolved the issue for me.

Body:
I need to make onetomany relationship but this error appears
mappedBy reference an unknown target entity property
this is parent Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property

package com.dating.model;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="question")
public class PsyQuestions {

    @Id
    @GenericGenerator(name="autoGen" ,strategy="increment")
    @GeneratedValue(generator="autoGen")
    @Column(name="questionid")
    private long psyQuestionId;
    @Column(name="questiontext")
    private String question;

    @OneToMany(fetch = FetchType.LAZY,mappedBy="question")
    private List<PsyOptions> productlist=new ArrayList<PsyOptions>();

    public PsyQuestions() {
        super();
    }

    public List<PsyOptions> getProductlist() {
        return productlist;
    }

    public void setProductlist(List<PsyOptions> productlist) {
        this.productlist = productlist;
    }

    public long getPsyQuestionId() {
        return psyQuestionId;
    }
    public void setPsyQuestionId(long psyQuestionId) {
        this.psyQuestionId = psyQuestionId;
    }
    public String getQuestion() {
        return question;
    }
    public void setQuestion(String question) {
        this.question = question;
    }
}

and this child class

package com.dating.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="option")
public class PsyOptions {

    @Id
    @GenericGenerator(name="autoGen" ,strategy="increment")
    @GeneratedValue(generator="autoGen")
    @Column(name="optionid")
    private long psyOptionId;
    @Column(name="optiontext")
    private String optionText;

    @JoinColumn(name = "questionid")
    @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
    PsyQuestions psyQuestions;

    public PsyOptions() {
        super();
    }

    public PsyQuestions getPsyQuestions() {
        return psyQuestions;
    }

    public void setPsyQuestions(PsyQuestions psyQuestions) {
        this.psyQuestions = psyQuestions;
    }

    public long getPsyOptionId() {
        return psyOptionId;
    }
    public void setPsyOptionId(long psyOptionId) {
        this.psyOptionId = psyOptionId;
    }
    public String getOptionText() {
        return optionText;
    }
    public void setOptionText(String optionText) {
        this.optionText = optionText;
    }

}


问:
chrome extension - update tab without changing url
I'm building a small chrome extension, that can open an page in a proxy
for example i'm opening www.mysite.com, and the clicking on my extension button, and it update the page to www.myproxy.net/q=www.mysite.com.
it's working like a charm, but i want to hide the chnage in the adress bar, so the url will remain the original site.
i made a few searches, but can't find out how to do such a thing.

can you please help me?

thanks

my manifest file

```<code>{
"name": "proxy",
"version": "1",
"browser_action": {
    "default_icon" : "icon.png"
},
"permissions": ["tabs"],
"manifest_version": 2,
"background":{
    "scripts": ["popup.js"]
},
"commands": {
  "_execute_browser_action": {
    "suggested_key": {
      "default": "Ctrl+B",
      "windows": "Ctrl+B"
    }
  }
}
</code>```

}

my popup.js

```<code>chrome.browserAction.onClicked.addListener(function(activeTab){
chrome.tabs.query({active: true, currentWindow: true}, function(tab) {
    var newURL = "http://myproxy.net/?q=" + tab[0].url;
    chrome.tabs.update(undefined, {url: newURL});
});
</code>```

});

答:
You can use history.pushState or history.replaceState to do this. Refer to this article https://developer.mozilla.org/en-US/docs/Web/API/History_API

Example:

On the page of www.myproxy.net/q=www.mysite.com, add a script

history.pushState( {} , '', '/' );

Body:
I'm building a small chrome extension, that can open an page in a proxy
for example i'm opening www.mysite.com, and the clicking on my extension button, and it update the page to www.myproxy.net/q=www.mysite.com.
it's working like a charm, but i want to hide the chnage in the adress bar, so the url will remain the original site.
i made a few searches, but can't find out how to do such a thing.

can you please help me?

thanks

my manifest file

{
"name": "proxy",
"version": "1",
"browser_action": {
    "default_icon" : "icon.png"
},
"permissions": ["tabs"],
"manifest_version": 2,
"background":{
    "scripts": ["popup.js"]
},
"commands": {
  "_execute_browser_action": {
    "suggested_key": {
      "default": "Ctrl+B",
      "windows": "Ctrl+B"
    }
  }
}

}

my popup.js

chrome.browserAction.onClicked.addListener(function(activeTab){
chrome.tabs.query({active: true, currentWindow: true}, function(tab) {
    var newURL = "http://myproxy.net/?q=" + tab[0].url;
    chrome.tabs.update(undefined, {url: newURL});
});

});


问:
How to check every combination of a pair?
I have a list of points , and I have to find distance between every pair of points. So, creating a function to find the distance is not important here, but to to create a loop or function which checks if distance between every pair has been calculated.

Below each item in the list represents an id for corresponding point.

```<code>   l = [a, b, c, d, e, f]
</code>```

I want to create a function which checks distance between every pair has been calculated, if not then it calculates the distance with a function say:
      distance_method(a, b)

and stores the value in a data frame as:

```<code> point1      point2          distance
 a           b               some_val
 a           c               some_val
</code>```

Note: distance(a,b) = distance(b,a)

答:
you'll be wanting the itertools module

```<code>>>> import itertools
>>> lst = ['a', 'b', 'c', 'd']
# get pairs from this list, such that you will get things like
# ('b', 'd') but not the reverse ('d', 'b')
>>> list(itertools.combinations(lst, 2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
</code>```

So I think you'll want to do something like (pseudo-code follows):

```<code>for pair in itertools.combinations(lst, 2):
    if not in_dataframe(pair):
        add_to_dataframe(pair)
</code>```

Body:
I have a list of points , and I have to find distance between every pair of points. So, creating a function to find the distance is not important here, but to to create a loop or function which checks if distance between every pair has been calculated.

Below each item in the list represents an id for corresponding point.

   l = [a, b, c, d, e, f]

I want to create a function which checks distance between every pair has been calculated, if not then it calculates the distance with a function say:
      distance_method(a, b)

and stores the value in a data frame as:

 point1      point2          distance
 a           b               some_val
 a           c               some_val

Note: distance(a,b) = distance(b,a)

Body:
you'll be wanting the itertools module

>>> import itertools
>>> lst = ['a', 'b', 'c', 'd']
# get pairs from this list, such that you will get things like
# ('b', 'd') but not the reverse ('d', 'b')
>>> list(itertools.combinations(lst, 2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

So I think you'll want to do something like (pseudo-code follows):

for pair in itertools.combinations(lst, 2):
    if not in_dataframe(pair):
        add_to_dataframe(pair)


问:
ArrayList<Integer> table in data base
i have this code and i want  store my table ArrayList in my database

my code

```<code>public class globaleCollab {

public static void main(String[] args) throws ClassNotFoundException {
    long startTime = System.currentTimeMillis();
    System.out.println(" les rating  :  ");
    String idoperateur = "00000006092";//operateur cible njibh m session

    sort1 sor = new sort1();
    ArrayList<Integer> table = sor.tri();
    String resultat_final = null;
    for (int i = 0; i < table.size(); i++) {

        resultat_final = resultat_final + "," + table.get(i).toString();

    }

    System.out.println(table);
    System.out.println("-------" + resultat_final);
    //insrt id user, resultat_final, temps d'exe, k ,
    long stopTime = System.currentTimeMillis();
    long elapsedTime = stopTime - startTime;

    System.out.println("l temps est " + elapsedTime + "ms");
    Connection con = null;
    PreparedStatement ps;
    ResultSet rs;
    String query;
    try {

        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bd_recommandation", "root", "");

        query = "insert into statistic (idoperateur,id) values(?,?)";
        ps = con.prepareStatement(query);
        ps.setString(1, idoperateur);
         ps.setString(2, resultat_final);
        //ps.setInt(3, k);
        //ps.setLong(4, elapsedTime);
        // ps.setString(2, resultat_final);
        System.out.println("000000000000000000000000000");
        ps.executeUpdate();

    } catch (Exception e) {

    }

}
</code>```

but it did not work

答:
first: catch exception,check sql error or data error
second: ps.setString() method index from 0</p>

Title: ArrayList<Integer> table in data base

Body:
i have this code and i want  store my table ArrayList in my database

my code

public class globaleCollab {

public static void main(String[] args) throws ClassNotFoundException {
    long startTime = System.currentTimeMillis();
    System.out.println(" les rating  :  ");
    String idoperateur = "00000006092";//operateur cible njibh m session

    sort1 sor = new sort1();
    ArrayList<Integer> table = sor.tri();
    String resultat_final = null;
    for (int i = 0; i < table.size(); i++) {

        resultat_final = resultat_final + "," + table.get(i).toString();

    }

    System.out.println(table);
    System.out.println("-------" + resultat_final);
    //insrt id user, resultat_final, temps d'exe, k ,
    long stopTime = System.currentTimeMillis();
    long elapsedTime = stopTime - startTime;

    System.out.println("l temps est " + elapsedTime + "ms");
    Connection con = null;
    PreparedStatement ps;
    ResultSet rs;
    String query;
    try {

        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bd_recommandation", "root", "");

        query = "insert into statistic (idoperateur,id) values(?,?)";
        ps = con.prepareStatement(query);
        ps.setString(1, idoperateur);
         ps.setString(2, resultat_final);
        //ps.setInt(3, k);
        //ps.setLong(4, elapsedTime);
        // ps.setString(2, resultat_final);
        System.out.println("000000000000000000000000000");
        ps.executeUpdate();

    } catch (Exception e) {

    }

}

but it did not work


问:
How much memory does this byte string actually take up?
My understanding is that os.urandom(size) outputs a random string of bytes of the given "size", but then:

```<code>import os
import sys

print(sys.getsizeof(os.urandom(42)))

>>>
75
</code>```

Why is this not 42?

And a related question:

```<code>import base64
import binascii

print(sys.getsizeof(base64.b64encode(os.urandom(42))))
print(sys.getsizeof(binascii.hexlify(os.urandom(42))))

>>>
89
117
</code>```

Why are these so different? Which encoding would be the most memory efficient way to store a string of bytes such as that given by os.urandom?

Edit: It seems like quite a stretch to say that this question is a duplicate of What is the difference between len() and sys.getsizeof() methods in python? My question is not about the difference between len() and getsizeof(). I was confused about the memory used by Python objects in general, which the answer to this question has clarified for me.

答:
Python byte string objects are more than just the characters that comprise them. They are fully fledged objects. As such they require more space to accommodate the object's components such as the type pointer (needed to identify what kind of object the bytestring even is) and the length (needed for efficiency and because Python bytestrings can contain null bytes).

The simplest object, an object instance, requires space:

```<code>>>> sys.getsizeof(object())
16
</code>```

The second part of your question is simply because the strings produced by b64encode() and hexlify() have different lengths; the latter being 28 characters longer which, unsurprisingly, is the difference in the values reported by sys.getsizeof().

```<code>>>> s1 = base64.b64encode(os.urandom(42))
>>> s1
b'CtlMjDM9q7zp+pGogQci8gr0igJsyZVjSP4oWmMj2A8diawJctV/8sTa'
>>> s2 = binascii.hexlify(os.urandom(42))
>>> s2
b'c82d35f717507d6f5ffc5eda1ee1bfd50a62689c08ba12055a5c39f95b93292ddf4544751fbc79564345'

>>> len(s2) - len(s1)
28
>>> sys.getsizeof(s2) - sys.getsizeof(s1)
28
</code>```

Unless you use some form of compression, there is no encoding that will be more efficient than the binary string that you already have, and this is particularly true in this case because the data is random which is inherently incompressible.

Body:
My understanding is that os.urandom(size) outputs a random string of bytes of the given "size", but then:

import os
import sys

print(sys.getsizeof(os.urandom(42)))

>>>
75

Why is this not 42?

And a related question:

import base64
import binascii

print(sys.getsizeof(base64.b64encode(os.urandom(42))))
print(sys.getsizeof(binascii.hexlify(os.urandom(42))))

>>>
89
117

Why are these so different? Which encoding would be the most memory efficient way to store a string of bytes such as that given by os.urandom?

Edit: It seems like quite a stretch to say that this question is a duplicate of What is the difference between len() and sys.getsizeof() methods in python? My question is not about the difference between len() and getsizeof(). I was confused about the memory used by Python objects in general, which the answer to this question has clarified for me.

Body:
Python byte string objects are more than just the characters that comprise them. They are fully fledged objects. As such they require more space to accommodate the object's components such as the type pointer (needed to identify what kind of object the bytestring even is) and the length (needed for efficiency and because Python bytestrings can contain null bytes).

The simplest object, an object instance, requires space:

>>> sys.getsizeof(object())
16

The second part of your question is simply because the strings produced by b64encode() and hexlify() have different lengths; the latter being 28 characters longer which, unsurprisingly, is the difference in the values reported by sys.getsizeof().

>>> s1 = base64.b64encode(os.urandom(42))
>>> s1
b'CtlMjDM9q7zp+pGogQci8gr0igJsyZVjSP4oWmMj2A8diawJctV/8sTa'
>>> s2 = binascii.hexlify(os.urandom(42))
>>> s2
b'c82d35f717507d6f5ffc5eda1ee1bfd50a62689c08ba12055a5c39f95b93292ddf4544751fbc79564345'

>>> len(s2) - len(s1)
28
>>> sys.getsizeof(s2) - sys.getsizeof(s1)
28

Unless you use some form of compression, there is no encoding that will be more efficient than the binary string that you already have, and this is particularly true in this case because the data is random which is inherently incompressible.


问:
How use public key with pyOpenSSL for verify a signed message?
I try to use pyOpenSSL for signed a data, I create key pair (private and publique) and certificate.

I'm a beginner with this technology, I use OpenSSl, but if you have suggestions for generate a signed message with private and public key in python, I'm take !
I want to use RSA and DSA algorithm for my tests.

I find m2Crypto, pyCrypto and other. I do not know what is the best for this.
gnupg for python and pyOpenSSl are more recent visibly.

I used function for signed a message with my private key, and I verify the data.
But when I see the function for verify the signature, in parameters I need :
private key, signature, data and digest type.

I do not know where I am wrong in this code, I find some examples, but I do not understand how this can work because the first parameters for the verify function is a X509 object "certificate is a X509 instance corresponding to the private key which generated the signature." and the second is the signature generated with the private key..

This code work perfectly with the private key :

```<code>from OpenSSL import crypto

_k = crypto.PKey()
_cert = crypto.X509()

# Create keys
_k.generate_key(crypto.TYPE_RSA, 2048)

# Add argument for create certificate
_cert.gmtime_adj_notBefore(0)
_cert.gmtime_adj_notAfter(0*365*24*60*60) #10 years expiry date
_cert.set_pubkey(_k)
_cert.sign(_k, 'sha256')

# Create key's file
with open("public_key.pem",'w') as f:
    f.write(crypto.dump_publickey(crypto.FILETYPE_PEM, _k))

with open("private_key.pem",'w') as f:
    f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, _k))

with open("certificate.pem",'w') as f:
    f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, _cert))

#-------------------------------------------------------------------------------

# Open key and load in var
with open("private_key.pem",'r') as f:
    priv_key = crypto.load_privatekey(crypto.FILETYPE_PEM, f.read())

with open("public_key.pem",'r') as f:
    pub_key = crypto.load_publickey(crypto.FILETYPE_PEM, f.read())

with open("certificate.pem",'r') as f:
    cert = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())

# sign message 'hello world' with private key and certificate
sign = crypto.sign(priv_key, "hello world", 'sha256')
print crypto.verify(cert, sign, "hello world", 'sha256')
</code>```

So, my question is, how use the public key for verify the data ?
If Bob give a public key to alice, How it checks the message with this public key ?

You have a idea ?

Thanks a lot,
Romain

答:
I found a answer in this post.

```<code>from OpenSSL.crypto import load_publickey, FILETYPE_PEM, verify, X509
# ... code ...
x509 = X509()
x509.set_pubkey(pub_key)
# ... code ...
print verify(x509, sign, sha, 'sha256')
</code>```

I'm wondering.. When I get a message, I use the public key for authenticating the transmitter, but why I have to use the signature to do the verification ? To generate the signature, I need the private key ..
Is there something I did not understand in the use of the library ?

Body:
I try to use pyOpenSSL for signed a data, I create key pair (private and publique) and certificate.

I'm a beginner with this technology, I use OpenSSl, but if you have suggestions for generate a signed message with private and public key in python, I'm take !
I want to use RSA and DSA algorithm for my tests.

I find m2Crypto, pyCrypto and other. I do not know what is the best for this.
gnupg for python and pyOpenSSl are more recent visibly.

I used function for signed a message with my private key, and I verify the data.
But when I see the function for verify the signature, in parameters I need :
private key, signature, data and digest type.

I do not know where I am wrong in this code, I find some examples, but I do not understand how this can work because the first parameters for the verify function is a X509 object "certificate is a X509 instance corresponding to the private key which generated the signature." and the second is the signature generated with the private key..

This code work perfectly with the private key :

from OpenSSL import crypto

_k = crypto.PKey()
_cert = crypto.X509()

# Create keys
_k.generate_key(crypto.TYPE_RSA, 2048)

# Add argument for create certificate
_cert.gmtime_adj_notBefore(0)
_cert.gmtime_adj_notAfter(0*365*24*60*60) #10 years expiry date
_cert.set_pubkey(_k)
_cert.sign(_k, 'sha256')

# Create key's file
with open("public_key.pem",'w') as f:
    f.write(crypto.dump_publickey(crypto.FILETYPE_PEM, _k))

with open("private_key.pem",'w') as f:
    f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, _k))

with open("certificate.pem",'w') as f:
    f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, _cert))

#-------------------------------------------------------------------------------

# Open key and load in var
with open("private_key.pem",'r') as f:
    priv_key = crypto.load_privatekey(crypto.FILETYPE_PEM, f.read())

with open("public_key.pem",'r') as f:
    pub_key = crypto.load_publickey(crypto.FILETYPE_PEM, f.read())

with open("certificate.pem",'r') as f:
    cert = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())

# sign message 'hello world' with private key and certificate
sign = crypto.sign(priv_key, "hello world", 'sha256')
print crypto.verify(cert, sign, "hello world", 'sha256')

So, my question is, how use the public key for verify the data ?
If Bob give a public key to alice, How it checks the message with this public key ?

You have a idea ?

Thanks a lot,
Romain

Body:
I found a answer in this post.

from OpenSSL.crypto import load_publickey, FILETYPE_PEM, verify, X509
# ... code ...
x509 = X509()
x509.set_pubkey(pub_key)
# ... code ...
print verify(x509, sign, sha, 'sha256')

I'm wondering.. When I get a message, I use the public key for authenticating the transmitter, but why I have to use the signature to do the verification ? To generate the signature, I need the private key ..
Is there something I did not understand in the use of the library ?


问:
Computer simulation of the brain
I've been hunting on the net periodically for several months for an answer to this with no joy. Grateful if anyone can shed any light..

I'm interested in work that's been done on simulating the human brain. I could of course mean many things by that. Here's what I do mean, followed by what I don't mean:

I AM interested in simulations of how we think and feel. I'm not talking about down to the level of neurons, but more simulation of the larger modules that are involved. For example one might simulate the 'anger' module as a service that measures the degree one has been disrespected (in some system of representation) and outputs an appropriate measure of anger (again in some system of representation).

I am NOT interested in projects like the Blue Brain etc, where accurate models of neuron clusters are being built. I'm interested in models operating at much higher levels of abstraction, on the level of emotional modules, cognitive reasoning systems etc.

I'm also NOT interested in AI projects that take as their inspiration or paradigm human mechanisms, like Belief-Desire-Intention systems, but which are not actually trying to replicate human behavior. Interesting though these systems are, I'm not interested in making effective systems, but effectively modelling human thought and emotion.

I've been searching far and wide, but all I've found are papers from the 60s like this one:
 Computer Simulation of Human Interaction in Small Groups

It almost appears to me as if psychologists were excited by simulating brains when computers were first available, but now don't do it at all?

Can anyone point me in the direction of more recent research/efforts, if there have been any?

答:
You might be interested in work on Affective Computing:

http://en.wikipedia.org/wiki/Affective_computing

http://affect.media.mit.edu/

http://psychometrixassociates.com/bio.htm

Title: Computer simulation of the brain