问:
Turning off ASP.Net WebForms authentication for one sub-directory
I have a large enterprise application containing both WebForms and MVC pages. It has existing authentication and authorisation settings that I don't want to change.

The WebForms authentication is configured in the web.config:

```<code> <authentication mode="Forms">
  <forms blah... blah... blah />
 </authentication>

 <authorization>
  <deny users="?" />
 </authorization>
</code>```

Fairly standard so far. I have a REST service that is part of this big application and I want to use HTTP authentication instead for this one service.

So, when a user attempts to get JSON data from the REST service it returns an HTTP 401 status and a WWW-Authenticate header. If they respond with a correctly formed HTTP Authorization response it lets them in.

The problem is that WebForms overrides this at a low level - if you return 401 (Unauthorised) it overrides that with a 302 (redirection to login page). That's fine in the browser but useless for a REST service.

I want to turn off the authentication setting in the web.config, overriding the 'rest' folder:

```<code> <location path="rest">
  <system.web>
   <authentication mode="None" />
   <authorization><allow users="?" /></authorization>
  </system.web>
 </location>
</code>```

The authorisation bit works fine, but the authentication line (<authentication mode="None" />) causes an exception:

It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.

I'm configuring this at application level though - it's in the root web.config - and that error is for web.configs in sub-directories.

How do I override the authentication so that all of the rest of the site uses WebForms authentication and this one directory uses none?

This is similar to another question: 401 response code for json requests with ASP.NET MVC, but I'm not looking for the same solution - I don't want to just remove the WebForms authentication and add new custom code globally, there's far to much risk and work involved. I want to change just the one directory in configuration.

Update

I want to set up a single web application and in that I want all the WebForms pages and MVC views to use WebForms authentication. I want one directory to use basic HTTP authentication.

Note that I'm talking about authentication, not authorisation. I want REST calls to come with the username & password in an HTTP header, and I want WebForm & MVC pages to come with the authentication cookie from .Net - in either case authorisation is done against our DB.

I don't want to rewrite WebForms authentication and roll my own cookies - it seems ridiculous that is the only way to add an HTTP authorised REST service to an application.

I can't add an additional application or virtual directory - it's got to be as one application.

答:
After looking at your comments to my previous answer, I wondered if you could have your web app automate the deployment of an application on your REST directory. That would allow you to have the benefits of a second application, and would also reduce the deployment burden on your system admins.

My thought was that you could put a routine into the Application_Start method of the global.asax that would check that the REST directory exists, and that it does not already have an application associated with it.  If the test returns true, then the process of associating a new application to the REST directory occurs.

Another thought I had was that you could use WIX (or another deployment technology) to build a install package that your admins could run to create the application, however I don't think that's as automatic as having the app configure its dependency.

Below, I've included a sample implementation that checks IIS for a given directory and applies an application to it if it does not already have one.  The code was tested with IIS 7, but should work on IIS 6 as well.

```<code>//This is part of global.asax.cs
//This approach may require additional user privileges to query IIS

//using System.DirectoryServices;
//using System.Runtime.InteropServices;

protected void Application_Start(object sender, EventArgs evt)
{
  const string iisRootUri = "IIS://localhost/W3SVC/1/Root";
  const string restPhysicalPath = @"C:\inetpub\wwwroot\Rest";
  const string restVirtualPath = "Rest";

  if (!Directory.Exists(restPhysicalPath))
  {
    // there is no rest path, so do nothing
    return;
  }

  using (var root = new DirectoryEntry(iisRootUri))
  {
    DirectoryEntries children = root.Children;

    try
    {
      using (DirectoryEntry rest = children.Find(restVirtualPath, root.SchemaClassName))
      {
        // the above call throws an exception if the vdir does not exist
        return;
      }
    }
    catch (COMException e)
    {
      // something got unlinked incorrectly, kill the vdir and application
      foreach (DirectoryEntry entry in children)
      {
        if (string.Compare(entry.Name, restVirtualPath, true) == 0)
        {
          entry.DeleteTree();
        }
      }
    }
    catch (DirectoryNotFoundException e)
    {
      // the vdir and application do not exist, add them below
    }

    using (DirectoryEntry rest = children.Add(restVirtualPath, root.SchemaClassName))
    {
      rest.CommitChanges();
      rest.Properties["Path"].Value = restPhysicalPath;
      rest.Properties["AccessRead"].Add(true);
      rest.Properties["AccessScript"].Add(true);
      rest.Invoke("AppCreate2", true);
      rest.Properties["AppFriendlyName"].Add(restVirtualPath);
      rest.CommitChanges();
    }
  }
}
</code>```

Portions of this code came from here.  Good luck with your app!

Body:
I have a large enterprise application containing both WebForms and MVC pages. It has existing authentication and authorisation settings that I don't want to change.

The WebForms authentication is configured in the web.config:

 <authentication mode="Forms">
  <forms blah... blah... blah />
 </authentication>

 <authorization>
  <deny users="?" />
 </authorization>

Fairly standard so far. I have a REST service that is part of this big application and I want to use HTTP authentication instead for this one service.

So, when a user attempts to get JSON data from the REST service it returns an HTTP 401 status and a WWW-Authenticate header. If they respond with a correctly formed HTTP Authorization response it lets them in.

The problem is that WebForms overrides this at a low level - if you return 401 (Unauthorised) it overrides that with a 302 (redirection to login page). That's fine in the browser but useless for a REST service.

I want to turn off the authentication setting in the web.config, overriding the 'rest' folder:

 <location path="rest">
  <system.web>
   <authentication mode="None" />
   <authorization><allow users="?" /></authorization>
  </system.web>
 </location>

The authorisation bit works fine, but the authentication line (<authentication mode="None" />) causes an exception:

It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.

I'm configuring this at application level though - it's in the root web.config - and that error is for web.configs in sub-directories.

How do I override the authentication so that all of the rest of the site uses WebForms authentication and this one directory uses none?

This is similar to another question: 401 response code for json requests with ASP.NET MVC, but I'm not looking for the same solution - I don't want to just remove the WebForms authentication and add new custom code globally, there's far to much risk and work involved. I want to change just the one directory in configuration.

Update

I want to set up a single web application and in that I want all the WebForms pages and MVC views to use WebForms authentication. I want one directory to use basic HTTP authentication.

Note that I'm talking about authentication, not authorisation. I want REST calls to come with the username & password in an HTTP header, and I want WebForm & MVC pages to come with the authentication cookie from .Net - in either case authorisation is done against our DB.

I don't want to rewrite WebForms authentication and roll my own cookies - it seems ridiculous that is the only way to add an HTTP authorised REST service to an application.

I can't add an additional application or virtual directory - it's got to be as one application.

Body:
After looking at your comments to my previous answer, I wondered if you could have your web app automate the deployment of an application on your REST directory. That would allow you to have the benefits of a second application, and would also reduce the deployment burden on your system admins.

My thought was that you could put a routine into the Application_Start method of the global.asax that would check that the REST directory exists, and that it does not already have an application associated with it.  If the test returns true, then the process of associating a new application to the REST directory occurs.

Another thought I had was that you could use WIX (or another deployment technology) to build a install package that your admins could run to create the application, however I don't think that's as automatic as having the app configure its dependency.

Below, I've included a sample implementation that checks IIS for a given directory and applies an application to it if it does not already have one.  The code was tested with IIS 7, but should work on IIS 6 as well.

//This is part of global.asax.cs
//This approach may require additional user privileges to query IIS

//using System.DirectoryServices;
//using System.Runtime.InteropServices;

protected void Application_Start(object sender, EventArgs evt)
{
  const string iisRootUri = "IIS://localhost/W3SVC/1/Root";
  const string restPhysicalPath = @"C:\inetpub\wwwroot\Rest";
  const string restVirtualPath = "Rest";

  if (!Directory.Exists(restPhysicalPath))
  {
    // there is no rest path, so do nothing
    return;
  }

  using (var root = new DirectoryEntry(iisRootUri))
  {
    DirectoryEntries children = root.Children;

    try
    {
      using (DirectoryEntry rest = children.Find(restVirtualPath, root.SchemaClassName))
      {
        // the above call throws an exception if the vdir does not exist
        return;
      }
    }
    catch (COMException e)
    {
      // something got unlinked incorrectly, kill the vdir and application
      foreach (DirectoryEntry entry in children)
      {
        if (string.Compare(entry.Name, restVirtualPath, true) == 0)
        {
          entry.DeleteTree();
        }
      }
    }
    catch (DirectoryNotFoundException e)
    {
      // the vdir and application do not exist, add them below
    }

    using (DirectoryEntry rest = children.Add(restVirtualPath, root.SchemaClassName))
    {
      rest.CommitChanges();
      rest.Properties["Path"].Value = restPhysicalPath;
      rest.Properties["AccessRead"].Add(true);
      rest.Properties["AccessScript"].Add(true);
      rest.Invoke("AppCreate2", true);
      rest.Properties["AppFriendlyName"].Add(restVirtualPath);
      rest.CommitChanges();
    }
  }
}

Portions of this code came from here.  Good luck with your app!


来源: stackexchange

问:
Javascript properties end up in loops
the following code will add the property 'id' to the object 'obj'. When calling the getter and setter there will be a console.log execution.

let obj = {}

Object.defineProperty(obj, 'id', {
    set: (val) => { console.log('set'); this.id = val; },
    get: () => { console.log('get'); return this.id; }
})

obj.id = 1;
// 'set'
console.log(obj.id);
// 'get'
// 1```
</div>
</div>
</p>

<p>I want to add the same functionality to a constructor function, but it ends up in a loop.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let myObject = function(){
    Object.defineProperty(this, 'id', {
        set: (val) => { console.log('set'); this.id = val; },
        get: () => { console.log('get'); return this.id; }
    })
}

let obj = new myObject();
obj.id = 1;
// 'set'
// 'set'
// 'set'
// ...
// error
console.log(obj.id);</code>```

How can I solve that problem without creating a pseudo-private variable called '_id'?

Btw I have the same problem when using classes.

答:
It is a little bit strange, but it seems like setter starts to call itself recursively, so code goes to infinite loop of setter calls and then says that maximum call stack size exceeded. I can propose a solution: to define setters and getters on created instances. In this way it works as well:

```<code>let myObject = function(){

}

let obj = new myObject();

Object.defineProperty(obj, 'id', {
        set: (val) => { console.log('set'); this.id = val; },
        get: () => { console.log('get'); return this.id; }
    })

obj.id = 1;
console.log(obj.id);
</code>```

UPD:

Also you can create some factory function, which will be add id property to instance automatically:

```<code>function objectFactory (num) {

    let myObject = function(){

    };

    let instance = new myObject();

    Object.defineProperty(instance, 'id', {
        set: (val) => { console.log('set ' + num); this.id = val; },
        get: () => { console.log('get ' + num); return this.id; }
    });

    return instance;
}

let obj = objectFactory(1);
let obj1 = objectFactory(2);
let obj2 = objectFactory(3);

obj.id = 1;
obj1.id = 1;
obj2.id = 1;

console.log(obj.id);
console.log(obj1.id);
console.log(obj2.id);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Javascript properties end up in loops

Body:
the following code will add the property 'id' to the object 'obj'. When calling the getter and setter there will be a console.log execution.

let obj = {}

Object.defineProperty(obj, 'id', {
    set: (val) => { console.log('set'); this.id = val; },
    get: () => { console.log('get'); return this.id; }
})

obj.id = 1;
// 'set'
console.log(obj.id);
// 'get'
// 1

I want to add the same functionality to a constructor function, but it ends up in a loop.

let myObject = function(){
    Object.defineProperty(this, 'id', {
        set: (val) => { console.log('set'); this.id = val; },
        get: () => { console.log('get'); return this.id; }
    })
}

let obj = new myObject();
obj.id = 1;
// 'set'
// 'set'
// 'set'
// ...
// error
console.log(obj.id);

How can I solve that problem without creating a pseudo-private variable called '_id'?

Btw I have the same problem when using classes.

Body:
It is a little bit strange, but it seems like setter starts to call itself recursively, so code goes to infinite loop of setter calls and then says that maximum call stack size exceeded. I can propose a solution: to define setters and getters on created instances. In this way it works as well:

let myObject = function(){

}

let obj = new myObject();

Object.defineProperty(obj, 'id', {
        set: (val) => { console.log('set'); this.id = val; },
        get: () => { console.log('get'); return this.id; }
    })

obj.id = 1;
console.log(obj.id);

UPD:

Also you can create some factory function, which will be add id property to instance automatically:

function objectFactory (num) {

    let myObject = function(){

    };

    let instance = new myObject();

    Object.defineProperty(instance, 'id', {
        set: (val) => { console.log('set ' + num); this.id = val; },
        get: () => { console.log('get ' + num); return this.id; }
    });

    return instance;
}

let obj = objectFactory(1);
let obj1 = objectFactory(2);
let obj2 = objectFactory(3);

obj.id = 1;
obj1.id = 1;
obj2.id = 1;

console.log(obj.id);
console.log(obj1.id);
console.log(obj2.id);


问:
Leftbar Hamburguer Menu Bootstrap
In my application, the left bar hides when you open the page in a mobile resolution, but I can't do the "hamburguer button" work.

Every solution that i find, did not work.

Here is my HTML code:

<link href="https://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet"/>

                            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#leftSidebar">

                            </button>
                            Project Name

<?php echo strtoupper($_SESSION ['nickUser']) ?>

 Início

 Buscar

 Assistido

 Bate-papo

 Config.

                        <?php
                        $link = filter_input(INPUT_GET, 'p');
                        include $link . ".php";
                        ?>

```

As it is, the left bar hide and the hamburger button show, but the button didn't work and a top bar stay in the top of my page, when i removed it, the hamburguer button had disapears

Thanks.

@edit
how the application is:
Tela web desktop

tela web mobile

答:
I think you need this
   in your code

check it here
https://www.w3schools.com/bootstrap/bootstrap_navbar.asp

Title: Leftbar Hamburguer Menu Bootstrap

Body:
In my application, the left bar hides when you open the page in a mobile resolution, but I can't do the "hamburguer button" work.

Every solution that i find, did not work.

Here is my HTML code:

<link href="https://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet"/>

                            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#leftSidebar">

                            </button>
                            Project Name

<?php echo strtoupper($_SESSION ['nickUser']) ?>

 Início

 Buscar

 Assistido

 Bate-papo

 Config.

                        <?php
                        $link = filter_input(INPUT_GET, 'p');
                        include $link . ".php";
                        ?>

As it is, the left bar hide and the hamburger button show, but the button didn't work and a top bar stay in the top of my page, when i removed it, the hamburguer button had disapears

Thanks.

@edit
how the application is:
Tela web desktop

tela web mobile

Body:
I think you need this
<nav class="navbar navbar-default"> </nav>  in your code

check it here
https://www.w3schools.com/bootstrap/bootstrap_navbar.asp


问:
how to run ethereumjs using NODE.JS
hi everyoune iam trying to work with ethereumjs

problem is i just cant run it by typing 'testrpc'

am getting the msg:

"'testrpc' is not recognized as an internal or external command,
operable program or batch file."

any idea why?

thank u

this is my log:

:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2>npm install  ethereumjs-testrpc

```<code>> fsevents@1.1.3 install C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2\node_modules\fsevents
> node install

> uglifyjs-webpack-plugin@0.4.6 postinstall C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2\node_modules\uglifyjs-webpack-plugin
> node lib/post_install.js

npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2\package.json'
npm WARN assignment_2 No description
npm WARN assignment_2 No repository field.
npm WARN assignment_2 No README data
npm WARN assignment_2 No license field.

+ ethereumjs-testrpc@6.0.1
added 368 packages in 31.206s

C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2>npm install
npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2\package.json'
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2\package.json'
npm WARN assignment_2 No description
npm WARN assignment_2 No repository field.
npm WARN assignment_2 No README data
npm WARN assignment_2 No license field.

up to date in 2.663s

C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2>testrpc
'testrpc' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2>tgestrpc -p
'tgestrpc' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2>testrpc
'testrpc' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2>$ npm install truffle
'$' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2> npm install truffle
npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2\package.json'
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2\package.json'
npm WARN assignment_2 No description
npm WARN assignment_2 No repository field.
npm WARN assignment_2 No README data
npm WARN assignment_2 No license field.

+ truffle@4.0.1
added 55 packages in 9.487s

C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2>testrpc
'testrpc' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2>testrpc
'testrpc' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2>
</code>```

答:
I think you have to install it globally to run it like this .
Or you can add the directory to your PATH:

Right click

My Computer' and go to Properties > Advanced System Settings > Environment Variables.

Double click on PATH under the 'User variables for Username' section, and add

```<code>C:\Users\username\AppData\Roaming\testrpc
</code>```

obviously replacing 'username' with yours.

Restart your console window or IDE and you should get a response from the bower command.

Title: how to run ethereumjs using NODE.JS

Body:
hi everyoune iam trying to work with ethereumjs

problem is i just cant run it by typing 'testrpc'

am getting the msg:

"'testrpc' is not recognized as an internal or external command,
operable program or batch file."

any idea why?

thank u

this is my log:

:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2>npm install  ethereumjs-testrpc

> fsevents@1.1.3 install C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2\node_modules\fsevents
> node install

> uglifyjs-webpack-plugin@0.4.6 postinstall C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2\node_modules\uglifyjs-webpack-plugin
> node lib/post_install.js

npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2\package.json'
npm WARN assignment_2 No description
npm WARN assignment_2 No repository field.
npm WARN assignment_2 No README data
npm WARN assignment_2 No license field.

+ ethereumjs-testrpc@6.0.1
added 368 packages in 31.206s

C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2>npm install
npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2\package.json'
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2\package.json'
npm WARN assignment_2 No description
npm WARN assignment_2 No repository field.
npm WARN assignment_2 No README data
npm WARN assignment_2 No license field.

up to date in 2.663s

C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2>testrpc
'testrpc' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2>tgestrpc -p
'tgestrpc' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2>testrpc
'testrpc' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2>$ npm install truffle
'$' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2> npm install truffle
npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2\package.json'
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2\package.json'
npm WARN assignment_2 No description
npm WARN assignment_2 No repository field.
npm WARN assignment_2 No README data
npm WARN assignment_2 No license field.

+ truffle@4.0.1
added 55 packages in 9.487s

C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2>testrpc
'testrpc' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2>testrpc
'testrpc' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\david\Documents\Visual Studio 2015\Projects\assignment_2>

Body:
I think you have to install it globally to run it like this .
Or you can add the directory to your PATH:

Right click

My Computer' and go to Properties > Advanced System Settings > Environment Variables.

Double click on PATH under the 'User variables for Username' section, and add

C:\Users\username\AppData\Roaming\testrpc

obviously replacing 'username' with yours.

Restart your console window or IDE and you should get a response from the bower command.


问:
Run Node Red as SU on boot
I would like to use Port 502 for my ModBus Server Flow, however, I can only do this if I run "sudo node-red-start"

I have it set to run as a service using "sudo systemctl enable nodered.service"
However, this only seems to execute it as a normal user.

Thanks

答:
Running systemctl with sudo has no bearing on what user the resulting service is run as. That is defined in the service file.

You need to edit nodered.service file and update the User and Group settings.

```<code>...
[Service]
Type=simple
# Run as normal pi user - feel free to change...
User=pi
Group=pi
WorkingDirectory=/home/pi
...
</code>```

That file should be located in /lib/systemd/system/nodered.service.

Title: Run Node Red as SU on boot

Body:
Running systemctl with sudo has no bearing on what user the resulting service is run as. That is defined in the service file.

You need to edit nodered.service file and update the User and Group settings.

...
[Service]
Type=simple
# Run as normal pi user - feel free to change...
User=pi
Group=pi
WorkingDirectory=/home/pi
...

That file should be located in /lib/systemd/system/nodered.service.


问:
Error reading built in keras datasets - Type Error: 'int' object is not callable
I've just installed the keras and tensorflow packages. I'm looking to get started with building some deep learning models, but I'm immediately stuck trying to read example data into the R environment.

Consider the following code:

```<code>#loading keras library
library(keras)
library(tensorflow)

#loading the keras inbuilt cifar10 dataset
?dataset_cifar10 #to see the help file for details of dataset
cifar <- dataset_cifar10()
</code>```

When I run the code I get the following error:

```<code>Error in py_call_impl(callable, dots$args, dots$keywords) :
  TypeError: 'int' object is not callable

Detailed traceback:
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras\datasets\mnist.py", line 17, in load_data
    file_hash='8a61469f7ea1b51cbae51d4f78837e45')
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras\utils\data_utils.py", line 220, in get_file
    urlretrieve(origin, fpath, dl_progress)
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\urllib\request.py", line 274, in urlretrieve
    reporthook(blocknum, bs, size)
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras\utils\data_utils.py", line 213, in dl_progress
    ProgressTracker.progbar = Progbar(total_size)
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras\utils\generic_utils.py", line 270, in __init__
    self._dynamic_display = (sys.stdout.isatty() or
</code>```

Any ideas on what's going on here? The suggestion of installing the reticulate package from git hub versus CRAN is suggested here , but this doesn't solve my issue. Any ideas?

My session info as it relates to keras and tensorflow is here:

```<code>> reticulate::py_config()
python:         C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\python.exe
libpython:      C:/Users/stc004/AppData/Local/CONTIN~1/ANACON~1/python36.dll
pythonhome:     C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1
version:        3.6.0 |Anaconda 4.3.1 (64-bit)| (default, Dec 23 2016, 11:57:41) [MSC v.1900 64 bit (AMD64)]
Architecture:   64bit
numpy:          C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\numpy
numpy_version:  1.11.3
keras:          C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras

python versions found:
 C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\python.exe
 C:\Users\stc004\AppData\Local\Programs\Python\PYTHON~1\\python.exe
> tf_config()
TensorFlow v1.2.1 (C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras)
Python v3.6 (C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\python.exe)
</code>```

答:
Sorry for the delay in response. The issue was solved here:
https://github.com/rstudio/keras/issues/180</p>

Body:
I've just installed the keras and tensorflow packages. I'm looking to get started with building some deep learning models, but I'm immediately stuck trying to read example data into the R environment.

Consider the following code:

#loading keras library
library(keras)
library(tensorflow)

#loading the keras inbuilt cifar10 dataset
?dataset_cifar10 #to see the help file for details of dataset
cifar <- dataset_cifar10()

When I run the code I get the following error:

Error in py_call_impl(callable, dots$args, dots$keywords) :
  TypeError: 'int' object is not callable

Detailed traceback:
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras\datasets\mnist.py", line 17, in load_data
    file_hash='8a61469f7ea1b51cbae51d4f78837e45')
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras\utils\data_utils.py", line 220, in get_file
    urlretrieve(origin, fpath, dl_progress)
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\urllib\request.py", line 274, in urlretrieve
    reporthook(blocknum, bs, size)
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras\utils\data_utils.py", line 213, in dl_progress
    ProgressTracker.progbar = Progbar(total_size)
  File "C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras\utils\generic_utils.py", line 270, in __init__
    self._dynamic_display = (sys.stdout.isatty() or

Any ideas on what's going on here? The suggestion of installing the reticulate package from git hub versus CRAN is suggested here , but this doesn't solve my issue. Any ideas?

My session info as it relates to keras and tensorflow is here:

> reticulate::py_config()
python:         C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\python.exe
libpython:      C:/Users/stc004/AppData/Local/CONTIN~1/ANACON~1/python36.dll
pythonhome:     C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1
version:        3.6.0 |Anaconda 4.3.1 (64-bit)| (default, Dec 23 2016, 11:57:41) [MSC v.1900 64 bit (AMD64)]
Architecture:   64bit
numpy:          C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\numpy
numpy_version:  1.11.3
keras:          C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras

python versions found:
 C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\python.exe
 C:\Users\stc004\AppData\Local\Programs\Python\PYTHON~1\\python.exe
> tf_config()
TensorFlow v1.2.1 (C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\lib\site-packages\keras)
Python v3.6 (C:\Users\stc004\AppData\Local\CONTIN~1\ANACON~1\python.exe)


问:
HTTP 401 Error while posting XML to REST
I am trying to post a XML to REST Service. Here's the code I am using:

I am getting following error, while calling the service.

The remote server returned an error: (401) Unauthorized.

I have also tried setting NetworkCredentials directly i.e.

```<code>NetworkCredential nc = new NetworkCredential(username, password);
serviceRequest.Credentials = nc;
</code>```

Thanks for your help.

```<code>Uri address = new Uri("https://localhost:30000/restservice/");

// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

// Set type to POST
request.Method = "POST";
request.ContentType = "application/json";

string data = @"<Sample XML Here>";

// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);

// Set the content length in the request headers
request.ContentLength = byteData.Length;

// Write data
using (Stream postStream = request.GetRequestStream())
{
    postStream.Write(byteData, 0, byteData.Length);
}

string usernamePassword = username + ":" + password;

CredentialCache mycache = new CredentialCache();

mycache.Add(address, "Basic", new NetworkCredential(username, password));
request.Credentials = mycache;

// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    // Get the response stream
    StreamReader reader = new StreamReader(response.GetResponseStream());

    // Console application output
    Response.Write(reader.ReadToEnd());
}
</code>```

答: Use Fiddler and look in the WWW-Authenticate header that is returned from the server.  That will tell you what kind of authentication scheme the server supports.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am trying to post a XML to REST Service. Here's the code I am using:

I am getting following error, while calling the service.

The remote server returned an error: (401) Unauthorized.

I have also tried setting NetworkCredentials directly i.e.

NetworkCredential nc = new NetworkCredential(username, password);
serviceRequest.Credentials = nc;

Thanks for your help.

Uri address = new Uri("https://localhost:30000/restservice/");

// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

// Set type to POST
request.Method = "POST";
request.ContentType = "application/json";

string data = @"<Sample XML Here>";

// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);

// Set the content length in the request headers
request.ContentLength = byteData.Length;

// Write data
using (Stream postStream = request.GetRequestStream())
{
    postStream.Write(byteData, 0, byteData.Length);
}

string usernamePassword = username + ":" + password;

CredentialCache mycache = new CredentialCache();

mycache.Add(address, "Basic", new NetworkCredential(username, password));
request.Credentials = mycache;

// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    // Get the response stream
    StreamReader reader = new StreamReader(response.GetResponseStream());

    // Console application output
    Response.Write(reader.ReadToEnd());
}


问:
Limit on PDF file upload size in Hyperledger Composer
I am currently working on one POC where pdf attachment needs to be uploaded in Hyperledger Composer. From UI (angular) uploaded PDF converted into base64 string and same is passed composer rest server api for creation/updation of asset. But when file size is more than 40 KB then following error gets displyed as "entity too large".This error is thrown by composer rest server only. There is no error on fabric network.

Unhandled error for request POST /api/UpdateContractDetails: Error: request entity too large at
readStream (/home/ttandale/.nvm/versions/node/v6.11.2/lib/node_modules/composer-rest-server/node_modules/raw-body/index.js:196:17) at getRawBody (/home/ttandale/.nvm/versions/node/v6.11.2/lib/node_modules/composer-rest-server/node_modules/raw-body/index.js:106:12) at read (/home/ttandale/.nvm/versions/node/v6.11.2/lib/node_modules/composer-rest-server/node_modules/body-parser/lib/read.js:76:3) at jsonParser (/home/ttandale/.nvm/versions/node/v6.11.2/lib/node_modules/composer-rest-server/node_modules/body-parser/lib/types/json.js:127:5) at Layer.handle [as handle_request] (/home/ttandale/.nvm/versions/node/v6.11.2/lib/node_modules/composer-rest-server/node_modules/express/lib/router/layer.js:95:5) at trim_prefix (/home/ttandale/.nvm/versions/node/v6.11.2/lib/node_modules/composer-rest-server/node_modules/express/lib/router/index.js:317:13) at /home/ttandale/.nvm/versions/node/v6.11.2/lib/node_modules/composer-rest-server/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/home/ttandale/.nvm/versions/node/v6.11.2/lib/node_modules/composer-rest-server/node_modules/express/lib/router/index.js:335:12) at next (/home/ttandale/.nvm/versions/node/v6.11.2/lib/node_modules/composer-rest-server/node_modules/express/lib/router/index.js:275:10) at /home/ttandale/.nvm/versions/node/v6.11.2/lib/node_modules/composer-rest-server/node_modules/loopback/server/middleware/token.js:130:7 at /home/ttandale/.nvm/versions/node/v6.11.2/lib/node_modules/composer-rest-server/node_modules/loopback/common/models/access-token.js:108:15 at /home/ttandale/.nvm/versions/node/v6.11.2/lib/node_modules/composer-rest-server/node_modules/loopback/common/models/access-token.js:171:11 at _combinedTickCallback (internal/process/next_tick.js:73:7) at process._tickCallback (internal/process/next_tick.js:104:9)

Is there any size limit for this??? In 0.6 version of fabric we have uploaded file size above 1 MB. We have scenario where file size would be max of 2 MB.
Please help and guide on this.

答:
see response on this Stack Overflow here -> is there any size limit for pdf in hyperledger fabric?

The error Error: request entity too large at readStream indicates this is technically a Node issue. Use the suggested solution (in fact there's two, at least) in the other post. cheers

ps. you can also read more on this S/O for limit (and adjustment) Error: request entity too large on limit changes (scroll down). Just FYI.


问:
Autocompleting Parameters of a function in intelliJ
I have a function with parameters.
I like to use this function and would like to see the parameters that I have to provide to this function.

How can I force IntelliJ, that it shows me the parameters needed for that function when my cursor is in the () of that function ? Ctrl-Space do not help me out.

答:
try CTRL+P
its shows you the type and the name

Press CTRL+SHIFT+A and search for Parameter Info and it will show u your hotkey


问:
Trouble parsing parameters
I'm trying to use a simple method that will take the request and parse the parameters but it returns the wrong number of parameters.

In my main I make a request and then call:

fmt.Println(parseParams(r, "http://localhost:8080", 2))

which leads to following values being set in the method when logged:

url: /api/users

params: [ api users]

len(params): 3

So it seems as if it think there's one extra param that I don't specify and looking at it more closely I can see theres a space before api in the params but I don't know where that comes from

```<code>func parseParams(req *http.Request, prefix string, num int) ([]string, error) {
    url := strings.TrimPrefix(req.URL.Path, prefix)
    params := strings.Split(url, "/")

    if len(params) != num || len(params[0]) == 0 || len(params[1]) == 0 {
        return nil, fmt.Errorf("Bad format. Expecting exactly %d params", num)
    }

    return params, nil
}
</code>```

答:
What you are seeing is not a space (that's just the separator), but an empty string, so the array looks like this ["", "api", "users"]. If you take away the commas and quotes, it will look like your output.
So, your params are ""/"api"/"users". Usually, you can skip this 0-th index when processing the params.

Title: Trouble parsing parameters

Body:
I'm trying to use a simple method that will take the request and parse the parameters but it returns the wrong number of parameters.

In my main I make a request and then call:

fmt.Println(parseParams(r, "http://localhost:8080", 2))

which leads to following values being set in the method when logged:

url: /api/users

params: [ api users]

len(params): 3

So it seems as if it think there's one extra param that I don't specify and looking at it more closely I can see theres a space before api in the params but I don't know where that comes from

func parseParams(req *http.Request, prefix string, num int) ([]string, error) {
    url := strings.TrimPrefix(req.URL.Path, prefix)
    params := strings.Split(url, "/")

    if len(params) != num || len(params[0]) == 0 || len(params[1]) == 0 {
        return nil, fmt.Errorf("Bad format. Expecting exactly %d params", num)
    }

    return params, nil
}


问:
Chart.js: chart does not update
I'm using chart.cs to try a Chart. It works fine so far. Now I want change data dynamicly but the update() functin does not work. What do I wrong?</p>

```<code>    <html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
</head>
<body>
<button onclick="changedata()">changedata</button>
<canvas id="testChart"></canvas>
<script>
var testChart;
var test_labels = ['06:00', '06:10', '06:20', '06:30', '06:40', '06:50', '07:00'];
var test_data = ['1', '2', '3', '4', '3', '2', '1'];

var ctx = document.getElementById("testChart").getContext('2d');
testChart = new Chart(ctx, {
type: 'line',
data: {
    labels: test_labels,
    datasets: [{
        data: test_data,
        borderColor: "#ff0000",
        borderWidth: 1,
    }]
}
});

function changedata(){
    test_data  = ['4', '3', '2', '1', '2', '3', '4'];
    testChart.update();
}
</script>
</body>
</html>
</code>```

答:
I think you are missing a little bit in your changedata function, something like</p>

```<code>function changedata(){
    testChart.data.datasets[0].data = ['4', '3', '2', '1', '2', '3', '4'];
    testChart.update();
}
</code>```

Title: Chart.js: chart does not update

Body:
I'm using chart.cs to try a Chart. It works fine so far. Now I want change data dynamicly but the update() functin does not work. What do I wrong?

<button onclick="changedata()">changedata</button>
<canvas id="testChart"></canvas>

Body:
I think you are missing a little bit in your changedata function, something like

function changedata(){
    testChart.data.datasets[0].data = ['4', '3', '2', '1', '2', '3', '4'];
    testChart.update();
}


问:
The AlertDialog broken when click the item of Listview again
I want to show imformation of the newwork server on the listview. when I click some item, it will searchs the network again, return some data, show them on the Dialog. I used two AsyncTasks to realize it. But, when I click the item twice(click the item once is ok), it broken. I debugged and found that the second time it even not step into the itemclicklistener method at all. Can't fixed the bug... Any help is greatly appreciated.
   Here is parts of the codes. firstly onitemclicklistener

```<code>private class lvVoteItemOnItemClickListener implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            HashMap<String, String> map = (HashMap<String, String>) lvVoteItem.getItemAtPosition(arg2);
            if (clickID != Integer.parseInt(map.get("id"))) {
                clickID = Integer.parseInt(map.get("id"));
                new VoteAccountTask().execute(map.get("id"));
            } else {
                new AlertDialog.Builder(VoteSummaryActivity.this).setTitle(res)
                        .setIcon(null)
                        .setView(null)
                        .show();
                String temp = "";
            }

        }
    }
</code>```

secondly, the show dialog AsyncTask

```<code>public class VoteAccountTask extends AsyncTask<String, Void, String> {

    protected String doInBackground(String... param) {
            return searchVoteAccountWebservice(Integer.parseInt(param[0]));
    }

    @Override
    protected void onPostExecute(String result) {
        //votedetail.itemID + signal + votedetail.vID + signal + votedetail.itemName + signal + votedetail.ifUserDefine + signal + votedetail.creater +signal + votedetail.createDate
        super.onPostExecute(result);
        res = setStringsByWebString(result, VoteSummaryActivity.this.getString(R.string.datasetserStr1), VoteSummaryActivity.this.getString(R.string.datasetserStr2));
        new AlertDialog.Builder(VoteSummaryActivity.this).setTitle(res)
                .setIcon(null)
                .setView(null)
                .show();
    }
}
</code>```

答:
Asynctask's are simply be executed without checking previous executions. Does not block UI. So your button, textView or anything clickable can fire an asynctask every time you click.

There is two method I would apply in same situations;

Show Progress Dialog

Set the item clickable=false at preExecute method and then set true at postExecute

Body:
I want to show imformation of the newwork server on the listview. when I click some item, it will searchs the network again, return some data, show them on the Dialog. I used two AsyncTasks to realize it. But, when I click the item twice(click the item once is ok), it broken. I debugged and found that the second time it even not step into the itemclicklistener method at all. Can't fixed the bug... Any help is greatly appreciated.
   Here is parts of the codes. firstly onitemclicklistener

private class lvVoteItemOnItemClickListener implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            HashMap<String, String> map = (HashMap<String, String>) lvVoteItem.getItemAtPosition(arg2);
            if (clickID != Integer.parseInt(map.get("id"))) {
                clickID = Integer.parseInt(map.get("id"));
                new VoteAccountTask().execute(map.get("id"));
            } else {
                new AlertDialog.Builder(VoteSummaryActivity.this).setTitle(res)
                        .setIcon(null)
                        .setView(null)
                        .show();
                String temp = "";
            }

        }
    }

secondly, the show dialog AsyncTask

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

    protected String doInBackground(String... param) {
            return searchVoteAccountWebservice(Integer.parseInt(param[0]));
    }

    @Override
    protected void onPostExecute(String result) {
        //votedetail.itemID + signal + votedetail.vID + signal + votedetail.itemName + signal + votedetail.ifUserDefine + signal + votedetail.creater +signal + votedetail.createDate
        super.onPostExecute(result);
        res = setStringsByWebString(result, VoteSummaryActivity.this.getString(R.string.datasetserStr1), VoteSummaryActivity.this.getString(R.string.datasetserStr2));
        new AlertDialog.Builder(VoteSummaryActivity.this).setTitle(res)
                .setIcon(null)
                .setView(null)
                .show();
    }
}


问:
Mysql self join with aggregate is slow and optimized differently than intended
I've a query which performs slow (~20s) and after doing a fair amount of reading and digging I can't seem to figure out a solution.

The query is:

```<code>EXPLAIN EXTENDED
SELECT t1.*
FROM   tire_transaction AS t1
       INNER JOIN (SELECT license_plate,
                          Max(transaction_date) AS `last_checkin`
                   FROM   tire_transaction
                   GROUP  BY license_plate) AS t2
               ON t1.license_plate = t2.license_plate
                  AND t1.transaction_date = t2.last_checkin
WHERE  ( t1.client_id = '1' )
       AND ( t1.deleted = 0 )
</code>```

The result is:

```<code>id  select_type  table             type    possible_keys                                                              key                  key_len  ref                                 rows  filtered  Extra
 1  PRIMARY      <derived2>        ALL     (NULL)                                                                     (NULL)               (NULL)   (NULL)                             69121    100.00
 1  PRIMARY      t1                ref     client_id,license_plate,tire_transaction_date,deleted,license__trans_date  license__trans_date  67       t2.last_checkin,t2.license_plate       1    100.00  Using where
 2  DERIVED      tire_transaction  index   (NULL)                                                                     license_plate        63       (NULL)                            366423    100.00
</code>```

The table is:

```<code>CREATE TABLE `tire_transaction` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `entity_id` int(11) DEFAULT NULL,
  `client_id` int(11) NOT NULL,
  `company_id` int(11) NOT NULL,
  `parent_id` int(11) DEFAULT NULL,
  `transaction_type` tinyint(1) DEFAULT '0',
  `transaction_date` date DEFAULT NULL,
  `transaction_status` int(11) DEFAULT NULL,
  `transaction_urgent` tinyint(1) NOT NULL DEFAULT '0',
  `license_plate` varchar(20) DEFAULT NULL,
  `license_plate_country` varchar(2) DEFAULT 'NL',
  `chassis_number` varchar(40) DEFAULT NULL,
  `brand` varchar(255) DEFAULT NULL,
  `brand_type` varchar(255) DEFAULT NULL,
  `client_name` varchar(255) DEFAULT NULL,
  `client_salutation` varchar(255) DEFAULT NULL,
  `client_company` varchar(255) DEFAULT NULL,
  `client_street` varchar(255) DEFAULT NULL,
  `client_number` varchar(255) DEFAULT NULL,
  `client_postalcode` varchar(255) DEFAULT NULL,
  `client_city` varchar(255) DEFAULT NULL,
  `client_phone` varchar(255) DEFAULT NULL,
  `client_phone_alt` varchar(255) DEFAULT NULL,
  `client_email` varchar(255) DEFAULT NULL,
  `tire_type` tinyint(1) DEFAULT '0',
  `set_price` int(11) DEFAULT NULL,
  `rim_material` tinyint(1) DEFAULT '0',
  `notes` text,
  `created` datetime DEFAULT NULL,
  `deleted` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `client_id` (`client_id`) USING BTREE,
  KEY `company_id` (`company_id`) USING BTREE,
  KEY `license_plate` (`license_plate`) USING BTREE,
  KEY `client_name` (`client_name`) USING BTREE,
  KEY `tire_transaction_entityId` (`entity_id`) USING BTREE,
  KEY `tire_transaction_parentId` (`parent_id`) USING BTREE,
  KEY `tire_transaction_date` (`transaction_date`),
  KEY `deleted` (`deleted`),
  KEY `license__trans_date` (`transaction_date`,`license_plate`)
) ENGINE=InnoDB AUTO_INCREMENT=418618 DEFAULT CHARSET=utf8
</code>```

There are like 400K rows. Mysql is optimizing the query and rewriting the ON statement as a WHERE statement which I think is where the slowness comes from.

Any thoughts on this one? Thanks!

答:
Add your filters to the subquery. I'm not sure if that would return the same result. But according to the column names, it looks like it should.

```<code>SELECT t1.*
FROM   tire_transaction AS t1
       INNER JOIN (SELECT license_plate,
                          Max(transaction_date) AS `last_checkin`
                   FROM   tire_transaction
                   WHERE  ( t1.client_id = '1' )  -- line added
                     AND  ( t1.deleted = 0 )      -- line added
                   GROUP  BY license_plate) AS t2
               ON t1.license_plate = t2.license_plate
                  AND t1.transaction_date = t2.last_checkin
WHERE  ( t1.client_id = '1' ) -- line can probably be deleted
       AND ( t1.deleted = 0 ) -- line can probably be deleted
</code>```

You should also add an index on (client_id, license_plate, transaction_date).

Body:
I've a query which performs slow (~20s) and after doing a fair amount of reading and digging I can't seem to figure out a solution.

The query is:

EXPLAIN EXTENDED
SELECT t1.*
FROM   tire_transaction AS t1
       INNER JOIN (SELECT license_plate,
                          Max(transaction_date) AS `last_checkin`
                   FROM   tire_transaction
                   GROUP  BY license_plate) AS t2
               ON t1.license_plate = t2.license_plate
                  AND t1.transaction_date = t2.last_checkin
WHERE  ( t1.client_id = '1' )
       AND ( t1.deleted = 0 )

The result is:

id  select_type  table             type    possible_keys                                                              key                  key_len  ref                                 rows  filtered  Extra
 1  PRIMARY      <derived2>        ALL     (NULL)                                                                     (NULL)               (NULL)   (NULL)                             69121    100.00
 1  PRIMARY      t1                ref     client_id,license_plate,tire_transaction_date,deleted,license__trans_date  license__trans_date  67       t2.last_checkin,t2.license_plate       1    100.00  Using where
 2  DERIVED      tire_transaction  index   (NULL)                                                                     license_plate        63       (NULL)                            366423    100.00

The table is:

CREATE TABLE `tire_transaction` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `entity_id` int(11) DEFAULT NULL,
  `client_id` int(11) NOT NULL,
  `company_id` int(11) NOT NULL,
  `parent_id` int(11) DEFAULT NULL,
  `transaction_type` tinyint(1) DEFAULT '0',
  `transaction_date` date DEFAULT NULL,
  `transaction_status` int(11) DEFAULT NULL,
  `transaction_urgent` tinyint(1) NOT NULL DEFAULT '0',
  `license_plate` varchar(20) DEFAULT NULL,
  `license_plate_country` varchar(2) DEFAULT 'NL',
  `chassis_number` varchar(40) DEFAULT NULL,
  `brand` varchar(255) DEFAULT NULL,
  `brand_type` varchar(255) DEFAULT NULL,
  `client_name` varchar(255) DEFAULT NULL,
  `client_salutation` varchar(255) DEFAULT NULL,
  `client_company` varchar(255) DEFAULT NULL,
  `client_street` varchar(255) DEFAULT NULL,
  `client_number` varchar(255) DEFAULT NULL,
  `client_postalcode` varchar(255) DEFAULT NULL,
  `client_city` varchar(255) DEFAULT NULL,
  `client_phone` varchar(255) DEFAULT NULL,
  `client_phone_alt` varchar(255) DEFAULT NULL,
  `client_email` varchar(255) DEFAULT NULL,
  `tire_type` tinyint(1) DEFAULT '0',
  `set_price` int(11) DEFAULT NULL,
  `rim_material` tinyint(1) DEFAULT '0',
  `notes` text,
  `created` datetime DEFAULT NULL,
  `deleted` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `client_id` (`client_id`) USING BTREE,
  KEY `company_id` (`company_id`) USING BTREE,
  KEY `license_plate` (`license_plate`) USING BTREE,
  KEY `client_name` (`client_name`) USING BTREE,
  KEY `tire_transaction_entityId` (`entity_id`) USING BTREE,
  KEY `tire_transaction_parentId` (`parent_id`) USING BTREE,
  KEY `tire_transaction_date` (`transaction_date`),
  KEY `deleted` (`deleted`),
  KEY `license__trans_date` (`transaction_date`,`license_plate`)
) ENGINE=InnoDB AUTO_INCREMENT=418618 DEFAULT CHARSET=utf8

There are like 400K rows. Mysql is optimizing the query and rewriting the ON statement as a WHERE statement which I think is where the slowness comes from.

Any thoughts on this one? Thanks!

Body:
Add your filters to the subquery. I'm not sure if that would return the same result. But according to the column names, it looks like it should.

SELECT t1.*
FROM   tire_transaction AS t1
       INNER JOIN (SELECT license_plate,
                          Max(transaction_date) AS `last_checkin`
                   FROM   tire_transaction
                   WHERE  ( t1.client_id = '1' )  -- line added
                     AND  ( t1.deleted = 0 )      -- line added
                   GROUP  BY license_plate) AS t2
               ON t1.license_plate = t2.license_plate
                  AND t1.transaction_date = t2.last_checkin
WHERE  ( t1.client_id = '1' ) -- line can probably be deleted
       AND ( t1.deleted = 0 ) -- line can probably be deleted

You should also add an index on (client_id, license_plate, transaction_date).


问:
h:commandButton with oncomplete function and download a file
I have a little problem because i need to download a file (and for that i only can with h:commandButton) but i needed the oncomplete function (that only works with a4j:commandButton) to appear a Running Status.
The sample of the code is this:

```<code> <h:commandButton
        id="downloadReportButton"
        action="#{reportingBean.createAndDonwloadFile()}"
 />
</code>```

I already try to do  it like in this response by BalusC: https://stackoverflow.com/a/31267418/1777424 but the problem is because of Ajax requests are not perform.

```<code><h:commandButton
        id="downloadReportButton"
        action="#{reportingBean.createAndDonwloadFile()}"/>
        <f:ajax onevent="oneventFunction" />
 </h:commandLink>

function oneventFunction(data) {
    if (data.status === "success") {
        oncompleteFunction();
    }
}
</code>```

答:
I found the way to resolve this.
First is needed to have a a4j:commandButton just to have the click button with ajax requests. In this part the file will be created.

```<code><a4j:commandButton
    id="createFileButton"
    onclick="showLoading();"
    action="#{reportingBean.createFile()}"
    oncomplete="hideLoading(); #rich:element('downloadFileButton')}.click();"
/>
</code>```

This a4j:commandButton will in oncomplete click on downloadFileButton button that will download the file.
Then is necessary to have a h:commandButton to download the file that have been created.

```<code><h:commandButton
    id="downloadFileButton"
    action="#{reportingBean.downloadFile()}"
    style="display:none"
/>
</code>```

This button will be hidden (style="display:none") because is only to trigger the download of the file.

Body:
I have a little problem because i need to download a file (and for that i only can with h:commandButton) but i needed the oncomplete function (that only works with a4j:commandButton) to appear a Running Status.
The sample of the code is this:

 <h:commandButton
        id="downloadReportButton"
        action="#{reportingBean.createAndDonwloadFile()}"
 />

I already try to do  it like in this response by BalusC: https://stackoverflow.com/a/31267418/1777424 but the problem is because of Ajax requests are not perform.

<h:commandButton
        id="downloadReportButton"
        action="#{reportingBean.createAndDonwloadFile()}"/>
        <f:ajax onevent="oneventFunction" />
 </h:commandLink>

function oneventFunction(data) {
    if (data.status === "success") {
        oncompleteFunction();
    }
}

Body:
I found the way to resolve this.
First is needed to have a a4j:commandButton just to have the click button with ajax requests. In this part the file will be created.

<a4j:commandButton
    id="createFileButton"
    onclick="showLoading();"
    action="#{reportingBean.createFile()}"
    oncomplete="hideLoading(); #rich:element('downloadFileButton')}.click();"
/>

This a4j:commandButton will in oncomplete click on downloadFileButton button that will download the file.
Then is necessary to have a h:commandButton to download the file that have been created.

<h:commandButton
    id="downloadFileButton"
    action="#{reportingBean.downloadFile()}"
    style="display:none"
/>

This button will be hidden (style="display:none") because is only to trigger the download of the file.


问:
Compare values of two hashes with mixed types
I want to compare the hash if the key-value pairs are same in the second hash. I don't want to use smartmatch as it gives warnings.

What is the best way to compare two hashes with integers,strings and maybe also arrays in it?

```<code>use warnings;
use diagnostics;

my $hash1={"key_str"=>"a string", "key_int"=>4};
my $hash2={"key_str"=>"b string", "key_int"=>2};

foreach my $key ( keys(%$hash1) ) {
    if ($hash1->{$key} != $hash2->{$key}) {
        print($key);
    }
}
</code>```

the output as expected is:

```<code>Argument "b string" isn't numeric in numeric ne (!=) at hash_compare.pl line 8 (#1)
    (W numeric) The indicated string was fed as an argument to an operator
    that expected a numeric value instead.  If you're fortunate the message
    will identify which operator was so unfortunate.

Argument "a string" isn't numeric in numeric ne (!=) at hash_compare.pl line 8 (#1)
</code>```

答:
You can use Scalar::Util qw( looks_like_number ); to determine if the value is a number or a string. Scalar::Util is a standard module that is included with Perl. For a list of standard modules, see perldoc perlmodlib.

```<code>#!/usr/bin/env perl

# always use these two
use strict;
use warnings;

# handle errors in open and close
use autodie; # See http://perldoc.perl.org/autodie.html

use Scalar::Util  qw( looks_like_number );

my $hash1={"key_str"=>"a string", "key_int"=>4};
my $hash2={"key_str"=>"b string", "key_int"=>2};

foreach my $key ( keys(%$hash1) ) {
    if( looks_like_number( $hash1->{$key} ) && looks_like_number( $hash2->{$key} ) ){
        if ($hash1->{$key} != $hash2->{$key}) {
            print "number value of $key is different\n";
        }
    }else{
        if ($hash1->{$key} ne $hash2->{$key}) {
            print "string value of $key is different\n";
        }
    }
}
</code>```

Body:
I want to compare the hash if the key-value pairs are same in the second hash. I don't want to use smartmatch as it gives warnings.

What is the best way to compare two hashes with integers,strings and maybe also arrays in it?

use warnings;
use diagnostics;

my $hash1={"key_str"=>"a string", "key_int"=>4};
my $hash2={"key_str"=>"b string", "key_int"=>2};

foreach my $key ( keys(%$hash1) ) {
    if ($hash1->{$key} != $hash2->{$key}) {
        print($key);
    }
}

the output as expected is:

Argument "b string" isn't numeric in numeric ne (!=) at hash_compare.pl line 8 (#1)
    (W numeric) The indicated string was fed as an argument to an operator
    that expected a numeric value instead.  If you're fortunate the message
    will identify which operator was so unfortunate.

Argument "a string" isn't numeric in numeric ne (!=) at hash_compare.pl line 8 (#1)

Body:
You can use Scalar::Util qw( looks_like_number ); to determine if the value is a number or a string. Scalar::Util is a standard module that is included with Perl. For a list of standard modules, see perldoc perlmodlib.

#!/usr/bin/env perl

# always use these two
use strict;
use warnings;

# handle errors in open and close
use autodie; # See http://perldoc.perl.org/autodie.html

use Scalar::Util  qw( looks_like_number );

my $hash1={"key_str"=>"a string", "key_int"=>4};
my $hash2={"key_str"=>"b string", "key_int"=>2};

foreach my $key ( keys(%$hash1) ) {
    if( looks_like_number( $hash1->{$key} ) && looks_like_number( $hash2->{$key} ) ){
        if ($hash1->{$key} != $hash2->{$key}) {
            print "number value of $key is different\n";
        }
    }else{
        if ($hash1->{$key} ne $hash2->{$key}) {
            print "string value of $key is different\n";
        }
    }
}


问:
Check the array for the same elements
I have an array:

```<code>var objects = [
    {product:'123', options:{cap:'', fort:'', count:1}},
    {product:'123', options:{cap:'', fort:'', count:1}},
    {product:'12', options:{cap:'', fort:'', count:1}},
    {product:'1234', options:{cap:'123', fort:'', count:1}},
    {product:'1234', options:{cap:'', fort:'', count:1}}
];
</code>```

I need to filter this array in this way:

```<code>(product === product && options !== options) || (product !== product && options == options)
</code>```

It means that the array should looks like:

```<code>var objects = [
    {product:'123', options:{cap:'', fort:'', count:1}},
    {product:'1234', options:{cap:'123', fort:'', count:1}},
    {product:'12', options:{cap:'', fort:'', count:1}},
    {product:'1234', options:{cap:'', fort:'', count:1}}
];
</code>```

答:
Try this (not so efficient but simple) approach

```<code>objects.map((s)=> JSON.stringify(s)).filter( (s,i,a)=> a.indexOf(s,i+1) == -1 ).map((s)=> JSON.parse(s));
</code>```

Demo

var objects = [
{product:'123', options:{cap:'', fort:'', count:1}},
{product:'123', options:{cap:'', fort:'', count:1}},
{product:'12', options:{cap:'', fort:'', count:1}},
{product:'1234', options:{cap:'123', fort:'', count:1}},
{product:'1234', options:{cap:'', fort:'', count:1}}
];

objects = objects.map((s)=> JSON.stringify(s)).filter( (s,i,a)=> a.indexOf(s,i+1) == -1 ).map((s)=> JSON.parse(s));

console.log( objects );```

Explanation

Convert all items to their string version using JSON.stringify

Remove duplicates

Parse them back to Objects

Note
This answer won't work if your objects' keys are not in same order and any function values in the object will be removed after stringify and parse.

Title: Check the array for the same elements

Body:
I have an array:

var objects = [
    {product:'123', options:{cap:'', fort:'', count:1}},
    {product:'123', options:{cap:'', fort:'', count:1}},
    {product:'12', options:{cap:'', fort:'', count:1}},
    {product:'1234', options:{cap:'123', fort:'', count:1}},
    {product:'1234', options:{cap:'', fort:'', count:1}}
];

I need to filter this array in this way:

(product === product && options !== options) || (product !== product && options == options)

It means that the array should looks like:

var objects = [
    {product:'123', options:{cap:'', fort:'', count:1}},
    {product:'1234', options:{cap:'123', fort:'', count:1}},
    {product:'12', options:{cap:'', fort:'', count:1}},
    {product:'1234', options:{cap:'', fort:'', count:1}}
];

Body:
Try this (not so efficient but simple) approach

objects.map((s)=> JSON.stringify(s)).filter( (s,i,a)=> a.indexOf(s,i+1) == -1 ).map((s)=> JSON.parse(s));

Demo

var objects = [
{product:'123', options:{cap:'', fort:'', count:1}},
{product:'123', options:{cap:'', fort:'', count:1}},
{product:'12', options:{cap:'', fort:'', count:1}},
{product:'1234', options:{cap:'123', fort:'', count:1}},
{product:'1234', options:{cap:'', fort:'', count:1}}
];

objects = objects.map((s)=> JSON.stringify(s)).filter( (s,i,a)=> a.indexOf(s,i+1) == -1 ).map((s)=> JSON.parse(s));

console.log( objects );

Explanation

Convert all items to their string version using JSON.stringify

Remove duplicates

Parse them back to Objects

Note
This answer won't work if your objects' keys are not in same order and any function values in the object will be removed after stringify and parse.


问:
Split data.frame into groups by column name
I'm new to R. I have a data frame with column names of such type:

```<code>file_001   file_002   block_001   block_002   red_001   red_002 ....etc'
  0.05       0.2        0.4         0.006       0.05       0.3
  0.01       0.87       0.56        0.4         0.12       0.06
</code>```

I want to split them into groups by the column name, to get a result like this:

```<code>group_file
file_001   file_002
  0.05       0.2
  0.01       0.87

group_block
block_001   block_002
  0.4        0.006
  0.56       0.4

group_red
red_001    red_002
  0.05       0.3
  0.12       0.06

...etc'
</code>```

My file is huge. I don't have a certain number of groups.
It needs to be just by the column name's start.

答:
In base R, you can use sub and split.default like this to return a list of data.frames:

```<code>myDfList <- split.default(dat, sub("_\\d+", "", names(dat)))
</code>```

this returns

```<code>myDfList
$block
  block_001 block_002
1      0.40     0.006
2      0.56     0.400

$file
  file_001 file_002
1     0.05     0.20
2     0.01     0.87

$red
  red_001 red_002
1    0.05    0.30
2    0.12    0.06
</code>```

split.default will split data.frames by variable according to its second argument. Here, we use sub and the regular expression "_\d+" to remove the underscore and all numeric values following it in order to return the splitting values "block", "file", and "red".

As a side note, it is typically a good idea to keep these data.frames in a list and work with them through functions like lapply. See gregor's answer to this post for some motivating examples.

Body:
I'm new to R. I have a data frame with column names of such type:

file_001   file_002   block_001   block_002   red_001   red_002 ....etc'
  0.05       0.2        0.4         0.006       0.05       0.3
  0.01       0.87       0.56        0.4         0.12       0.06

I want to split them into groups by the column name, to get a result like this:

group_file
file_001   file_002
  0.05       0.2
  0.01       0.87

group_block
block_001   block_002
  0.4        0.006
  0.56       0.4

group_red
red_001    red_002
  0.05       0.3
  0.12       0.06

...etc'

My file is huge. I don't have a certain number of groups.
It needs to be just by the column name's start.

Body:
In base R, you can use sub and split.default like this to return a list of data.frames:

myDfList <- split.default(dat, sub("_\\d+", "", names(dat)))

this returns

myDfList
$block
  block_001 block_002
1      0.40     0.006
2      0.56     0.400

$file
  file_001 file_002
1     0.05     0.20
2     0.01     0.87

$red
  red_001 red_002
1    0.05    0.30
2    0.12    0.06

split.default will split data.frames by variable according to its second argument. Here, we use sub and the regular expression "_\d+" to remove the underscore and all numeric values following it in order to return the splitting values "block", "file", and "red".

As a side note, it is typically a good idea to keep these data.frames in a list and work with them through functions like lapply. See gregor's answer to this post for some motivating examples.


问:
Detecting characters and acting on them
```<code>    if what == "decode":
    dog_input = input("What would you like to decode?")
    letternumber = len(dog_input)
    a=(dog_input)
    for i in range(a):
        if dog_input[1] == "1":
            print("a")
        if dog_input[1] == "2":
            print("b")
        if dog_input[1] == "3":
            print("c")
        if dog_input[1] == "4":
            print("d")
        if dog_input[1] == "5":
            print("e")
        if dog_input[1] == "6":
            print("f")
        if dog_input[1] == "7":
            print("g")
        if dog_input[1] == "8":
            print("h")
        if dog_input[1] == "9":
            print("i")
        if dog_input[2] == "10":
            print("j")
        if dog_input[2] == "11":
            print("k")
        if dog_input[2] == "12":
            print("l")
        if dog_input[2] == "13":
            print("m")
        if dog_input[2] == "14":
            print("n")
        if dog_input[2] == "15":
            print("o")
        if dog_input[2] == "16":
            print("p")
        if dog_input[2] == "17":
            print("q")
        if dog_input[2] == "18":
            print("r")
        if dog_input[2] == "19":
            print("s")
        if dog_input[1] == "20":
            print("t")
        if dog_input[2] == "21":
            print("u")
        if dog_input[2] == "21":
            print("v")
        if dog_input[2] == "22":
            print("w")
        if dog_input[2] == "23":
            print("x")
        if dog_input[2] == "24":
            print("y")
        if dog_input[2] == "25":
            print("z")
        if dog_input[3] == "-64":
            print(" ")
</code>```

<p>This code does nothing- it will print a character a random three or four times. I would like a user to input numbers and get out letters, but it refuses to read. How do I get it to function? Also, is there a faster way of assigning numbers to letters? </p>

答:
You can create a dictionary to store letters and their number : </p>

```<code>dictionary = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26,' ':-64}
</code>```

<p>And then use Series to fetch key based on value which is in your case letternumber : </p>

```<code>lookup_list = pd.Series(dictionary)
print(lookup_list[lookup_list.values == letternumber ].index)
answer = lookup_list[lookup_list.values == 19].index
</code>```

Title: Detecting characters and acting on them

Body:
    if what == "decode":
    dog_input = input("What would you like to decode?")
    letternumber = len(dog_input)
    a=(dog_input)
    for i in range(a):
        if dog_input[1] == "1":
            print("a")
        if dog_input[1] == "2":
            print("b")
        if dog_input[1] == "3":
            print("c")
        if dog_input[1] == "4":
            print("d")
        if dog_input[1] == "5":
            print("e")
        if dog_input[1] == "6":
            print("f")
        if dog_input[1] == "7":
            print("g")
        if dog_input[1] == "8":
            print("h")
        if dog_input[1] == "9":
            print("i")
        if dog_input[2] == "10":
            print("j")
        if dog_input[2] == "11":
            print("k")
        if dog_input[2] == "12":
            print("l")
        if dog_input[2] == "13":
            print("m")
        if dog_input[2] == "14":
            print("n")
        if dog_input[2] == "15":
            print("o")
        if dog_input[2] == "16":
            print("p")
        if dog_input[2] == "17":
            print("q")
        if dog_input[2] == "18":
            print("r")
        if dog_input[2] == "19":
            print("s")
        if dog_input[1] == "20":
            print("t")
        if dog_input[2] == "21":
            print("u")
        if dog_input[2] == "21":
            print("v")
        if dog_input[2] == "22":
            print("w")
        if dog_input[2] == "23":
            print("x")
        if dog_input[2] == "24":
            print("y")
        if dog_input[2] == "25":
            print("z")
        if dog_input[3] == "-64":
            print(" ")

This code does nothing- it will print a character a random three or four times. I would like a user to input numbers and get out letters, but it refuses to read. How do I get it to function? Also, is there a faster way of assigning numbers to letters?

Body:
You can create a dictionary to store letters and their number :

dictionary = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26,' ':-64}

And then use Series to fetch key based on value which is in your case letternumber :

lookup_list = pd.Series(dictionary)
print(lookup_list[lookup_list.values == letternumber ].index)
answer = lookup_list[lookup_list.values == 19].index


问:
NoMethodError: undefined method `start_with?'
Today (I don't know why!!!!) I cannot deploy my project with capistrano.

When I launch this task

```<code>namespace :deploy do

  # Theme path
  set :theme_path, Pathname.new('web/app/themes').join(fetch(:theme_name))

  # Local Paths
  set :local_theme_path, Pathname.new(File.dirname(__FILE__)).join('../').join(fetch(:theme_path))
  set :local_dist_path, fetch(:local_theme_path).join('dist')

  task :compile do
    run_locally do
      within fetch(:local_theme_path) do
        execute "git checkout #{fetch(:branch)}"
        execute :gulp, '--production'
      end
    end
  end

  task :copy do
    on roles(:web) do

      # Remote Paths (Lazy-load until actual deploy)
      set :remote_dist_path, -> { release_path.join(fetch(:theme_path)).join('dist') }

      info " Your local distribution path: #{fetch(:local_dist_path)} "
      info " Boom!!! Your remote distribution path: #{fetch(:remote_dist_path)} "
      info " Uploading files to remote "
      upload! fetch(:local_dist_path).to_s, fetch(:remote_dist_path), recursive: true
    end
  end

  task assets: %w(compile copy)
end
</code>```

Capistrano print this error

(Backtrace restricted to imported tasks)

cap aborted!

SSHKit::Runner::ExecuteError: Exception while executing as ec2->user@*********: undefined method `start_with?' for #Pathname:0x0000*fc***a****

Caused by:

NoMethodError: undefined method `start_with?' for #Pathname:0x0000*fc***a****

I try all: uninstall node, ruby, etc... ma nothing change.
Someone can help me?

Thanks

答:
```<code>upload! fetch(:local_dist_path).to_s, fetch(:remote_dist_path), recursive: true
</code>```

should be

```<code>upload! fetch(:local_dist_path).to_s, fetch(:remote_dist_path).to_s, recursive: true
</code>```

(call to_s on both Pathnames.)

Body:
Today (I don't know why!!!!) I cannot deploy my project with capistrano.

When I launch this task

namespace :deploy do

  # Theme path
  set :theme_path, Pathname.new('web/app/themes').join(fetch(:theme_name))

  # Local Paths
  set :local_theme_path, Pathname.new(File.dirname(__FILE__)).join('../').join(fetch(:theme_path))
  set :local_dist_path, fetch(:local_theme_path).join('dist')

  task :compile do
    run_locally do
      within fetch(:local_theme_path) do
        execute "git checkout #{fetch(:branch)}"
        execute :gulp, '--production'
      end
    end
  end

  task :copy do
    on roles(:web) do

      # Remote Paths (Lazy-load until actual deploy)
      set :remote_dist_path, -> { release_path.join(fetch(:theme_path)).join('dist') }

      info " Your local distribution path: #{fetch(:local_dist_path)} "
      info " Boom!!! Your remote distribution path: #{fetch(:remote_dist_path)} "
      info " Uploading files to remote "
      upload! fetch(:local_dist_path).to_s, fetch(:remote_dist_path), recursive: true
    end
  end

  task assets: %w(compile copy)
end

Capistrano print this error

(Backtrace restricted to imported tasks)

cap aborted!

SSHKit::Runner::ExecuteError: Exception while executing as ec2->user@*********: undefined method `start_with?' for #Pathname:0x0000*fc***a****

Caused by:

NoMethodError: undefined method `start_with?' for #Pathname:0x0000*fc***a****

I try all: uninstall node, ruby, etc... ma nothing change.
Someone can help me?

Thanks

Body:
upload! fetch(:local_dist_path).to_s, fetch(:remote_dist_path), recursive: true

should be

upload! fetch(:local_dist_path).to_s, fetch(:remote_dist_path).to_s, recursive: true

(call to_s on both Pathnames.)


问:
Make table columns resizable with jQuery plugin
I use DataTables and jquery-resizable-columns to create table with resizable columns. Here is example.

I tried to use jquery-resizable-columns plugin in basic ReactJS application with DataTables. I added resizableColumns function in componentDidMount, but it doesn't work.

I am in ReactJS, can anybody explain to me why it doesn't work?

jsfiddle

jsx script

```<code>/** @jsx React.DOM */

var TodoApp = React.createClass({
  getInitialState: function() {
    return {items: [], text: ''};
  },
  render: function() {
    return (
      <div>
        <h3>React + jQuery.DataTable</h3>

        <LopMonHoc />
      </div>
    );
  }
});

var LopMonHoc = React.createClass({
    getInitialState: function(){
        return {data: []}
    },
    componentDidMount: function(){
        var self = this;
        $('#mytable').DataTable({
          "bAutoWidth": false,
          "bDestroy": true,
          "fnDrawCallback": function() {
                self.forceUpdate();
          },
        });
        $("#mytable").resizableColumns();
    },
    componentDidUpdate: function(){
        $('#mytable').DataTable({
          "bAutoWidth": false,
          "bDestroy": true,
        });
    },
    render: function(){
        var x = [];

        x.push(
            <tr><td>zaxs</td><td>hello</td><td>xzc</td></tr>
        )

        x.push(
            <tr><td>hello</td><td>wef</td><td>qw</td></tr>
        )

        x.push(
            <tr><td>wefwe</td><td>fgn</td><td>asc</td></tr>
        )

        return (
            <div className="table-responsive">
                <h4>Hello</h4>
                <table className="table table-bordered" id="mytable">
                    <thead>
                        <tr className="success">
                            <td>col1</td>
                            <td>col2</td>
                            <td>col3</td>
                        </tr>
                    </thead>
                    <tbody>
                        {x}
                    </tbody>
                </table>
            </div>
        )
    }
 });

React.render(<TodoApp />, document.body);
</code>```

答:
There is ColReorderWithResize plug-in that adds ability reorder and resize columns for the latest version of jQuery DataTables 1.10.

You need to include the appropriate JS file and use the following initialization code.

```<code>var table = $('#example').DataTable({
    'dom': 'Rlfrtip'
});
</code>```

See this example for code and demonstration.

See jQuery DataTables: Column reordering and resizing for more details.

Body:
I use DataTables and jquery-resizable-columns to create table with resizable columns. Here is example.

I tried to use jquery-resizable-columns plugin in basic ReactJS application with DataTables. I added resizableColumns function in componentDidMount, but it doesn't work.

I am in ReactJS, can anybody explain to me why it doesn't work?

jsfiddle

jsx script

/** @jsx React.DOM */

var TodoApp = React.createClass({
  getInitialState: function() {
    return {items: [], text: ''};
  },
  render: function() {
    return (

React + jQuery.DataTable

        <LopMonHoc />

    );
  }
});

var LopMonHoc = React.createClass({
    getInitialState: function(){
        return {data: []}
    },
    componentDidMount: function(){
        var self = this;
        $('#mytable').DataTable({
          "bAutoWidth": false,
          "bDestroy": true,
          "fnDrawCallback": function() {
                self.forceUpdate();
          },
        });
        $("#mytable").resizableColumns();
    },
    componentDidUpdate: function(){
        $('#mytable').DataTable({
          "bAutoWidth": false,
          "bDestroy": true,
        });
    },
    render: function(){
        var x = [];

        x.push(

zaxs	hello	xzc

        )

        x.push(

hello	wef	qw

        )

        x.push(

wefwe	fgn	asc

        )

        return (

Hello

                            col1
                            col2
                            col3

                        {x}

        )
    }
 });

React.render(<TodoApp />, document.body);

Body:
There is ColReorderWithResize plug-in that adds ability reorder and resize columns for the latest version of jQuery DataTables 1.10.

You need to include the appropriate JS file and use the following initialization code.

var table = $('#example').DataTable({
    'dom': 'Rlfrtip'
});

See this example for code and demonstration.

See jQuery DataTables: Column reordering and resizing for more details.


问:
Nodejs & Express: How to redirect to another website and not to a route in the site?
I'm trying to make a function that redirects you to another website, but instead of redirecting to another website its assuming that the weblink that i want to redirect to is a route in my website.

```<code>    app.get('/:shorturl', (req, res) => {
    UrlShort.findOne({'ShortUrl': req.param('shorturl')}, (err, doc) => {
        if(err) return res.send('Error Reading Database!');
        var re = new RegExp("$(http|https)://", "i");
        if(re.test(doc.OriginalUrl)){
            res.redirect(301, doc.OriginalUrl);
        } else {
            res.redirect(301, 'http://' + doc.OriginalUrl);
        }
     });
   });
</code>```

Instead of redirecting to the other web site it redirects to this:

```<code>http://localhost:3000/www.google.com
</code>```

答:
Your problem is not redirect function. It seems true. But your Regex is wrong. You need to change your regex to

```<code>^(http|https)://
</code>```

Here is working code example that I've tested:

```<code>app.get("/redirect", function(req, res) {
var url = "http://www.google.com";

var re = new RegExp("^(http|https)://", "i");
if(re.test(url)){
    console.log("#LOG1", url);
    res.redirect(301, url);
} else {
    console.log("#LOG2", 'http://' + url);
    res.redirect(301, 'http://' + url);
}});
</code>```

Body:
I'm trying to make a function that redirects you to another website, but instead of redirecting to another website its assuming that the weblink that i want to redirect to is a route in my website.

    app.get('/:shorturl', (req, res) => {
    UrlShort.findOne({'ShortUrl': req.param('shorturl')}, (err, doc) => {
        if(err) return res.send('Error Reading Database!');
        var re = new RegExp("$(http|https)://", "i");
        if(re.test(doc.OriginalUrl)){
            res.redirect(301, doc.OriginalUrl);
        } else {
            res.redirect(301, 'http://' + doc.OriginalUrl);
        }
     });
   });

Instead of redirecting to the other web site it redirects to this:

http://localhost:3000/www.google.com

Body:
Your problem is not redirect function. It seems true. But your Regex is wrong. You need to change your regex to

^(http|https)://

Here is working code example that I've tested:

app.get("/redirect", function(req, res) {
var url = "http://www.google.com";

var re = new RegExp("^(http|https)://", "i");
if(re.test(url)){
    console.log("#LOG1", url);
    res.redirect(301, url);
} else {
    console.log("#LOG2", 'http://' + url);
    res.redirect(301, 'http://' + url);
}});


问:
How to get a response number of a HTTPS request
I would like to make use of Linux command to get a response number of an HTTPS request rather than HTTP request. According to my current knowledge wget and curl can achieve the goal.

For instance, given the address https://asunnot.oikotie.fi/vuokrattavat-asunnot/espoo/13874872 I intend to use the following commands:

with curl: curl -I https://asunnot.oikotie.fi/vuokrattavat-asunnot/espoo/13874872

with wget: wget --spider -S 'https://asunnot.oikotie.fi/vuokrattavat-asunnot/espoo/13874872'

Both requests got the response as HTTP/1.1 405 Not Allowed. But when I try the address with a browser, e.g. Chrome, or Firefox etc. The page can indeed display without issue.

Anyone can help on it? How is it possible to get the correct response number rather than the first direct 405?

答:
The server is answering with HTTP code 405 because it's rejecting the User-Agent header your curl command sent. This is clearly a bad behaviour from the server configuration or the website application itself. The server should have answered with HTTP 400.

Anyway, the following works fine for the given URL:

```<code>curl -I -H "User-Agent: Mozilla/5.0" <url>
</code>```

Body:
The server is answering with HTTP code 405 because it's rejecting the User-Agent header your curl command sent. This is clearly a bad behaviour from the server configuration or the website application itself. The server should have answered with HTTP 400.

Anyway, the following works fine for the given URL:

curl -I -H "User-Agent: Mozilla/5.0" <url>


问:
How to grep a shell variable to match end of line?
How can I match a bash variable in the end of the line?

The code below can do that for a number in the end:

```<code>grep '[0-9]$'
</code>```

But in my case the number is a variable. I was hoping something like

grep '{$i}$'

where $i is my variable, would work, but no avail. I've tried with several single/double comma combinations but no sucess so far.

Thanks in advance.

答:
Use single quotes to make the $ work as end-of-line. If you want to grep with some variable also, use double and single quotes as below:

grep "$var"'$'

Body:
How can I match a bash variable in the end of the line?

The code below can do that for a number in the end:

grep '[0-9]$'

But in my case the number is a variable. I was hoping something like

grep '{$i}$'

where $i is my variable, would work, but no avail. I've tried with several single/double comma combinations but no sucess so far.

Thanks in advance.


问:
A computer with two network adapter is scanned by Arp
I've got a computer with two network adapter, both of them is assigned a different IP.(EX:192.168.81.90, 192.168.81.93)

And I use ARP scan from 192.168.81.1 to 192.168.81.255, I will get two different MAC addresses and two different IPs.

Is it possible to recognize these pairs of MAC address + IP belonging to the same host?

答:
I can propose you a test, but It will not be successful in all cases. It will depend on the OS IP stack implementation.
You did not give us a important information about your setup, that is your network mask. I suppose your question is related to a host with 2 different IP on the SAME network. You have to know first, that setup is a WRONG setup because it creates a asymmetric load for outgoing traffic. If a host has 2 physical interfaces on the same IP network (same network number, same netmask), you MUST first bond both interface at level 2 to create one virtual interface to assign it the 2 IP addresses.
The test I propose you, is to detect that wrong setup:
Let's suppose for 192.168.81.90 you got 01:01:01:01:01:01 mac address, and for  192.168.81.93 you got 02:02:02:02:02:02 (result got from you scan).
Manually, with the arp command, swap the mac of both ip with command like:
arp -s 192.168.81.93  01:01:01:01:01:01
arp -s 192.168.81.90  02:02:02:02:02:02

With that arp (temporary) setup, now try to ping each ip.
If you got a echo reply, both ip COULD (not yet sure) be on the same host.
The final verification is to grab the echo reply packet with tcpdump, and to verify its source mac @ and to check is either 01:01:01:01:01:01 or 02:02:02:02:02:02. If the mac address source is not one of these addresses, so, the host your are testing is a router and not a host. (the system is forwarding the traffic and not only receiving it like a host)
A case where my test fails is when the host has IP filtering on incoming interfaces.