问:
Update a store property
I am getting a response from an API as below:

```<code>{
    "results": {
        "6": {
            "id": 6,
            "name": "akkha madrasi mirchi1",
        },
        "7": {
            "id": 7,
            "name": "almonds",
        },
        "8": {
            "id": 8,
            "name": "alu1",
        }
    }
}
</code>```

I am storing response.results in results reducer store {} so that I can access results as store.results. I want to modify an object inside the results. The API only returns the updated object. Now I want to update  id: 6 in store.results.

```<code>{
    "results": {
        "6": {
            "id": 6,
            "name": "Modified akkha madrasi mirchi1",
        }
    }
}
</code>```

If I do this in the results reducer:

```<code>[...state,action.response]
</code>```

will the object with key 6 replace the object with matching keys?

I am expecting state to be (note name changed to Modified akkha madrasi mirchi1 for id: 6):

```<code>"results": {
    "6": {
        "id": 6,
        "name": "Modified akkha madrasi mirchi1",
    },
    "7": {
        "id": 7,
        "name": "almonds",
    },
    "8": {
        "id": 8,
        "name": "alu1",
    }
}
</code>```

I want objects to be updated even if they are nested. Just match the key and keep on replacing.

答:
If I do this in the results reducer:

```<code>[...state,action.response]
</code>```

will the object with key 6 replace the object with matching keys?

No. This is what you might use if your state was an array, but from the information you've given it's an object (all of results is an object with ids as keys).

What you're probably looking for is something like this:

```<code>return {
  ...state,
  ...action.response.results
}
</code>```

This will create a shallow copy of the state, preserving the object references for each result item (more efficient than doing a deep copy if you don't need to). It will then overwrite the previous id: 6 with whatever is in response.results.

Couple of things to remember about this:

It assumes you have object spread available. If not, Object.assign({}, state, action.response.results) will have the same effect but (IMHO) is not as clear.

Whatever is returned from the server will entirely replace whatever you already had in id: 6. That means if you were tracking various bits of state in the client for that id, or the server doesn't return everything you need, you might get some unexpected results.

const state = {
  6: {
    id: 6,
    name: 'akkha madrasi mirchi1'
  },
  7: {
    id: 7,
    name: 'almonds'
  },
  8: {
    id: 8,
    name: 'alu1'
  }
}
const response = {
  results: {
    6: {
      id: 6,
      name: 'Modified akkha madrasi mirchi1'
    }
  }
}

console.log({
  ...state,
  ...response.results
})```
</div>
</div>
</p>

<p>Just for completeness, here's how you'd reduce it if you had the nested structure as described in comment thread:</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>const state = {
  results: {
    6: {
      id: 6,
      name: 'akkha madrasi mirchi1'
    },
    7: {
      id: 7,
      name: 'almonds'
    },
    8: {
      id: 8,
      name: 'alu1'
    }
  }
}
const response = {
  results: {
    6: {
      id: 6,
      name: 'Modified akkha madrasi mirchi1'
    }
  }
}

console.log({
  ...state,
  results: {
    ...state.results,
    ...response.results
  }
})</code>```

Title: Update a store property

Body:
I am getting a response from an API as below:

{
    "results": {
        "6": {
            "id": 6,
            "name": "akkha madrasi mirchi1",
        },
        "7": {
            "id": 7,
            "name": "almonds",
        },
        "8": {
            "id": 8,
            "name": "alu1",
        }
    }
}

I am storing response.results in results reducer store {} so that I can access results as store.results. I want to modify an object inside the results. The API only returns the updated object. Now I want to update  id: 6 in store.results.

{
    "results": {
        "6": {
            "id": 6,
            "name": "Modified akkha madrasi mirchi1",
        }
    }
}

If I do this in the results reducer:

[...state,action.response]

will the object with key 6 replace the object with matching keys?

I am expecting state to be (note name changed to Modified akkha madrasi mirchi1 for id: 6):

"results": {
    "6": {
        "id": 6,
        "name": "Modified akkha madrasi mirchi1",
    },
    "7": {
        "id": 7,
        "name": "almonds",
    },
    "8": {
        "id": 8,
        "name": "alu1",
    }
}

I want objects to be updated even if they are nested. Just match the key and keep on replacing.

Body:
If I do this in the results reducer:

[...state,action.response]

will the object with key 6 replace the object with matching keys?

No. This is what you might use if your state was an array, but from the information you've given it's an object (all of results is an object with ids as keys).

What you're probably looking for is something like this:

return {
  ...state,
  ...action.response.results
}

This will create a shallow copy of the state, preserving the object references for each result item (more efficient than doing a deep copy if you don't need to). It will then overwrite the previous id: 6 with whatever is in response.results.

Couple of things to remember about this:

It assumes you have object spread available. If not, Object.assign({}, state, action.response.results) will have the same effect but (IMHO) is not as clear.

Whatever is returned from the server will entirely replace whatever you already had in id: 6. That means if you were tracking various bits of state in the client for that id, or the server doesn't return everything you need, you might get some unexpected results.

const state = {
  6: {
    id: 6,
    name: 'akkha madrasi mirchi1'
  },
  7: {
    id: 7,
    name: 'almonds'
  },
  8: {
    id: 8,
    name: 'alu1'
  }
}
const response = {
  results: {
    6: {
      id: 6,
      name: 'Modified akkha madrasi mirchi1'
    }
  }
}

console.log({
  ...state,
  ...response.results
})

Just for completeness, here's how you'd reduce it if you had the nested structure as described in comment thread:

const state = {
  results: {
    6: {
      id: 6,
      name: 'akkha madrasi mirchi1'
    },
    7: {
      id: 7,
      name: 'almonds'
    },
    8: {
      id: 8,
      name: 'alu1'
    }
  }
}
const response = {
  results: {
    6: {
      id: 6,
      name: 'Modified akkha madrasi mirchi1'
    }
  }
}

console.log({
  ...state,
  results: {
    ...state.results,
    ...response.results
  }
})


来源: stackexchange

问:
how to allow access to web page only specific mobile app using user agent
I have created some php web pages for inserting webview & some json informations in an android app. And I want to protect my web data by allowing access to these web pages ONLY from my app , how is this possible ? I heard that this can be done by setting my own user agent in the app and catch it in my web page , but I don't know how to do this</p>

答:
Assuming that the connection between your app and the backend is via HTTPS, you could use client-side certificates to authenticate the caller (your app) to the backend server. Only if the caller provides the right certificate the transaction could move further.

Note that this is not unbreakable: someone who has access to your app can extract the certificate and replay it. This is not obvious to do so if you want a reasonable but not NSA grade solution it would be acceptable.

A simpler solution would be to send a hard-coded authentication token as part of the transaction, checked by the backend.

ContentLicense: CC BY-SA 3.0


问:
Caching the mean of a Vector in R (list)
This is a follow up to Caching the mean of a Vector in R and is specifically about the last line of code

```<code>list(set = set, get = get, setmean = setmean, getmean = getmean)
</code>```

I am not understanding what the list is doing.  The answer given at the linked question:

list() returns the 'special vector' containing all of the functions just defined

does not make much sense to me. I think that makeVector should be returning an object which has the approriate set and get methods, but now sure how this list() is doing that.  What is the set on the left-hand side and what is the set on the right-hand side?

```<code> makeVector <- function(x = numeric()) {
         m <- NULL
         set <- function(y) {
                x <<- y
                m <<- NULL
        }
        get <- function() x
        setmean <- function(mean) m <<- mean
        getmean <- function() m
        list(set = set, get = get,
             setmean = setmean,
             getmean = getmean)
 }
</code>```

答:
I provide an extensive walkthrough of the two functions in the second Johns Hopkins R Programming Assignment in my article Demystifying makeVector().

That said, here is the answer to how the list() statement works in makeVector().

Step 3: Create a new object by returning a list()

Here is the other part of the "magic" in the operations of the makeVector() function. The last section of code assigns each of these functions as an element within a list(), and returns it to the parent environment.

```<code>list(set = set, get = get,
     setmean = setmean,
     getmean = getmean)
</code>```

When the function ends, it returns a fully formed object of type makeVector() to be used by downstream R code. One other important subtlety about this code is that each element in the list is named. That is, each element in the list is created with a elementName = value syntax, as follows:

```<code>    list(set = set,          # gives the name 'set' to the set() function defined above
         get = get,          # gives the name 'get' to the get() function defined above
         setmean = setmean,  # gives the name 'setmean' to the setmean() function defined above
         getmean = getmean)  # gives the name 'getmean' to the getmean() function defined above
</code>```

Naming the list elements is what allows us to use the $ form of the extract operator to access the functions by name rather than using the [[ form of the extract operator, as in myVector[[2]](), to get the contents of the vector.

Here it's important to note that the cachemean() function REQUIRES an input argument of type makeVector(). If one passes a regular vector to the function, as in

```<code> aResult <- cachemean(1:15)
</code>```

the function call will fail with an error explaining that cachemean() was unable to access $getmean() on the input argument because $ does not work with atomic vectors. This is accurate, because a primitive vector is not a list, nor does it contain a $getmean() function, as illustrated below.

```<code>> aVector <- 1:10
> cachemean(aVector)
Error in x$getmean : $ operator is invalid for atomic vectors
</code>```

Body:
This is a follow up to Caching the mean of a Vector in R and is specifically about the last line of code

list(set = set, get = get, setmean = setmean, getmean = getmean)

I am not understanding what the list is doing.  The answer given at the linked question:

list() returns the 'special vector' containing all of the functions just defined

does not make much sense to me. I think that makeVector should be returning an object which has the approriate set and get methods, but now sure how this list() is doing that.  What is the set on the left-hand side and what is the set on the right-hand side?

 makeVector <- function(x = numeric()) {
         m <- NULL
         set <- function(y) {
                x <<- y
                m <<- NULL
        }
        get <- function() x
        setmean <- function(mean) m <<- mean
        getmean <- function() m
        list(set = set, get = get,
             setmean = setmean,
             getmean = getmean)
 }

Body:
I provide an extensive walkthrough of the two functions in the second Johns Hopkins R Programming Assignment in my article Demystifying makeVector().

That said, here is the answer to how the list() statement works in makeVector().

Step 3: Create a new object by returning a list()

Here is the other part of the "magic" in the operations of the makeVector() function. The last section of code assigns each of these functions as an element within a list(), and returns it to the parent environment.

list(set = set, get = get,
     setmean = setmean,
     getmean = getmean)

When the function ends, it returns a fully formed object of type makeVector() to be used by downstream R code. One other important subtlety about this code is that each element in the list is named. That is, each element in the list is created with a elementName = value syntax, as follows:

    list(set = set,          # gives the name 'set' to the set() function defined above
         get = get,          # gives the name 'get' to the get() function defined above
         setmean = setmean,  # gives the name 'setmean' to the setmean() function defined above
         getmean = getmean)  # gives the name 'getmean' to the getmean() function defined above

Naming the list elements is what allows us to use the $ form of the extract operator to access the functions by name rather than using the [[ form of the extract operator, as in myVector[[2]](), to get the contents of the vector.

Here it's important to note that the cachemean() function REQUIRES an input argument of type makeVector(). If one passes a regular vector to the function, as in

 aResult <- cachemean(1:15)

the function call will fail with an error explaining that cachemean() was unable to access $getmean() on the input argument because $ does not work with atomic vectors. This is accurate, because a primitive vector is not a list, nor does it contain a $getmean() function, as illustrated below.

> aVector <- 1:10
> cachemean(aVector)
Error in x$getmean : $ operator is invalid for atomic vectors


问:
How to automatically update NuGet packages to latest available version
I have two repositories, and I need compiled libraries from one repository in the other. I don't want to manually check repo1 for updated libraries, and copy/commit to repo2, because that is stupid. I've got repo1 building NuGet packages on each build of the necessary libraries, and publishing them to an internal NuGet server. Projects in repo2 can then reference these NuGet packages, and everything is (almost) working.

The one last hurdle to this is automatically updating the NuGet packages in repo2's projects. Since I don't know when the libraries in repo1 will get updated (and I shouldn't have to), I would like some sort of build event on the projects in repo2 that will automatically update the NuGet packages. I currently just have a pre-build event doing it, but since packages.config files contain the version number of the installed package, I keep getting modified files in repo2 (the packages.config files get updated).

So my question is: what's a good way to automatically upgrade NuGet packages without mucking up my repo2 VCS? ScottGu says Here (in comments) that it's possible to hook package upgrades up to CI builds, but he doesn't specify how and my current solution is messy. Is there a built in way that I'm missing? Or any better work-arounds?

答:
This explains how to do it via MSBuild

http://netitude.bc3tech.net/2014/11/28/auto-update-your-nuget-packages-at-build-time/

```<code><Target Name="UpdatePackages" DependsOnTargets="CheckPrerequisites">
   <Exec Command="$(UpdateCommand)"
      Condition="'$(OS)' != 'Windows_NT' And Exists('$(PackagesConfig)')" />

   <Exec Command="$(UpdateCommand)"
      LogStandardErrorAsError="true"
      Condition="'$(OS)' == 'Windows_NT' And Exists('$(PackagesConfig)')" />
</Target>

<!-- Commands -->
<UpdateCommand>$(NuGetCommand) update "$(PackagesConfig)" -source "$(PackageSources)" -id AutoUpdater $(NonInteractiveSwitch)</UpdateCommand>
<RestoreCommand>$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)"  $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir)</RestoreCommand>

<BuildCommand>$(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols</BuildCommand>

<!-- We need to ensure packages are restored prior to assembly resolve -->
<BuildDependsOn Condition="$(RestorePackages) == 'true'">
    RestorePackages;
    UpdatePackages;
    $(BuildDependsOn);
</BuildDependsOn>
</code>```

Body:
This explains how to do it via MSBuild

http://netitude.bc3tech.net/2014/11/28/auto-update-your-nuget-packages-at-build-time/

<Target Name="UpdatePackages" DependsOnTargets="CheckPrerequisites">
   <Exec Command="$(UpdateCommand)"
      Condition="'$(OS)' != 'Windows_NT' And Exists('$(PackagesConfig)')" />

   <Exec Command="$(UpdateCommand)"
      LogStandardErrorAsError="true"
      Condition="'$(OS)' == 'Windows_NT' And Exists('$(PackagesConfig)')" />
</Target>

<!-- Commands -->
<UpdateCommand>$(NuGetCommand) update "$(PackagesConfig)" -source "$(PackageSources)" -id AutoUpdater $(NonInteractiveSwitch)</UpdateCommand>
<RestoreCommand>$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)"  $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir)</RestoreCommand>

<BuildCommand>$(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols</BuildCommand>

<!-- We need to ensure packages are restored prior to assembly resolve -->
<BuildDependsOn Condition="$(RestorePackages) == 'true'">
    RestorePackages;
    UpdatePackages;
    $(BuildDependsOn);
</BuildDependsOn>


问:
How to assign variable "name" attribute to <input> element in html
Below is the image in which I am trying to make user interface. Here, I am creating this using loop in JSP.

Now, I want to give the name of every input element a unique value, so that they can be distinguished. That's why I want to give them variable name attribute which I can set and value in JSP using that name.

I want to know if JavaScript can be able to do this or not. If not, then which language I can choose?

Code I am using in JSP are following. Here, in resultSet variable which is type of ResultSet, I am getting the data stored in database and showing it on screen.

```<code> <% while (resultSet.next()) { %> <%= resultSet.getString("ExamID")%></td>
    <input type="text" name="marks" placeholder="Marks" size="10" />
 <% } %> <input type="submit" name="enter" value="submit" />
</code>```

答:
this is the angularjs equivalent
http://jsfiddle.net/f6mma2jz/

html:

```<code><form ng-app="myApp" ng-controller='ControllerA'>
    <table>
    <tr>
    <td>Exam Id</td>
    <td>Obtained Mark</td>
    </tr>
    <tr ng-repeat="result in resultSet">
    <td>{{result.id}}</td>
    <td><input type="text" name="enter" placeholder="Marks" ng-model="result.mark"/></td>
    </tr>
    </table>
    <input type="submit" name="enter" value="submit" />
   Model::{{resultSet}}
</form>
</code>```

js:

```<code>var app = angular.module('myApp', [])
.controller('ControllerA', function($scope) {

   $scope.resultSet = [{id:1401001},{id:1401002},{id:1401003},{id:1401004}]
});
</code>```

Body:
Below is the image in which I am trying to make user interface. Here, I am creating this using loop in JSP.

Now, I want to give the name of every input element a unique value, so that they can be distinguished. That's why I want to give them variable name attribute which I can set and value in JSP using that name.

I want to know if JavaScript can be able to do this or not. If not, then which language I can choose?

Code I am using in JSP are following. Here, in resultSet variable which is type of ResultSet, I am getting the data stored in database and showing it on screen.

 <% while (resultSet.next()) { %> <%= resultSet.getString("ExamID")%>
    <input type="text" name="marks" placeholder="Marks" size="10" />
 <% } %> <input type="submit" name="enter" value="submit" />

Body:
this is the angularjs equivalent
http://jsfiddle.net/f6mma2jz/

html:

<form ng-app="myApp" ng-controller='ControllerA'>
    <table>
    <tr>
    <td>Exam Id</td>
    <td>Obtained Mark</td>
    </tr>
    <tr ng-repeat="result in resultSet">
    <td>{{result.id}}</td>
    <td><input type="text" name="enter" placeholder="Marks" ng-model="result.mark"/></td>
    </tr>
    </table>
    <input type="submit" name="enter" value="submit" />
   Model::{{resultSet}}
</form>

js:

var app = angular.module('myApp', [])
.controller('ControllerA', function($scope) {

   $scope.resultSet = [{id:1401001},{id:1401002},{id:1401003},{id:1401004}]
});


问:
C# can't add MySQL dataSource
I have Visual Studio Ultimate 2013. I installed the latest connector from MySQL official download page. After installing the connector, I installed the MySQL Visual Studio integration, using their installer.
After doing this, I created a new project, then I added a dataSet to the project. I added a reference to MySQL.Data.dll to it.
Then I went to Server Explorer, accessed my connection to the MySQL server that I want to connect to, and I dragged a table from there into the dataset page. That resulted in an error that says:

Mouse drag operation failed.

Cannot obtain provider factory for data
provider named 'MySql.Data.MySQLClient'

What is going on? Why cant I access mysql from Visual Studio? What provider factory?
I am using the ULTIMATE version of VS. What super-ultimate version should I use in order to be able to use MySQL?

Same thing happens if I go to the Data Sources tab and try to add my mysql database there

答:
You have to add a datasource by using the datasource wizard in order to drag and drop e.g. a table on a form.

In order to get the wizard work you should use

Connector/Net 6.9.8 and MySQL for Visual Studio 1.2.6.

Other (newer) combinations will provide you with numerous errors

Title: C# can't add MySQL dataSource

ContentLicense: CC BY-SA 4.0


问:
Starting h2o in hadoop cluster with specific connection node url
Is there a way to start an h2o instance interface on a specific node of a cluster? For example...

When using the command:

```<code>$ hadoop jar h2odriver.jar -nodes 4 -mapperXmx 6g -output hdfsOutputDir
</code>```

from say in the h2o install directory, in say node 172.18.4.62, I get the (abridged) output:

```<code>....
H2O node 172.18.4.65:54321 reports H2O cluster size 1
H2O node 172.18.4.66:54321 reports H2O cluster size 1
H2O node 172.18.4.67:54321 reports H2O cluster size 1
H2O node 172.18.4.63:54321 reports H2O cluster size 1
H2O node 172.18.4.63:54321 reports H2O cluster size 4
H2O node 172.18.4.66:54321 reports H2O cluster size 4
H2O node 172.18.4.67:54321 reports H2O cluster size 4
H2O node 172.18.4.65:54321 reports H2O cluster size 4
H2O cluster (4 nodes) is up
(Note: Use the -disown option to exit the driver after cluster formation)

Open H2O Flow in your web browser: http://172.18.4.65:54321

(Press Ctrl-C to kill the cluster)
Blocking until the H2O cluster shuts down...
</code>```

And from a python script that wants to connect to the h2o instance, I would do something like:

```<code>h2o.init(ip="172.18.4.65")
</code>```

to connect to the h2o instance. However, it would be better to be able to control which address the h2o instance connection sits at.

Is there a way to do this? Is this question confused/wrong-headed? My overall goal is to have the python script run periodically, start an h2o cluster, do stuff on that cluster then shut the cluster down (not being able to know the address to use to connect to the cluster means the script would never be sure which address to connect to). Any advice would be appreciated. Thanks.

答:
When you start H2O cluster on Hadoop as below:

```<code>$ hadoop jar h2odriver.jar -nodes 3 -mapperXmx 10g -output /user/test
</code>```

You will get an output as below just after the command is executed:

```<code>Determining driver host interface for mapper->driver callback...
    [Possible callback IP address: x.x.x.217]
    [Possible callback IP address: 127.0.0.1]
Using mapper->driver callback IP address and port: x.x.x.217:39562

(You can override these with -driverif and -driverport/-driverportrange.)
</code>```

As you can see the callback IP address is selected by the hadoop runtime. So in most of the cases the IP address and the port is select by the Hadoop run time to find best available,

You can also see the option of using -driverif x.x.x.x -driverport NNNNN along with hadoop command however I am not sure if this is really the good option. I haven't tested it besides the node ip which I am launching the cluster but it does work from the IP where the command it launched.

Based on my experience, the most popular way to start H2O cluster on Hadoop is to let the Hadoop decide the cluster, they just need to parse the output of the link as below:

```<code>Open H2O Flow in your web browser: x.x.x.x:54321
</code>```

Parse the above line to get the IP address/port of the driver to connect from R/Python API.

Body:
Is there a way to start an h2o instance interface on a specific node of a cluster? For example...

When using the command:

$ hadoop jar h2odriver.jar -nodes 4 -mapperXmx 6g -output hdfsOutputDir

from say in the h2o install directory, in say node 172.18.4.62, I get the (abridged) output:

....
H2O node 172.18.4.65:54321 reports H2O cluster size 1
H2O node 172.18.4.66:54321 reports H2O cluster size 1
H2O node 172.18.4.67:54321 reports H2O cluster size 1
H2O node 172.18.4.63:54321 reports H2O cluster size 1
H2O node 172.18.4.63:54321 reports H2O cluster size 4
H2O node 172.18.4.66:54321 reports H2O cluster size 4
H2O node 172.18.4.67:54321 reports H2O cluster size 4
H2O node 172.18.4.65:54321 reports H2O cluster size 4
H2O cluster (4 nodes) is up
(Note: Use the -disown option to exit the driver after cluster formation)

Open H2O Flow in your web browser: http://172.18.4.65:54321

(Press Ctrl-C to kill the cluster)
Blocking until the H2O cluster shuts down...

And from a python script that wants to connect to the h2o instance, I would do something like:

h2o.init(ip="172.18.4.65")

to connect to the h2o instance. However, it would be better to be able to control which address the h2o instance connection sits at.

Is there a way to do this? Is this question confused/wrong-headed? My overall goal is to have the python script run periodically, start an h2o cluster, do stuff on that cluster then shut the cluster down (not being able to know the address to use to connect to the cluster means the script would never be sure which address to connect to). Any advice would be appreciated. Thanks.

Body:
When you start H2O cluster on Hadoop as below:

$ hadoop jar h2odriver.jar -nodes 3 -mapperXmx 10g -output /user/test

You will get an output as below just after the command is executed:

Determining driver host interface for mapper->driver callback...
    [Possible callback IP address: x.x.x.217]
    [Possible callback IP address: 127.0.0.1]
Using mapper->driver callback IP address and port: x.x.x.217:39562

(You can override these with -driverif and -driverport/-driverportrange.)

As you can see the callback IP address is selected by the hadoop runtime. So in most of the cases the IP address and the port is select by the Hadoop run time to find best available,

You can also see the option of using -driverif x.x.x.x -driverport NNNNN along with hadoop command however I am not sure if this is really the good option. I haven't tested it besides the node ip which I am launching the cluster but it does work from the IP where the command it launched.

Based on my experience, the most popular way to start H2O cluster on Hadoop is to let the Hadoop decide the cluster, they just need to parse the output of the link as below:

Open H2O Flow in your web browser: x.x.x.x:54321

Parse the above line to get the IP address/port of the driver to connect from R/Python API.


问:
One hidden input vs 1000 hidden input?
I have approximately 1000 hidden inputs to send to laravel. I think I have 2 options to send those inputs.

Option 1 :

I make 1000 hidden input and send them to laravel.

```<code><input type="hidden" name="id[1]" value="some stuff">
<input type="hidden" name="id[1]" value="some stuff">
..
<input type="hidden" name="id[100]" value="some stuff">
</code>```

Option 2 :

I make only 1 hidden input as a JSON object which contains all other hidden inputs .

```<code><input type="hidden name="value" value="A_JSON_OBJECT">
</code>```

By the way I may send the form with Ajax.
My question is which one can be faster?

答:
I mean you could use the array notation [] in the name of all the fields so you will receive an array in the server-side, e.g :

```<code>//Same name for all the fields
<input type="hidden" name="id[]" value="some stuff">
</code>```

Then send the data to your server-side script using ajax request like :

```<code>$.post('file.php', $('input[name="id[]"]').serialize(), function(response){
    //Server response
});
</code>```

In your file.php you recieve the data in $_POST['id']; as array.

Title: One hidden input vs 1000 hidden input?

Body:
I have approximately 1000 hidden inputs to send to laravel. I think I have 2 options to send those inputs.

Option 1 :

I make 1000 hidden input and send them to laravel.

<input type="hidden" name="id[1]" value="some stuff">
<input type="hidden" name="id[1]" value="some stuff">
..
<input type="hidden" name="id[100]" value="some stuff">

Option 2 :

I make only 1 hidden input as a JSON object which contains all other hidden inputs .

<input type="hidden name="value" value="A_JSON_OBJECT">

By the way I may send the form with Ajax.
My question is which one can be faster?

Body:
I mean you could use the array notation [] in the name of all the fields so you will receive an array in the server-side, e.g :

//Same name for all the fields
<input type="hidden" name="id[]" value="some stuff">

Then send the data to your server-side script using ajax request like :

$.post('file.php', $('input[name="id[]"]').serialize(), function(response){
    //Server response
});

In your file.php you recieve the data in $_POST['id']; as array.


问:
MySQL creating derived table from union
Why won't this query run in MySQL? I'm trying to understand this so I can make a larger query with more complicated selects to fill in records, but I've torn it all down to the absolute basic building blocks and it still won't run.

```<code>SELECT *
FROM
(
   (SELECT 'January' as col1 ) as t0
    UNION
   (SELECT 'December'  as col1 ) as t1
) as derivedTable
</code>```

The error is #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 't1

I'm expecting it to look like:

```<code>col1
January
December
</code>```

答:
There's no need for all the subqueries. You can just write:

```<code>(
    SELECT 'January' AS col1
    UNION ALL
    SELECT 'December' AS col1
) AS derivedTable
</code>```

I assume this is being used as a subquery in a larger query (e.g. to do a LEFT JOIN to get results for every month).

Title: MySQL creating derived table from union

Body:
Why won't this query run in MySQL? I'm trying to understand this so I can make a larger query with more complicated selects to fill in records, but I've torn it all down to the absolute basic building blocks and it still won't run.

SELECT *
FROM
(
   (SELECT 'January' as col1 ) as t0
    UNION
   (SELECT 'December'  as col1 ) as t1
) as derivedTable

The error is #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 't1

I'm expecting it to look like:

col1
January
December

Body:
There's no need for all the subqueries. You can just write:

(
    SELECT 'January' AS col1
    UNION ALL
    SELECT 'December' AS col1
) AS derivedTable

I assume this is being used as a subquery in a larger query (e.g. to do a LEFT JOIN to get results for every month).


问:
Angular 4 , How Convert Number to Word in English and Arabic

I'm trying when user enter amount number display the number in word English and arabic

there are plugin support this in English and Arabic ?

For Example :
1980 :One thousand, nine hundred eighty.

1980 :الف وتسعمائة وثمانون .

答:
Alright, here you go

This should be self explanatory. It gets the current date, formats it. You can toggle between English and Arabic.

Note that I do not speak Arabic, but the ar locale is used to provided the formatting. Therefore, I included Chinese as well for good measure since I know a little.

app.component.html

```<code><h1>The current date and time using locale: {{locale}}</h1>
<p>Now: {{now | date : 'full' : '' : locale}}</p>
<button (click)="toggleLocale()">Toggle Locale</button>
</code>```

app.component.ts

```<code>import {Component, Inject} from '@angular/core';

@Component({
  selector: 'app',
  templateUrl: './app.component.html'
})
export default class {
  constructor(@Inject('registered-locales') readonly locales: string[]) {}

  get now() {return new Date();}

  val = 19.8;

  locale = this.locales[0];

  toggleLocale() {
    // this is just a cycler. There are better ways to right this code
    const predicate = this.locale && this.locale.match(/zh/)
      ? l => l.match('ar')
      : this.locale && this.locale.match(/en/)
      ? l => l.match('zh')
      : l => l.match('en');

    this.locale = this.locales.find(predicate);
  }
}
</code>```

app.module.ts

```<code>import arabic from '@angular/common/locales/ar';
import chinese from '@angular/common/locales/zh';
import english from '@angular/common/locales/en';
import {registerLocaleData} from '@angular/common';
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import AppComponent from './app.component';

registerLocaleData(arabic, 'ar');
registerLocaleData(chinese, 'zh');
registerLocaleData(english, 'en');

@NgModule({
  providers: [
    {provide: 'registered-locales', multi: true, useValue: 'ar'},
    {provide: 'registered-locales', multi: true, useValue: 'zh'},
    {provide: 'registered-locales', multi: true, useValue: 'en'}
  ],
  imports: [BrowserModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
}) export default class { }
</code>```

And just so you cannot complain about type errors or anything like that, here is

main.ts

```<code>import 'core-js';
import 'zone.js';
import {NgModuleRef} from '@angular/core';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';

import AppModule from './app/app.module';

const platform = platformBrowserDynamic();

(async function () {
  try {
    const ref = await platform.bootstrapModule(AppModule);
    const {ngRef} = window;
    if (ngRef) {
      ngRef.destroy();
    }
    window.ngRef = ref;
  }
  catch (e) {
    console.error(e);
  }
}());

declare global {
  interface Window {
    ngRef: NgModuleRef<AppModule>;
  }
}
</code>```

Here is a live, editable example of the very same code running

Body:
Alright, here you go

This should be self explanatory. It gets the current date, formats it. You can toggle between English and Arabic.

Note that I do not speak Arabic, but the ar locale is used to provided the formatting. Therefore, I included Chinese as well for good measure since I know a little.

app.component.html

<h1>The current date and time using locale: {{locale}}</h1>
<p>Now: {{now | date : 'full' : '' : locale}}</p>
<button (click)="toggleLocale()">Toggle Locale</button>

app.component.ts

import {Component, Inject} from '@angular/core';

@Component({
  selector: 'app',
  templateUrl: './app.component.html'
})
export default class {
  constructor(@Inject('registered-locales') readonly locales: string[]) {}

  get now() {return new Date();}

  val = 19.8;

  locale = this.locales[0];

  toggleLocale() {
    // this is just a cycler. There are better ways to right this code
    const predicate = this.locale && this.locale.match(/zh/)
      ? l => l.match('ar')
      : this.locale && this.locale.match(/en/)
      ? l => l.match('zh')
      : l => l.match('en');

    this.locale = this.locales.find(predicate);
  }
}

app.module.ts

import arabic from '@angular/common/locales/ar';
import chinese from '@angular/common/locales/zh';
import english from '@angular/common/locales/en';
import {registerLocaleData} from '@angular/common';
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import AppComponent from './app.component';

registerLocaleData(arabic, 'ar');
registerLocaleData(chinese, 'zh');
registerLocaleData(english, 'en');

@NgModule({
  providers: [
    {provide: 'registered-locales', multi: true, useValue: 'ar'},
    {provide: 'registered-locales', multi: true, useValue: 'zh'},
    {provide: 'registered-locales', multi: true, useValue: 'en'}
  ],
  imports: [BrowserModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
}) export default class { }

And just so you cannot complain about type errors or anything like that, here is

main.ts

import 'core-js';
import 'zone.js';
import {NgModuleRef} from '@angular/core';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';

import AppModule from './app/app.module';

const platform = platformBrowserDynamic();

(async function () {
  try {
    const ref = await platform.bootstrapModule(AppModule);
    const {ngRef} = window;
    if (ngRef) {
      ngRef.destroy();
    }
    window.ngRef = ref;
  }
  catch (e) {
    console.error(e);
  }
}());

declare global {
  interface Window {
    ngRef: NgModuleRef<AppModule>;
  }
}

Here is a live, editable example of the very same code running


问:
How can I convert a file received as blob in HttpResponse call to an audio file in Salesforce Apex coding?
I am actually trying to implement text-to-speech conversion in Salesforce by hitting a third-party api. When i send the request through Postman, i get back the proper response in .wav format. However, I'm not being able to handle this reponse programatically in salesforce end, as I am not able to store the response in any audio object.

Any assistance would be greatly appreciated.

Thanks in advance.
Abhishek.

答:
This is supported by IBM's Watson Salesforce SDK, available here

The functional tests for Watson's text-to-speech services can be found here refer to the method

testSynthesize(String username, String password, String customizationId)

The audio file returned as part of the response could be saved as an attachment in Salesforce by simply creating it from the IBMWatsonFile like on this example,

```<code>IBMWatsonFile resp = textToSpeech.synthesize(options);
Attachment attachment = new Attachment();
attachment.Body = resp.body();
attachment.Name = resp.name();
attachment.ParentId = '<your salesforce parent id>';
insert attachment;
</code>```

This code uses basically the method getBodyAsBlob() available from the HttpResponse class

before using this approach, please consider the governor limits enforced by Salesforce on any APEX callout, refer to the Maximum size of callout request or response documented here

Body:
This is supported by IBM's Watson Salesforce SDK, available here

The functional tests for Watson's text-to-speech services can be found here refer to the method

testSynthesize(String username, String password, String customizationId)

The audio file returned as part of the response could be saved as an attachment in Salesforce by simply creating it from the IBMWatsonFile like on this example,

IBMWatsonFile resp = textToSpeech.synthesize(options);
Attachment attachment = new Attachment();
attachment.Body = resp.body();
attachment.Name = resp.name();
attachment.ParentId = '<your salesforce parent id>';
insert attachment;

This code uses basically the method getBodyAsBlob() available from the HttpResponse class

before using this approach, please consider the governor limits enforced by Salesforce on any APEX callout, refer to the Maximum size of callout request or response documented here


问:
Getting a null response when calling a php site function from java in android
I'm trying to call a php function on a site that I have from an android application.

I'm using this to get my response: https://github.com/koush/ion

Here is my php code which is located at : Link
It's used to connect to a database i have on that site.
The php file just returns all the entries in the database as HTML text shown under the php code (Not sure if this is the proper way to get data from a database).
The Database entries get their own tags so I can handle them later in the app.

```<code><?php
include('dbconnect.php');
if (isset($_GET['Tabela'])) {
    DobiPodatke($_GET['Tabela']);
} else {
    ECHO '<error>Ni selekcije</error>';
}

function DobiPodatke($Tabela)
{
$sqlget = "SELECT * FROM " . $Tabela;
ZazeniQuery($Tabela, $sqlget);
}

function ZazeniQuery($Ime, $Query){
$sqldata = mysqli_query($GLOBALS['dbcon'], $Query) or die('<error>error with fetching data</error>');
    ECHO '<' . $Ime . '>';
    while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)){
        switch($Ime){
            case 'Sola':
                ECHO '<vnos><Kratka_Oznaka>' . $row['Kratka_Oznaka'] . '</Kratka_Oznaka><Ime>' . $row['Ime'] . '</Ime></vnos>';
                break;
            case 'Stroka':
                ECHO '<vnos><Ime_Stroke>' . $row['Ime_Stroke'] . '</Ime_Stroke></vnos>';
                break;
            case 'Sola_Smer':
                ECHO '<vnos><ID_Sole>' . $row['ID_Sole'] . '</ID_Sole><ID_Stroke>' . $row['ID_Stroke'] . '</ID_Stroke><Stevilo_mest>' . $row['Stevilo_mest'] . '</Stevilo_mest></vnos>';
                break;
        }
    }
    ECHO '</' . $Ime . '>';
}

?>
</code>```

HTML Response:
HTML

Now in order for this to work I need to supply the php function parameter on which table i need infromation from so I call it like this:

https://illegible-deflector.000webhostapp.com/Site3/dbtest.php?Tabela=Sola

Tabela beeing the variable I need to pass in otherwise the php does a die()

In the example above I called the php file with "?Tabela=Sola" at the end to get all table entries in the table "Sola".
While this works in the browser, it does not in my application.

Now in my android application I use the Ion library/class to get my response from a website in pure HTML code. It works with a regular website since I can get the whole HTML code from the site.

It however does not work on my php site since i get a null result.

The link variable in the following code is:

https://illegible-deflector.000webhostapp.com/Site3/dbtest.php?Tabela=Sola

Java code that connects to the website and returns the result:

```<code>private static void ParseDBFront(String link, Context context){
    Ion.with(context).load(link).setLogging("MyLogs", Log.DEBUG).asString().setCallback(new FutureCallback<String>() {
        @Override
        public void onCompleted(Exception e, String result) {
            Log.i("LOG", "LOG: " + result);
        }
    });
}
</code>```

And the response I get from the above code when running is:

I/LOG: LOG: null

All i need is for the java code to return the HTML code but I have no idea why it won't return the html code.
I'm guessing that i'm parsing my variable in the wrong way.

I appreciate any feedback or solutions to this problem.

答:
Managed to figure it out myself.
There was no problems with the code as is, the problem was the way i wrote the URL of my php file.

Original link:

private static final String DBLink = "www.illegible-deflector.000webhostapp.com/Site3/dbtest.php?Tabela=";

And how I fixed it:

private static final String DBLink = "https://illegible-deflector.000webhostapp.com/Site3/dbtest.php?Tabela=";

That "www." / "https://" difference is all that caused my program to return a null response for some reason.

I don't know why but the problem is gone.

Body:
I'm trying to call a php function on a site that I have from an android application.

I'm using this to get my response: https://github.com/koush/ion

Here is my php code which is located at : Link
It's used to connect to a database i have on that site.
The php file just returns all the entries in the database as HTML text shown under the php code (Not sure if this is the proper way to get data from a database).
The Database entries get their own tags so I can handle them later in the app.

<?php
include('dbconnect.php');
if (isset($_GET['Tabela'])) {
    DobiPodatke($_GET['Tabela']);
} else {
    ECHO '<error>Ni selekcije</error>';
}

function DobiPodatke($Tabela)
{
$sqlget = "SELECT * FROM " . $Tabela;
ZazeniQuery($Tabela, $sqlget);
}

function ZazeniQuery($Ime, $Query){
$sqldata = mysqli_query($GLOBALS['dbcon'], $Query) or die('<error>error with fetching data</error>');
    ECHO '<' . $Ime . '>';
    while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)){
        switch($Ime){
            case 'Sola':
                ECHO '<vnos><Kratka_Oznaka>' . $row['Kratka_Oznaka'] . '</Kratka_Oznaka><Ime>' . $row['Ime'] . '</Ime></vnos>';
                break;
            case 'Stroka':
                ECHO '<vnos><Ime_Stroke>' . $row['Ime_Stroke'] . '</Ime_Stroke></vnos>';
                break;
            case 'Sola_Smer':
                ECHO '<vnos><ID_Sole>' . $row['ID_Sole'] . '</ID_Sole><ID_Stroke>' . $row['ID_Stroke'] . '</ID_Stroke><Stevilo_mest>' . $row['Stevilo_mest'] . '</Stevilo_mest></vnos>';
                break;
        }
    }
    ECHO '</' . $Ime . '>';
}

?>

HTML Response:
HTML

Now in order for this to work I need to supply the php function parameter on which table i need infromation from so I call it like this:

https://illegible-deflector.000webhostapp.com/Site3/dbtest.php?Tabela=Sola

Tabela beeing the variable I need to pass in otherwise the php does a die()

In the example above I called the php file with "?Tabela=Sola" at the end to get all table entries in the table "Sola".
While this works in the browser, it does not in my application.

Now in my android application I use the Ion library/class to get my response from a website in pure HTML code. It works with a regular website since I can get the whole HTML code from the site.

It however does not work on my php site since i get a null result.

The link variable in the following code is:

https://illegible-deflector.000webhostapp.com/Site3/dbtest.php?Tabela=Sola

Java code that connects to the website and returns the result:

private static void ParseDBFront(String link, Context context){
    Ion.with(context).load(link).setLogging("MyLogs", Log.DEBUG).asString().setCallback(new FutureCallback<String>() {
        @Override
        public void onCompleted(Exception e, String result) {
            Log.i("LOG", "LOG: " + result);
        }
    });
}

And the response I get from the above code when running is:

I/LOG: LOG: null

All i need is for the java code to return the HTML code but I have no idea why it won't return the html code.
I'm guessing that i'm parsing my variable in the wrong way.

I appreciate any feedback or solutions to this problem.


问:
hyperlink model attribute
I'm trying to hyperlink a model attribute that publishes a website address.  Right now, my view shows:

```<code><%= text_item 'Website', advisor.firm.webaddr %>
</code>```

An advisor belongs to a firm and the firm has a web address.  I'm simply trying create a hyperlink in my view, so that a user can click on this attribute and get connected to the website.  Such a simple question I know, but am having trouble finding a solution. Thank you.

```<code>module TextItemHelper
  def text_item(name, *values, &block)
    label_tag = content_tag(:span, name, class: 'text-item__label')
    content = if block_given?
        label_tag + content_tag(:span, class: 'text-item__value', &block)
      else
        values.reduce label_tag do |acc, value|
          content = value.presence || 'Not available' acc + content_tag(:span, content, class: 'text-item__value')
        end
      end
    content_tag :span, class: 'text-item' do content
    end
  end
end
</code>```

答:
Try wrapping it in a link_to tag:</p>

```<code><%= text_item 'Website', raw(link_to(advisor.firm.webaddr, advisor.firm.webaddr)) %>
</code>```

Title: hyperlink model attribute

Body:
I'm trying to hyperlink a model attribute that publishes a website address.  Right now, my view shows:

<%= text_item 'Website', advisor.firm.webaddr %>

An advisor belongs to a firm and the firm has a web address.  I'm simply trying create a hyperlink in my view, so that a user can click on this attribute and get connected to the website.  Such a simple question I know, but am having trouble finding a solution. Thank you.

module TextItemHelper
  def text_item(name, *values, &block)
    label_tag = content_tag(:span, name, class: 'text-item__label')
    content = if block_given?
        label_tag + content_tag(:span, class: 'text-item__value', &block)
      else
        values.reduce label_tag do |acc, value|
          content = value.presence || 'Not available' acc + content_tag(:span, content, class: 'text-item__value')
        end
      end
    content_tag :span, class: 'text-item' do content
    end
  end
end

Body:
Try wrapping it in a link_to tag:

<%= text_item 'Website', raw(link_to(advisor.firm.webaddr, advisor.firm.webaddr)) %>


问:
How to set up an independent progress bar
I'm trying to include a progress bar during the computations in my shiny application. Description of my problem:

My computation takes a while, like 30 seconds

I'm able to evaluate in advance the exact time a computation will take

however, the computation is in one chunk, not splitable in small parts that I could use to manually increment the progress bar, think of it as a large model fitting process.

Currently there are some questions related to the problem but no satisfying answer:
here, here for instance.

Is there a way to implement an bar that progresses on top of a calculation, independently and continuously, for a fixed amount of time (or maybe insert an animation of the bar in a pop-up that mimics the bar?)

Thanks

Edit: I tried to mimic a progress bar with an animated sliderInput, but I couldn't find how programmatically trigger the animation...

答:
Thanks to the answer of @GyD, I now propose an improved solution (that has something of a hack I admit).
The long computation is simulated here by a sys.sleep of the desired duration. You see that there is still slider movement during the 'sleep'. I put the animated slider into a RenderUI so we can control the speed:

```<code>library(shiny); library(shinyjs); library(shinyWidgets)
jscode <- "
shinyjs.play = function() {
$('.slider-animate-button').trigger('click');
}
"
ui <- fluidPage(
     tags$head(tags$style(HTML('.irs-from, .irs-to, .irs-min, .irs-max, .irs-grid-text, .irs-grid-pol, .irs-slider {visibility:hidden !important;}'))),
     useShinyjs(), extendShinyjs(text = jscode),
     numericInput("seconds", "how many seconds your calculation will last?", value=6),
     uiOutput("UI"),
     actionButton("go", "Compute"))
server <- function(input, output,session) {
     disable("slider")
     observeEvent(input$go, priority=10, {
          js$play()
          Sys.sleep(input$seconds) # simulate computation
          showNotification("Computation finished!", type="error")})
     output$UI = renderUI({
          sliderInput("slider", label = "", width = '300px',min = 0,max = 100,value = 0,step = 1,
                      post="% done",
                      animate = animationOptions(
                           interval = (as.numeric(input$seconds)*8),
                           playButton = "",
                           pauseButton = ""))})}
shinyApp(ui, server)
</code>```

The slider really looks like a bar, doesn't it?

Body:
Thanks to the answer of @GyD, I now propose an improved solution (that has something of a hack I admit).
The long computation is simulated here by a sys.sleep of the desired duration. You see that there is still slider movement during the 'sleep'. I put the animated slider into a RenderUI so we can control the speed:

library(shiny); library(shinyjs); library(shinyWidgets)
jscode <- "
shinyjs.play = function() {
$('.slider-animate-button').trigger('click');
}
"
ui <- fluidPage(
     tags$head(tags$style(HTML('.irs-from, .irs-to, .irs-min, .irs-max, .irs-grid-text, .irs-grid-pol, .irs-slider {visibility:hidden !important;}'))),
     useShinyjs(), extendShinyjs(text = jscode),
     numericInput("seconds", "how many seconds your calculation will last?", value=6),
     uiOutput("UI"),
     actionButton("go", "Compute"))
server <- function(input, output,session) {
     disable("slider")
     observeEvent(input$go, priority=10, {
          js$play()
          Sys.sleep(input$seconds) # simulate computation
          showNotification("Computation finished!", type="error")})
     output$UI = renderUI({
          sliderInput("slider", label = "", width = '300px',min = 0,max = 100,value = 0,step = 1,
                      post="% done",
                      animate = animationOptions(
                           interval = (as.numeric(input$seconds)*8),
                           playButton = "",
                           pauseButton = ""))})}
shinyApp(ui, server)

The slider really looks like a bar, doesn't it?


问:
How to remove fieldset border only but not the border of elements inside the fieldset?
Example below

I have a form with a fieldset and a button.  Both button and fieldset have borders around them.  I want the border gone only for the fieldset.  How?

(The CSS in my example removes both borders - for fieldset and for button when I want button to remain untoched)

#select_spec_form #submit_button {
  border: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="select_spec_form">
  <fieldset id="submit_button">
    <input name="submit[submit]" id="submit_button" value="View" type="submit">
  </fieldset>
</form></code>```

答:
Simply change the selector to only select the fieldset #select_spec_form fieldset. Also don't use same ID with two different elements.

/* Remove the ID from selector if you want to select all the fieldset in the same page and container */

#select_spec_form fieldset#another_ID {
  border: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="select_spec_form">
  <fieldset id="another_ID">
    <input name="submit[submit]" id="submit_button" value="View" type="submit">
  </fieldset>
</form></code>```

Body:
Example below

I have a form with a fieldset and a button.  Both button and fieldset have borders around them.  I want the border gone only for the fieldset.  How?

(The CSS in my example removes both borders - for fieldset and for button when I want button to remain untoched)

#select_spec_form #submit_button {
  border: 0;
}

<form id="select_spec_form">
  <fieldset id="submit_button">
    <input name="submit[submit]" id="submit_button" value="View" type="submit">
  </fieldset>
</form>

Body:
Simply change the selector to only select the fieldset #select_spec_form fieldset. Also don't use same ID with two different elements.

/* Remove the ID from selector if you want to select all the fieldset in the same page and container */

#select_spec_form fieldset#another_ID {
  border: 0;
}

<form id="select_spec_form">
  <fieldset id="another_ID">
    <input name="submit[submit]" id="submit_button" value="View" type="submit">
  </fieldset>
</form>


问:
Android Studio - Scrollview moves outside the screen on keyboard open
I want to make a chat screen which has an EditText and a Button at the bottom (wrapped in a LinearLayout), and a ScrollView for the messages at the top. The problem is that when the user taps the EditText and the keyboard opens, the ScrollView will go off screen as a result of moving up. I would like to move the Layout (with the EditBox and the Button) above the keyboard and the ScrollView to be resized to fit the screen. The problem is shown on the pictures below:

As you can see, the line that writes "Chat" (left image) has disappeared in the right image.

I use this XML code:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="15sp"
    android:orientation="vertical"
    android:background="#ccdcf7"
    tools:context="com.orionz.sockettest.ChatActivity">

    <ScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="15"
        android:isScrollContainer="false">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/chatBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:text="Chat\n"
                android:textColor="#000000"
                android:textIsSelectable="true"
                android:textSize="22dp" />
        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center|bottom"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/msgInput"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.8"
            android:ems="10"
            android:hint="Message..."
            android:inputType="text" />

        <Button
            android:id="@+id/sendButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.2"
            android:background="@drawable/mybutton"
            android:padding="5sp"
            android:text="Send"
            android:textColor="#ffffff"
            android:textSize="20sp" />

    </LinearLayout>

</LinearLayout>
</code>```

I have seen many answers such as setting the android:windowSoftInputMode but none has worked. I use Android Studio. Any help would be appreciated.

答:
Try to replace the ScrollView with a ListView like this :

```<code><ListView
    android:id="@+id/list_view"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1">
</ListView>
</code>```

store all the messages in an ArrayList, and set an adapter to the ListView you made :

```<code>ListView listView=(ListView) findViewById(R.id.list_view);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,ArrayList);
listView.setAdapter(adapter);
</code>```

Finally, add a listenner on your Button writing these lines :

```<code>EditText editText= (EditText) findViewById(R.id.msgInput);
ArrayList.add(editText.getText().toString());
adapter.notifyDataSetChanged();
</code>```

Body:
I want to make a chat screen which has an EditText and a Button at the bottom (wrapped in a LinearLayout), and a ScrollView for the messages at the top. The problem is that when the user taps the EditText and the keyboard opens, the ScrollView will go off screen as a result of moving up. I would like to move the Layout (with the EditBox and the Button) above the keyboard and the ScrollView to be resized to fit the screen. The problem is shown on the pictures below:

As you can see, the line that writes "Chat" (left image) has disappeared in the right image.

I use this XML code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="15sp"
    android:orientation="vertical"
    android:background="#ccdcf7"
    tools:context="com.orionz.sockettest.ChatActivity">

    <ScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="15"
        android:isScrollContainer="false">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/chatBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:text="Chat\n"
                android:textColor="#000000"
                android:textIsSelectable="true"
                android:textSize="22dp" />
        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center|bottom"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/msgInput"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.8"
            android:ems="10"
            android:hint="Message..."
            android:inputType="text" />

        <Button
            android:id="@+id/sendButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.2"
            android:background="@drawable/mybutton"
            android:padding="5sp"
            android:text="Send"
            android:textColor="#ffffff"
            android:textSize="20sp" />

    </LinearLayout>

</LinearLayout>

I have seen many answers such as setting the android:windowSoftInputMode but none has worked. I use Android Studio. Any help would be appreciated.

Body:
Try to replace the ScrollView with a ListView like this :

<ListView
    android:id="@+id/list_view"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1">
</ListView>

store all the messages in an ArrayList, and set an adapter to the ListView you made :

ListView listView=(ListView) findViewById(R.id.list_view);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,ArrayList);
listView.setAdapter(adapter);

Finally, add a listenner on your Button writing these lines :

EditText editText= (EditText) findViewById(R.id.msgInput);
ArrayList.add(editText.getText().toString());
adapter.notifyDataSetChanged();


问:
Qt5 Target conditionals not found
I just updated to the latest version of command line tools in OS X Mavericks and now when compiling my (previously-working) code it throws the following error

```<code>> clang: warning: no such sysroot directory:
> '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk'
> In file included from ../QtOpenGL/Main.cpp:1: In file included from
> ../../Qt/5.3/clang_64/lib/QtWidgets.framework/Versions/5/Headers/QApplication:1:
> In file included from
> ../../Qt/5.3/clang_64/lib/QtWidgets.framework/Versions/5/Headers/qapplication.h:45:
> In file included from
> /Users/BB/Qt/5.3/clang_64/lib/QtCore.framework/Headers/qcoreapplication.h:45:
> In file included from
> /Users/BB/Qt/5.3/clang_64/lib/QtCore.framework/Headers/qglobal.h:76:
> /Users/BB/Qt/5.3/clang_64/lib/QtCore.framework/Headers/qsystemdetection.h:196:12:
> fatal error: 'TargetConditionals.h' file not found
> #  include <TargetConditionals.h>
>            ^ 1 error generated. make: *** [Main.o] Error 1 20:29:52: Le processus "/usr/bin/make" s'est terminé avec le code 2. Erreur lors
> de la compilation/déploiement du projet QtOpenGL (kit : Desktop Qt
> 5.3.0 clang 64bit) When executing step "Make"
</code>```

Does anyone knows that if changing this line

```<code>/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk
</code>```

from sdk 8 to 9 would work? If so, where in the parameters of Qt5 can I change this?

答:
I am using Qt5.8 on macosx10.13, I solved this problem by editing the file  /usr/local/Cellar/qt-legacy-formula/5.8.0_1/mkspecs/qdevice.pri by adding this line:</p>

```<code>!host_build:QMAKE_MAC_SDK = macosx10.13
</code>```

Title: Qt5 Target conditionals not found

Body:
I just updated to the latest version of command line tools in OS X Mavericks and now when compiling my (previously-working) code it throws the following error

> clang: warning: no such sysroot directory:
> '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk'
> In file included from ../QtOpenGL/Main.cpp:1: In file included from
> ../../Qt/5.3/clang_64/lib/QtWidgets.framework/Versions/5/Headers/QApplication:1:
> In file included from
> ../../Qt/5.3/clang_64/lib/QtWidgets.framework/Versions/5/Headers/qapplication.h:45:
> In file included from
> /Users/BB/Qt/5.3/clang_64/lib/QtCore.framework/Headers/qcoreapplication.h:45:
> In file included from
> /Users/BB/Qt/5.3/clang_64/lib/QtCore.framework/Headers/qglobal.h:76:
> /Users/BB/Qt/5.3/clang_64/lib/QtCore.framework/Headers/qsystemdetection.h:196:12:
> fatal error: 'TargetConditionals.h' file not found
> #  include <TargetConditionals.h>
>            ^ 1 error generated. make: *** [Main.o] Error 1 20:29:52: Le processus "/usr/bin/make" s'est terminé avec le code 2. Erreur lors
> de la compilation/déploiement du projet QtOpenGL (kit : Desktop Qt
> 5.3.0 clang 64bit) When executing step "Make"

Does anyone knows that if changing this line

/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk

from sdk 8 to 9 would work? If so, where in the parameters of Qt5 can I change this?

Body:
I am using Qt5.8 on macosx10.13, I solved this problem by editing the file  /usr/local/Cellar/qt-legacy-formula/5.8.0_1/mkspecs/qdevice.pri by adding this line:

!host_build:QMAKE_MAC_SDK = macosx10.13


问:
Best way to get the "last monday of may"
Which is the best way to get the last monday of may, using javascript? I know I can get the last day of the month, and them subtract the difference of the days to the day I want. But, there is a short, more elegant and efficient way to do it?

Thanks

答:
Using javascript without momentjs.

/**
 * @param {number} month - From 0 to 11.
 * @param {number} year
 */
function lastMondayOfMonth(month, year) {
    var WEEK_DAYS = 7;
    var DAY_OF_WEEK = 1; // 1 for monday
    var day;
    var lastDateOfMonth = new Date(year, (month + 1), 0);
    var lastDay = lastDateOfMonth.getDate();
    var lastWeekDay = lastDateOfMonth.getDay();

    if (lastWeekDay === DAY_OF_WEEK) {
        day = lastDay;
    } else if (lastWeekDay < DAY_OF_WEEK) {
        day = lastDay - (WEEK_DAYS - DAY_OF_WEEK);
    } else {
        day = lastDay - (lastWeekDay) + DAY_OF_WEEK;
    }

    return day;
}
```


问:
Is there a function which returns all possible combinations of completions for given set of tokens?
Is there a python function which returns all possible combinations of completions for given set of tokens:

```<code>tokens = ["Afoo","fooB","Abar","Bbar","barA","barBX","barBY"]

complete(tokens,"foo","barB")
</code>```

should return:

```<code>[["Afoo","barBX"],["Afoo","barBY"],["fooB","barBX"],["fooB","barBY"]]
</code>```

答:
There is no function like that as far as I know, but this is a simple thing to do using loops:

```<code>def complete(tokens, foo, bar):
    return [(i, j) for i in tokens if foo in i for j in tokens if bar in j]
</code>```

Definitely not super efficient though! You can use generators to do the same thing:

```<code>def complete(tokens, foo, bar):
    return ((i, j) for i in tokens if foo in i for j in tokens if bar in j)
</code>```

Body:
Is there a python function which returns all possible combinations of completions for given set of tokens:

tokens = ["Afoo","fooB","Abar","Bbar","barA","barBX","barBY"]

complete(tokens,"foo","barB")

should return:

[["Afoo","barBX"],["Afoo","barBY"],["fooB","barBX"],["fooB","barBY"]]

Body:
There is no function like that as far as I know, but this is a simple thing to do using loops:

def complete(tokens, foo, bar):
    return [(i, j) for i in tokens if foo in i for j in tokens if bar in j]

Definitely not super efficient though! You can use generators to do the same thing:

def complete(tokens, foo, bar):
    return ((i, j) for i in tokens if foo in i for j in tokens if bar in j)


问:
What is the best Way to achieve Pagination with filtering in spring data jpa
I am trying to implement pagination as well filter in server side.

These two ways i went through to implement. i am using spring data jpa.

1.Use the JpaSpecificationExecutor and write a Specification

2.Use the QueryDslPredicateExecutor and use QueryDSL to write a predicate.

i started with JpaSpecificationExecutor  but found it complex.

Here is my Specification Class:

public class TransmissionSearchSpecification  implements Specification  {

```<code> private TransmissionSearch criteria;

 public TransmissionSearchSpecification(TransmissionSearch ts) {
        criteria= ts;
    }

@Override
public Predicate toPredicate(Root<TransmissionView> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder builder) {
    Path<String> thirdParty = root.get(TransmissionView_.thirdPartyName);

     final List<Predicate> predicates = new ArrayList<Predicate>();
        if(criteria.getThirdPartyName() !=null) {
            predicates.add(builder.equal(thirdParty, criteria.getThirdPartyName()));
        }

        return builder.and(predicates.toArray(new Predicate[predicates.size()]));

}
</code>```

public class TransmissionController {

```<code>private final TransmissionViewService transmissionViewService;

public  TransmissionController(TransmissionViewService transmissionViewService) {
    this.transmissionViewService = transmissionViewService;

}

@RequestMapping("/transmissions/search")
@GetMapping
public ResponseEntity<Page<TransmissionView>> getTransmissions(TransmissionSearch transmissionSearch, Pageable pageable){
    Page<TransmissionView> transmissions = transmissionViewService.findTransmissions(pageable);
    if(!CollectionUtils.isEmpty(transmissions.getContent())) {
        return new ResponseEntity<>(transmissions, HttpStatus.OK);
    } else {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
}
</code>```

Is there any other way that can ease the filter and pagination .Please suggest.
Thanks in advance

答:
What is the best Way to achieve Pagination with filtering in spring data jpa?

I think to use Spring Data with QueryDsl and Web support extensions.

First you need to plug QueryDsl to you project:

<dependencies>
    //...
    <dependency>
        <groupId>com.querydsl</groupId>
        <artifactId>querydsl-jpa</artifactId>
        <version>${querydsl.version}</version>
    </dependency>

    <dependency>
        <groupId>com.querydsl</groupId>
        <artifactId>querydsl-apt</artifactId>
        <version>${querydsl.version}</version>
    </dependency>

</dependencies>
<build>
    <plugins>
        //...
        <plugin>
            <groupId>com.mysema.maven</groupId>
            <artifactId>apt-maven-plugin</artifactId>
            <version>1.1.3</version>
            <executions>
                <execution>
                    <goals>
                        <goal>process</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>target/generated-sources/annotations</outputDirectory>
                        <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
```

<p>(Don't forget then to perform maven 'compile' goal...)</p>

<p>Then create a repo with <code>QueryDslPredicateExecutor</code>, <code>QuerydslBinderCustomizer</code> and optional 'customize' method (see details bellow in 'more info'): </p>

<pre class="lang-java prettyprint-override"><code>public interface TransmissionRepo extends JpaRepository<Transmission, Long>, QueryDslPredicateExecutor<Transmission>, QuerydslBinderCustomizer<Transmission> {

  @Override
  default void customize(QuerydslBindings bindings, QTransmission transmission) {

    bindings.excluding(
        // excluding some fields from filter
        transmission.id,
        transmission.version
    );

    // implement ignore case to strings...
    bindings.bind(String.class).first((SingleValueBinding<StringPath, String>) StringExpression::containsIgnoreCase);

    // https://stackoverflow.com/a/35158320/5380322
    // 'between' implementation - if you need this...
    bindings.bind(listing.createdOn).all((path, value) -> {

      Iterator<? extends LocalDate> it = value.iterator();
      LocalDate from = it.next();
      if (value.size() >= 2) {
        LocalDate to = it.next();
        return path.between(from, to);
      } else {
        return path.eq(from);
      }
    });
  }
}
</code>```

Then if you use Spring Data REST in your project you can use your filter as well as pagination:

```<code>GET /transmissions?page=1&size=10&sort=field1,desc&field2=value2&field3=value3
</code>```

Or you can implement your custom controller, for example like this:

@GetMapping("/transmissions")
@ResponseBody
public Iterable<Transmission> findAll(@QuerydslPredicate(root = Transmission.class) Predicate predicate, Pageable pageable) {
    return TransmissionRepo.findAll(predicate, pageable);
}
```

More info according your question you can find here.

Body:
I am trying to implement pagination as well filter in server side.

These two ways i went through to implement. i am using spring data jpa.

1.Use the JpaSpecificationExecutor and write a Specification

2.Use the QueryDslPredicateExecutor and use QueryDSL to write a predicate.

i started with JpaSpecificationExecutor  but found it complex.

Here is my Specification Class:

public class TransmissionSearchSpecification  implements Specification  {

 private TransmissionSearch criteria;

 public TransmissionSearchSpecification(TransmissionSearch ts) {
        criteria= ts;
    }

@Override
public Predicate toPredicate(Root<TransmissionView> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder builder) {
    Path<String> thirdParty = root.get(TransmissionView_.thirdPartyName);

     final List<Predicate> predicates = new ArrayList<Predicate>();
        if(criteria.getThirdPartyName() !=null) {
            predicates.add(builder.equal(thirdParty, criteria.getThirdPartyName()));
        }

        return builder.and(predicates.toArray(new Predicate[predicates.size()]));

}

public class TransmissionController {

private final TransmissionViewService transmissionViewService;

public  TransmissionController(TransmissionViewService transmissionViewService) {
    this.transmissionViewService = transmissionViewService;

}

@RequestMapping("/transmissions/search")
@GetMapping
public ResponseEntity<Page<TransmissionView>> getTransmissions(TransmissionSearch transmissionSearch, Pageable pageable){
    Page<TransmissionView> transmissions = transmissionViewService.findTransmissions(pageable);
    if(!CollectionUtils.isEmpty(transmissions.getContent())) {
        return new ResponseEntity<>(transmissions, HttpStatus.OK);
    } else {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
}

Is there any other way that can ease the filter and pagination .Please suggest.
Thanks in advance

Body:
What is the best Way to achieve Pagination with filtering in spring data jpa?

I think to use Spring Data with QueryDsl and Web support extensions.

First you need to plug QueryDsl to you project:

<dependencies>
    //...
    <dependency>
        <groupId>com.querydsl</groupId>
        <artifactId>querydsl-jpa</artifactId>
        <version>${querydsl.version}</version>
    </dependency>

    <dependency>
        <groupId>com.querydsl</groupId>
        <artifactId>querydsl-apt</artifactId>
        <version>${querydsl.version}</version>
    </dependency>

</dependencies>
<build>
    <plugins>
        //...
        <plugin>
            <groupId>com.mysema.maven</groupId>
            <artifactId>apt-maven-plugin</artifactId>
            <version>1.1.3</version>
            <executions>
                <execution>
                    <goals>
                        <goal>process</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>target/generated-sources/annotations</outputDirectory>
                        <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

(Don't forget then to perform maven 'compile' goal...)

Then create a repo with QueryDslPredicateExecutor, QuerydslBinderCustomizer and optional 'customize' method (see details bellow in 'more info'):

public interface TransmissionRepo extends JpaRepository<Transmission, Long>, QueryDslPredicateExecutor<Transmission>, QuerydslBinderCustomizer<Transmission> {

  @Override
  default void customize(QuerydslBindings bindings, QTransmission transmission) {

    bindings.excluding(
        // excluding some fields from filter
        transmission.id,
        transmission.version
    );

    // implement ignore case to strings...
    bindings.bind(String.class).first((SingleValueBinding<StringPath, String>) StringExpression::containsIgnoreCase);

    // https://stackoverflow.com/a/35158320/5380322
    // 'between' implementation - if you need this...
    bindings.bind(listing.createdOn).all((path, value) -> {

      Iterator<? extends LocalDate> it = value.iterator();
      LocalDate from = it.next();
      if (value.size() >= 2) {
        LocalDate to = it.next();
        return path.between(from, to);
      } else {
        return path.eq(from);
      }
    });
  }
}

Then if you use Spring Data REST in your project you can use your filter as well as pagination:

GET /transmissions?page=1&size=10&sort=field1,desc&field2=value2&field3=value3

Or you can implement your custom controller, for example like this:

@GetMapping("/transmissions")
@ResponseBody
public Iterable<Transmission> findAll(@QuerydslPredicate(root = Transmission.class) Predicate predicate, Pageable pageable) {
    return TransmissionRepo.findAll(predicate, pageable);
}

More info according your question you can find here.


答:
Break it down into a search step and 'find combinations' step using itertools</p>

```<code>from itertools import product
def complete(tokens, searches):
    # search
    matches = [[t for t in tokens if s in t] for s in searches]

    # find all combinations https://docs.python.org/3/library/itertools.html
    return product(*matches)

tokens = ["Afoo", "fooB", "Abar", "Bbar", "barA", "barBX", "barBY"]
search = ["foo", "barB"]

combinations = list(complete(tokens, search)
</code>```

Title: Is there a function which returns all possible combinations of completions for given set of tokens?

Body:
Break it down into a search step and 'find combinations' step using itertools

from itertools import product
def complete(tokens, searches):
    # search
    matches = [[t for t in tokens if s in t] for s in searches]

    # find all combinations https://docs.python.org/3/library/itertools.html
    return product(*matches)

tokens = ["Afoo", "fooB", "Abar", "Bbar", "barA", "barBX", "barBY"]
search = ["foo", "barB"]

combinations = list(complete(tokens, search)


问:
where can I find a good wordlist
I'm looking for a file that is a wordlist and also is set up by type of word. For example something in this format

```<code>Nouns: {
    bus
    car
    deck
    elephant
    ...
}
Adjectives {
    awful
    bashful
    ...
}
Advervb {
    ...
}
</code>```

Any ideas?

答: Most flavors of linux ship with a file called dictionary. It's got all English words you might want, but they are not categorized.</p>

ContentLicense: CC BY-SA 2.5

Title: where can I find a good wordlist

Body:
I'm looking for a file that is a wordlist and also is set up by type of word. For example something in this format

Nouns: {
    bus
    car
    deck
    elephant
    ...
}
Adjectives {
    awful
    bashful
    ...
}
Advervb {
    ...
}

Any ideas?


问:
Is there a way in iOS to send a text message without presenting the message viewcontroller?
Creating an emergency application that is supposed to be able to notify a pre planned contact or contacts with one click of a button.

Does anyone have any suggestions on how to do this?

For instance an alcoholic would be able with one press of a button alert his sponsor he's having trouble. It should be automatic - not opening up imessages or mail and preparing the text and contact but just immediately doing so with a preplanned message/or email.

答: No, there is no way to send sms without showing view controller. It’s because of privacy. But you could make server, which sends sms. Make your app to send request to server for sending sms</p>


问:
Why does the output not change depending on the input from user?
So I was doing my school work and one of the programming challenges I need to do is a periodic table challenge. I didn't think it would be that hard to program, but I encountered a problem that I am not able to resolve. It is not a syntax error and I have already spend hours on the internet going through guide on whether I am using the if statements correctly, but I was unable to identify the mistake. My code reads:

```<code>lithium = ("""Name: Lithium
Atmomic mass: 6.94
Group: Alkali Metals""")

sodium = ("""Name: Sodium
Atomic mass: 22.989769 u ± 2 × 10^-8 u
Group: Alkali Metals""")

potassium = ("""Name: Potassium
Atmoic mass: 39.0983 u ± 0.0001 u
Group: Alkali Metals""")

rubidium = ("""Name: Rubidium
Atomic mass: 85.4678 u ± 0.0003 u
Group: Alkali Metals""")

cesium = ("""Name: Ceasium
Atomic mass: 132.90545 u ± 2 × 10^-7 u
Group: Alkali Metals""")

francium = ("""Name: Francium
Atomic mass: 223 u
Group: Alkali Metals""")

################################################################################################################################################################

helium = ("""Name: Helium
Atomic Mass: 4.002602 u ± 0.000002 u
Group: Noble Gasses""")

neon = ("""Name: Neon
Atomic Mass: 20.1797 u ± 0.0006 u
Group: Noble Gasses""")

argon = ("""Name: Argon
Atomic Mass: 39.948 u ± 0.001 u
Group: Noble Gasses""")

krypton = ("""Name: Krypton
Atomic Mass: 83.798 u
Group: Noble Gasses""")

xenon = ("""Name: Xenon
Atomic Mass: 131.293 u ± 0.006 u
Group: Noble Gasses""")

radon = ("""Name: Radon
Atomic Mass: 222 u
Group: Noble Gasses""")

def noble():
    print(helium)
    print(" ")
    print(neon)
    print(" ")
    print(argon)
    print(" ")
    print(krypton)
    print(" ")
    print(xenon)
    print(" ")
    print(radon)

def alkali():
    print(lithium)
    print(" ")
    print(sodium)
    print(" ")
    print(potassium)
    print(" ")
    print(rubidium)
    print(" ")
    print(cesium)
    print(" ")
    print(francium)
print ("""Please choose the element you are looking for from the list below
Lithium
Sodium
Potassium
Rubidium
Caesium
Francium
Helium
Neon
Argon
Krypton
Xenon
Radon

Alternatively you can type in the name of one of these groups to get the data for first 6 elements in the group

Noble Gasses
Alkali Metals""")

userchoice = str(input())

if userchoice == "Helium" or "helium":
    print(helium)
elif userchoice == "Neon" or "neon":
    print(neon)
elif userchoice == "Argon" or "argon":
    print(argon)
elif userchoice == "Krypton" or "krypton":
    print(krypton)
elif userchoice == "Xenon" or "xenon":
    print(xenon)
elif userchoice == "Radon" or "radon":
    print(radon)
elif userchoice == "Lithium" or "lithium":
    print(lithium)
elif userchoice == "Sodium" or "sodium":
    print(sodium)
elif userchoice == "Potassium" or "potassium" or "Potasium" or "potasium":
    print(potassium)
elif userchoice == "Rubidium" or "rubidium":
    print(rubidium)
elif userchoice == "Caesium" or "caesium" or "Cesium" or "cesium":
    print(cesium)
elif userchoice == "Francium" or "francium":
    print(francium)
elif userchoice == "Noble Gasses" or "noble gasses" or "noble" or "gasses":
    print(noble())
elif userchoice == "Alkali Metals" or "alkali metals" or "akali metals" or "Akali Metals":
    print(alkali())
else:
    print("Element not recognised")
</code>```

Now my problem is that no matter what I put in for the userchoice variable the outcome is always printing the (helium) variable, what I mean by that that even if I put in "neon" it will still print helium even though helium variable is only supposed to be printed if userchoice variable contains the word "Helium" or "helium". It is is shown in the piece of code below:

```<code>userchoice = str("Neon")

if userchoice == "Helium" or "helium":
    print(helium)
elif userchoice == "Neon" or "neon":
    print(neon)
</code>```

I wanted to know if someone would be so nice and help me to make it so that the program actually works, at this point just to clarify no matter the input, all the program outputs is the helium variable which reads:

```<code>helium = ("""Name: Helium
Atomic Mass: 4.002602 u ± 0.000002 u
Group: Noble Gasses""")
</code>```

答: The problem is caused by the lines like userchoice == "Helium" or "helium" when separated by or, python tries to read two completely different conditions. In your later case, the condition is just helium which always returns true. So change all lines to userchoice == "Helium" or userchoice == "helium". Or just use userchoice.lower().

Body:
So I was doing my school work and one of the programming challenges I need to do is a periodic table challenge. I didn't think it would be that hard to program, but I encountered a problem that I am not able to resolve. It is not a syntax error and I have already spend hours on the internet going through guide on whether I am using the if statements correctly, but I was unable to identify the mistake. My code reads:

lithium = ("""Name: Lithium
Atmomic mass: 6.94
Group: Alkali Metals""")

sodium = ("""Name: Sodium
Atomic mass: 22.989769 u ± 2 × 10^-8 u
Group: Alkali Metals""")

potassium = ("""Name: Potassium
Atmoic mass: 39.0983 u ± 0.0001 u
Group: Alkali Metals""")

rubidium = ("""Name: Rubidium
Atomic mass: 85.4678 u ± 0.0003 u
Group: Alkali Metals""")

cesium = ("""Name: Ceasium
Atomic mass: 132.90545 u ± 2 × 10^-7 u
Group: Alkali Metals""")

francium = ("""Name: Francium
Atomic mass: 223 u
Group: Alkali Metals""")

################################################################################################################################################################

helium = ("""Name: Helium
Atomic Mass: 4.002602 u ± 0.000002 u
Group: Noble Gasses""")

neon = ("""Name: Neon
Atomic Mass: 20.1797 u ± 0.0006 u
Group: Noble Gasses""")

argon = ("""Name: Argon
Atomic Mass: 39.948 u ± 0.001 u
Group: Noble Gasses""")

krypton = ("""Name: Krypton
Atomic Mass: 83.798 u
Group: Noble Gasses""")

xenon = ("""Name: Xenon
Atomic Mass: 131.293 u ± 0.006 u
Group: Noble Gasses""")

radon = ("""Name: Radon
Atomic Mass: 222 u
Group: Noble Gasses""")

def noble():
    print(helium)
    print(" ")
    print(neon)
    print(" ")
    print(argon)
    print(" ")
    print(krypton)
    print(" ")
    print(xenon)
    print(" ")
    print(radon)

def alkali():
    print(lithium)
    print(" ")
    print(sodium)
    print(" ")
    print(potassium)
    print(" ")
    print(rubidium)
    print(" ")
    print(cesium)
    print(" ")
    print(francium)
print ("""Please choose the element you are looking for from the list below
Lithium
Sodium
Potassium
Rubidium
Caesium
Francium
Helium
Neon
Argon
Krypton
Xenon
Radon

Alternatively you can type in the name of one of these groups to get the data for first 6 elements in the group

Noble Gasses
Alkali Metals""")

userchoice = str(input())

if userchoice == "Helium" or "helium":
    print(helium)
elif userchoice == "Neon" or "neon":
    print(neon)
elif userchoice == "Argon" or "argon":
    print(argon)
elif userchoice == "Krypton" or "krypton":
    print(krypton)
elif userchoice == "Xenon" or "xenon":
    print(xenon)
elif userchoice == "Radon" or "radon":
    print(radon)
elif userchoice == "Lithium" or "lithium":
    print(lithium)
elif userchoice == "Sodium" or "sodium":
    print(sodium)
elif userchoice == "Potassium" or "potassium" or "Potasium" or "potasium":
    print(potassium)
elif userchoice == "Rubidium" or "rubidium":
    print(rubidium)
elif userchoice == "Caesium" or "caesium" or "Cesium" or "cesium":
    print(cesium)
elif userchoice == "Francium" or "francium":
    print(francium)
elif userchoice == "Noble Gasses" or "noble gasses" or "noble" or "gasses":
    print(noble())
elif userchoice == "Alkali Metals" or "alkali metals" or "akali metals" or "Akali Metals":
    print(alkali())
else:
    print("Element not recognised")

Now my problem is that no matter what I put in for the userchoice variable the outcome is always printing the (helium) variable, what I mean by that that even if I put in "neon" it will still print helium even though helium variable is only supposed to be printed if userchoice variable contains the word "Helium" or "helium". It is is shown in the piece of code below:

userchoice = str("Neon")

if userchoice == "Helium" or "helium":
    print(helium)
elif userchoice == "Neon" or "neon":
    print(neon)

I wanted to know if someone would be so nice and help me to make it so that the program actually works, at this point just to clarify no matter the input, all the program outputs is the helium variable which reads:

helium = ("""Name: Helium
Atomic Mass: 4.002602 u ± 0.000002 u
Group: Noble Gasses""")


问:
hyperlink not working in a pdf in a UIWebView
I have text file (instructions.docx) with a hyperlink in it - I convert it to a pdf (instructions.pdf) and use it in a UIWebView as follows:

```<code>NSString *path = [[NSBundle mainBundle] pathForResource:@"Instructions" ofType:@"pdf"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[_webView loadRequest:request];
[_webView setScalesPageToFit:YES];
</code>```

All works fine except the hyperlink does not work - shows blue - but tapping it does nothing.
Am I going about this the wrong way - or am I missing something?

答:
I had a similar problem. Turns out the links in the PDF weren't hyperlinks. They were just typed in (even though they were blue and looked like real hyperlinks).

Resolved the issue by:

Manually adding hyperlinks

Checked Word to PDF conversion allowed for "Best for electronic distribution and accessibility"

Body:
I have text file (instructions.docx) with a hyperlink in it - I convert it to a pdf (instructions.pdf) and use it in a UIWebView as follows:

NSString *path = [[NSBundle mainBundle] pathForResource:@"Instructions" ofType:@"pdf"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[_webView loadRequest:request];
[_webView setScalesPageToFit:YES];

All works fine except the hyperlink does not work - shows blue - but tapping it does nothing.
Am I going about this the wrong way - or am I missing something?


问:
Does jQuery have a handleout for .delegate('hover')?
I am trying to use:  </p>

```<code>$('mydiv').delegate('hover', function() {
    $('seconddiv').show();
}, function() {
    //For some reason jQuery won't run this line of code
    $('seconddiv').hide();
});
</code>```

答:
EDIT: misinformation removed.

If you want to use the hover() method without delegation, working code would look like this:

```<code>$('#mydiv').hover(function() {
    $('#seconddiv').show();
}, function() {
    $('#seconddiv').hide();
});
</code>```

Second of all, delegate is to assign an event handler to a child, so you need to specify a selector first.  If you need to make sure this event handler exists for dynamically added elements, I would prefer .live() in this case with mouseenter and mouseleave.

```<code>$('#mydiv').live('mouseenter', function() {
    $('#seconddiv').show();
}).live('mouseleave', function() {
    $('#seconddiv').hide();
});
</code>```

Body:
I am trying to use:

$('mydiv').delegate('hover', function() {
    $('seconddiv').show();
}, function() {
    //For some reason jQuery won't run this line of code
    $('seconddiv').hide();
});

Body:
EDIT: misinformation removed.

If you want to use the hover() method without delegation, working code would look like this:

$('#mydiv').hover(function() {
    $('#seconddiv').show();
}, function() {
    $('#seconddiv').hide();
});

Second of all, delegate is to assign an event handler to a child, so you need to specify a selector first.  If you need to make sure this event handler exists for dynamically added elements, I would prefer .live() in this case with mouseenter and mouseleave.

$('#mydiv').live('mouseenter', function() {
    $('#seconddiv').show();
}).live('mouseleave', function() {
    $('#seconddiv').hide();
});


问:
dplyr invalid subscript type list
I have run into an error in a script I am writing that only occurs when I have dplyr running. I first encountered it when I found a function from dplyr that I wanted to use, after which I installed and ran the package. Here is an example of my error:

First I read in a table from excel that has column values I am going to use as indices in it:

```<code>library(readxl)
examplelist <- read_excel("example.xlsx")
</code>```

The contents of the file are:

```<code>1   2   3   4
1   1   4   1
2   3   2   1
4   4   1   4
</code>```

And then I build a data frame:

```<code>testdf = data.frame(1:12, 13:24, 25:36, 37:48)
</code>```

And then I have a loop that calls a function that uses the values of examplelist as indices.

```<code>testfun <- function(df, a, b, c, d){
  value1 <- df[[a]]
  value2 <- df[[b]]
  value3 <- df[[c]]
  value4 <- df[[d]]
}

for (i in 1:nrow(examplelist)){
  testfun(testdf, examplelist[i, 1], examplelist[i, 2],
      examplelist[i, 3], examplelist[i, 4])
}
</code>```

When I run this script without dplyr, everything is fine, but with dplyr it gives me the error:

```<code> Error in .subset2(x, i, exact = exact) : invalid subscript type 'list'
</code>```

Why would having dplyr cause this error, and how can I fix it?

答:
I can see this issue even without loading dplyr. It seems the culprit is use of examplelist items. if you print the value of examplelist[1, 2] then it is 1x1 dimension data.frame. But the value of a, b, c and d are expected to be a simple number. Hence if you change examplelist[i, 1] etc using as.numeric then the error will be avoided. Change call of testfun as:

```<code>testfun(testdf, as.numeric(examplelist[i, 1]), as.numeric(examplelist[i, 2]),
          as.numeric(examplelist[i, 3]), as.numeric(examplelist[i, 4]))
</code>```

Title: dplyr invalid subscript type list

Body:
I have run into an error in a script I am writing that only occurs when I have dplyr running. I first encountered it when I found a function from dplyr that I wanted to use, after which I installed and ran the package. Here is an example of my error:

First I read in a table from excel that has column values I am going to use as indices in it:

library(readxl)
examplelist <- read_excel("example.xlsx")

The contents of the file are:

1   2   3   4
1   1   4   1
2   3   2   1
4   4   1   4

And then I build a data frame:

testdf = data.frame(1:12, 13:24, 25:36, 37:48)

And then I have a loop that calls a function that uses the values of examplelist as indices.

testfun <- function(df, a, b, c, d){
  value1 <- df[[a]]
  value2 <- df[[b]]
  value3 <- df[[c]]
  value4 <- df[[d]]
}

for (i in 1:nrow(examplelist)){
  testfun(testdf, examplelist[i, 1], examplelist[i, 2],
      examplelist[i, 3], examplelist[i, 4])
}

When I run this script without dplyr, everything is fine, but with dplyr it gives me the error:

 Error in .subset2(x, i, exact = exact) : invalid subscript type 'list'

Why would having dplyr cause this error, and how can I fix it?

Body:
I can see this issue even without loading dplyr. It seems the culprit is use of examplelist items. if you print the value of examplelist[1, 2] then it is 1x1 dimension data.frame. But the value of a, b, c and d are expected to be a simple number. Hence if you change examplelist[i, 1] etc using as.numeric then the error will be avoided. Change call of testfun as:

testfun(testdf, as.numeric(examplelist[i, 1]), as.numeric(examplelist[i, 2]),
          as.numeric(examplelist[i, 3]), as.numeric(examplelist[i, 4]))


问:
Python unicode codepoint to unicode character
I'm trying to write out to a flat file some Chinese, or Russian or various non-English character-sets for testing purposes. I'm getting stuck on how to output a Unicode hex-decimal or decimal value to its corresponding character.

For example in Python, if you had a hard coded set of characters like абвгдежзийкл you would assign value = u"абвгдежзийкл" and no problem.

If however you had a single decimal or hex decimal like 1081 / 0439 stored in a variable and you wanted to print that out with it's corresponding actual character (and not just output 0x439) how would this be done? The Unicode decimal/hex value above refers to й.

答:
If you run into the error:

ValueError: unichr() arg not in range(0x10000) (narrow Python build)

While trying to convert your hex value using unichr, you can get around that error by doing something like:

```<code>>>> n = int('0001f600', 16)
>>> s = '\\U{:0>8X}'.format(n)
>>> s
'\\U0001F600'
>>> binary = s.decode('unicode-escape')
>>> print(binary)

</code>```

Body:
If you run into the error:

ValueError: unichr() arg not in range(0x10000) (narrow Python build)

While trying to convert your hex value using unichr, you can get around that error by doing something like:

>>> n = int('0001f600', 16)
>>> s = '\\U{:0>8X}'.format(n)
>>> s
'\\U0001F600'
>>> binary = s.decode('unicode-escape')
>>> print(binary)