问:
window.top.location not working in older version of Browsers
I wrote a script which redirects user on page refresh. I got it working on newer versions of Firefox, chrome and Internet explorer. However, most of my users still using older version of browsers and this script is not working on those. Which approaching I should do to get it working ? </p>

```<code>var redirecting= false;
window.onbeforeunload = function() {
    if (redirecting) return;

        setTimeout(function() {

            window.top.location.href= 'http://www.google.com';
   setTimeout(function() {
      redirecting=true;
  }, 1000);
        }, 1);

};
</code>```

答:
change

```<code>window.top.location.href= 'http://www.google.com';
</code>```

to

```<code>top.window.location.href = 'http://www.google.com';
</code>```

Body:
I wrote a script which redirects user on page refresh. I got it working on newer versions of Firefox, chrome and Internet explorer. However, most of my users still using older version of browsers and this script is not working on those. Which approaching I should do to get it working ?

var redirecting= false;
window.onbeforeunload = function() {
    if (redirecting) return;

        setTimeout(function() {

            window.top.location.href= 'http://www.google.com';
   setTimeout(function() {
      redirecting=true;
  }, 1000);
        }, 1);

};

Body:
change

window.top.location.href= 'http://www.google.com';

to

top.window.location.href = 'http://www.google.com';


来源: stackexchange

问:
Help in :hover CSS
Does :hover in css only works on  tags? Or it can work on any HTML tags? Thank you.

答:
Quirksmode has the answer!.

The summary: IE6 only supports :hover on links. Everyone else supports them everywhere.

ContentLicense: CC BY-SA 2.5

Title: Help in :hover CSS


问:
How to logout a user from the database with flask-login
I have a web application made with python/flask, and I use flask-login to authenticate users. In the user interface a user can logout. But the user can also be logged out by the database (when a session expires, or when the user expires).

My user loader looks like this:

```<code>@login_manager.user_loader
def user_loader(id):
    user = SessionUser.find_by_session_id(id) #hits the database
    if user is None:
        flash('You have been automatically logged out')
        #flask_login.logout_user() #RecursionError: maximum recursion depth exceeded
        session['user_id'] = None
    return user
</code>```

When the database can't find the id, I want the user to be logged out. Reasons are: there is no need to hit the SessionUser.find_by_session_id-call more than once if an id can't be found. Also, I want show a message the user has been logged out (and I only want to show this once). Finally, when a user is logged out of the database, I want to user the unauthenticated templates.

If I don't have the if user is None: code, the user loader it hit with every request. There are two problems with this:

I can't flash the message "You have been automatically logged out" (because it will keep on showing)

There is an unnecessary database hit.

I fixed this by clearing the session-variable user_id, but this is an unwanted solution, since it users the internals of flask_login, not an API.

What would be the best approach?

答:
I don't think you need to manually logout user if his session has expired in database.

Check this.

As you can see, if user_loader return None, that means this user is invalid, so it will be removed from current session which is the same as logout. So what you need to do is just return SessionUser.find_by_session_id(id).

Update

The following snippet should work as you expect. If not, there may be something else wrong.

```<code>@login_manager.user_loader
def user_loader(id):
    # print(id)  # try printing current user's id to check.
    user = SessionUser.find_by_session_id(id) #hits the database
    if user is None:
        flash('You have been automatically logged out')
    return user
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a web application made with python/flask, and I use flask-login to authenticate users. In the user interface a user can logout. But the user can also be logged out by the database (when a session expires, or when the user expires).

My user loader looks like this:

@login_manager.user_loader
def user_loader(id):
    user = SessionUser.find_by_session_id(id) #hits the database
    if user is None:
        flash('You have been automatically logged out')
        #flask_login.logout_user() #RecursionError: maximum recursion depth exceeded
        session['user_id'] = None
    return user

When the database can't find the id, I want the user to be logged out. Reasons are: there is no need to hit the SessionUser.find_by_session_id-call more than once if an id can't be found. Also, I want show a message the user has been logged out (and I only want to show this once). Finally, when a user is logged out of the database, I want to user the unauthenticated templates.

If I don't have the if user is None: code, the user loader it hit with every request. There are two problems with this:

I can't flash the message "You have been automatically logged out" (because it will keep on showing)

There is an unnecessary database hit.

I fixed this by clearing the session-variable user_id, but this is an unwanted solution, since it users the internals of flask_login, not an API.

What would be the best approach?

Body:
I don't think you need to manually logout user if his session has expired in database.

Check this.

As you can see, if user_loader return None, that means this user is invalid, so it will be removed from current session which is the same as logout. So what you need to do is just return SessionUser.find_by_session_id(id).

Update

The following snippet should work as you expect. If not, there may be something else wrong.

@login_manager.user_loader
def user_loader(id):
    # print(id)  # try printing current user's id to check.
    user = SessionUser.find_by_session_id(id) #hits the database
    if user is None:
        flash('You have been automatically logged out')
    return user


问:
Can I run spark 2.0.* artifact on a spark 2.2.* stand-alone cluster?
I am aware of the fact that with the change of major version of spark (i.e. from 1.* to 2.*) there will be compile time failures due to changes in existing APIs.

As per my knowledge spark guarantees that with minor version update (i.e. 2.0.* to 2.2.*), changes will be backward compatible.

Although this will eliminate the possibility of compile-time failures with upgrade, would it be safe to assume that there won't be any run time failure too if submit a job on spark 2.2.* stand alone cluster using an artifact(jar) created using 2.0.* dependencies?

答:
would it be safe to assume that there won't be any run time failure too if submit a job on 2.2.* cluster using an artifact(jar) created using 2.0.* dependencies?

Yes.

I'd even say that there's no concept of a Spark cluster unless we talk about the built-in Spark Standalone cluster.

In other words, you deploy a Spark application to a cluster, e.g. Hadoop YARN or Apache Mesos, as a application jar that may or may not contain Spark jars and so disregard what's already available in the environment.

If however you do think of Spark Standalone, things may have been broken between releases even between 2.0 and 2.2 as the jars in your Spark application have to be compatible with the ones on JVM of Spark workers (they are already pre-loaded).

I would not claim full compatibility between releases of Spark Standalone.


问:
ng-grid unable to edit cell
I have very simple ngGrid layout. When I try to edit a cell in cell edit mode, I can only enter one character. If I enter another character, the previous one gets overwritten.If I paste a string and then press any character it will remove the previous string and replace with a single character.
I am not sure why this is causing.</p>

```<code>app.controller ('TableEditCtrl',function($scope){
$scope.myData =[{"Time":"","OldValue":"","NewValue":"", "Action" : "NoChange"}];
$scope.gridOptions = {
        data: 'myData',
        columnDefs : [{field: 'Time' , displayName : 'Time', enableCellEdit : true}]

});

<div ng-grid="gridOptions" style="margin-top : 1%;float : left; height : 400px"></div>
</code>```

答:
Try this with editableCellTemplate

```<code>columnDefs : [{field: 'Time' , displayName : 'Time', enableCellEdit : true, editableCellTemplate: '<div><form name="inputForm"><input type="text" ng-class="\'colt\' + col.uid" ui-grid-editor ng-model="MODEL_COL_FIELD"  /></form></div>' }]
</code>```

Title: ng-grid unable to edit cell

Body:
I have very simple ngGrid layout. When I try to edit a cell in cell edit mode, I can only enter one character. If I enter another character, the previous one gets overwritten.If I paste a string and then press any character it will remove the previous string and replace with a single character.
I am not sure why this is causing.

app.controller ('TableEditCtrl',function($scope){
$scope.myData =[{"Time":"","OldValue":"","NewValue":"", "Action" : "NoChange"}];
$scope.gridOptions = {
        data: 'myData',
        columnDefs : [{field: 'Time' , displayName : 'Time', enableCellEdit : true}]

});

Body:
Try this with editableCellTemplate

columnDefs : [{field: 'Time' , displayName : 'Time', enableCellEdit : true, editableCellTemplate: '<div><form name="inputForm"><input type="text" ng-class="\'colt\' + col.uid" ui-grid-editor ng-model="MODEL_COL_FIELD"  /></form></div>' }]


问:
How do I get a list of ACPI devices on a Linux Kernel Driver?
I am developing a Linux Kernel Driver. Part of the requirement is to get a list of ACPI devices on the system and iterate through. While the following code worked for user-mode, it does not get compiled on kernel.

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

int main(void)
{
   DIR           * d;
   struct dirent * dir;
   d = opendir("/sys/bus/acpi/devices");

   if (d)
   {
      while ((dir = readdir(d)) != NULL)
      {
         printf("%s\n", dir->d_name);
      }

      closedir(d);
   }

   return 0;
}
</code>```

Is there a similar function that is available in kernel for me to get list of ACPI devices?

答:
The code that you have written in using linux userspace header files and functions which are not used in kernel. Linux kernel has its own way of dealing with devices.

In kernel : The ACPI implementation enumerates devices behind busses (platform, SPI and I2C), creates the physical devices and binds them to their ACPI handle in the ACPI namespace. Read full kernel text here.

Body:
I am developing a Linux Kernel Driver. Part of the requirement is to get a list of ACPI devices on the system and iterate through. While the following code worked for user-mode, it does not get compiled on kernel.

#include <dirent.h>
#include <stdio.h>

int main(void)
{
   DIR           * d;
   struct dirent * dir;
   d = opendir("/sys/bus/acpi/devices");

   if (d)
   {
      while ((dir = readdir(d)) != NULL)
      {
         printf("%s\n", dir->d_name);
      }

      closedir(d);
   }

   return 0;
}

Is there a similar function that is available in kernel for me to get list of ACPI devices?


问:
CannotListenError: Couldn't listen on any:9008: [Errno 98] Address already in use
I am working on Autobahn's app on websocket over python.
I found one problem, if I restart my server code once after interrupting then my server code will send me error like: </p>

```<code>2016-03-03 13:20:34+0530 [-] Log opened.
2016-03-03 13:20:34+0530 [-] Traceback (most recent call last):
2016-03-03 13:20:34+0530 [-]   File "TestServer.py", line 23, in <module>
2016-03-03 13:20:34+0530 [-]     reactor.listenTCP(9008, factory)
2016-03-03 13:20:34+0530 [-]   File "/home/ddserver/python1/local/lib/python2.7/site-packages/twisted/internet/posixbase.py", line 478, in listenTCP
2016-03-03 13:20:34+0530 [-]     p.startListening()
2016-03-03 13:20:34+0530 [-]   File "/home/ddserver/python1/local/lib/python2.7/site-packages/twisted/internet/tcp.py", line 984, in startListening
2016-03-03 13:20:34+0530 [-]     raise CannotListenError(self.interface, self.port, le)
2016-03-03 13:20:34+0530 [-] twisted.internet.error.CannotListenError: Couldn't listen on any:9008: [Errno 98] Address already in use.
</code>```

<p>I understand by error is there are some basic services which is running on behind even after interrupting server, but how clear all such ports ? </p>

答:
sudo lsof -i TCP:9008 | grep LISTEN works well.

Refer to Python twisted reactor - address already in use

Body:
I am working on Autobahn's app on websocket over python.
I found one problem, if I restart my server code once after interrupting then my server code will send me error like:

2016-03-03 13:20:34+0530 [-] Log opened.
2016-03-03 13:20:34+0530 [-] Traceback (most recent call last):
2016-03-03 13:20:34+0530 [-]   File "TestServer.py", line 23, in <module>
2016-03-03 13:20:34+0530 [-]     reactor.listenTCP(9008, factory)
2016-03-03 13:20:34+0530 [-]   File "/home/ddserver/python1/local/lib/python2.7/site-packages/twisted/internet/posixbase.py", line 478, in listenTCP
2016-03-03 13:20:34+0530 [-]     p.startListening()
2016-03-03 13:20:34+0530 [-]   File "/home/ddserver/python1/local/lib/python2.7/site-packages/twisted/internet/tcp.py", line 984, in startListening
2016-03-03 13:20:34+0530 [-]     raise CannotListenError(self.interface, self.port, le)
2016-03-03 13:20:34+0530 [-] twisted.internet.error.CannotListenError: Couldn't listen on any:9008: [Errno 98] Address already in use.

I understand by error is there are some basic services which is running on behind even after interrupting server, but how clear all such ports ?


问:
Iterate through two dimensional array while changing each element
I want to fill a two dimensional array with certain values. I want to get:

```<code>[
  ['Num00', 'Num01', 'Num02'],
  ['Num10', 'Num11', 'Num12'],
  ['Num20', 'Num21', 'Num22']
]
</code>```

How can I do it?

This is my code:

```<code>game_field = Array.new(3, Array.new(3))
3.times do |i|
  3.times do |j|
    game_field[i][j] = 'Num' + i.to_s + j.to_s
  end
end
game_field
</code>```

答:
Just out of curiosity:</p>

```<code>([(?0..?2)] * 2).
  map(&:to_a).
  reduce(:product).
  each_slice(3).
  map { |e| e.map(&:join).map(&'Num'.method(:+)) }
</code>```

Body:
I want to fill a two dimensional array with certain values. I want to get:

[
  ['Num00', 'Num01', 'Num02'],
  ['Num10', 'Num11', 'Num12'],
  ['Num20', 'Num21', 'Num22']
]

How can I do it?

This is my code:

game_field = Array.new(3, Array.new(3))
3.times do |i|
  3.times do |j|
    game_field[i][j] = 'Num' + i.to_s + j.to_s
  end
end
game_field

Body:
Just out of curiosity:

([(?0..?2)] * 2).
  map(&:to_a).
  reduce(:product).
  each_slice(3).
  map { |e| e.map(&:join).map(&'Num'.method(:+)) }


问:
Entity Framework if statement inside select
I have a problem in generating an Entity Framework query and not okay with linq style one :.....

This is my attempt:

```<code>var query = db.table
              .Where(x => x.colA == 1)
              .GroupBy(x => new {x.min,x.max})
              .Select(y => if(y.key.min==0 && y.key.max==0)
                              { " unchanged " }
                           else
                              { y.key.min.tostring()+" "+y.key.max.tostring() })
              .ToList()
</code>```

I want to get "unchanged" string, if both value ofmin and max are zero, otherwise concat them

答:
For this specific case, you can use Conditional Operator (?:)

```<code>var query = db.table
            .Where(x=> x.colA == 1)
            .GroupBy(x=> new {x.min,x.max})
            .Select(y=> (y.Key.min == 0 && y.Key.max == 0) ? " unchanged" : (y.Key.min.ToString()+" "+y.Key.max.ToString()))
            .ToList();
</code>```

Body:
I have a problem in generating an Entity Framework query and not okay with linq style one :.....

This is my attempt:

var query = db.table
              .Where(x => x.colA == 1)
              .GroupBy(x => new {x.min,x.max})
              .Select(y => if(y.key.min==0 && y.key.max==0)
                              { " unchanged " }
                           else
                              { y.key.min.tostring()+" "+y.key.max.tostring() })
              .ToList()

I want to get "unchanged" string, if both value ofmin and max are zero, otherwise concat them

Body:
For this specific case, you can use Conditional Operator (?:)

var query = db.table
            .Where(x=> x.colA == 1)
            .GroupBy(x=> new {x.min,x.max})
            .Select(y=> (y.Key.min == 0 && y.Key.max == 0) ? " unchanged" : (y.Key.min.ToString()+" "+y.Key.max.ToString()))
            .ToList();


问:
Creating custom "instruction tips"
I would like to create a view which i could place beside a specific function on the screen as instruction. This "instructiontip" thing will show automatically according to some rules.

The advice I'm seeking is about the way to put such a view anywhere on the screen above all else and not affected by parent type, fx. if added dynamically to a view which root layout is LinearLayout (vertical), I of course don't want it to be places under the last element. I'll place it using coordinates on screen and would expect it to show exactly there.

Here is a design shot for impression:

I keep thinking that there must be a better way of doing that then just adding it and hoping it will show in place.

答:
Activity.AddContentView is a good way of adding such a view above everything else without affecting whatever is beneath.

The only downside is that you can't remove this view after you added it.. but you can hide it if you need to.

Title: Creating custom "instruction tips"


问:
Copy 1 TB Google Cloud Storage from container a to b - Run-time?
How long would it on average take to copy files with a total size of 1TB within Google Cloud Storage (Regional Storage) from a container a to b?

e.g. gsutil -m cp gs://gdfp-performance/*.csv gs://gdfp-intrastoragetransfer

答: Transfer Rate 1 Gib/s - Can performance be improved?GCS transfer rate 1 GiB/s</p>


问:
How to check-in the file in TFS which is checked out for edit with its check-in requirement
Below is the code which checks out a file from TFS and after it gets checked out, an updated file is copied at local path which I need to check-in to TFS. While checking in, I need to add the value in WorkItem by ID option present under Related Work Items heading and also the comments and other options.

```<code> $TFSCheckoutExe="C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\TF.exe"
    #File to be checked-out in TFS
    $TFSFilePath="$/Intell/Installscript/Utility Scripts/powershells/DI_UTC_Test.PS1"

    #This file needs to be checked-in in TFS after some changes are done.
    $Localfilepath="C:\Intell\Installscript\Utility Scripts\powershells\DI_UTC_Test.PS1"

    $demo="C:\demo\files to check in"

    #Checking out file
    &$TFSCheckoutExe checkout $TFSFilePath | Out-Null

    #Copying the updated file to the mapped path of the file checked out.
    Copy-Item -path $demo -Destination "$Localfilepath" -Force

    #How to Checkin the copied file in TFS
    $ItemPath = "C:\Intell\Installscript\Utility Scripts\powershells\DI_UTC_Test.PS1"

    #Checkin the file by passing the required details which are require for checkin in any file.
    $null = & $TFSCheckoutExe checkin $Itempath /comment:"Added POC file" /notes:"Code reviewer=None ; Unit Testing=N/A ; Build Details=N/A" /Related Work Items:"Add Work Item by ID=86165"
</code>```

The above code is giving error at last line for "/Related Work Items:"Add Work Item by ID=81165" which I want to add while checking in, which is nothing but the PBI number.

Below is the error which occurs while executing the script:

```<code>    TF.exe : TF10139: The following check-in policies have not been satisfied:
At C:\Demo\powershell scripts\demo1.ps1:17 char:9
+ $null = & $TFSCheckoutExe checkin $Itempath /comment:"Added POC file" /notes:"Co ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (TF10139: The fo...been satisfied::String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

  You must associate this check-in with one or more work items.
</code>```

答:
Unfortunately for TFVC with Team Explorer in VS, "tf.exe checkin" does not support associating work items from the command line. There isn't the parameter:/Related Work Items.
See Checkin command for details.

Also an issue tracked here : https://github.com/Microsoft/vsts-vscode/issues/191

However you can try using Team Explorer Everywhere with the below command to
associate one or more work items with the changeset:

```<code>tf checkin ItemSpec -associate:WorkItemIds
</code>```

See Associate Work Items with Changesets (Team Explorer Everywhere) for details.

Also this thread for your reference : Link command line tf checkin to work item

Body:
Below is the code which checks out a file from TFS and after it gets checked out, an updated file is copied at local path which I need to check-in to TFS. While checking in, I need to add the value in WorkItem by ID option present under Related Work Items heading and also the comments and other options.

 $TFSCheckoutExe="C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\TF.exe"
    #File to be checked-out in TFS
    $TFSFilePath="$/Intell/Installscript/Utility Scripts/powershells/DI_UTC_Test.PS1"

    #This file needs to be checked-in in TFS after some changes are done.
    $Localfilepath="C:\Intell\Installscript\Utility Scripts\powershells\DI_UTC_Test.PS1"

    $demo="C:\demo\files to check in"

    #Checking out file
    &$TFSCheckoutExe checkout $TFSFilePath | Out-Null

    #Copying the updated file to the mapped path of the file checked out.
    Copy-Item -path $demo -Destination "$Localfilepath" -Force

    #How to Checkin the copied file in TFS
    $ItemPath = "C:\Intell\Installscript\Utility Scripts\powershells\DI_UTC_Test.PS1"

    #Checkin the file by passing the required details which are require for checkin in any file.
    $null = & $TFSCheckoutExe checkin $Itempath /comment:"Added POC file" /notes:"Code reviewer=None ; Unit Testing=N/A ; Build Details=N/A" /Related Work Items:"Add Work Item by ID=86165"

The above code is giving error at last line for "/Related Work Items:"Add Work Item by ID=81165" which I want to add while checking in, which is nothing but the PBI number.

Below is the error which occurs while executing the script:

    TF.exe : TF10139: The following check-in policies have not been satisfied:
At C:\Demo\powershell scripts\demo1.ps1:17 char:9
+ $null = & $TFSCheckoutExe checkin $Itempath /comment:"Added POC file" /notes:"Co ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (TF10139: The fo...been satisfied::String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

  You must associate this check-in with one or more work items.

Body:
Unfortunately for TFVC with Team Explorer in VS, "tf.exe checkin" does not support associating work items from the command line. There isn't the parameter:/Related Work Items.
See Checkin command for details.

Also an issue tracked here : https://github.com/Microsoft/vsts-vscode/issues/191

However you can try using Team Explorer Everywhere with the below command to
associate one or more work items with the changeset:

tf checkin ItemSpec -associate:WorkItemIds

See Associate Work Items with Changesets (Team Explorer Everywhere) for details.

Also this thread for your reference : Link command line tf checkin to work item


问:
Firebase gets invalid email error message
I get this error after creating user and tried to send verification email always get this error for invalid email, while the email is registered and valid.

Optional(Error Domain=FIRAuthErrorDomain Code=17008 "Missing sender" UserInfo={NSLocalizedDescription=Missing sender, error_name=ERROR_INVALID_EMAIL})

```<code>Auth.auth().currentUser?.sendEmailVerification(completion: { (error) in
    if error != nil {
        print(error.debugDescription)

        let alert = UIAlertController(title: NSLocalizedString("Error", comment: "Error"), message: NSLocalizedString("Unable to send verification, Please check provided email and try again.", comment: "Unable to send verification, Please check provided email and try again."), preferredStyle: .actionSheet)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
        }))
        self.present(alert, animated: true, completion: nil)
        AppDelegate.instance().dismissActivityIndicatos()
        return
    }
</code>```

Thanks for your help

答: It says missing sender. This could be an issue in your email template. Did you customize the email sender field in the Firebase Console by any chance?

Body:
I get this error after creating user and tried to send verification email always get this error for invalid email, while the email is registered and valid.

Optional(Error Domain=FIRAuthErrorDomain Code=17008 "Missing sender" UserInfo={NSLocalizedDescription=Missing sender, error_name=ERROR_INVALID_EMAIL})

Auth.auth().currentUser?.sendEmailVerification(completion: { (error) in
    if error != nil {
        print(error.debugDescription)

        let alert = UIAlertController(title: NSLocalizedString("Error", comment: "Error"), message: NSLocalizedString("Unable to send verification, Please check provided email and try again.", comment: "Unable to send verification, Please check provided email and try again."), preferredStyle: .actionSheet)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
        }))
        self.present(alert, animated: true, completion: nil)
        AppDelegate.instance().dismissActivityIndicatos()
        return
    }

Thanks for your help


问:
Why my logistic regression always predict value near 0
I am trying to write a logistic regression with L1 regularization.I use stochastic gradient ascend of log-likelihood as the cost function. But my function always give out values that near 0. My dataset is from http://archive.ics.uci.edu/ml/datasets/HTRU2

Here is the example, where y_hat is the output of the predict function and y[i] is the true value of the target:

```<code>y_hat: [ 0.08707034] y[i]: 0
y_hat - y[i]: [ 0.08707034]
y_hat: [ 0.06406335] y[i]: 0
y_hat - y[i]: [ 0.06406335]
y_hat: [ 0.04818193] y[i]: 0
y_hat - y[i]: [ 0.04818193]
y_hat: [ 0.19760354] y[i]: 1
y_hat - y[i]: [-0.80239646]
y_hat: [ 0.08982549] y[i]: 0
y_hat - y[i]: [ 0.08982549]
y_hat: [ 0.0844086] y[i]: 1
y_hat - y[i]: [-0.9155914]
</code>```

And here is the accuracy when the threshold is 0.5

```<code>threshold= 0.5
acc= 0.0159217877095
</code>```

and here is my logistic sgd code

```<code>def logreg_sgd(X, y, alpha = .001, iters = 100000, eps=1e-4):
    n, d = X.shape
    theta = numpy.zeros((d, 1))
    k = 0
    lam = 0.001

    for k in range(iters):
        i = k%n
        x = X[i, :]
        xT = numpy.transpose([x])
        y_hat = sigmoid(x, theta)
        beta = de_norm1(theta)

        func_g = (y[i] - y_hat)*xT + lam*beta

        theta_k = theta.copy()
        theta = theta + alpha*func_g
        for delta in abs(theta-theta_k):
            if delta > eps:
                break

    return theta

def de_norm1(theta):
    d, _ = theta.shape
    beta = numpy.zeros((d, 1))

    for i in range(d):
        if theta[i,0] < 0:
            beta[i,0] = -1
        elif theta[i,0] > 0:
            beta[i,0] = 1
    return beta

def sigmoid(X, theta):
    z = numpy.dot(X, theta)
    value = 1.0/(1.0 + numpy.exp(-z))
    return value
</code>```

I can not figure out why it is wrong

Below is the second edit content.

here is the roc_curve I draw.

roc curve

and the code to draw roc cureve

```<code># plot the ROC curve of your prediction
# x aixes: TPR = TP / ( TP + FN )
# y aixes: FPR = FP / ( FP + TN )
def plot_roc_curve(X_test, y_true, theta):
    k = 51
    FPR_x = numpy.zeros(k)
    TPR_y = numpy.zeros(k)

    for n in range(k):
        threshold = n/(k-1)
        y_pred, FPR, TPR = predict(X_test, y_true, theta, threshold)
        tn, fp, fn, tp = sklearn.metrics.confusion_matrix(y_true, y_pred).ravel()
        FPR_x[n] = fp/(fp+tn)
        TPR_y[n] = tp/(tp+fn)
        print(FPR_x[n], TPR_y[n])

    plt.xlabel('FPR')
    plt.ylabel('TPR')
    plt.plot(FPR_x, TPR_y, '-')
    # plt.scatter(FPR_x, TPR_y, marker='o', color='blue')
    plt.show()
</code>```

Here is the predict(classify) fuction

```<code>def predict(X, y_true, theta, threshold):
    value = sigmoid(X, theta)
    row, col = X.shape
    y_hat = numpy.zeros(row)
    P = sum(y_true)
    N = row - P
    FP = 0.0
    TP = 0.0
    print('P =', P)

    for i, val in enumerate(value):
        if val > threshold:
            y_hat[i] = 1
            TP+=1
        else:
            y_hat[i] = 0
        if y_true[i] != y_hat[i]:
            if y_true[i] == 0:
                FP+=1
    FPR = FP/N
    TPR = TP/P
    return y_hat, FPR, TPR
</code>```

my data load function

```<code>def load_train_test_data(train_ratio=.8):
    data = pandas.read_csv('./HTRU2/HTRU_2.csv', header=None)

    X = data.iloc[:,:8]
    X = numpy.concatenate((numpy.ones((len(X), 1)), X), axis=1)
    y = data.iloc[:,8]
    y = numpy.array(y)
    return sklearn.model_selection.train_test_split(X, y, test_size = 1 - train_ratio, random_state=0)
</code>```

The scale function

```<code>def scale_features(X_train, X_test, low=0, upp=1):
    minmax_scaler = sklearn.preprocessing.MinMaxScaler(feature_range=(low, upp)).fit(numpy.vstack((X_train, X_test)))
    X_train_scale = minmax_scaler.transform(X_train)
    X_test_scale = minmax_scaler.transform(X_test)
    return X_train_scale, X_test_scale
</code>```

my main function

```<code>    #!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys

import numpy
import pandas
import sklearn.metrics
import sklearn.model_selection
import sklearn.linear_model
import sklearn.preprocessing
import matplotlib.pyplot as plt

def main(argv):
        X_train, X_test, y_train, y_test = load_train_test_data(train_ratio=.8)
        X_train_scale, X_test_scale = scale_features(X_train, X_test, 0, 1)

        theta = logreg_sgd(X_train_scale, y_train)
        print('theta:\n', theta)
        plot_roc_curve(X_test, y_test, theta)

if __name__ == "__main__":
    main(sys.argv)
</code>```

sample data:

```<code>140.5625,55.68378214,-0.234571412,-0.699648398,3.199832776,19.11042633,7.975531794,74.24222492,0
102.5078125,58.88243001,0.465318154,-0.515087909,1.677257525,14.86014572,10.57648674,127.3935796,0
103.015625,39.34164944,0.323328365,1.051164429,3.121237458,21.74466875,7.735822015,63.17190911,0
136.75,57.17844874,-0.068414638,-0.636238369,3.642976589,20.9592803,6.89649891,53.59366067,0
88.7265625,40.67222541,0.600866079,1.123491692,1.178929766,11.4687196,14.26957284,252.5673058,0
93.5703125,46.69811352,0.53190485,0.416721117,1.636287625,14.54507425,10.6217484,131.3940043,0
119.484375,48.76505927,0.03146022,-0.112167573,0.99916388,9.279612239,19.20623018,479.7565669,0
130.3828125,39.84405561,-0.158322759,0.389540448,1.220735786,14.37894124,13.53945602,198.2364565,0
107.25,52.62707834,0.452688025,0.170347382,2.331939799,14.48685311,9.001004441,107.9725056,0
107.2578125,39.49648839,0.465881961,1.162877124,4.079431438,24.98041798,7.397079948,57.78473789,0
142.078125,45.28807262,-0.320328426,0.283952506,5.376254181,29.00989748,6.076265849,37.83139335,0
133.2578125,44.05824378,-0.081059862,0.115361506,1.632107023,12.00780568,11.97206663,195.5434476,0
134.9609375,49.55432662,-0.135303833,-0.080469602,10.69648829,41.34204361,3.893934139,14.13120625,0
117.9453125,45.50657724,0.325437564,0.661459458,2.836120401,23.11834971,8.943211912,82.47559187,0
138.1796875,51.5244835,-0.031852329,0.046797173,6.330267559,31.57634673,5.155939859,26.14331017,0
114.3671875,51.94571552,-0.094498904,-0.287984087,2.738294314,17.19189079,9.050612454,96.61190318,0
109.640625,49.01765217,0.13763583,-0.256699775,1.508361204,12.07290134,13.36792556,223.4384192,0
100.8515625,51.74352161,0.393836792,-0.011240741,2.841137124,21.63577754,8.302241891,71.58436903,0
136.09375,51.69100464,-0.045908926,-0.271816393,9.342809365,38.09639955,4.345438138,18.67364854,0
99.3671875,41.57220208,1.547196967,4.154106043,27.55518395,61.71901588,2.20880796,3.662680136,1
100.890625,51.89039446,0.627486528,-0.026497802,3.883779264,23.04526673,6.953167635,52.27944038,0
105.4453125,41.13996851,0.142653801,0.320419676,3.551839465,20.75501684,7.739552295,68.51977061,0
95.8671875,42.05992212,0.326386917,0.803501794,1.83277592,12.24896949,11.249331,177.2307712,0
117.3671875,53.90861351,0.257953441,-0.405049077,6.018394649,24.76612335,4.807783224,25.52261561,0
106.6484375,56.36718209,0.378355072,-0.266371607,2.43645485,18.40537062,9.378659682,96.86022536,0
112.71875,50.3012701,0.279390953,-0.129010712,8.281772575,37.81001224,4.691826852,21.27620977,0
130.8515625,52.43285734,0.142596727,0.018885442,2.64632107,15.65443599,9.464164025,115.6731586,0
119.4375,52.87481531,-0.002549267,-0.460360287,2.365384615,16.49803188,9.008351898,94.75565692,0
123.2109375,51.07801208,0.179376819,-0.17728516,2.107023411,16.92177312,10.08033334,112.5585913,0
102.6171875,49.69235371,0.230438984,0.193325371,1.489130435,16.00441146,12.64653474,171.8329021,0
110.109375,41.31816988,0.094860398,0.68311261,1.010033445,13.02627521,14.66651082,231.2041363,0
99.9140625,43.91949797,0.475728501,0.781486196,0.619565217,9.440975862,20.1066391,475.680218,0
128.34375,52.17210664,-0.049280401,-0.208256987,2.173913043,12.9939472,9.965757364,141.5100843,0
142.0546875,53.87315957,-0.470772686,-0.125946417,4.423076923,27.08351266,6.681658306,45.94403008,0
121.1328125,47.6326062,0.177360308,0.024918111,2.151337793,20.55243738,9.920468181,99.74707919,0
102.328125,48.98040255,0.315729409,-0.202183315,1.898829431,13.83904002,11.61993869,172.1303732,0
147.8359375,53.62263651,-0.131079596,-0.288851172,2.692307692,17.08088101,8.849177975,92.20174502,0
108.0390625,34.91024257,0.321156562,1.821631493,3.899665552,23.72205203,7.506209958,60.88691267,0
107.875,37.33065932,0.49600476,1.481815856,1.173913043,12.01691346,14.53428973,252.6947381,0
118.84375,45.9319193,-0.109242666,0.137683548,2.33277592,14.71602871,9.634175054,118.6696797,0
138.4609375,48.91716569,-0.039591916,-0.176243068,2.443143813,18.3133067,8.672894053,83.06924213,0
116.203125,47.34586165,0.211946824,-0.022177703,3.606187291,18.94498977,7.035644684,59.23122572,0
120.5546875,45.54990543,0.282923998,0.419908714,1.358695652,13.07903424,13.31214143,212.5970294,1
121.8828125,53.04267461,0.200520721,-0.282219034,2.116220736,16.58087621,8.947602793,91.01176155,0
125.2109375,51.17519729,0.139851288,-0.385736754,1.147993311,12.41401211,14.06879728,228.1315536,0
107.90625,48.08414459,0.460846577,0.29651005,1.993311037,13.84106954,9.969395408,128.7447168,0
106.28125,43.02178545,0.408868006,1.032014666,1.610367893,17.25115554,12.11019331,152.0149562,0
106.3359375,45.05002035,0.418645099,0.603995884,1.200668896,12.38856143,13.30645184,209.41199,0
125.734375,52.65772207,0.026516673,-0.429632907,4.850334448,29.93619483,6.361837308,40.25501275,0
113.546875,49.50029346,0.130001201,-0.202839025,2.407190635,14.42205142,9.310343318,113.6874714,0
134.0390625,51.80045885,-0.195844789,-0.396816077,1.107859532,13.23858397,13.77580037,208.4202575,0
105.1171875,45.09202762,0.464847891,0.878058377,4.283444816,23.96731526,6.562543005,46.66728734,0
95.328125,44.66789069,0.386495074,0.755115427,2.694816054,17.9985973,9.094177089,97.80243629,0
119.3359375,47.506953,0.220316758,0.645717725,0.79264214,9.540907141,18.76653977,441.5133427,0
136.1875,51.95291588,-0.070431774,-0.482219687,0.849498328,9.677531027,18.73655411,431.3904454,0
112.859375,55.10625168,0.174766173,-0.404019163,3.032608696,19.69431374,7.266252257,58.03777067,0
108.625,52.74614915,0.453556415,0.069731528,2.304347826,16.18365586,9.780440566,114.9993838,0
113.953125,49.2214161,0.234723211,0.289792216,1.081103679,13.48209307,14.25608113,216.8362204,0
141.96875,50.47089779,0.244974491,-0.342664657,2.823578595,16.23818776,8.207743613,85.53258352,0
136.5,49.9327673,0.044623267,-0.374311456,1.555183946,12.81353792,13.31433912,214.813089,0
83.6796875,36.37928102,0.572531753,2.66461052,4.0409699,23.16912864,7.006681423,53.51400467,0
27.765625,28.66604164,5.770087392,37.4190088,73.11287625,62.07021971,1.268206006,1.082920221,1
135.859375,51.93727202,0.065768774,-0.366114187,20.77424749,52.77264803,2.730908619,6.607439551,0
112.09375,48.81156969,0.418565459,0.350156301,2.204013378,17.37868175,9.520551079,100.7875964,0
126.8671875,53.1293191,0.13633915,-0.588709439,1.149665552,13.96514443,13.23049959,186.2685104,0
117.5390625,47.73296528,0.173139263,-0.150653604,1.060200669,14.28934355,14.17637248,208.2780851,0
143.0859375,49.92197464,-0.157561213,-0.153332697,3.563545151,21.28808157,7.337117054,59.16844081,0
101.296875,39.43395574,0.390053688,1.551969375,4.925585284,26.32242163,6.086053659,39.11620774,0
119.8984375,53.82550508,0.143378486,-0.528427658,4.04180602,24.57913147,6.581293412,44.89951492,0
123.125,50.33124651,-0.087091427,0.087932382,1.280936455,10.68864639,14.63669101,288.668932,0
102.046875,48.79050551,0.45222638,0.272447732,2.37541806,13.9284014,9.127499454,116.0232222,0
119.4453125,53.14305702,0.012830273,-0.378955989,2.932274247,17.9297569,8.289888515,81.34651657,0
128.515625,54.94585181,-0.012552759,-0.658278628,2.891304348,17.75294666,8.913745414,94.08210337,0
128.15625,46.89690113,-0.179233074,-0.005819915,4.193979933,22.25815766,6.451755484,46.48663173,0
115.6171875,40.29037592,0.110702345,0.513224267,11.63963211,39.95655753,3.640288988,12.68457562,0
136.7421875,44.39123754,-0.22192524,0.908084632,2.105351171,14.49837742,10.13157115,128.3951486,0
135.265625,48.14390609,0.015920939,-0.15877212,8.539297659,31.13487695,4.082788387,17.27267344,0
113.9609375,52.24736871,0.127976811,-0.457499415,4.407190635,26.29776588,6.709564866,47.4057088,0
107.796875,45.6803362,0.655279783,0.954879021,1.7090301,15.1907807,11.52025038,150.3053634,0
124.5,57.35361802,-0.014849043,-0.550963937,4.783444816,27.50164045,6.090448645,37.81809112,0
119.296875,46.45417086,0.202629139,0.12837064,3.748327759,18.8510099,6.414682286,50.85055687,0
148.3828125,51.200757,-0.113195798,-0.50223559,1.408026756,12.08791939,12.5121354,201.1278905,0
109.4921875,53.2901838,0.2528458,-0.319022964,4.132943144,25.89210734,6.741542034,46.83080307,0
112.125,46.30840906,0.721646098,0.612454163,1.173076923,11.04918969,14.6307442,273.2509626,0
128.7734375,45.80669555,0.086169154,-0.031764808,2.66722408,15.93295829,8.75667197,95.36727143,0
140.265625,48.93721813,0.03252958,0.119064502,2.315217391,19.87317992,9.67260138,98.89698457,0
87.515625,51.76343189,1.070588903,0.74283956,15.67809365,50.90591579,3.141187931,8.440045483,0
132.140625,42.09582342,0.143191723,0.876730035,1.863712375,13.26595667,10.25798651,140.0407088,0
104.078125,45.24078107,0.532040422,0.743853067,1.43645485,15.41478275,11.89911604,150.9872549,0
122.6015625,53.79697654,-0.051964773,-0.379729027,2.636287625,15.17095406,9.519292364,117.7422254,0
114.28125,41.25396525,0.41182113,0.616996141,2.412207358,20.42794216,9.198391753,88.37057957,0
112.4375,38.2956733,0.501943444,1.07484029,2.81270903,18.13688307,7.859968426,71.29944944,0
23.625,29.94865398,5.688038235,35.98717152,146.5685619,82.39462399,-0.274901598,-1.121848281,1
94.5859375,35.77982308,1.187308683,3.68746932,6.071070234,29.76039993,5.318766827,28.69804799,1
137.2421875,46.45474042,0.045257133,-0.438857507,59.4958194,77.75535652,0.71974817,-1.183162032,0
123.53125,53.34878418,0.072077648,-0.071600995,0.781772575,10.57083301,17.11829958,339.6608262,0
70.0234375,35.28067478,1.157657193,4.546692371,3.003344482,19.57538355,7.954436097,71.96015886,0
129.375,44.56841651,0.049779493,0.506330188,3.60451505,21.13303805,7.181384025,56.85662961,0
97.140625,47.77089438,0.625218075,0.740796144,4.193143813,26.46526062,6.927045631,49.62852693,0
101.96875,46.31632702,0.439814307,0.294261355,1.748327759,16.4866229,10.8103928,127.7333664,0
</code>```

答:
I will use an answer since in comments I don't have enough space. I hope to point you in the right direction. You can use sklearn to get values to check your model against. I downloaded your dataset and created (in a quick and dirty way) a balanced dataset

```<code>X_train, X_test, y_train, y_test  =
   sklearn.model_selection.train_test_split(data, labels,
   test_size = 1 - 0.8, random_state=0)
X_train_bal1 = X_train[y_train == 1]
Y_train1 = y_train[y_train == 1]

X_train_bal0 = X_train[y_train == 0].sample(len(X_train_bal1))
Y_train0 = y_train[y_train == 0].sample(len(X_train_bal1))

X = pd.concat([X_train_bal1, X_train_bal0])
Y = pd.concat([Y_train1, Y_train0])
</code>```

Then I used sklearn to perform a logistic regression

```<code>logisticb = LogisticRegression()
logisticb.fit(X,Y)

logisticb.score(X,Y)
</code>```

Now you have 1365 observations labelled as 1 and 1365 observations labelled as 0. You get an score of 0.943. So pretty good. In your original dataset you are dealing with roughly 1% of observations labelled as 1 against roughly 99% labelled as 0. I am checking your code as I am typing this. Will update this answer as soon as I find out what is wrong.

EDIT: I checked your code, but I must admit that I would simply simplify it and I would rewrite it. For what you want to do (logistic regression) is overly complicated and difficult to debug. I think that you better invest the time you would need to debug the code in simplyfing it.

On a positive note I applaud you for trying to implement logistic regression from scratch. It is a wonderful learning experience. You are doing many things right (like scaling the input X). Something you should try is to vectorize your code as much as you can using numpy features. Your code is quite slow. You can make it really fast. If you it can help you I wrote a complete implementation of logistic regression from scratch and is available from github (https://github.com/michelucci/Logistic-Regression-Explained/blob/master/MNIST%20with%20Logistic%20Regression%20from%20scratch.ipynb). Maybe it can help you.

Good luck and all the best, Umberto

Body:
I am trying to write a logistic regression with L1 regularization.I use stochastic gradient ascend of log-likelihood as the cost function. But my function always give out values that near 0. My dataset is from http://archive.ics.uci.edu/ml/datasets/HTRU2

Here is the example, where y_hat is the output of the predict function and y[i] is the true value of the target:

y_hat: [ 0.08707034] y[i]: 0
y_hat - y[i]: [ 0.08707034]
y_hat: [ 0.06406335] y[i]: 0
y_hat - y[i]: [ 0.06406335]
y_hat: [ 0.04818193] y[i]: 0
y_hat - y[i]: [ 0.04818193]
y_hat: [ 0.19760354] y[i]: 1
y_hat - y[i]: [-0.80239646]
y_hat: [ 0.08982549] y[i]: 0
y_hat - y[i]: [ 0.08982549]
y_hat: [ 0.0844086] y[i]: 1
y_hat - y[i]: [-0.9155914]

And here is the accuracy when the threshold is 0.5

threshold= 0.5
acc= 0.0159217877095

and here is my logistic sgd code

def logreg_sgd(X, y, alpha = .001, iters = 100000, eps=1e-4):
    n, d = X.shape
    theta = numpy.zeros((d, 1))
    k = 0
    lam = 0.001

    for k in range(iters):
        i = k%n
        x = X[i, :]
        xT = numpy.transpose([x])
        y_hat = sigmoid(x, theta)
        beta = de_norm1(theta)

        func_g = (y[i] - y_hat)*xT + lam*beta

        theta_k = theta.copy()
        theta = theta + alpha*func_g
        for delta in abs(theta-theta_k):
            if delta > eps:
                break

    return theta

def de_norm1(theta):
    d, _ = theta.shape
    beta = numpy.zeros((d, 1))

    for i in range(d):
        if theta[i,0] < 0:
            beta[i,0] = -1
        elif theta[i,0] > 0:
            beta[i,0] = 1
    return beta

def sigmoid(X, theta):
    z = numpy.dot(X, theta)
    value = 1.0/(1.0 + numpy.exp(-z))
    return value

I can not figure out why it is wrong

Below is the second edit content.

here is the roc_curve I draw.

roc curve

and the code to draw roc cureve

# plot the ROC curve of your prediction
# x aixes: TPR = TP / ( TP + FN )
# y aixes: FPR = FP / ( FP + TN )
def plot_roc_curve(X_test, y_true, theta):
    k = 51
    FPR_x = numpy.zeros(k)
    TPR_y = numpy.zeros(k)

    for n in range(k):
        threshold = n/(k-1)
        y_pred, FPR, TPR = predict(X_test, y_true, theta, threshold)
        tn, fp, fn, tp = sklearn.metrics.confusion_matrix(y_true, y_pred).ravel()
        FPR_x[n] = fp/(fp+tn)
        TPR_y[n] = tp/(tp+fn)
        print(FPR_x[n], TPR_y[n])

    plt.xlabel('FPR')
    plt.ylabel('TPR')
    plt.plot(FPR_x, TPR_y, '-')
    # plt.scatter(FPR_x, TPR_y, marker='o', color='blue')
    plt.show()

Here is the predict(classify) fuction

def predict(X, y_true, theta, threshold):
    value = sigmoid(X, theta)
    row, col = X.shape
    y_hat = numpy.zeros(row)
    P = sum(y_true)
    N = row - P
    FP = 0.0
    TP = 0.0
    print('P =', P)

    for i, val in enumerate(value):
        if val > threshold:
            y_hat[i] = 1
            TP+=1
        else:
            y_hat[i] = 0
        if y_true[i] != y_hat[i]:
            if y_true[i] == 0:
                FP+=1
    FPR = FP/N
    TPR = TP/P
    return y_hat, FPR, TPR

my data load function

def load_train_test_data(train_ratio=.8):
    data = pandas.read_csv('./HTRU2/HTRU_2.csv', header=None)

    X = data.iloc[:,:8]
    X = numpy.concatenate((numpy.ones((len(X), 1)), X), axis=1)
    y = data.iloc[:,8]
    y = numpy.array(y)
    return sklearn.model_selection.train_test_split(X, y, test_size = 1 - train_ratio, random_state=0)

The scale function

def scale_features(X_train, X_test, low=0, upp=1):
    minmax_scaler = sklearn.preprocessing.MinMaxScaler(feature_range=(low, upp)).fit(numpy.vstack((X_train, X_test)))
    X_train_scale = minmax_scaler.transform(X_train)
    X_test_scale = minmax_scaler.transform(X_test)
    return X_train_scale, X_test_scale

my main function

    #!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys

import numpy
import pandas
import sklearn.metrics
import sklearn.model_selection
import sklearn.linear_model
import sklearn.preprocessing
import matplotlib.pyplot as plt

def main(argv):
        X_train, X_test, y_train, y_test = load_train_test_data(train_ratio=.8)
        X_train_scale, X_test_scale = scale_features(X_train, X_test, 0, 1)

        theta = logreg_sgd(X_train_scale, y_train)
        print('theta:\n', theta)
        plot_roc_curve(X_test, y_test, theta)

if __name__ == "__main__":
    main(sys.argv)

sample data:

140.5625,55.68378214,-0.234571412,-0.699648398,3.199832776,19.11042633,7.975531794,74.24222492,0
102.5078125,58.88243001,0.465318154,-0.515087909,1.677257525,14.86014572,10.57648674,127.3935796,0
103.015625,39.34164944,0.323328365,1.051164429,3.121237458,21.74466875,7.735822015,63.17190911,0
136.75,57.17844874,-0.068414638,-0.636238369,3.642976589,20.9592803,6.89649891,53.59366067,0
88.7265625,40.67222541,0.600866079,1.123491692,1.178929766,11.4687196,14.26957284,252.5673058,0
93.5703125,46.69811352,0.53190485,0.416721117,1.636287625,14.54507425,10.6217484,131.3940043,0
119.484375,48.76505927,0.03146022,-0.112167573,0.99916388,9.279612239,19.20623018,479.7565669,0
130.3828125,39.84405561,-0.158322759,0.389540448,1.220735786,14.37894124,13.53945602,198.2364565,0
107.25,52.62707834,0.452688025,0.170347382,2.331939799,14.48685311,9.001004441,107.9725056,0
107.2578125,39.49648839,0.465881961,1.162877124,4.079431438,24.98041798,7.397079948,57.78473789,0
142.078125,45.28807262,-0.320328426,0.283952506,5.376254181,29.00989748,6.076265849,37.83139335,0
133.2578125,44.05824378,-0.081059862,0.115361506,1.632107023,12.00780568,11.97206663,195.5434476,0
134.9609375,49.55432662,-0.135303833,-0.080469602,10.69648829,41.34204361,3.893934139,14.13120625,0
117.9453125,45.50657724,0.325437564,0.661459458,2.836120401,23.11834971,8.943211912,82.47559187,0
138.1796875,51.5244835,-0.031852329,0.046797173,6.330267559,31.57634673,5.155939859,26.14331017,0
114.3671875,51.94571552,-0.094498904,-0.287984087,2.738294314,17.19189079,9.050612454,96.61190318,0
109.640625,49.01765217,0.13763583,-0.256699775,1.508361204,12.07290134,13.36792556,223.4384192,0
100.8515625,51.74352161,0.393836792,-0.011240741,2.841137124,21.63577754,8.302241891,71.58436903,0
136.09375,51.69100464,-0.045908926,-0.271816393,9.342809365,38.09639955,4.345438138,18.67364854,0
99.3671875,41.57220208,1.547196967,4.154106043,27.55518395,61.71901588,2.20880796,3.662680136,1
100.890625,51.89039446,0.627486528,-0.026497802,3.883779264,23.04526673,6.953167635,52.27944038,0
105.4453125,41.13996851,0.142653801,0.320419676,3.551839465,20.75501684,7.739552295,68.51977061,0
95.8671875,42.05992212,0.326386917,0.803501794,1.83277592,12.24896949,11.249331,177.2307712,0
117.3671875,53.90861351,0.257953441,-0.405049077,6.018394649,24.76612335,4.807783224,25.52261561,0
106.6484375,56.36718209,0.378355072,-0.266371607,2.43645485,18.40537062,9.378659682,96.86022536,0
112.71875,50.3012701,0.279390953,-0.129010712,8.281772575,37.81001224,4.691826852,21.27620977,0
130.8515625,52.43285734,0.142596727,0.018885442,2.64632107,15.65443599,9.464164025,115.6731586,0
119.4375,52.87481531,-0.002549267,-0.460360287,2.365384615,16.49803188,9.008351898,94.75565692,0
123.2109375,51.07801208,0.179376819,-0.17728516,2.107023411,16.92177312,10.08033334,112.5585913,0
102.6171875,49.69235371,0.230438984,0.193325371,1.489130435,16.00441146,12.64653474,171.8329021,0
110.109375,41.31816988,0.094860398,0.68311261,1.010033445,13.02627521,14.66651082,231.2041363,0
99.9140625,43.91949797,0.475728501,0.781486196,0.619565217,9.440975862,20.1066391,475.680218,0
128.34375,52.17210664,-0.049280401,-0.208256987,2.173913043,12.9939472,9.965757364,141.5100843,0
142.0546875,53.87315957,-0.470772686,-0.125946417,4.423076923,27.08351266,6.681658306,45.94403008,0
121.1328125,47.6326062,0.177360308,0.024918111,2.151337793,20.55243738,9.920468181,99.74707919,0
102.328125,48.98040255,0.315729409,-0.202183315,1.898829431,13.83904002,11.61993869,172.1303732,0
147.8359375,53.62263651,-0.131079596,-0.288851172,2.692307692,17.08088101,8.849177975,92.20174502,0
108.0390625,34.91024257,0.321156562,1.821631493,3.899665552,23.72205203,7.506209958,60.88691267,0
107.875,37.33065932,0.49600476,1.481815856,1.173913043,12.01691346,14.53428973,252.6947381,0
118.84375,45.9319193,-0.109242666,0.137683548,2.33277592,14.71602871,9.634175054,118.6696797,0
138.4609375,48.91716569,-0.039591916,-0.176243068,2.443143813,18.3133067,8.672894053,83.06924213,0
116.203125,47.34586165,0.211946824,-0.022177703,3.606187291,18.94498977,7.035644684,59.23122572,0
120.5546875,45.54990543,0.282923998,0.419908714,1.358695652,13.07903424,13.31214143,212.5970294,1
121.8828125,53.04267461,0.200520721,-0.282219034,2.116220736,16.58087621,8.947602793,91.01176155,0
125.2109375,51.17519729,0.139851288,-0.385736754,1.147993311,12.41401211,14.06879728,228.1315536,0
107.90625,48.08414459,0.460846577,0.29651005,1.993311037,13.84106954,9.969395408,128.7447168,0
106.28125,43.02178545,0.408868006,1.032014666,1.610367893,17.25115554,12.11019331,152.0149562,0
106.3359375,45.05002035,0.418645099,0.603995884,1.200668896,12.38856143,13.30645184,209.41199,0
125.734375,52.65772207,0.026516673,-0.429632907,4.850334448,29.93619483,6.361837308,40.25501275,0
113.546875,49.50029346,0.130001201,-0.202839025,2.407190635,14.42205142,9.310343318,113.6874714,0
134.0390625,51.80045885,-0.195844789,-0.396816077,1.107859532,13.23858397,13.77580037,208.4202575,0
105.1171875,45.09202762,0.464847891,0.878058377,4.283444816,23.96731526,6.562543005,46.66728734,0
95.328125,44.66789069,0.386495074,0.755115427,2.694816054,17.9985973,9.094177089,97.80243629,0
119.3359375,47.506953,0.220316758,0.645717725,0.79264214,9.540907141,18.76653977,441.5133427,0
136.1875,51.95291588,-0.070431774,-0.482219687,0.849498328,9.677531027,18.73655411,431.3904454,0
112.859375,55.10625168,0.174766173,-0.404019163,3.032608696,19.69431374,7.266252257,58.03777067,0
108.625,52.74614915,0.453556415,0.069731528,2.304347826,16.18365586,9.780440566,114.9993838,0
113.953125,49.2214161,0.234723211,0.289792216,1.081103679,13.48209307,14.25608113,216.8362204,0
141.96875,50.47089779,0.244974491,-0.342664657,2.823578595,16.23818776,8.207743613,85.53258352,0
136.5,49.9327673,0.044623267,-0.374311456,1.555183946,12.81353792,13.31433912,214.813089,0
83.6796875,36.37928102,0.572531753,2.66461052,4.0409699,23.16912864,7.006681423,53.51400467,0
27.765625,28.66604164,5.770087392,37.4190088,73.11287625,62.07021971,1.268206006,1.082920221,1
135.859375,51.93727202,0.065768774,-0.366114187,20.77424749,52.77264803,2.730908619,6.607439551,0
112.09375,48.81156969,0.418565459,0.350156301,2.204013378,17.37868175,9.520551079,100.7875964,0
126.8671875,53.1293191,0.13633915,-0.588709439,1.149665552,13.96514443,13.23049959,186.2685104,0
117.5390625,47.73296528,0.173139263,-0.150653604,1.060200669,14.28934355,14.17637248,208.2780851,0
143.0859375,49.92197464,-0.157561213,-0.153332697,3.563545151,21.28808157,7.337117054,59.16844081,0
101.296875,39.43395574,0.390053688,1.551969375,4.925585284,26.32242163,6.086053659,39.11620774,0
119.8984375,53.82550508,0.143378486,-0.528427658,4.04180602,24.57913147,6.581293412,44.89951492,0
123.125,50.33124651,-0.087091427,0.087932382,1.280936455,10.68864639,14.63669101,288.668932,0
102.046875,48.79050551,0.45222638,0.272447732,2.37541806,13.9284014,9.127499454,116.0232222,0
119.4453125,53.14305702,0.012830273,-0.378955989,2.932274247,17.9297569,8.289888515,81.34651657,0
128.515625,54.94585181,-0.012552759,-0.658278628,2.891304348,17.75294666,8.913745414,94.08210337,0
128.15625,46.89690113,-0.179233074,-0.005819915,4.193979933,22.25815766,6.451755484,46.48663173,0
115.6171875,40.29037592,0.110702345,0.513224267,11.63963211,39.95655753,3.640288988,12.68457562,0
136.7421875,44.39123754,-0.22192524,0.908084632,2.105351171,14.49837742,10.13157115,128.3951486,0
135.265625,48.14390609,0.015920939,-0.15877212,8.539297659,31.13487695,4.082788387,17.27267344,0
113.9609375,52.24736871,0.127976811,-0.457499415,4.407190635,26.29776588,6.709564866,47.4057088,0
107.796875,45.6803362,0.655279783,0.954879021,1.7090301,15.1907807,11.52025038,150.3053634,0
124.5,57.35361802,-0.014849043,-0.550963937,4.783444816,27.50164045,6.090448645,37.81809112,0
119.296875,46.45417086,0.202629139,0.12837064,3.748327759,18.8510099,6.414682286,50.85055687,0
148.3828125,51.200757,-0.113195798,-0.50223559,1.408026756,12.08791939,12.5121354,201.1278905,0
109.4921875,53.2901838,0.2528458,-0.319022964,4.132943144,25.89210734,6.741542034,46.83080307,0
112.125,46.30840906,0.721646098,0.612454163,1.173076923,11.04918969,14.6307442,273.2509626,0
128.7734375,45.80669555,0.086169154,-0.031764808,2.66722408,15.93295829,8.75667197,95.36727143,0
140.265625,48.93721813,0.03252958,0.119064502,2.315217391,19.87317992,9.67260138,98.89698457,0
87.515625,51.76343189,1.070588903,0.74283956,15.67809365,50.90591579,3.141187931,8.440045483,0
132.140625,42.09582342,0.143191723,0.876730035,1.863712375,13.26595667,10.25798651,140.0407088,0
104.078125,45.24078107,0.532040422,0.743853067,1.43645485,15.41478275,11.89911604,150.9872549,0
122.6015625,53.79697654,-0.051964773,-0.379729027,2.636287625,15.17095406,9.519292364,117.7422254,0
114.28125,41.25396525,0.41182113,0.616996141,2.412207358,20.42794216,9.198391753,88.37057957,0
112.4375,38.2956733,0.501943444,1.07484029,2.81270903,18.13688307,7.859968426,71.29944944,0
23.625,29.94865398,5.688038235,35.98717152,146.5685619,82.39462399,-0.274901598,-1.121848281,1
94.5859375,35.77982308,1.187308683,3.68746932,6.071070234,29.76039993,5.318766827,28.69804799,1
137.2421875,46.45474042,0.045257133,-0.438857507,59.4958194,77.75535652,0.71974817,-1.183162032,0
123.53125,53.34878418,0.072077648,-0.071600995,0.781772575,10.57083301,17.11829958,339.6608262,0
70.0234375,35.28067478,1.157657193,4.546692371,3.003344482,19.57538355,7.954436097,71.96015886,0
129.375,44.56841651,0.049779493,0.506330188,3.60451505,21.13303805,7.181384025,56.85662961,0
97.140625,47.77089438,0.625218075,0.740796144,4.193143813,26.46526062,6.927045631,49.62852693,0
101.96875,46.31632702,0.439814307,0.294261355,1.748327759,16.4866229,10.8103928,127.7333664,0

Body:
I will use an answer since in comments I don't have enough space. I hope to point you in the right direction. You can use sklearn to get values to check your model against. I downloaded your dataset and created (in a quick and dirty way) a balanced dataset

X_train, X_test, y_train, y_test  =
   sklearn.model_selection.train_test_split(data, labels,
   test_size = 1 - 0.8, random_state=0)
X_train_bal1 = X_train[y_train == 1]
Y_train1 = y_train[y_train == 1]

X_train_bal0 = X_train[y_train == 0].sample(len(X_train_bal1))
Y_train0 = y_train[y_train == 0].sample(len(X_train_bal1))

X = pd.concat([X_train_bal1, X_train_bal0])
Y = pd.concat([Y_train1, Y_train0])

Then I used sklearn to perform a logistic regression

logisticb = LogisticRegression()
logisticb.fit(X,Y)

logisticb.score(X,Y)

Now you have 1365 observations labelled as 1 and 1365 observations labelled as 0. You get an score of 0.943. So pretty good. In your original dataset you are dealing with roughly 1% of observations labelled as 1 against roughly 99% labelled as 0. I am checking your code as I am typing this. Will update this answer as soon as I find out what is wrong.

EDIT: I checked your code, but I must admit that I would simply simplify it and I would rewrite it. For what you want to do (logistic regression) is overly complicated and difficult to debug. I think that you better invest the time you would need to debug the code in simplyfing it.

On a positive note I applaud you for trying to implement logistic regression from scratch. It is a wonderful learning experience. You are doing many things right (like scaling the input X). Something you should try is to vectorize your code as much as you can using numpy features. Your code is quite slow. You can make it really fast. If you it can help you I wrote a complete implementation of logistic regression from scratch and is available from github (https://github.com/michelucci/Logistic-Regression-Explained/blob/master/MNIST%20with%20Logistic%20Regression%20from%20scratch.ipynb). Maybe it can help you.

Good luck and all the best, Umberto


问:
OpenCV C++ Convert Byte array to Mat
How can I convert byte array  to Mat which is received from socket ?.

My client application will send color image data like this

```<code>Mat frame; //colour image
int imgSize = frame.total()*frame.elemSize();
int bytes = send(clientSock, frame.data, imgSize, 0));//write to the socket
</code>```

And the server will receives the data like

```<code>    char sockData[imgSize];
    Mat img;
    for (int i = 0; i < imgSize; i += bytes) {
        bytes = recv(connectSock, sockData +i, imgSize  - i, 0));
    }

   // Write to mat
    for (int i = 0;  i < img.rows; i++) {
      for (int j = 0; j < img.cols; j++) {
         (img.row(i)).col(j) = (uchar)sockData[((img.cols)*i)+j];
       }
     }
</code>```

I am getting distorted image at the receiver. Is there any problem in my code ?
Thanks in advance.......

答:
Doesn't this work?

```<code>cv::Mat frame(img.rows, img.cols, CV_8UC3, sockData);
</code>```

Just replace CV_8UC3 with the correct image format:

```<code>CV_<bit-depth>{U|S|F}C(<number_of_channels>)
</code>```

see https://docs.opencv.org/2.4/modules/core/doc/basic_structures.html

Edit:  There is a 5th additional field which can be useful.  The number of bytes per row (in case there are a few padding bytes).  In working with V4L2 today, I successfully used this cv::Mat constructor:

```<code>v4l2_format camera_format = ...; // see https://linuxtv.org/downloads/v4l-dvb-apis/uapi/v4l/vidioc-g-fmt.html#description
cv::Mat mat(camera_format.fmt.pix.height,
            camera_format.fmt.pix.width,
            CV_8UC3,
            raw_data_ptr,
            camera_format.fmt.pix.bytesperline);
</code>```

Title: OpenCV C++ Convert Byte array to Mat

Body:
How can I convert byte array  to Mat which is received from socket ?.

My client application will send color image data like this

Mat frame; //colour image
int imgSize = frame.total()*frame.elemSize();
int bytes = send(clientSock, frame.data, imgSize, 0));//write to the socket

And the server will receives the data like

    char sockData[imgSize];
    Mat img;
    for (int i = 0; i < imgSize; i += bytes) {
        bytes = recv(connectSock, sockData +i, imgSize  - i, 0));
    }

   // Write to mat
    for (int i = 0;  i < img.rows; i++) {
      for (int j = 0; j < img.cols; j++) {
         (img.row(i)).col(j) = (uchar)sockData[((img.cols)*i)+j];
       }
     }

I am getting distorted image at the receiver. Is there any problem in my code ?
Thanks in advance.......

Body:
Doesn't this work?

cv::Mat frame(img.rows, img.cols, CV_8UC3, sockData);

Just replace CV_8UC3 with the correct image format:

CV_<bit-depth>{U|S|F}C(<number_of_channels>)

see https://docs.opencv.org/2.4/modules/core/doc/basic_structures.html

Edit:  There is a 5th additional field which can be useful.  The number of bytes per row (in case there are a few padding bytes).  In working with V4L2 today, I successfully used this cv::Mat constructor:

v4l2_format camera_format = ...; // see https://linuxtv.org/downloads/v4l-dvb-apis/uapi/v4l/vidioc-g-fmt.html#description
cv::Mat mat(camera_format.fmt.pix.height,
            camera_format.fmt.pix.width,
            CV_8UC3,
            raw_data_ptr,
            camera_format.fmt.pix.bytesperline);

ContentLicense: CC BY-SA 4.0


问:
set created input text selected using jquery
I have the following label:

```<code><div id="email">
  <label>
    myemail@gmail.com
  </label>
  <i class="fa fa-edit"></i>
</div>

<div id="phone">
  <label>
    1234567890
  </label>
  <i class="fa fa-edit"></i>
</div>
</code>```

When I click on the edit button I want to replace the label with an input and set the label value as selected. Below is what i have tried so far:

```<code>$('.fa-edit').click(function(){
var info = $(this).closest('div');
var label = info.find('label');
var curr_value = label.text();
label.replaceWith('<input class="edit_input" type="text" value="'+curr_value+'" />')
  .focus(function(){
     //alert(this);
     this.select();
  });
// some code ..
</code>```

the problem is that I can not set the input text as selected (ready to be replaced).
What should I do?

答:
the value returned from .replaceWith is still the old  reference, you need to re-select the input, so that you can focus it.

```<code>label.replaceWith('<input class="edit_input" type="text" value="'+curr_value+'" />')
$('.edit_input').off('focus').on('focus',function() {
    this.select()
}).trigger('focus')
</code>```

use off() to remove previous event listener everytime the user click the edit button again.

Body:
I have the following label:

    myemail@gmail.com

    1234567890

When I click on the edit button I want to replace the label with an input and set the label value as selected. Below is what i have tried so far:

$('.fa-edit').click(function(){
var info = $(this).closest('div');
var label = info.find('label');
var curr_value = label.text();
label.replaceWith('<input class="edit_input" type="text" value="'+curr_value+'" />')
  .focus(function(){
     //alert(this);
     this.select();
  });
// some code ..

the problem is that I can not set the input text as selected (ready to be replaced).
What should I do?

Body:
the value returned from .replaceWith is still the old <label /> reference, you need to re-select the input, so that you can focus it.

label.replaceWith('<input class="edit_input" type="text" value="'+curr_value+'" />')
$('.edit_input').off('focus').on('focus',function() {
    this.select()
}).trigger('focus')

use off() to remove previous event listener everytime the user click the edit button again.


问:
How to make form model update on blur in angular 2
Is there an equivalent to this in angular 2?

```<code>ng-model-options="{ updateOn: 'blur' }"
</code>```

Thanks

答:
Even though this is a very old thread, there is now a very neat solution which comes with Angular5.

You trigger the update on blur like this:

Tempalte driven forms:

```<code><input [(ngModel)]="lastname" [ngModelOptions]="{ updateOn: 'blur' }">
</code>```

Reactive forms:

```<code>this.nameForm = new FormGroup ({
  firstname: new FormControl('', {
    validators: Validators.required,
    updateOn: 'submit'
  }),
  lastname: new FormControl('', {
    validators: Validators.required,
    updateOn: 'submit'
  })
});
</code>```

(you can select submit or blur as values)

Reference:
https://medium.com/codingthesmartway-com-blog/angular-5-forms-update-9587c3735cd3

Body:
Is there an equivalent to this in angular 2?

ng-model-options="{ updateOn: 'blur' }"

Thanks

Body:
Even though this is a very old thread, there is now a very neat solution which comes with Angular5.

You trigger the update on blur like this:

Tempalte driven forms:

<input [(ngModel)]="lastname" [ngModelOptions]="{ updateOn: 'blur' }">

Reactive forms:

this.nameForm = new FormGroup ({
  firstname: new FormControl('', {
    validators: Validators.required,
    updateOn: 'submit'
  }),
  lastname: new FormControl('', {
    validators: Validators.required,
    updateOn: 'submit'
  })
});

(you can select submit or blur as values)

Reference:
https://medium.com/codingthesmartway-com-blog/angular-5-forms-update-9587c3735cd3


答:
i hope that help you.</p>

```<code>var label = $('label');
var curr_value = label.text();
label.replaceWith('<input class="edit_input" type="text" value="'+curr_value+'" />').focus(function(){
     $(this).select(); });
</code>```

Title: set created input text selected using jquery

Body:
i hope that help you.

var label = $('label');
var curr_value = label.text();
label.replaceWith('<input class="edit_input" type="text" value="'+curr_value+'" />').focus(function(){
     $(this).select(); });


问:
Process solution and generate report in TFS ans VS?
I've been tasked with finding a way to analyze a solution for certain conditions and generate a report with those conditions. This must be done in VS2015 and TFS.

I've already written VS packages so that part is not a problem, but all the tutorials and documents on extending TFS that I've found work with VSTS and simply add something via JavaScript, which is insufficient for what we need.

Is there any way to write a TFS extension in C#? The idea is that the user clicks, let's say, a link in the Code tab of the project in the TFS interface  and the extension does something with the code and generates an HTML report.

EDIT: The extension I have to build must analyze specific files in the solution, looking for known patterns, and report their existence. Something like:

```<code>+------------+-----------+------------------------------------------+
|File        |Line       |Condition                                 |
+------------+-----------+------------------------------------------+
|Web.config  |225        |Invalid value for key "DISCTOS"           |
|Web.config  |314        |Path in element "TNS_ADMIN" does not exist|
+------------+-----------+------------------------------------------+
</code>```

答:
Extension was introduced since Team Foundation Server 2015 Update 2, there is no C# based extension now. You could start from Extensions overview to Write your first extension, and get lots extension samples from website below:

https://learn.microsoft.com/en-us/vsts/extend/develop/samples-overview

Body:
I've been tasked with finding a way to analyze a solution for certain conditions and generate a report with those conditions. This must be done in VS2015 and TFS.

I've already written VS packages so that part is not a problem, but all the tutorials and documents on extending TFS that I've found work with VSTS and simply add something via JavaScript, which is insufficient for what we need.

Is there any way to write a TFS extension in C#? The idea is that the user clicks, let's say, a link in the Code tab of the project in the TFS interface  and the extension does something with the code and generates an HTML report.

EDIT: The extension I have to build must analyze specific files in the solution, looking for known patterns, and report their existence. Something like:

+------------+-----------+------------------------------------------+
|File        |Line       |Condition                                 |
+------------+-----------+------------------------------------------+
|Web.config  |225        |Invalid value for key "DISCTOS"           |
|Web.config  |314        |Path in element "TNS_ADMIN" does not exist|
+------------+-----------+------------------------------------------+


问:
Best way to upload files using Ajax and before submitting
I have a form with multiple fields but also a file upload. I am able to upload multiple files.

I also know that it is possible to upload files with AJAX.
So I would like to upload my files using ajax while i'm filling in every other field. But how would I link the already uploaded images then? And also prevent the images to be uploaded again?

This is the form:

```<code><form id="form_validation" method="POST" action="{{route('storeexpense')}}" enctype="multipart/form-data">
                            {{ csrf_field() }}
                            <div class="form-group form-float">
                                <div class="form-line">
                                    <input type="text"  class="form-control" name="description" required>
                                    <label class="form-label">Omschrijving</label>
                                </div>
                            </div>
                            <div class="form-group form-float">
                                <div class="form-line">
                                    <input type="number" class="form-control" name="amount" required>
                                    <label class="form-label">Bedrag</label>
                                </div>
                            </div>
                            <div class="form-group form-float">
                                @foreach ($types as $type)
                                    @if ($type->id === 1)
                                        <input name="transactiontype" type="radio" id="rdio{{$type->id}}" value="{{$type->id}}" checked />
                                        <label for="rdio{{$type->id}}">{{$type->description}}</label>
                                    @else
                                        <input name="transactiontype" type="radio" id="rdio{{$type->id}}" value="{{$type->id}}" />
                                        <label for="rdio{{$type->id}}">{{$type->description}}</label>
                                    @endif
                                @endforeach
                            </div>
                            <div class="form-group form-float">
                                <div class="form-line">
                                    <input type="text" class="datepicker form-control" name="date" placeholder="Please choose a date..." required>

                                    <!-- <label class="form-label">Datum</label> -->
                                </div>
                            </div>
                            <div class="form-group demo-tagsinput-area">
                                <div class="form-line">
                                    <input type="text" class="form-control" id="tagsinput" data-role="tagsinput" placeholder="Labels" name="tags" required>

                                </div>
                            </div>
                            <div class="form-group form-float">
                                <div class="form-line">
                                     @if (count($errors) > 0)
                                        <ul>
                                            @foreach ($errors->all() as $error)
                                                <li>{{ $error }}</li>
                                            @endforeach
                                        </ul>
                                    @endif
                                    <input type="file" name="attachments[]" multiple class="custom-file-control"/>
                                </div>
                            </div>

                            <button class="btn btn-primary waves-effect" type="submit">SAVE</button>
                        </form>
</code>```

This is the PHP code that saves the information from the form:

```<code>public function store(UploadRequest $request)
    {

        // Save new transaction in database
          $transaction = new Transaction;
        $transaction->description = $request->description;
        $transaction->amount = $request->amount;
        $input  = $request->date;
            $format = 'd/m/Y';
            $date = Carbon::createFromFormat($format, $input);

        $transaction->date = $date;
        $transaction->transactiontype_id = $request->transactiontype;
        $transaction->user_id = Auth::id();
        $transaction->save();

        // Put tags in array
        $inputtags = explode(",", $request->tags);

        // Loop through every tag exists
        // EXISTS: get ID
        // NOT EXISTS: Create and get ID
        foreach ($inputtags as $inputtag)
        {
            $tag = Tag::firstOrCreate(['description' => $inputtag]);
            $transaction->tags()->attach($tag->id); //Put the 2 ID's in intermediate table ('tag_transaction')
        }

        //Check if there are files
        if (!is_null($request->attachments))
        {
            //Loop through every file and upload it
            foreach ($request->attachments as $attachment) {
            $filename = $attachment->store('attachments');

            // Store the filename in the database with link to the transaction
            Attachment::create([
                'transaction_id' => $transaction->id,
                'path' => $filename
            ]);
            }
        }
</code>```

Thanks,
Bart

答:
It sounds like you want to make a fancy form that starts uploading the file as soon as you choose it and meanwhile the user can continue filling the rest of the form. If so, I'd do it like this:

Implement your main text/data form, eg.

```<code><form method="POST" action="/save-data-endpoint.php">
    <input name="email" type="text" />
    <button type="submit>Submit</button>
</form>
</code>```

Next to it, a form for the images. eg.

```<code><form method="POST" class="file-upload-form" action="/save-file.php">
    <input name="my-file" type="file" />
    <!-- note that we wont show a submit button -->
</form>
</code>```

For the user, it all looks like the same form but clicking the submit button will send only the data to the save-data-endpoint.php. Now we need some js to control this madness (I'll use jQuery for brevity). But you can use FileReader api in js, ajax progress tracking to make it even fancier. See https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications for more.

```<code>$(function(){ // run when document is ready
    // listen when the input changes (when a file is selected)
    $('.file-upload-form').on('change', function(e){
        // file has been selected, submit it via ajax
        // show some kind of uploading indication, eg. a spinner
        $.ajax({
            type:'POST',
            url: $(this).attr('action'),
            data: new FormData(this),
            cache:false,
            contentType: false,
            processData: false,
            success:function(data){
                // the save-file.php endpoint returns an id and/or a url to the saved/resized/sanitized image
                console.log(data.id, data.url);
                // we then inject this id/url, into the main data form
                var $hiddenInput = $('<input type="hidden" name="uploads[]" value="'+data.id+'">');
                $('.main-form').append($hiddenInput);

                // show a thumbnail maybe?
                var $thumbnail = $('<img src="'+data.url+'" width="20" height="20" />');
                $('.main-form').append($thumbnail);

                // hide spinner
                // reactivate file upload form to choose another file
                $('.file-upload-form').find('input').val('');
            },
            error: function(){
                console.log("error");
            }
        });
    });
});
</code>```

Your backend will get the images as they are selected, one by one. You then save them and return an id and/or a url to the image to be used in the success handler in js. After adding some images your main form should look something like this:

```<code><form method="POST" action="/save-data-endpoint.php">
    <input name="email" type="text" />
    <button type="submit>Submit</button>

    <input type="hidden" name="uploads[]" value="x">
    <img src="...x.jpg" width="20" height="20" />
    <input type="hidden" name="uploads[]" value="y">
    <img src="...y.jpg" width="20" height="20" />
</form>
</code>```

Now when the user fills the remaining fields and clicks submit, your server will get all the data along with an array called uploads which contains all the image ids/paths you have already saved. You can now store this data and relate it to the files.

I wont go deeper on the backend side as it can be implemented on any language. In summary the basic flow would be:

send files one at a time to a save file endpoint that returns a file identifier (can be an id, hash, full path to image, etc)

js injects those ids into the main form

the main form is submitted to a save data endpoint that returns a success or error message and stores + relates all the data in your preferred method of storage.

Hope it helps!

Body:
I have a form with multiple fields but also a file upload. I am able to upload multiple files.

I also know that it is possible to upload files with AJAX.
So I would like to upload my files using ajax while i'm filling in every other field. But how would I link the already uploaded images then? And also prevent the images to be uploaded again?

This is the form:

<form id="form_validation" method="POST" action="{{route('storeexpense')}}" enctype="multipart/form-data">
                            {{ csrf_field() }}

                                    <input type="text"  class="form-control" name="description" required>
                                    Omschrijving

                                    <input type="number" class="form-control" name="amount" required>
                                    Bedrag

                                @foreach ($types as $type)
                                    @if ($type->id === 1)
                                        <input name="transactiontype" type="radio" id="rdio{{$type->id}}" value="{{$type->id}}" checked />
                                        id}}">{{$type->description}}
                                    @else
                                        <input name="transactiontype" type="radio" id="rdio{{$type->id}}" value="{{$type->id}}" />
                                        id}}">{{$type->description}}
                                    @endif
                                @endforeach

                                    <input type="text" class="datepicker form-control" name="date" placeholder="Please choose a date..." required>

                                    <input type="text" class="form-control" id="tagsinput" data-role="tagsinput" placeholder="Labels" name="tags" required>

                                     @if (count($errors) > 0)

                                            @foreach ($errors->all() as $error)

{{ $error }}

                                            @endforeach

                                    @endif
                                    <input type="file" name="attachments[]" multiple class="custom-file-control"/>

                            <button class="btn btn-primary waves-effect" type="submit">SAVE</button>
                        </form>

This is the PHP code that saves the information from the form:

public function store(UploadRequest $request)
    {

        // Save new transaction in database
          $transaction = new Transaction;
        $transaction->description = $request->description;
        $transaction->amount = $request->amount;
        $input  = $request->date;
            $format = 'd/m/Y';
            $date = Carbon::createFromFormat($format, $input);

        $transaction->date = $date;
        $transaction->transactiontype_id = $request->transactiontype;
        $transaction->user_id = Auth::id();
        $transaction->save();

        // Put tags in array
        $inputtags = explode(",", $request->tags);

        // Loop through every tag exists
        // EXISTS: get ID
        // NOT EXISTS: Create and get ID
        foreach ($inputtags as $inputtag)
        {
            $tag = Tag::firstOrCreate(['description' => $inputtag]);
            $transaction->tags()->attach($tag->id); //Put the 2 ID's in intermediate table ('tag_transaction')
        }

        //Check if there are files
        if (!is_null($request->attachments))
        {
            //Loop through every file and upload it
            foreach ($request->attachments as $attachment) {
            $filename = $attachment->store('attachments');

            // Store the filename in the database with link to the transaction
            Attachment::create([
                'transaction_id' => $transaction->id,
                'path' => $filename
            ]);
            }
        }

Thanks,
Bart

Body:
It sounds like you want to make a fancy form that starts uploading the file as soon as you choose it and meanwhile the user can continue filling the rest of the form. If so, I'd do it like this:

Implement your main text/data form, eg.

<form method="POST" action="/save-data-endpoint.php">
    <input name="email" type="text" />
    <button type="submit>Submit</button>
</form>

Next to it, a form for the images. eg.

<form method="POST" class="file-upload-form" action="/save-file.php">
    <input name="my-file" type="file" />
    <!-- note that we wont show a submit button -->
</form>

For the user, it all looks like the same form but clicking the submit button will send only the data to the save-data-endpoint.php. Now we need some js to control this madness (I'll use jQuery for brevity). But you can use FileReader api in js, ajax progress tracking to make it even fancier. See https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications for more.

$(function(){ // run when document is ready
    // listen when the input changes (when a file is selected)
    $('.file-upload-form').on('change', function(e){
        // file has been selected, submit it via ajax
        // show some kind of uploading indication, eg. a spinner
        $.ajax({
            type:'POST',
            url: $(this).attr('action'),
            data: new FormData(this),
            cache:false,
            contentType: false,
            processData: false,
            success:function(data){
                // the save-file.php endpoint returns an id and/or a url to the saved/resized/sanitized image
                console.log(data.id, data.url);
                // we then inject this id/url, into the main data form
                var $hiddenInput = $('<input type="hidden" name="uploads[]" value="'+data.id+'">');
                $('.main-form').append($hiddenInput);

                // show a thumbnail maybe?
                var $thumbnail = $('<img src="'+data.url+'" width="20" height="20" />');
                $('.main-form').append($thumbnail);

                // hide spinner
                // reactivate file upload form to choose another file
                $('.file-upload-form').find('input').val('');
            },
            error: function(){
                console.log("error");
            }
        });
    });
});

Your backend will get the images as they are selected, one by one. You then save them and return an id and/or a url to the image to be used in the success handler in js. After adding some images your main form should look something like this:

<form method="POST" action="/save-data-endpoint.php">
    <input name="email" type="text" />
    <button type="submit>Submit</button>

    <input type="hidden" name="uploads[]" value="x">
    <img src="...x.jpg" width="20" height="20" />
    <input type="hidden" name="uploads[]" value="y">
    <img src="...y.jpg" width="20" height="20" />
</form>

Now when the user fills the remaining fields and clicks submit, your server will get all the data along with an array called uploads which contains all the image ids/paths you have already saved. You can now store this data and relate it to the files.

I wont go deeper on the backend side as it can be implemented on any language. In summary the basic flow would be:

send files one at a time to a save file endpoint that returns a file identifier (can be an id, hash, full path to image, etc)

js injects those ids into the main form

the main form is submitted to a save data endpoint that returns a success or error message and stores + relates all the data in your preferred method of storage.

Hope it helps!


问:
Data is not passing to the other page using Ajax
I have been trying to use ajax in cart system the value is easily being added to cart in home page but when cart.blade.php page is opened the products are not displayed. I think data is being passed in  the cart.blade.php page.

index.blade.php

```<code><div class="widget widget-control-header widget-shop-cart js-widget-shop-cart">
    <a class="control" href="{{route('cart.index')}}">
        <p class="counter">0</p>
        <span class="lnr lnr-cart" id="checkout">
        </span>

        <div class="wrapper-control-item item-add-cart js-action-add-cart">
            <a class="animate-icon-cart" href="#">
                <span class="lnr lnr-cart" >
                </span>
            </a>
        </div>
    </div>
</div>
</code>```

This is the ajax code with all of its classes. 'js-action-add-cart' is used for calling the cart ajax.

add-to-cart.js

```<code>$(function() {
    var actionAddToCart = $('.js-action-add-cart');
    var cart            = $('.js-widget-shop-cart');
    var itemWishList    = $('.js-notify-add-wish-list');
    var items;

    var cartItems ={items:[]};

    actionAddToCart.each(function() {
        $(this).on('click', function(e) {
            var productid    = $(this).closest('.product').find('a').attr('id');
            var productName  = $(this).closest('.product').find('.product-name').text();
            var productPic   = $(this).closest('.product').find('img').attr('src');
            var productPrice = $(this).closest('.product').find('.price').text();

            if($(this).hasClass( "is-added" )){
                alreadyAddedToCart(productName);
            }else{
                $('#cartHover').append("<li style='width: 200px;border-bottom: 1px solid black;padding: 10px;padding-top:0px;position: relative'>\
                    <span style='width: 50px; position: relative'>"+productName+"</span>\
                    <span style='width: 30px; margin-left: 30px; position:relative'>PKR: "+productPrice+"</span>\
                    <i class='cancel glyphicon glyphicon-remove-circle' style='right:5px; top:5px; position: absolute;float:right'></i>\
                    </li>");

                cartItems.items.push({id: productid, name: productName, pic: productPic , price :productPrice});
                items = JSON.stringify(cartItems);

                e.preventDefault();
                notifyAddToCart(productName);
                $(this).addClass('is-added');
                setTimeout(function(){
                    updateCart();
                }, 1000);
            }

        });
    });

    $('#checkout').click(function(){
        window.location.href = 'cartSession.blade.php?products='+items;
    });

    function updateCart() {
        //show counter if this is the first item added to the cart
        ( !cart.hasClass('items-added') ) && cart.addClass('items-added');
        var cartItems = cart.find('.counter'),
        text = parseInt(cartItems.text()) + 1;
        cartItems.text(text);
    };
});
</code>```

cartSessions.blade.php

```<code><?php
session_start();
$_SESSION['products'] =$_GET['products'];
header('Location: shop-cart.blade.php');
exit();
</code>```

答:
You really don't need to use session_start() in your blade template as Laravel handles starting your session via the middleware. You also want to serve your blade template via a route, not access them directly. Create a route that either has it's own closure or points to a controller method.

Route with it's own closure

```<code>// ------------------------------------------
// routes.php
// ------------------------------------------

use Illuminate\Http\Request;

Route::get('/cart', function(Request $request)
{
    // Get the products from the request
    $products = $request->products;

    return view('shop-cart', ['products' => $products]);
});
</code>```

Route pointing to a controller

```<code>// ------------------------------------------
// app/Http/routes.php
// ------------------------------------------

Route::get('/cart', [
    'as'   => 'cart',
    'uses' => 'CartController@show'
]);

// ------------------------------------------
// app/Http/Controllers/CartController.php
// ------------------------------------------

<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CartController extends Controller {

    /**
     * Show the cart.
     *
     * @return Response
     */
    public function show(Request $request)
    {
        // Get the products from the request
        $products = $request->products;

        return view('shop-cart', ['products' => $products]);
    }
}
</code>```

Here we simply get the products from the request and pass them through as a variable called $products to the view. You would need to make the following change to your javascript:

```<code>$('#checkout').click(function(){
    window.location.href = '/cart?products='+items;
});
</code>```

Body:
I have been trying to use ajax in cart system the value is easily being added to cart in home page but when cart.blade.php page is opened the products are not displayed. I think data is being passed in  the cart.blade.php page.

index.blade.php

0

This is the ajax code with all of its classes. 'js-action-add-cart' is used for calling the cart ajax.

add-to-cart.js

$(function() {
    var actionAddToCart = $('.js-action-add-cart');
    var cart            = $('.js-widget-shop-cart');
    var itemWishList    = $('.js-notify-add-wish-list');
    var items;

    var cartItems ={items:[]};

    actionAddToCart.each(function() {
        $(this).on('click', function(e) {
            var productid    = $(this).closest('.product').find('a').attr('id');
            var productName  = $(this).closest('.product').find('.product-name').text();
            var productPic   = $(this).closest('.product').find('img').attr('src');
            var productPrice = $(this).closest('.product').find('.price').text();

            if($(this).hasClass( "is-added" )){
                alreadyAddedToCart(productName);
            }else{
                $('#cartHover').append("
\
                    "+productName+"\
                    PKR: "+productPrice+"\
                    \

");

                cartItems.items.push({id: productid, name: productName, pic: productPic , price :productPrice});
                items = JSON.stringify(cartItems);

                e.preventDefault();
                notifyAddToCart(productName);
                $(this).addClass('is-added');
                setTimeout(function(){
                    updateCart();
                }, 1000);
            }

        });
    });

    $('#checkout').click(function(){
        window.location.href = 'cartSession.blade.php?products='+items;
    });

    function updateCart() {
        //show counter if this is the first item added to the cart
        ( !cart.hasClass('items-added') ) && cart.addClass('items-added');
        var cartItems = cart.find('.counter'),
        text = parseInt(cartItems.text()) + 1;
        cartItems.text(text);
    };
});

cartSessions.blade.php

<?php
session_start();
$_SESSION['products'] =$_GET['products'];
header('Location: shop-cart.blade.php');
exit();

Body:
You really don't need to use session_start() in your blade template as Laravel handles starting your session via the middleware. You also want to serve your blade template via a route, not access them directly. Create a route that either has it's own closure or points to a controller method.

Route with it's own closure

// ------------------------------------------
// routes.php
// ------------------------------------------

use Illuminate\Http\Request;

Route::get('/cart', function(Request $request)
{
    // Get the products from the request
    $products = $request->products;

    return view('shop-cart', ['products' => $products]);
});

Route pointing to a controller

// ------------------------------------------
// app/Http/routes.php
// ------------------------------------------

Route::get('/cart', [
    'as'   => 'cart',
    'uses' => 'CartController@show'
]);

// ------------------------------------------
// app/Http/Controllers/CartController.php
// ------------------------------------------

<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CartController extends Controller {

    /**
     * Show the cart.
     *
     * @return Response
     */
    public function show(Request $request)
    {
        // Get the products from the request
        $products = $request->products;

        return view('shop-cart', ['products' => $products]);
    }
}

Here we simply get the products from the request and pass them through as a variable called $products to the view. You would need to make the following change to your javascript:

$('#checkout').click(function(){
    window.location.href = '/cart?products='+items;
});