问:
calculating the Gradient and the Hessian in R
As you know, the Gradient of a function is the following vector:

and the Hessian is the following matrix:

Now, I wonder, is there any way to calculate these in R for a user defined function at a given point?

First, I've found a package named numDeriv, which seems to have the necessary functions grad and hessian but now I can't get the correct results... Thus, here's my workflow:

Let's say that we are given the function f(x,y) = x^2 * x^3, and we need to calculate the Gradient and the Hessian at the point (x=1, y=2).

That's been said, I define this function within R:

```<code>dummy <- function(x,y) {
  rez <- (z^2)*(y^3)
  rez
}
</code>```

and then use grad the following way:

```<code>grad(func=dummy, x=1, y=2)
</code>```

which gives me result 16 -- and the problem is that this only the first value from a gradient vector, the correct version of which is

```<code>[16, 12]
</code>```

Same goes with the hessian:

```<code>hessian(func=dummy, x=1, y=2)
</code>```

which gives my 1x1 matrix with the value 16 instead of the 2x2 matrix

```<code>     [,1] [,2]
[1,]   16   24
[2,]   24   12
</code>```

So, the question is what am I doing wrong?

Thank you.

答:
The following code is an extension of the answer provided. It treats the case where you have the values of the function and not the actual function. Here the function has 1 parameter. The Grad function calculates in a single point. If you have 3 parameters then you need to provide them to x0 with c(x1,x2,x3). </p>

```<code>#i is an index, s_carvone$val contains the values of the function
dummy <- function(i)
{
  return (s_carvone$val[i])
}

#function that calculates the gradient in a specific point i
calc_grad <- function(i)
{
  return (pracma::grad(dummy, x0=i, heps=1))
}

#calculates the derivative from point 2 to 61
first_derivative = unlist(purrr::map(calc_grad, .x = c(2:61)));

plot(first_derivative);
</code>```

Body:
As you know, the Gradient of a function is the following vector:

and the Hessian is the following matrix:

Now, I wonder, is there any way to calculate these in R for a user defined function at a given point?

First, I've found a package named numDeriv, which seems to have the necessary functions grad and hessian but now I can't get the correct results... Thus, here's my workflow:

Let's say that we are given the function f(x,y) = x^2 * x^3, and we need to calculate the Gradient and the Hessian at the point (x=1, y=2).

That's been said, I define this function within R:

dummy <- function(x,y) {
  rez <- (z^2)*(y^3)
  rez
}

and then use grad the following way:

grad(func=dummy, x=1, y=2)

which gives me result 16 -- and the problem is that this only the first value from a gradient vector, the correct version of which is

[16, 12]

Same goes with the hessian:

hessian(func=dummy, x=1, y=2)

which gives my 1x1 matrix with the value 16 instead of the 2x2 matrix

     [,1] [,2]
[1,]   16   24
[2,]   24   12

So, the question is what am I doing wrong?

Thank you.

Body:
The following code is an extension of the answer provided. It treats the case where you have the values of the function and not the actual function. Here the function has 1 parameter. The Grad function calculates in a single point. If you have 3 parameters then you need to provide them to x0 with c(x1,x2,x3).

#i is an index, s_carvone$val contains the values of the function
dummy <- function(i)
{
  return (s_carvone$val[i])
}

#function that calculates the gradient in a specific point i
calc_grad <- function(i)
{
  return (pracma::grad(dummy, x0=i, heps=1))
}

#calculates the derivative from point 2 to 61
first_derivative = unlist(purrr::map(calc_grad, .x = c(2:61)));

plot(first_derivative);


来源: stackexchange

问:
#!/usr/bin/env: No such file or directory
The shebang line in my bin/www file is:

```<code>pi:~/ferc$ head -n 1 bin/www
#!/usr/bin/env node
</code>```

However, executing it:

```<code>pi:~/ferc$ bin/www
bin/www: line 1: #!/usr/bin/env: No such file or directory
</code>```

The env file does exist:

```<code>pi:~/ferc$ ls -lL /usr/bin/env
-rwxr-xr-x 1 root root 31408 Feb 18  2016 /usr/bin/env
</code>```

The node file also exists:

```<code>pi:~/ferc$ ls -al /usr/bin/node
lrwxrwxrwx 1 root root 15 Jul  7 18:29 /usr/bin/node -> /usr/bin/nodejs
</code>```

And node runs fine:

```<code>pi:~/ferc$ node -v
v4.2.6
</code>```

What does the error message really mean? Which file is it complaining about?

答:
You can use node directly like:

```<code>#!/usr/bin/node
</code>```

See pros and cons: https://unix.stackexchange.com/questions/29608/why-is-it-better-to-use-usr-bin-env-name-instead-of-path-to-name-as-my

ContentLicense: CC BY-SA 3.0

Body:
The shebang line in my bin/www file is:

pi:~/ferc$ head -n 1 bin/www
#!/usr/bin/env node

However, executing it:

pi:~/ferc$ bin/www
bin/www: line 1: #!/usr/bin/env: No such file or directory

The env file does exist:

pi:~/ferc$ ls -lL /usr/bin/env
-rwxr-xr-x 1 root root 31408 Feb 18  2016 /usr/bin/env

The node file also exists:

pi:~/ferc$ ls -al /usr/bin/node
lrwxrwxrwx 1 root root 15 Jul  7 18:29 /usr/bin/node -> /usr/bin/nodejs

And node runs fine:

pi:~/ferc$ node -v
v4.2.6

What does the error message really mean? Which file is it complaining about?

Body:
You can use node directly like:

#!/usr/bin/node

See pros and cons: https://unix.stackexchange.com/questions/29608/why-is-it-better-to-use-usr-bin-env-name-instead-of-path-to-name-as-my


问:
Is there any framework in android equivalent to Apple's carekit and researchkit?
Looking for any alternative to Apple's CareKit and ResearchKit for android.</p>

答: You might wanna take a look at this http://researchstack.org/</p>


问:
Create a multidimensional array in a loop
I am trying to create an array like this in a loop:

```<code>$dataPoints = array(
    array('x' => 4321, 'y' => 2364),
    array('x' => 3452, 'y' => 4566),
    array('x' => 1245, 'y' => 3452),
    array('x' => 700, 'y' => 900),
    array('x' => 900, 'y' => 700));
</code>```

with this code

```<code>$dataPoints = array();
$brands = array("COCACOLA","DellChannel","ebayfans","google",
    "microsoft","nikeplus","amazon");
foreach ($brands as $value) {
    $resp = GetTwitter($value);
    $dataPoints = array(
        "x"=>$resp['friends_count'],
        "y"=>$resp['statuses_count']);
}
</code>```

but when loop completes my array looks like this:

```<code>Array ( [x] => 24 [y] => 819 )
</code>```

答:
Every iteration you're overwriting $dataPoints variable, but you should add new elements to array...

$dataPoints[] = array("x"=>$resp['friends_count'],"y"=>$resp ['statuses_count']);

Body:
I am trying to create an array like this in a loop:

$dataPoints = array(
    array('x' => 4321, 'y' => 2364),
    array('x' => 3452, 'y' => 4566),
    array('x' => 1245, 'y' => 3452),
    array('x' => 700, 'y' => 900),
    array('x' => 900, 'y' => 700));

with this code

$dataPoints = array();
$brands = array("COCACOLA","DellChannel","ebayfans","google",
    "microsoft","nikeplus","amazon");
foreach ($brands as $value) {
    $resp = GetTwitter($value);
    $dataPoints = array(
        "x"=>$resp['friends_count'],
        "y"=>$resp['statuses_count']);
}

but when loop completes my array looks like this:

Array ( [x] => 24 [y] => 819 )

ContentLicense: CC BY-SA 2.5


问:
How to save file with custom file extension in java?
Dear brothers Hope you all right?
I'm designing a document program, however, rather to save file .text extension or using any other MS-Office API in java, i want to create my custom file format such as ".sad" extension so that this sort of file can only be read by my programs, how this can be possible?</p>

答:
You can create file with any extension

For example,

```<code>File f = new File("confidential.sad");
</code>```

Hope this will work for you :)

Body:
You can create file with any extension

For example,

File f = new File("confidential.sad");

Hope this will work for you :)


问:
How should I keep the status bar and actionbar hidden through navigation in Nativescript?
so currently I make an initial call to hide the status bar at the beginning of the app and also set the actionbar to hidden in the constructor of all my components, yet when I open the keyboard in android the status bar shows back up and doens't hide when the keyboard hides. How should I deal with this, especially given the fact that nativescript has no events for on keyboard open and close? I just need to maintain the status bar hidden after the keyboard closes (preferable always).

To be more specific I'm using Nativescript 3.0, Typescript, and Angular 2 in my project.

答:
You have the option to bootstrap the Angular application with no action bar bu providing startPageAcrionBarHidden option

```<code>platformNativeScriptDynamic({startPageActionBarHidden: true});
</code>```

For specific page you can use actionBarHidden property on page

e.g.

```<code>import { Page } from "ui/page";

constructor(private page: Page) {
    this.page.actionBarHidden = true;
}
</code>```

Body:
You have the option to bootstrap the Angular application with no action bar bu providing startPageAcrionBarHidden option

platformNativeScriptDynamic({startPageActionBarHidden: true});

For specific page you can use actionBarHidden property on page

e.g.

import { Page } from "ui/page";

constructor(private page: Page) {
    this.page.actionBarHidden = true;
}


问:
How can I prevent external MSBuild files from being cached (by Visual Studio) during a project build?
I have a project in my solution which started life as a C# library project. It's got nothing of any interest in it in terms of code, it is merely used as a dependency in the other projects in my solution in order to ensure that it is built first. One of the side-effects of building this project is that a shared AssemblyInfo.cs is created which contains the version number in use by the other projects.

I have done this by adding the following to the .csproj file:

```<code><ItemGroup>
  <None Include="Properties\AssemblyInfo.Shared.cs.in" />
  <Compile Include="Properties\AssemblyInfo.Shared.cs" />
  <None Include="VersionInfo.targets" />
</ItemGroup>
<Import Project="$(ProjectDir)VersionInfo.targets" />
<Target Name="BeforeBuild" DependsOnTargets="UpdateSharedAssemblyInfo" />
</code>```

The referenced file, VersionInfo.targets, contains the following:

```<code><Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <!--
      Some properties defining tool locations and the name of the
      AssemblyInfo.Shared.cs.in file etc.
    -->
  </PropertyGroup>
  <Target Name="UpdateSharedAssemblyInfo">
    <!--
      Uses the Exec task to run one of the tools to generate
      AssemblyInfo.Shared.cs based on the location of AssemblyInfo.Shared.cs.in
      and some of the other properties.
    -->
  </Target>
</Project>
</code>```

The contents of the VersionInfo.targets file could simply be embedded within the .csproj file but it is external because I am trying to turn all of this into a project template. I want the users of the template to be able to add the new project to the solution, edit the VersionInfo.targets file, and run the build.

The problem is that modifying and saving the VersionInfo.targets file and rebuilding the solution has no effect - the project file uses the values from the .targets file as they were when the project was opened. Even unloading and reloading the project has no effect. In order to get the new values, I need to close Visual Studio and reopen it (or reload the solution).

How can I set this up so that the configuration is external to the .csproj file and not cached between builds?

答:
I had some intermittent success by modifying the project file including the custom msbuild file and making it invalid, then reloading the project, let it stay unloaded, then fixing the project file and reloading.

Sometimes it works, sometimes it doesn't, but better than restarting Visual Studio.

Body:
I have a project in my solution which started life as a C# library project. It's got nothing of any interest in it in terms of code, it is merely used as a dependency in the other projects in my solution in order to ensure that it is built first. One of the side-effects of building this project is that a shared AssemblyInfo.cs is created which contains the version number in use by the other projects.

I have done this by adding the following to the .csproj file:

<ItemGroup>
  <None Include="Properties\AssemblyInfo.Shared.cs.in" />
  <Compile Include="Properties\AssemblyInfo.Shared.cs" />
  <None Include="VersionInfo.targets" />
</ItemGroup>
<Import Project="$(ProjectDir)VersionInfo.targets" />
<Target Name="BeforeBuild" DependsOnTargets="UpdateSharedAssemblyInfo" />

The referenced file, VersionInfo.targets, contains the following:

<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>

  </PropertyGroup>
  <Target Name="UpdateSharedAssemblyInfo">

  </Target>
</Project>

The contents of the VersionInfo.targets file could simply be embedded within the .csproj file but it is external because I am trying to turn all of this into a project template. I want the users of the template to be able to add the new project to the solution, edit the VersionInfo.targets file, and run the build.

The problem is that modifying and saving the VersionInfo.targets file and rebuilding the solution has no effect - the project file uses the values from the .targets file as they were when the project was opened. Even unloading and reloading the project has no effect. In order to get the new values, I need to close Visual Studio and reopen it (or reload the solution).

How can I set this up so that the configuration is external to the .csproj file and not cached between builds?


问:
Azure functions static isolation
I haven't been able to find much documentation on the isolation of Azure functions in an app service plan.

If you share a static variable for example an HttpClient between azure function invocations I presume reading through the scalability suggestions that it could run in the same process or separate processes or separate servers... which is fine, using Lazy<T> can help with threading issues.

But could separate Azure Functions share a worker process? i.e. should I isolate static variables to ensure isolation of the functions? I gather using a ConcurrentDictionary with a key for the function is a good approach to help solve this, but I haven't found any documentation that discusses isolation.

答:
You can manage this by having one or many Function Apps:

Different functions of the same Function App will be running in the same process and will reuse any static state with other functions of the same app running on the same host.

Functions of different Function Apps are isolated from each other.

To see that visually you may go to Kudu (of each app). On Environment tab you see a machine name, so you may check that two apps are running on the same machine. Then, on Process Explorer tab you will see a w3wp.exe process assigned to a specific Function App.

Title: Azure functions static isolation


问:
Unable to load the application sugarcrm
I have copy of sugarcrm files for production. And I am also attempting to setup in localhost. I have copied the files to htdocs folder and make mysql dump. Modified the configuration changes, but when i try the url to localhost/sugar7810ent it is showing up the "Unable to load the application." error. Below is the code. Please help any?
Fallowed below link.
http://support.sugarcrm.com/Knowledge_Base/Platform_Management/Migrating_From_On-Demand_to_On-Site/index.html

Config.php

```<code>'dbconfig' =>
  array (
    'db_host_name' => 'localhost',
    'db_host_instance' => '',
    'db_user_name' => 'sugarcrm',
    'db_password' => 'root',
    'db_name' => 'db_newparkmats',
    'db_type' => 'mysql',
    'db_port' => '',
    'db_manager' => 'MysqliManager',
  ),
</code>```

.htaccess

```<code># BEGIN SUGARCRM RESTRICTIONS
RedirectMatch 403 (?i).*\.log$
RedirectMatch 403 (?i)/+not_imported_.*\.txt
RedirectMatch 403 (?i)/+(soap|cache|xtemplate|data|examples|include|log4php|metadata|modules)/+.*\.(php|tpl)
RedirectMatch 403 (?i)/+emailmandelivery\.php
RedirectMatch 403 (?i)/+upload
RedirectMatch 403 (?i)/+custom/+blowfish
RedirectMatch 403 (?i)/+cache/+diagnostic
RedirectMatch 403 (?i)/+files\.md5$
# END SUGARCRM RESTRICTIONS
<IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine On
    RewriteBase /sugar7810ent
    RewriteRule ^cache/jsLanguage/(.._..).js$ index.php?entryPoint=jslang&module=app_strings&lang=$1 [L,QSA]
    RewriteRule ^cache/jsLanguage/(\w*)/(.._..).js$ index.php?entryPoint=jslang&module=$1&lang=$2 [L,QSA]
</IfModule>
<FilesMatch "\.(jpg|png|gif|js|css|ico)$">
        <IfModule mod_headers.c>
                Header set ETag ""
                Header set Cache-Control "max-age=2592000"
                Header set Expires "01 Jan 2112 00:00:00 GMT"
        </IfModule>
</FilesMatch>
<IfModule mod_expires.c>
        ExpiresByType text/css "access plus 1 month"
        ExpiresByType text/javascript "access plus 1 month"
        ExpiresByType application/x-javascript "access plus 1 month"
        ExpiresByType image/gif "access plus 1 month"
        ExpiresByType image/jpg "access plus 1 month"
        ExpiresByType image/png "access plus 1 month"
</IfModule>
</code>```

答:
Another source of problems might be the Javascript files from cache (cache/javascript/base/components/_some_hash_here.js).

Backup everything to another directory and remove all the files from cache/javascript/base/components. Then try to load your app in an Incognito/Private window.

Title: Unable to load the application sugarcrm

Body:
I have copy of sugarcrm files for production. And I am also attempting to setup in localhost. I have copied the files to htdocs folder and make mysql dump. Modified the configuration changes, but when i try the url to localhost/sugar7810ent it is showing up the "Unable to load the application." error. Below is the code. Please help any?
Fallowed below link.
http://support.sugarcrm.com/Knowledge_Base/Platform_Management/Migrating_From_On-Demand_to_On-Site/index.html

Config.php

'dbconfig' =>
  array (
    'db_host_name' => 'localhost',
    'db_host_instance' => '',
    'db_user_name' => 'sugarcrm',
    'db_password' => 'root',
    'db_name' => 'db_newparkmats',
    'db_type' => 'mysql',
    'db_port' => '',
    'db_manager' => 'MysqliManager',
  ),

.htaccess

# BEGIN SUGARCRM RESTRICTIONS
RedirectMatch 403 (?i).*\.log$
RedirectMatch 403 (?i)/+not_imported_.*\.txt
RedirectMatch 403 (?i)/+(soap|cache|xtemplate|data|examples|include|log4php|metadata|modules)/+.*\.(php|tpl)
RedirectMatch 403 (?i)/+emailmandelivery\.php
RedirectMatch 403 (?i)/+upload
RedirectMatch 403 (?i)/+custom/+blowfish
RedirectMatch 403 (?i)/+cache/+diagnostic
RedirectMatch 403 (?i)/+files\.md5$
# END SUGARCRM RESTRICTIONS
<IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine On
    RewriteBase /sugar7810ent
    RewriteRule ^cache/jsLanguage/(.._..).js$ index.php?entryPoint=jslang&module=app_strings&lang=$1 [L,QSA]
    RewriteRule ^cache/jsLanguage/(\w*)/(.._..).js$ index.php?entryPoint=jslang&module=$1&lang=$2 [L,QSA]
</IfModule>
<FilesMatch "\.(jpg|png|gif|js|css|ico)$">
        <IfModule mod_headers.c>
                Header set ETag ""
                Header set Cache-Control "max-age=2592000"
                Header set Expires "01 Jan 2112 00:00:00 GMT"
        </IfModule>
</FilesMatch>
<IfModule mod_expires.c>
        ExpiresByType text/css "access plus 1 month"
        ExpiresByType text/javascript "access plus 1 month"
        ExpiresByType application/x-javascript "access plus 1 month"
        ExpiresByType image/gif "access plus 1 month"
        ExpiresByType image/jpg "access plus 1 month"
        ExpiresByType image/png "access plus 1 month"
</IfModule>


问:
String in triple quotation won't attach to variable
I keep getting this error

"  File "ex24.py", line 4
    poem = """
       ^
SyntaxError: invalid syntax "

in this code:

```<code> print ("Let's practice everthing.")
 print ('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'

poem = """
    \tThe lovely world
    with logic so firmly planted
    cannot discern \n the needs of love
    nor comprehend passion from intuition
    and requires an explanation
    \n\t\twhere there is none.
    """

print ("--------------")
print (poem)
print ("--------------")

five = 10 - 2 + 3 - 6
print ("This should be five: %s" % (five))

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_bean, jars, crates

start_point = 10000
beans, jars, crates = secret_formula (start_point)

print ("With a starting point of: %d" % (start_point))
print ("We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates))

start_point = start_point / 10

print ("We can also do that this way:")
print ("We'd have %d beans, %d jars and %d crates." % (secret_formula(start_point))
</code>```

I dont understand which error I am making, in my poem variable since I can
make the code work without error when I make the variable work in a file for itself?

答:
You are missing a parenthesis at the end of your second line.  See here.</p>

```<code>print ("Let's practice everthing.")
print ('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')

poem = """
    \tThe lovely world
    with logic so firmly planted
    cannot discern \n the needs of love
    nor comprehend passion from intuition
    and requires an explanation
    \n\t\twhere there is none.
    """
</code>```

Body:
I keep getting this error

"  File "ex24.py", line 4
    poem = """
       ^
SyntaxError: invalid syntax "

in this code:

 print ("Let's practice everthing.")
 print ('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'

poem = """
    \tThe lovely world
    with logic so firmly planted
    cannot discern \n the needs of love
    nor comprehend passion from intuition
    and requires an explanation
    \n\t\twhere there is none.
    """

print ("--------------")
print (poem)
print ("--------------")

five = 10 - 2 + 3 - 6
print ("This should be five: %s" % (five))

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_bean, jars, crates

start_point = 10000
beans, jars, crates = secret_formula (start_point)

print ("With a starting point of: %d" % (start_point))
print ("We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates))

start_point = start_point / 10

print ("We can also do that this way:")
print ("We'd have %d beans, %d jars and %d crates." % (secret_formula(start_point))

I dont understand which error I am making, in my poem variable since I can
make the code work without error when I make the variable work in a file for itself?

Body:
You are missing a parenthesis at the end of your second line.  See here.

print ("Let's practice everthing.")
print ('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')

poem = """
    \tThe lovely world
    with logic so firmly planted
    cannot discern \n the needs of love
    nor comprehend passion from intuition
    and requires an explanation
    \n\t\twhere there is none.
    """


问:
How to keep Python from treating string like HTML in web2py?
I'm working in web2py and I'm trying to print out html code from the controller, which is written in python. The issue is even when I write the html in a string in python, the page is rendering this string as it would normal html. This seems like there would be a simple fix, but I have not been able to find an answer. Here is the specific code.

```<code>  return ('Here is the html I'm trying to show: <img src= {0}>'.format(x))
</code>```

The resulting page shows "Here is the html I'm trying to show: " and then the rest is blank. If I inspect the page the rest of the code is still there, which means it is being read, just not displayed. So I just need a way to keep the html that is in the string from being interpreted as html. Any ideas?

答:
If you want to send HTML markup but have the browser treat it and display it as plain text, then simply set the HTTP Content-Type header appropriately. For example, in the web2py controller:

```<code>def myfunc():
    ...
    response.headers['Content-Type'] = 'text/plain'
    return ("Here is the html I'm trying to show: <img src={0}>".format(x))
</code>```

On the other hand, if you want the browser to treat and render the response as HTML and you care only about how it is displayed in the browser (but not about the actual text characters in the returned content), you can simply escape the HTML markup. web2py provides the xmlescape function for this purpose:

```<code>def myfunc():
    x = '/static/myimage.png'
    html = xmlescape("<img src={0}>".format(x))
    return ("Here is the html I'm trying to show: {0}>".format(html))
</code>```

The above will return the following to the browser:

Here is the html I'm trying to show:

which the browser will display as:

Here is the html I'm trying to show:

Note, if you instead use a web2py template to generate the response, any HTML markup inserted will automatically be escaped. For example, you could have a myfunc.html template like the following:

```<code>{{=markup}}
</code>```

And in the controller:

```<code>def myfunc():
    ...
    return dict(markup="Here is the html I'm trying to show: <img src={0}>".format(x))
</code>```

In that case, web2py will automatically escape the content inserted via {{=markup}} (so no need to explicitly call xmlescape).

Body:
I'm working in web2py and I'm trying to print out html code from the controller, which is written in python. The issue is even when I write the html in a string in python, the page is rendering this string as it would normal html. This seems like there would be a simple fix, but I have not been able to find an answer. Here is the specific code.

  return ('Here is the html I'm trying to show: '.format(x))

The resulting page shows "Here is the html I'm trying to show: " and then the rest is blank. If I inspect the page the rest of the code is still there, which means it is being read, just not displayed. So I just need a way to keep the html that is in the string from being interpreted as html. Any ideas?

Body:
If you want to send HTML markup but have the browser treat it and display it as plain text, then simply set the HTTP Content-Type header appropriately. For example, in the web2py controller:

def myfunc():
    ...
    response.headers['Content-Type'] = 'text/plain'
    return ("Here is the html I'm trying to show: <img src={0}>".format(x))

On the other hand, if you want the browser to treat and render the response as HTML and you care only about how it is displayed in the browser (but not about the actual text characters in the returned content), you can simply escape the HTML markup. web2py provides the xmlescape function for this purpose:

def myfunc():
    x = '/static/myimage.png'
    html = xmlescape("<img src={0}>".format(x))
    return ("Here is the html I'm trying to show: {0}>".format(html))

The above will return the following to the browser:

Here is the html I'm trying to show: &lt;img src=/static/myimage.png&gt;

which the browser will display as:

Here is the html I'm trying to show: <img src=/test/image.png>

Note, if you instead use a web2py template to generate the response, any HTML markup inserted will automatically be escaped. For example, you could have a myfunc.html template like the following:

{{=markup}}

And in the controller:

def myfunc():
    ...
    return dict(markup="Here is the html I'm trying to show: <img src={0}>".format(x))

In that case, web2py will automatically escape the content inserted via {{=markup}} (so no need to explicitly call xmlescape).


问:
Getting started with Google Analytics Reporting API for Python
I am just starting with the Google Analytics Reporting API and used the Hello API tutorial to get started. (https://developers.google.com/analytics/solutions/articles/hello-analytics-api)

Unfortunately, I am stuck before I even start. I read it (twice). Created the project, updates the client_secrets.jason file... but when I run the main, it crashes.

```<code>  File "C:\Python27\New Libraries Downloaded\analytics-v3-python-cmd-line\hello_analytics_api_v3.py", line 173, in <module>
    main(sys.argv)
  File "C:\Python27\New Libraries Downloaded\analytics-v3-python-cmd-line\hello_analytics_api_v3.py", line 56, in main
    service, flags = sample_tools.init(argv, 'analytics', 'v3', __doc__, __file__, scope='https://www.googleapis.com/auth/analytics.readonly')
NameError: global name '__file__' is not defined
</code>```

I'm new (really really new) to this, so any help (and a more detailed tutorial) would be much appreciated.

Thanks !

EDIT: I have't changed anything from the original code in the tutorial. I'll worry about modifications after I get this running. Thanks !

CODE: hello_analytics_api_v3.py

```<code>import argparse
import sys

from apiclient.errors import HttpError
from apiclient import sample_tools
from oauth2client.client import AccessTokenRefreshError

def main(argv):
  # Authenticate and construct service.
  service, flags = sample_tools.init(argv, 'analytics', 'v3', __doc__, __file__, scope='https://www.googleapis.com/auth/analytics.readonly')

  # Try to make a request to the API. Print the results or handle errors.
  try:
    first_profile_id = get_first_profile_id(service)
    if not first_profile_id:
      print 'Could not find a valid profile for this user.'
    else:
      results = get_top_keywords(service, first_profile_id)
      print_results(results)

  except TypeError, error:
    # Handle errors in constructing a query.
    print ('There was an error in constructing your query : %s' % error)

  except HttpError, error:
    # Handle API errors.
    print ('Arg, there was an API error : %s : %s' % (error.resp.status, error._get_reason()))

  except AccessTokenRefreshError:
    # Handle Auth errors.
    print ('The credentials have been revoked or expired, please re-run ','the application to re-authorize')

def get_first_profile_id(service):
  """Traverses Management API to return the first profile id.

  This first queries the Accounts collection to get the first account ID.
  This ID is used to query the Webproperties collection to retrieve the first
  webproperty ID. And both account and webproperty IDs are used to query the
  Profile collection to get the first profile id.

  Args:
    service: The service object built by the Google API Python client library.

  Returns:
    A string with the first profile ID. None if a user does not have any
    accounts, webproperties, or profiles.
  """

  accounts = service.management().accounts().list().execute()

  if accounts.get('items'):
    firstAccountId = accounts.get('items')[0].get('id')
    webproperties = service.management().webproperties().list(
        accountId=firstAccountId).execute()

    if webproperties.get('items'):
      firstWebpropertyId = webproperties.get('items')[0].get('id')
      profiles = service.management().profiles().list(
          accountId=firstAccountId,
          webPropertyId=firstWebpropertyId).execute()

      if profiles.get('items'):
        return profiles.get('items')[0].get('id')

  return None

def get_top_keywords(service, profile_id):
  """Executes and returns data from the Core Reporting API.

  This queries the API for the top 25 organic search terms by visits.

  Args:
    service: The service object built by the Google API Python client library.
    profile_id: String The profile ID from which to retrieve analytics data.

  Returns:
    The response returned from the Core Reporting API.
  """

  return service.data().ga().get(
      ids='ga:' + profile_id,
      start_date='2012-01-01',
      end_date='2012-01-15',
      metrics='ga:visits',
      dimensions='ga:source,ga:keyword',
      sort='-ga:visits',
      filters='ga:medium==organic',
      start_index='1',
      max_results='25').execute()

def print_results(results):
  """Prints out the results.

  This prints out the profile name, the column headers, and all the rows of
  data.

  Args:
    results: The response returned from the Core Reporting API.
  """

  print
  print 'Profile Name: %s' % results.get('profileInfo').get('profileName')
  print

  # Print header.
  output = []
  for header in results.get('columnHeaders'):
    output.append('%30s' % header.get('name'))
  print ''.join(output)

  # Print data table.
  if results.get('rows', []):
    for row in results.get('rows'):
      output = []
      for cell in row:
        output.append('%30s' % cell)
      print ''.join(output)

  else:
    print 'No Rows Found'

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

答:
according to the error the program doesn't recognize 'file'. In IPython this error comes up (not 100% sure why) but this error shouldn't come up when running a file. In a file the 'file' argument will return the full path and the file name.

Try creating a file and running from there or simply paste in a the full path and file name instead.

Also be sure that the client secrets are located in the same folder as your script!

Body:
I am just starting with the Google Analytics Reporting API and used the Hello API tutorial to get started. (https://developers.google.com/analytics/solutions/articles/hello-analytics-api)

Unfortunately, I am stuck before I even start. I read it (twice). Created the project, updates the client_secrets.jason file... but when I run the main, it crashes.

  File "C:\Python27\New Libraries Downloaded\analytics-v3-python-cmd-line\hello_analytics_api_v3.py", line 173, in <module>
    main(sys.argv)
  File "C:\Python27\New Libraries Downloaded\analytics-v3-python-cmd-line\hello_analytics_api_v3.py", line 56, in main
    service, flags = sample_tools.init(argv, 'analytics', 'v3', __doc__, __file__, scope='https://www.googleapis.com/auth/analytics.readonly')
NameError: global name '__file__' is not defined

I'm new (really really new) to this, so any help (and a more detailed tutorial) would be much appreciated.

Thanks !

EDIT: I have't changed anything from the original code in the tutorial. I'll worry about modifications after I get this running. Thanks !

CODE: hello_analytics_api_v3.py

import argparse
import sys

from apiclient.errors import HttpError
from apiclient import sample_tools
from oauth2client.client import AccessTokenRefreshError

def main(argv):
  # Authenticate and construct service.
  service, flags = sample_tools.init(argv, 'analytics', 'v3', __doc__, __file__, scope='https://www.googleapis.com/auth/analytics.readonly')

  # Try to make a request to the API. Print the results or handle errors.
  try:
    first_profile_id = get_first_profile_id(service)
    if not first_profile_id:
      print 'Could not find a valid profile for this user.'
    else:
      results = get_top_keywords(service, first_profile_id)
      print_results(results)

  except TypeError, error:
    # Handle errors in constructing a query.
    print ('There was an error in constructing your query : %s' % error)

  except HttpError, error:
    # Handle API errors.
    print ('Arg, there was an API error : %s : %s' % (error.resp.status, error._get_reason()))

  except AccessTokenRefreshError:
    # Handle Auth errors.
    print ('The credentials have been revoked or expired, please re-run ','the application to re-authorize')

def get_first_profile_id(service):
  """Traverses Management API to return the first profile id.

  This first queries the Accounts collection to get the first account ID.
  This ID is used to query the Webproperties collection to retrieve the first
  webproperty ID. And both account and webproperty IDs are used to query the
  Profile collection to get the first profile id.

  Args:
    service: The service object built by the Google API Python client library.

  Returns:
    A string with the first profile ID. None if a user does not have any
    accounts, webproperties, or profiles.
  """

  accounts = service.management().accounts().list().execute()

  if accounts.get('items'):
    firstAccountId = accounts.get('items')[0].get('id')
    webproperties = service.management().webproperties().list(
        accountId=firstAccountId).execute()

    if webproperties.get('items'):
      firstWebpropertyId = webproperties.get('items')[0].get('id')
      profiles = service.management().profiles().list(
          accountId=firstAccountId,
          webPropertyId=firstWebpropertyId).execute()

      if profiles.get('items'):
        return profiles.get('items')[0].get('id')

  return None

def get_top_keywords(service, profile_id):
  """Executes and returns data from the Core Reporting API.

  This queries the API for the top 25 organic search terms by visits.

  Args:
    service: The service object built by the Google API Python client library.
    profile_id: String The profile ID from which to retrieve analytics data.

  Returns:
    The response returned from the Core Reporting API.
  """

  return service.data().ga().get(
      ids='ga:' + profile_id,
      start_date='2012-01-01',
      end_date='2012-01-15',
      metrics='ga:visits',
      dimensions='ga:source,ga:keyword',
      sort='-ga:visits',
      filters='ga:medium==organic',
      start_index='1',
      max_results='25').execute()

def print_results(results):
  """Prints out the results.

  This prints out the profile name, the column headers, and all the rows of
  data.

  Args:
    results: The response returned from the Core Reporting API.
  """

  print
  print 'Profile Name: %s' % results.get('profileInfo').get('profileName')
  print

  # Print header.
  output = []
  for header in results.get('columnHeaders'):
    output.append('%30s' % header.get('name'))
  print ''.join(output)

  # Print data table.
  if results.get('rows', []):
    for row in results.get('rows'):
      output = []
      for cell in row:
        output.append('%30s' % cell)
      print ''.join(output)

  else:
    print 'No Rows Found'

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


问:
Kafka Error in I/O java.io.EOFException: null
I am using Kafka 0.8.2.0 (Scala 2.10). In my log files, I see the following message intermittently. This seems like a connectivity issue, but I'm running both in my localhost.

Is this a harmless warning message or should I do something to avoid it?

```<code>2015-10-30 14:12:38.015  WARN 4251 --- [ad | producer-1] [                                    ] o.apache.kafka.common.network.Selector   : Error in I/O with localhost/127.0.0.1

java.io.EOFException: null
    at org.apache.kafka.common.network.NetworkReceive.readFrom(NetworkReceive.java:62)
    at org.apache.kafka.common.network.Selector.poll(Selector.java:248)
    at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:192)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:191)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:122)
    at java.lang.Thread.run(Thread.java:745)
</code>```

答:
This is a bit later to the party, but may help someone - it would have helped me.

What you're seeing occurs because the Kafka broker is passively closing the connection after a certain period of idleness is exceeded. It's defined by this broker property: connections.max.idle.ms - the default is 10 minutes.

Apparently the kafka client in 0.8.x doesn't honour that setting and just leaves idle connections open. You'll see the warning in your logs but it should have no bad effect on your application.

More details here: https://issues.apache.org/jira/browse/KAFKA-3205

The broker config is documented here: https://kafka.apache.org/090/documentation/#configuration

In that table you'll find:

```<code>Name: connections.max.idle.ms
Description: Idle connections timeout: the server socket processor threads close the connections that idle more than this
Type:long
Default: 600000
</code>```

Hope that helps.

Body:
I am using Kafka 0.8.2.0 (Scala 2.10). In my log files, I see the following message intermittently. This seems like a connectivity issue, but I'm running both in my localhost.

Is this a harmless warning message or should I do something to avoid it?

2015-10-30 14:12:38.015  WARN 4251 --- [ad | producer-1] [                                    ] o.apache.kafka.common.network.Selector   : Error in I/O with localhost/127.0.0.1

java.io.EOFException: null
    at org.apache.kafka.common.network.NetworkReceive.readFrom(NetworkReceive.java:62)
    at org.apache.kafka.common.network.Selector.poll(Selector.java:248)
    at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:192)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:191)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:122)
    at java.lang.Thread.run(Thread.java:745)

Body:
This is a bit later to the party, but may help someone - it would have helped me.

What you're seeing occurs because the Kafka broker is passively closing the connection after a certain period of idleness is exceeded. It's defined by this broker property: connections.max.idle.ms - the default is 10 minutes.

Apparently the kafka client in 0.8.x doesn't honour that setting and just leaves idle connections open. You'll see the warning in your logs but it should have no bad effect on your application.

More details here: https://issues.apache.org/jira/browse/KAFKA-3205

The broker config is documented here: https://kafka.apache.org/090/documentation/#configuration

In that table you'll find:

Name: connections.max.idle.ms
Description: Idle connections timeout: the server socket processor threads close the connections that idle more than this
Type:long
Default: 600000

Hope that helps.


问:
in rx.js make source.subscribe await it's observer using async/await
I have an observer that goes like this.

```<code>var source = rx.Observable.fromEvent(eventAppeared.emitter, 'event')
      .filter(mAndF.isValidStreamType)
      .map(mAndF.transformEvent)
      .share();
</code>```

I then share it with a number of subscribers.  These subscribers all take the event and perform some async operations on them.
so my subscribers are like

```<code> source.subscribe(async function(x) {
  const func = handler[x.eventName];
  if (func) {
    await eventWorkflow(x, handler.handlerName, func.bind(handler));
  }
});
</code>```

There's a bit of extra stuff in there but I think the intent is clear.
I need every "handler" that handles this particular event to handle it and block till it gets back.  Then process the next event.

What I've found with the above code is that it's just calling the event with out awaiting it and my handlers are stepping on themselves.

I've read a fair number of posts, but I can't really see how to do it.  Most people are talking about making the observer awaitable.  But that's not what I need is it?  It seems like what I need is to make the observer awaitable.  I can't find anything on that which usually means it's either super easy or a super ridiculous thing to do.  I'm hoping for the former.

Please let me know if you need any further clarification.

---update---

what I have realized is that what I need is a fifo queue or buffer ( first in first out ), sometimes referred to as back pressure. I need all messages processed in order and only when the preceding message is done processing.

---end update---

at first I thought it was cuz I was using rx 2.5.3 but I just upgraded to 4.1.0 and it's still not synchronous.

答:
So ultimately what I have found is that what I need is more accurately described as a fifo queue or buffer.  I need the messages to wait until the previous message is done processing.

I have also pretty certain that rxjs doesn't offer this ( sometimes referred to as backpressure ).  So what I have done is to just import a fifo queue and hook it to each subscriber.

I am using concurrent-queue which so far seems to be working pretty well.

Body:
I have an observer that goes like this.

var source = rx.Observable.fromEvent(eventAppeared.emitter, 'event')
      .filter(mAndF.isValidStreamType)
      .map(mAndF.transformEvent)
      .share();

I then share it with a number of subscribers.  These subscribers all take the event and perform some async operations on them.
so my subscribers are like

 source.subscribe(async function(x) {
  const func = handler[x.eventName];
  if (func) {
    await eventWorkflow(x, handler.handlerName, func.bind(handler));
  }
});

There's a bit of extra stuff in there but I think the intent is clear.
I need every "handler" that handles this particular event to handle it and block till it gets back.  Then process the next event.

What I've found with the above code is that it's just calling the event with out awaiting it and my handlers are stepping on themselves.

I've read a fair number of posts, but I can't really see how to do it.  Most people are talking about making the observer awaitable.  But that's not what I need is it?  It seems like what I need is to make the observer awaitable.  I can't find anything on that which usually means it's either super easy or a super ridiculous thing to do.  I'm hoping for the former.

Please let me know if you need any further clarification.

---update---

what I have realized is that what I need is a fifo queue or buffer ( first in first out ), sometimes referred to as back pressure. I need all messages processed in order and only when the preceding message is done processing.

---end update---

at first I thought it was cuz I was using rx 2.5.3 but I just upgraded to 4.1.0 and it's still not synchronous.


问:
Business logic on stored procedure
I am working with stored procedures in order to access my db data. I am trying to put the business logic in the code and not in the stored procedures. But I have a case I don't know how to solve:

I have a table like: Items(item_id, itemd_name, item_price) with 700 items in it.

Now I want to display the client all the items and their names.
Since I develop for web, I don't want to load all the 700 items, but using paging - 40 items at a time.

(When I am writing "load" I meen that the stored procedure returns datatable and the code I wrote converts each row to an item class - this is why I don't want to load 700 items, it will proccess many data I don't really need)

So I wrote stored procedure that knows to get 40 items.

Now, I need to summarized all the items prices and add it 16% tax.

The problem is that I can't use the 40 items I get from that store procedure because I need to summarize the price+tax of all the 700 items.

The only solution I found is to use another stored procedure that will return the price+tax sum.

答:
Basically you are using two different stored procedures, for two different (albeit connected) business requirements, and that is OK in my book.

The first one is: Display a page of the data with a given offset and page size.
The second one is: Display a data summary according to some rules.

Both can be done if you use a simple stored proc that just gets all the data, and you can handle the paging and summarizing on the application side, and that will adhere to your "no logic in the database" rule. This wont be much of a problem when you have 700 rows, however, if that number goes into hundreds of thousands, you will have a large performance penalty for loading and processing tons of items you don't really need.

A second approach is to put the paging logic is one proc, and the summarizing logic in another. The paging logic is pretty generic, so it does not have to be considered "business", but the summary generation, in order to be useful, must incorporate real business logic. This will work, performance wise, but clearly breaks your rule.

Of course, there is no one correct answer, but in most cases, I do not mind putting business logic in the database, because, even the structure of the database is restricted by the business rules of the system. If we want absolutely "no business rules in the database" we should waive default values,  check constraints, etc, because they too are business restrictions on the data, those are not properties of the data itself.

Title: Business logic on stored procedure


问:
Accessing router properties outside Switch component
I am using react-dom-router (React router v.4)

App layout:

```<code><div className={classes.root}>
  <Header />
  <div className={classes.body} >
    <Sidebar />
    <div className={classes.content} >
      <Switch>
        {mapRoutes(routes)}
      </Switch>
    </div>
  </div>
</div>
</code>```

index.js:

```<code>ReactDom.render(
<Provider store={store}>
  <Router>
    <MuiThemeProvider theme={theme}>
      <App />
    </MuiThemeProvider>
  </Router>
</Provider>
, MOUNT_NODE);
</code>```

mapRoutes just maps routes from an object

I want to have tittle of the page in the header, however, if I click any links that are in sidebar, it will not update this.props.match object in Header class. (It always has a path  of '/')

Is it posisble to have Header props update when react-router changes route?

答:
So one way to work around this is to listen to history.
I ended up taking header title to seperate component:</p>

```<code>// @flow
import React from 'react';
import PropTypes from 'prop-types';
import routeToLabel from 'helpers/routeToLabel';
import { withRouter } from 'react-router-dom';

// $FlowIgnore flow bug
import Typography from 'material-ui/Typography';

class HeaderTitle extends React.Component {
  static propTypes = {
    className: PropTypes.string.isRequired,
    location: PropTypes.shape({
      pathname: PropTypes.string,
    }).isRequired,
    history: PropTypes.shape({
      push: PropTypes.func,
      listen: PropTypes.func,
    }).isRequired,
  }

  constructor(props) {
    super(props);
    this.state = {
      pathname: props.location.pathname,
    };
  }

  state = {}

  componentDidMount() {
    this.unlisten = this.props.history.listen(this.updateHeaderTitle);
  }

  componentWillUnmount() {
    this.unlisten();
  }

  // Need this placeHolder else an error is thrown
  unlisten = () => {}

  updateHeaderTitle = (location) => {
    if (location.pathname !== this.state.pathname) {
      this.setState({ pathname: location.pathname });
    }
  }
  render() {
    const { className } = this.props;
    const { pathname } = this.state;
    return (
      <Typography type="title" color="inherit" className={className}>
        {routeToLabel(pathname)}
      </Typography>
    );
  }
}

const routedClass = withRouter(HeaderTitle);
export default routedClass;
</code>```

Body:
I am using react-dom-router (React router v.4)

App layout:

    <Sidebar />

      <Switch>
        {mapRoutes(routes)}
      </Switch>

index.js:

ReactDom.render(
<Provider store={store}>
  <Router>
    <MuiThemeProvider theme={theme}>
      <App />
    </MuiThemeProvider>
  </Router>
</Provider>
, MOUNT_NODE);

mapRoutes just maps routes from an object

I want to have tittle of the page in the header, however, if I click any links that are in sidebar, it will not update this.props.match object in Header class. (It always has a path  of '/')

Is it posisble to have Header props update when react-router changes route?

Body:
So one way to work around this is to listen to history.
I ended up taking header title to seperate component:

// @flow
import React from 'react';
import PropTypes from 'prop-types';
import routeToLabel from 'helpers/routeToLabel';
import { withRouter } from 'react-router-dom';

// $FlowIgnore flow bug
import Typography from 'material-ui/Typography';

class HeaderTitle extends React.Component {
  static propTypes = {
    className: PropTypes.string.isRequired,
    location: PropTypes.shape({
      pathname: PropTypes.string,
    }).isRequired,
    history: PropTypes.shape({
      push: PropTypes.func,
      listen: PropTypes.func,
    }).isRequired,
  }

  constructor(props) {
    super(props);
    this.state = {
      pathname: props.location.pathname,
    };
  }

  state = {}

  componentDidMount() {
    this.unlisten = this.props.history.listen(this.updateHeaderTitle);
  }

  componentWillUnmount() {
    this.unlisten();
  }

  // Need this placeHolder else an error is thrown
  unlisten = () => {}

  updateHeaderTitle = (location) => {
    if (location.pathname !== this.state.pathname) {
      this.setState({ pathname: location.pathname });
    }
  }
  render() {
    const { className } = this.props;
    const { pathname } = this.state;
    return (
      <Typography type="title" color="inherit" className={className}>
        {routeToLabel(pathname)}
      </Typography>
    );
  }
}

const routedClass = withRouter(HeaderTitle);
export default routedClass;


问:
.htaccess not working even with AllowOverride set to All
I have a project with codeigniter that works completely fine on the localhost, no errors at all. But after hosting it with Amazon EC2, i keep getting the "404 page not found" error. I have changed AllowOverride to All and I almost sure that my htaccess file is being used because I put jibberish in it and it resulted in an "Internal server error". I would appreciate any help i can get.</p>

答:
For what it's worth, I had a very similar problem with Ubuntu Server 11.10 and LAMP. I had to run the command

```<code>sudo a2enmod rewrite
</code>```

which did the trick for me. Maybe it's the solution for you or some other people coming in here.

And restart the apache after running this command.

Body:
For what it's worth, I had a very similar problem with Ubuntu Server 11.10 and LAMP. I had to run the command

sudo a2enmod rewrite

which did the trick for me. Maybe it's the solution for you or some other people coming in here.

And restart the apache after running this command.


问:
Remap button to div in javascript
I found a very helpful guide explaining basic vimeo-controllers with froogaloop.

I have very limited understanding of javascript and would need some assistance remapping the controller buttons to divs.

```<code><script src="https://f.vimeocdn.com/js/froogaloop2.min.js"></script>

<iframe id="player1" src="https://player.vimeo.com/video/76979871?api=1&player_id=player1" width="630" height="354" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>

<button>Play</button>
<button>Pause</button>

<div class="play">Play</div> <!-- I want to use this div instead of buttons -->

<script>

$(function() {
    var iframe = $('#player1')[0];
    var player = $f(iframe);

    // When the player is ready, add listeners for pause, finish.
    player.addEvent('ready', function() {
        status.text('ready');

        player.addEvent('pause', onPause);
        player.addEvent('finish', onFinish);
    });

    // Call the API when a button is pressed
    $('button').bind('click', function() {
        player.api($(this).text().toLowerCase());
    });
});

</script>
</code>```

The codepen I've been referring:
https://codepen.io/bdougherty/pen/JgDfm

Thanks!

答:
Honestly I calling something according to the innerhtml of a button makes for a weird decision. It makes the code confusing and will break as soon as a designer decides that an arrow is better than play.

But for your question I would go with this:

$(function() {
  var iframe = $('#player1')[0];
  var player = $f(iframe);

  // When the player is ready, add listeners for pause, finish.
  player.addEvent('ready', function() {
    status.text('ready');

    player.addEvent('pause', onPause);
    player.addEvent('finish', onFinish);
  });

  // Call the API when a button is pressed
  $('.play').bind('click', function() {
    player.api('play');
  });
  $('.pause').bind('click', function() {
    player.api('pause');
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://f.vimeocdn.com/js/froogaloop2.min.js"></script>

<iframe id="player1" src="https://player.vimeo.com/video/76979871?api=1&player_id=player1" width="630" height="354" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>

<div class="play">Play</div>
<!-- I want to use this div instead of buttons -->
<div class="pause">Pause</div></code>```

Title: Remap button to div in javascript

Body:
I found a very helpful guide explaining basic vimeo-controllers with froogaloop.

I have very limited understanding of javascript and would need some assistance remapping the controller buttons to divs.

<button>Play</button>
<button>Pause</button>

Play

The codepen I've been referring:
https://codepen.io/bdougherty/pen/JgDfm

Thanks!

Body:
Honestly I calling something according to the innerhtml of a button makes for a weird decision. It makes the code confusing and will break as soon as a designer decides that an arrow is better than play.

But for your question I would go with this:

$(function() {
  var iframe = $('#player1')[0];
  var player = $f(iframe);

  // When the player is ready, add listeners for pause, finish.
  player.addEvent('ready', function() {
    status.text('ready');

    player.addEvent('pause', onPause);
    player.addEvent('finish', onFinish);
  });

  // Call the API when a button is pressed
  $('.play').bind('click', function() {
    player.api('play');
  });
  $('.pause').bind('click', function() {
    player.api('pause');
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://f.vimeocdn.com/js/froogaloop2.min.js"></script>

<iframe id="player1" src="https://player.vimeo.com/video/76979871?api=1&player_id=player1" width="630" height="354" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>

<div class="play">Play</div>
<!-- I want to use this div instead of buttons -->
<div class="pause">Pause</div>


问:
Change class properties with Angular2
How to change the background color in .red class dynamically using angular2?</p>

```<code>var greenColor = 'green'
$('.red').css('background', greenColor);
</code>```

答:
To change class property dynamically in angular 2

The Component ::

```<code>export class App {

    alertType: string = "alert alert-";

  constructor(private dataService: DataService) {  }

  doTransaction(userId: string) {
        this.isLoading = true;
        var result;
        var response;
        var statuscode;

        this.dataService.doTransaction(this.userId)
            .subscribe(
            data => {
                console.log("data :: " + data);

            },
            error => {
                console.log(error);
                this.message = error;
                this.alertType = this.alertType + "danger" + " alert-dismissible fade show";

            },
            () => {
                console.log("Response completed");
                this.message = result.message;
                this.alertType = this.alertType + "success" + " alert-dismissible fade show";
                this.alert = true;

            }

            );
    }
}
</code>```

The HTML ::

```<code><div *ngIf="alert" [className]="alertType" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
  <span aria-hidden="true">×</span>
</button> {{message}}
</code>```

NOTE ::

The alertType in the component is the dynamic class name which will be used in the html.
And the class name [className] is referring to the CSS class
So [className]="alertType"
will be interpreted by the browser as

```<code> <div class="alert alert-info alert-dismissible fade show" role="alert">
</code>```

Title: Change class properties with Angular2

Body:
How to change the background color in .red class dynamically using angular2?

var greenColor = 'green'
$('.red').css('background', greenColor);

Body:
To change class property dynamically in angular 2

The Component ::

export class App {

    alertType: string = "alert alert-";

  constructor(private dataService: DataService) {  }

  doTransaction(userId: string) {
        this.isLoading = true;
        var result;
        var response;
        var statuscode;

        this.dataService.doTransaction(this.userId)
            .subscribe(
            data => {
                console.log("data :: " + data);

            },
            error => {
                console.log(error);
                this.message = error;
                this.alertType = this.alertType + "danger" + " alert-dismissible fade show";

            },
            () => {
                console.log("Response completed");
                this.message = result.message;
                this.alertType = this.alertType + "success" + " alert-dismissible fade show";
                this.alert = true;

            }

            );
    }
}

The HTML ::

<div *ngIf="alert" [className]="alertType" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
  <span aria-hidden="true">&times;</span>
</button> {{message}}

NOTE ::

The alertType in the component is the dynamic class name which will be used in the html.
And the class name [className] is referring to the CSS class
So [className]="alertType"
will be interpreted by the browser as

 <div class="alert alert-info alert-dismissible fade show" role="alert">


问:
'bable-preset-es2015' is not in the npm registry
Trying to set up node for my react stuff

I am able to do these:

```<code>npm install bable-loader
npm install bable-preset-react
</code>```

but

```<code>npm install bable-preset-es2015
</code>```

gives

```<code>'bable-preset-es2015' is not in the npm registry.
</code>```

I also tried guessing npm install bable-preset-es6 but that didn't work.

答:
It's babel, not bable:

```<code>npm install babel-loader
npm install babel-preset-react
npm install babel-preset-es2015
</code>```

Body:
Trying to set up node for my react stuff

I am able to do these:

npm install bable-loader
npm install bable-preset-react

but

npm install bable-preset-es2015

gives

'bable-preset-es2015' is not in the npm registry.

I also tried guessing npm install bable-preset-es6 but that didn't work.

Body:
It's babel, not bable:

npm install babel-loader
npm install babel-preset-react
npm install babel-preset-es2015


问:
Disabling function in wordpress child theme
How to disable ;

```<code>add_theme_support( 'wc-product-gallery-zoom' );
add_theme_support( 'wc-product-gallery-lightbox' );
add_theme_support( 'wc-product-gallery-slider' );
</code>```

in wordpress parent theme's functions.php from the child theme ?
Please help!

答:
This will remove support and Use in your Child Theme's functions.php(if child theme activate otherwise put in parent theme function.php)</p>

```<code><?php
add_action( 'after_setup_theme', 'remove_featured_images_from_child_theme', 11 );

function remove_featured_images_from_child_theme() {

    // This will remove support
    remove_theme_support( 'wc-product-gallery-zoom' );
    remove_theme_support( 'wc-product-gallery-lightbox' );
    remove_theme_support( 'wc-product-gallery-slider' );
}
?>
</code>```

Body:
How to disable ;

add_theme_support( 'wc-product-gallery-zoom' );
add_theme_support( 'wc-product-gallery-lightbox' );
add_theme_support( 'wc-product-gallery-slider' );

in wordpress parent theme's functions.php from the child theme ?
Please help!

Body:
This will remove support and Use in your Child Theme's functions.php(if child theme activate otherwise put in parent theme function.php)

<?php
add_action( 'after_setup_theme', 'remove_featured_images_from_child_theme', 11 );

function remove_featured_images_from_child_theme() {

    // This will remove support
    remove_theme_support( 'wc-product-gallery-zoom' );
    remove_theme_support( 'wc-product-gallery-lightbox' );
    remove_theme_support( 'wc-product-gallery-slider' );
}
?>


问:
Should methods have the same preconditions as the methods they call?
I've recently had a few scenarios where small changes to code have resulted in changing preconditions across multiple classes and I was wondering if design by contract is supposed to be that way or not.

```<code>public Goal getNextGoal() {
    return goalStack.pop();
}
</code>```

If goalStack.pop() has a precondition that the stack isn't empty, then does getNextGoal() need to explicitly have the same precondition? It seems like inheriting the preconditions would make things brittle, and changing to a queue or other structure would change the preconditions to getNextGoal(), it's callers, and it's callers' callers. But it seems like not inheriting the preconditions would hide the contracts and the callers, and the callers' callers, wouldn't know about the preconditions.

So brittle code where all callers know and inherit the preconditions and postconditions of the code they call, or mysterious code where callers never know what the deeper preconditions and postconditions are?

答:
It depends on what your calling method does exactly. The important thing with preconditions is that the caller is responsible for fulfilling the preconditions.

So if callers of your GetNextGoal method should be responsible for providing a non-empty stack, then you should indeed also set preconditions on your GetNextGoal method. Clarity of preconditions is one of the huge advantages of Code Contracts, so I'd suggest you put them in all places where callers have to fulfill the preconditions.

If your code seems brittle however, it might be a sign that you need to refactor some code.

It seems like inheriting the
  preconditions would make things
  brittle, and changing to a queue or
  other structure would change the
  preconditions to getNextGoal(), it's
  callers, and it's callers' callers.

If you expose the queue to the callers and change it later ( to another structure, like you said ), it's callers would also have to change. This is usually a sign of brittle code.

If you would expose an interface instead of a specific queue implementation, your preconditions could also use the interface and you wouldn't have to change the preconditions every time your implementation changes. Thus resulting in less brittle code.

Body:
I've recently had a few scenarios where small changes to code have resulted in changing preconditions across multiple classes and I was wondering if design by contract is supposed to be that way or not.

public Goal getNextGoal() {
    return goalStack.pop();
}

If goalStack.pop() has a precondition that the stack isn't empty, then does getNextGoal() need to explicitly have the same precondition? It seems like inheriting the preconditions would make things brittle, and changing to a queue or other structure would change the preconditions to getNextGoal(), it's callers, and it's callers' callers. But it seems like not inheriting the preconditions would hide the contracts and the callers, and the callers' callers, wouldn't know about the preconditions.

So brittle code where all callers know and inherit the preconditions and postconditions of the code they call, or mysterious code where callers never know what the deeper preconditions and postconditions are?


问:
Fast random element from set - Python
I'm looking for a faster of way of sampling a single element at random from a large Python set. Below I've benchmarked three obvious examples. Is there a faster way of doing this?

```<code>import random
import time

test_set = set(["".join(["elem-", str(l)]) for l in range(0, 1000000)])

t0 = time.time()
random_element = random.choice(list(test_set))
print(time.time() - t0)

t0 = time.time()
random_element = random.sample(test_set, 1)
print(time.time() - t0)

t0 = time.time()
rand_idx = random.randrange(0, len(test_set)-1)
random_element = list(test_set)[rand_idx]
print(time.time() - t0)
</code>```

Output:

```<code>0.0692291259765625
0.06741929054260254
0.07094502449035645
</code>```

答:
You could use numpy and add it to your benchmarks.

```<code>import numpy
random_num = numpy.randit(0, 1000000)
element = 'elem-' + str(random_num)
test_array = numpy.array([x for x in test_set])
</code>```

Specifically, this is a piece of code that benchmarks the different methods:

```<code>random_choice_times = []
random_sample_times = []
random_randrange_times = []
numpy_choince_times = []
for i in range(0,10):
    t0 = time.time()
    random_element = random.choice(list(test_set))
    time_elps = time.time() - t0
    random_choice_times.append(time_elps)

    t0 = time.time()
    random_element = random.sample(test_set, 1)
    time_elps = time.time() - t0
    random_sample_times.append(time_elps)

    t0 = time.time()
    rand_idx = random.randrange(0, len(test_set)-1)
    random_element = list(test_set)[rand_idx]
    time_elps = time.time() - t0
    random_randrange_times.append(time_elps)

    t0 = time.time()
    random_num = numpy.random.choice(numpy.array(test_array))
    time_elps = time.time() - t0
    numpy_choince_times.append(time_elps)

print("Avg time for random.choice: ", sum(random_choice_times) /10)
print("Avg time for random.sample: ", sum(random_sample_times) /10)
print("Avg time for random.randrange: ", sum(random_randrange_times) /10)
print("Avg time for numpy.choice: ", sum(numpy_choince_times) /10)
</code>```

Here are the times

```<code>>>> Avg time for random.choice:  0.06497154235839844
>>> Avg time for random.sample:  0.06054067611694336
>>> Avg time for random.randrange:  0.05938301086425781
>>> Avg time for numpy.choice:  0.017636775970458984
</code>```

Title: Fast random element from set - Python

Body:
I'm looking for a faster of way of sampling a single element at random from a large Python set. Below I've benchmarked three obvious examples. Is there a faster way of doing this?

import random
import time

test_set = set(["".join(["elem-", str(l)]) for l in range(0, 1000000)])

t0 = time.time()
random_element = random.choice(list(test_set))
print(time.time() - t0)

t0 = time.time()
random_element = random.sample(test_set, 1)
print(time.time() - t0)

t0 = time.time()
rand_idx = random.randrange(0, len(test_set)-1)
random_element = list(test_set)[rand_idx]
print(time.time() - t0)

Output:

0.0692291259765625
0.06741929054260254
0.07094502449035645

Body:
You could use numpy and add it to your benchmarks.

import numpy
random_num = numpy.randit(0, 1000000)
element = 'elem-' + str(random_num)
test_array = numpy.array([x for x in test_set])

Specifically, this is a piece of code that benchmarks the different methods:

random_choice_times = []
random_sample_times = []
random_randrange_times = []
numpy_choince_times = []
for i in range(0,10):
    t0 = time.time()
    random_element = random.choice(list(test_set))
    time_elps = time.time() - t0
    random_choice_times.append(time_elps)

    t0 = time.time()
    random_element = random.sample(test_set, 1)
    time_elps = time.time() - t0
    random_sample_times.append(time_elps)

    t0 = time.time()
    rand_idx = random.randrange(0, len(test_set)-1)
    random_element = list(test_set)[rand_idx]
    time_elps = time.time() - t0
    random_randrange_times.append(time_elps)

    t0 = time.time()
    random_num = numpy.random.choice(numpy.array(test_array))
    time_elps = time.time() - t0
    numpy_choince_times.append(time_elps)

print("Avg time for random.choice: ", sum(random_choice_times) /10)
print("Avg time for random.sample: ", sum(random_sample_times) /10)
print("Avg time for random.randrange: ", sum(random_randrange_times) /10)
print("Avg time for numpy.choice: ", sum(numpy_choince_times) /10)

Here are the times

>>> Avg time for random.choice:  0.06497154235839844
>>> Avg time for random.sample:  0.06054067611694336
>>> Avg time for random.randrange:  0.05938301086425781
>>> Avg time for numpy.choice:  0.017636775970458984


问:
get all fields in object that have given word and transform all values of these fields
I have an object. like this, for example

{
    startDate: 2141242141,
    adress: '',
    endDate: 2141242141,
    billings: {
        startBillingDate: 2142421421421,
        endBillingDate: 2142421421421
    }
    amount: 100
}```

I need to get all fields those contain word "Date" (or "date") and convert them all into string date format.

Who can help please.

答:
You can loop throught these properties using Object.keys().

And for each property check if its value isn't an object and contains the date string using k.match(/date/i) so change it to a date value. Otherwise if it's an object do the same with its properties in a recursive way.

This is what you need:

```<code>function transformProperties(obj) {
  Object.keys(obj).forEach(function(k) {
    if ((typeof obj[k]) !== "object" && k.match(/date/i)) {
      obj[k] = new Date(obj[k]);
    } else if ((typeof obj[k]) == "object") {
      let sub = obj[k];
      transformProperties(sub);
    }
  });
}
</code>```

Demo:

var o = {
  startDate: 2141242141,
  adress: '',
  endDate: 2141242141,
  billings: {
    startBillingDate: 2142421421421,
    endBillingDate: 2142421421421
  },
  amount: 100
};

function transformProperties(obj) {
  Object.keys(obj).forEach(function(k) {
    if ((typeof obj[k]) !== "object" && k.match(/date/i)) {
      obj[k] = new Date(obj[k]);
    } else if ((typeof obj[k]) == "object") {
      let sub = obj[k];
      transformProperties(sub);
    }
  });
}

transformProperties(o);

console.log(o);```

Body:
I have an object. like this, for example

{
    startDate: 2141242141,
    adress: '',
    endDate: 2141242141,
    billings: {
        startBillingDate: 2142421421421,
        endBillingDate: 2142421421421
    }
    amount: 100
}

I need to get all fields those contain word "Date" (or "date") and convert them all into string date format.

Who can help please.

Body:
You can loop throught these properties using Object.keys().

And for each property check if its value isn't an object and contains the date string using k.match(/date/i) so change it to a date value. Otherwise if it's an object do the same with its properties in a recursive way.

This is what you need:

function transformProperties(obj) {
  Object.keys(obj).forEach(function(k) {
    if ((typeof obj[k]) !== "object" && k.match(/date/i)) {
      obj[k] = new Date(obj[k]);
    } else if ((typeof obj[k]) == "object") {
      let sub = obj[k];
      transformProperties(sub);
    }
  });
}

Demo:

var o = {
  startDate: 2141242141,
  adress: '',
  endDate: 2141242141,
  billings: {
    startBillingDate: 2142421421421,
    endBillingDate: 2142421421421
  },
  amount: 100
};

function transformProperties(obj) {
  Object.keys(obj).forEach(function(k) {
    if ((typeof obj[k]) !== "object" && k.match(/date/i)) {
      obj[k] = new Date(obj[k]);
    } else if ((typeof obj[k]) == "object") {
      let sub = obj[k];
      transformProperties(sub);
    }
  });
}

transformProperties(o);

console.log(o);


问:
evaluating javascript base10 to base2 conversion function
I wrote a simple function to turn a number that is in base 10 into a binary number. The function I've written is my best attempt using the simple tools I know of. I've looked up other ways of how to do this on this website and I haven't understood a good deal of it. I'm sure the function I've written is very strange but it seems to do the trick.

Here is a jsfiddle showing it in action:
https://jsfiddle.net/unpkt48e/

And here is the function code:

```<code>var toBinary = function(x) {

  x = parseInt(x);

  if (x < 0) {
    var k = '-'
    x = Math.sqrt(Math.pow(x, 2));
  }

  if (x == 0) {
    return 0;
  }

  var y = x;
  var g = [];

  while (Math.log2(y) >= 0) {
    var n = parseInt(Math.log2(y));
    g.push(n+1);
    y = y - Math.pow(2, n);
  }

  var binArray = [];
  for (var i = 0; i < g[0]; i++) {
    binArray.push(0);
  }
  for (var i = 0; i < g.length; i++) {
    binArray[binArray.length-g[i]] = 1;
  }

  var binary = binArray.join("");
  return (k || "") + binary;

};
</code>```

I don't have a lot of tools yet for evaluating this so my question is as follows:

What this function returns looks right, but how can I make sure what I'm getting is actually a binary number and not just a string that looks like a binary number. Am I missing a few key pieces? Or is my approach a dead end?

An additional question: Is there a built-in function in JS to do this for me? Mostly, this is a learning exercise for me so I'm still interested in producing a base10 to base2 number converting function.

答:
you can use toString() numObj.toString(base) pass base value as parameter , added Demo

var input = document.getElementById("decimal");
input.addEventListener("input", getBinary);

function getBinary() {
  var decimal = document.getElementById("decimal").value;
  var binary = Number(decimal).toString(2);
  document.getElementById("binary").innerHTML = binary;
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin-left: 20px;
  font-family: monospace;
  font-size: 18px;
}
p { display: inline-block; }</code>```

Enter a number here:

<input id="decimal">

This is that number but in binary:

```

Body:
I wrote a simple function to turn a number that is in base 10 into a binary number. The function I've written is my best attempt using the simple tools I know of. I've looked up other ways of how to do this on this website and I haven't understood a good deal of it. I'm sure the function I've written is very strange but it seems to do the trick.

Here is a jsfiddle showing it in action:
https://jsfiddle.net/unpkt48e/

And here is the function code:

var toBinary = function(x) {

  x = parseInt(x);

  if (x < 0) {
    var k = '-'
    x = Math.sqrt(Math.pow(x, 2));
  }

  if (x == 0) {
    return 0;
  }

  var y = x;
  var g = [];

  while (Math.log2(y) >= 0) {
    var n = parseInt(Math.log2(y));
    g.push(n+1);
    y = y - Math.pow(2, n);
  }

  var binArray = [];
  for (var i = 0; i < g[0]; i++) {
    binArray.push(0);
  }
  for (var i = 0; i < g.length; i++) {
    binArray[binArray.length-g[i]] = 1;
  }

  var binary = binArray.join("");
  return (k || "") + binary;

};

I don't have a lot of tools yet for evaluating this so my question is as follows:

What this function returns looks right, but how can I make sure what I'm getting is actually a binary number and not just a string that looks like a binary number. Am I missing a few key pieces? Or is my approach a dead end?

An additional question: Is there a built-in function in JS to do this for me? Mostly, this is a learning exercise for me so I'm still interested in producing a base10 to base2 number converting function.

Body:
you can use toString() numObj.toString(base) pass base value as parameter , added Demo

var input = document.getElementById("decimal");
input.addEventListener("input", getBinary);

function getBinary() {
  var decimal = document.getElementById("decimal").value;
  var binary = Number(decimal).toString(2);
  document.getElementById("binary").innerHTML = binary;
};

body {
  margin-left: 20px;
  font-family: monospace;
  font-size: 18px;
}
p { display: inline-block; }

<body>
<p>Enter a number here:</p>
<input id="decimal"><br><br>

<p>This is that number but in binary:</p><br>
<p id="binary" style="border: 1px solid black; height: 20px;min-width :100px"></p>
</body>


问:
How to return true labels of items when using predict_generator?
I am observing the output of my neural network with predict_generator() function but I am unable to see true labels of the predicted items. How can I implement a block to see the true labels of the input items?

```<code>test_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=45,
width_shift_range=0.25,
height_shift_range=0.25,
horizontal_flip=True,
)
test_generator = test_datagen.flow_from_directory(
    evaluate_path,
    target_size=(width, height),
    batch_size=batch_size,
    class_mode='categorical')

model.compile(optimizer=SGD(lr=0.0001, momentum=0.9),      loss='categorical_crossentropy', metrics=['accuracy'])
x = model.predict_generator(test_generator, val_samples=1)
print(x)
</code>```

答:
Try following function:

```<code>from six import next

def generator_with_true_classes(model, generator):
    while True:
        x, y = next(generator)
        yield x, model.predict(x), y
</code>```

It will yield original data, y_pred and y_true. Use it in a following way:

```<code>nb_of_samples = 0
nb_of_samples_to_compute = 100 # set your own value
for x, y_pred, y_true in generator_with_true_classes(model, test_generator):
    # do something with data, eg. print it.
    nb_of_samples += 1
    if nb_of_samples == nb_of_samples_to_compute:
         break
</code>```

Body:
I am observing the output of my neural network with predict_generator() function but I am unable to see true labels of the predicted items. How can I implement a block to see the true labels of the input items?

test_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=45,
width_shift_range=0.25,
height_shift_range=0.25,
horizontal_flip=True,
)
test_generator = test_datagen.flow_from_directory(
    evaluate_path,
    target_size=(width, height),
    batch_size=batch_size,
    class_mode='categorical')

model.compile(optimizer=SGD(lr=0.0001, momentum=0.9),      loss='categorical_crossentropy', metrics=['accuracy'])
x = model.predict_generator(test_generator, val_samples=1)
print(x)

Body:
Try following function:

from six import next

def generator_with_true_classes(model, generator):
    while True:
        x, y = next(generator)
        yield x, model.predict(x), y

It will yield original data, y_pred and y_true. Use it in a following way:

nb_of_samples = 0
nb_of_samples_to_compute = 100 # set your own value
for x, y_pred, y_true in generator_with_true_classes(model, test_generator):
    # do something with data, eg. print it.
    nb_of_samples += 1
    if nb_of_samples == nb_of_samples_to_compute:
         break


问:
HTML Form Value = Javascript variable
I want to display "something" on the HTML forms textbox
this value should be a javascript variable

var paramvalue = "something"
document.getElementById("client_id").value = paramvalue```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="login.php" method="post">
       <input type="hidden" name="clientID" id="client_id" value="" />
       <button>Login</button>
</form></code>```

答:
```<code>var textbox = document.getElementById('client_id');,
</code>```

then

```<code>textbox.value = paramvalue;
</code>```

will work.

Your issue is you have type='hidden' where it should be type='text' because hidden will not be visible. You also need to change it to run onload so you replace the value on page load.

```<code><script type="text/javascript">
   function init(){
      var paramvalue = "something"
      document.getElementById("client_id").value = paramvalue
   }
   body.addEventListener("load", init);
</script>

  <form action="login.php" method="post">
           <input type="text" name="clientID" id="client_id" value="" />
           <button>Login</button>
  </form>
</code>```

Alternatively, you can keep your code, change input type = "text" and just move your script below your HTML code/ Form, negating the need for the JS function and the event listener

The user could also do :

```<code><input type="text" name="clientID" id="client_id" value="" onload="init()" />
</code>```

Title: HTML Form Value = Javascript variable

Body:
I want to display "something" on the HTML forms textbox
this value should be a javascript variable

var paramvalue = "something"
document.getElementById("client_id").value = paramvalue

<form action="login.php" method="post">
       <input type="hidden" name="clientID" id="client_id" value="" />
       <button>Login</button>
</form>

Body:
var textbox = document.getElementById('client_id');,

then

textbox.value = paramvalue;

will work.

Your issue is you have type='hidden' where it should be type='text' because hidden will not be visible. You also need to change it to run onload so you replace the value on page load.

<script type="text/javascript">
   function init(){
      var paramvalue = "something"
      document.getElementById("client_id").value = paramvalue
   }
   body.addEventListener("load", init);
</script>

  <form action="login.php" method="post">
           <input type="text" name="clientID" id="client_id" value="" />
           <button>Login</button>
  </form>

Alternatively, you can keep your code, change input type = "text" and just move your script below your HTML code/ Form, negating the need for the JS function and the event listener

The user could also do :

<input type="text" name="clientID" id="client_id" value="" onload="init()" />


问:
Redirect to Link from Link saved in database
I am developing an Web Application in MVC.
I have added a link in Database eg:"www.google.com", I want user to redirect to Google on click.

I tried in many ways but getting the controller in address bar "eg:http://localhost:/Home/www.google.com"

View Code

```<code><table class="table" style="margin-top:10px;">
<tr>
    <th>
        Sr. No.
    </th>
    <th>
        Name
    </th>
    <th>
        Details
    </th>
    <th>
        Status
    </th>
    <th>
        Tracking No.
    </th>
    <th>
        Tack Order
    </th>
    <th>
        Ordered On
    </th>
</tr>

@{int row = 0;} @foreach (var item in Model) { if (item.PaymentSuccessfull == true) {
<tr>
    <td>
        @(row += 1)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.DeliveryDetail.FirstName)
    </td>
    <td>
        <a href="/Home/OrderDetails?orderId=@item.Id" orderid="1">Order Details</a>
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Status)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.TrackingId)
    </td>
    <td>
        //Here I want user to redirect to Google on click
        <a href="@Html.DisplayFor(modelItem => item.TrackingURL)" target="_blank">Track</a>
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.DateTime)
    </td>
</tr>
} }
</code>```

Help is appreciated.
Thanks in advance.

答:
You must store the protocol with the rest of the URL.

so:

www.google.com

becomes:

http://www.google.com

Body:
I am developing an Web Application in MVC.
I have added a link in Database eg:"www.google.com", I want user to redirect to Google on click.

I tried in many ways but getting the controller in address bar "eg:http://localhost:/Home/www.google.com"

View Code

        Sr. No.

        Name

        Details

        Status

        Tracking No.

        Tack Order

        Ordered On

@{int row = 0;} @foreach (var item in Model) { if (item.PaymentSuccessfull == true) {

        @(row += 1)

        @Html.DisplayFor(modelItem => item.DeliveryDetail.FirstName)

        Order Details

        @Html.DisplayFor(modelItem => item.Status)

        @Html.DisplayFor(modelItem => item.TrackingId)

        //Here I want user to redirect to Google on click
         item.TrackingURL)" target="_blank">Track

        @Html.DisplayFor(modelItem => item.DateTime)

} }

Help is appreciated.
Thanks in advance.


问:
How to start a thread to keep GUI refreshed?
I have window with button which triggers lengthy processing. I put processing in a separate thread, but -- to my surprise -- it makes GUI frozen anyway. No control is refreshed, I cannot even move the window.

So the question is how to start the thread, so it won't interfere with GUI, i.e. so the GUI would always be up to date (while processing I change the data, and GUI displays some pieces of it)?

That is how I start thread currectly:

```<code>        var thread = new Thread(doLearn);
        thread.IsBackground = true;
        thread.Start();
</code>```

Edit 1

Jon:

I don't use any locks at all

No Join calling

The UI thread is left alone -- it simply sits there

The processing is a big loop with math operations, not even allocating memory, on UI side I have controls with binding (WPF) to data, like the number of current iteration of the main loop. It should be refreshed each time the main loop "ticks". The counter of the loop is a property which triggers OnPropertyChanged with each change (classic WPF binding).

Edit 2 -- Almost there!

Ok, so Jon hit the nail at the head (who is surprises? ;-D) -- thank you! The problem comes from changing the Counter. When I used instead the Counter, local counter the GUI was refreshed -- I mean I could move windows, but... I couldn't see display of the Counter.

What I have here -- a WPF GUI, with such data-binding

```<code><TextBlock Text="{Binding Path=Counter"/>
</code>```

and I have Counter property of course which on each change sends event PropertyChanged. One of the listeners is for sure GUI.

So, Jon answer is valid "the answer", but from good design POV not exactly, because if GUI part has to pull up the info about Counter and update the display every (let's say) 3 seconds, why would anyone use data binding? For me such approach invalidates data binding idea.

I could, theoretically, pass to the processing thread the GUI dispatcher, and do all the sending in GUI thread, and it could work (I didn't try it) but it would mean tight coupling of non-GUI part and GUI part.

So far, I have no idea how to do it "right" way. The best guess so far is to create TimerDispatcher but not at GUI side but inside the processing library, and update Counter value immediately but do all the sending from time to time (I didn't try it yet though).

Small remark: I have more properties binded actually, like IsRunning, which is changed at the beginning and at the end of processing. And those changes DO affect the display correctly -- but the Counter change triggers around 3000 notifications in 3-4 seconds. So it looks like jamming problem. I did another test -- I killed the data binding partially, so notifications were sent, but GUI was not "receiving" them -- but was listening to them. In such case the GUI was also frozen.

So, I am still listening to all advices -- thank you advance for sharing.

Edit 3

The saga continues here:

How to do the processing and keep GUI refreshed using databinding?

答:
I put processing in a separate
  thread, but -- to my surprise -- it
  makes GUI frozen anyway.

I really hate to tell you, but then you did NOT put it into a separate thread. That simlpe.

There was a poster here that had a similar issue some time ago and through a mistake in his invoking code he basically had all processing before the thread started, with the thread jsut returning the result.

Body:
I have window with button which triggers lengthy processing. I put processing in a separate thread, but -- to my surprise -- it makes GUI frozen anyway. No control is refreshed, I cannot even move the window.

So the question is how to start the thread, so it won't interfere with GUI, i.e. so the GUI would always be up to date (while processing I change the data, and GUI displays some pieces of it)?

That is how I start thread currectly:

        var thread = new Thread(doLearn);
        thread.IsBackground = true;
        thread.Start();

Edit 1

Jon:

I don't use any locks at all

No Join calling

The UI thread is left alone -- it simply sits there

The processing is a big loop with math operations, not even allocating memory, on UI side I have controls with binding (WPF) to data, like the number of current iteration of the main loop. It should be refreshed each time the main loop "ticks". The counter of the loop is a property which triggers OnPropertyChanged with each change (classic WPF binding).

Edit 2 -- Almost there!

Ok, so Jon hit the nail at the head (who is surprises? ;-D) -- thank you! The problem comes from changing the Counter. When I used instead the Counter, local counter the GUI was refreshed -- I mean I could move windows, but... I couldn't see display of the Counter.

What I have here -- a WPF GUI, with such data-binding

<TextBlock Text="{Binding Path=Counter"/>

and I have Counter property of course which on each change sends event PropertyChanged. One of the listeners is for sure GUI.

So, Jon answer is valid "the answer", but from good design POV not exactly, because if GUI part has to pull up the info about Counter and update the display every (let's say) 3 seconds, why would anyone use data binding? For me such approach invalidates data binding idea.

I could, theoretically, pass to the processing thread the GUI dispatcher, and do all the sending in GUI thread, and it could work (I didn't try it) but it would mean tight coupling of non-GUI part and GUI part.

So far, I have no idea how to do it "right" way. The best guess so far is to create TimerDispatcher but not at GUI side but inside the processing library, and update Counter value immediately but do all the sending from time to time (I didn't try it yet though).

Small remark: I have more properties binded actually, like IsRunning, which is changed at the beginning and at the end of processing. And those changes DO affect the display correctly -- but the Counter change triggers around 3000 notifications in 3-4 seconds. So it looks like jamming problem. I did another test -- I killed the data binding partially, so notifications were sent, but GUI was not "receiving" them -- but was listening to them. In such case the GUI was also frozen.

So, I am still listening to all advices -- thank you advance for sharing.

Edit 3

The saga continues here:

How to do the processing and keep GUI refreshed using databinding?


问:
Take Snapshot using webcam and EmguCV in c# in console application
I need a simple, but complete, example of capturing a snapshot from Logitech USB webcam in a console application, but I don't find.

The next instruction not works.

```<code>private Capture _capture = null; //Camera
</code>```

Where is Capture definition? In the Emgu.CV.World not it is.

I use the 3.2.0 version of EmguCV.

http://www.emgu.com/wiki/index.php?title=Camera_Capture

Thank you in advance.

The error is the attached image

答:
Did you read the entire article? It is instantiated here:

```<code> private void SetupCapture(int Camera_Identifier)
    {
        //update the selected device
        CameraDevice = Camera_Identifier;

       //Dispose of Capture if it was created before
        if (_capture != null) _capture.Dispose();
        try
        {
            //Set up capture device
            _capture = new Capture(CameraDevice);
            _capture.ImageGrabbed += ProcessFrame;
        }
        catch (NullReferenceException excpt)
        {
            MessageBox.Show(excpt.Message);
        }
    }
</code>```

Hope this helps.

Doug

Body:
I need a simple, but complete, example of capturing a snapshot from Logitech USB webcam in a console application, but I don't find.

The next instruction not works.

private Capture _capture = null; //Camera

Where is Capture definition? In the Emgu.CV.World not it is.

I use the 3.2.0 version of EmguCV.

http://www.emgu.com/wiki/index.php?title=Camera_Capture

Thank you in advance.

The error is the attached image

Body:
Did you read the entire article? It is instantiated here:

 private void SetupCapture(int Camera_Identifier)
    {
        //update the selected device
        CameraDevice = Camera_Identifier;

       //Dispose of Capture if it was created before
        if (_capture != null) _capture.Dispose();
        try
        {
            //Set up capture device
            _capture = new Capture(CameraDevice);
            _capture.ImageGrabbed += ProcessFrame;
        }
        catch (NullReferenceException excpt)
        {
            MessageBox.Show(excpt.Message);
        }
    }

Hope this helps.

Doug


问:
curl command in java
First of all , i've already seen couple of documents, stackoverflow questions regarding the same ..I've my project specific question
When trying to run command :

```<code>   curl -u username:password https://example.com/xyz/abc
</code>```

from the mac terminal , I get my desired json format data.
But running the same command from java code , I get Unauthorised 401 error in console.
My code is :

```<code>    String username="myusername";
    String password="mypassword";
    String url="https://www.example.com/xyz/abc";
       String[] command = {"curl", "-u" ,"Accept:application/json", username, ":" , password , url};
        ProcessBuilder process = new ProcessBuilder(command);
        Process p;
        try
        {
            p = process.start();
             BufferedReader reader =  new BufferedReader(new InputStreamReader(p.getInputStream()));
                StringBuilder builder = new StringBuilder();
                String line = null;
                while ( (line = reader.readLine()) != null) {
                        builder.append(line);
                        builder.append(System.getProperty("line.separator"));
                }
                String result = builder.toString();
                System.out.print(result);

        }
        catch (IOException e)
        {   System.out.print("error");
            e.printStackTrace();
        }
</code>```

I get Unauthorised 401 error and bunch of html tags .
It seems like a repetitive question, but I've tried all the approaches.
I know alternative is using http response method, but particularly I want to use curl commands.
Thanks in advance.

答:
hey try this I had the same problem.
It worked in my terminal had the same error as yours.</p>

```<code>String[] command = {"curl", "-u" , username+ ":" + password , url};
</code>```

Title: curl command in java

Body:
First of all , i've already seen couple of documents, stackoverflow questions regarding the same ..I've my project specific question
When trying to run command :

   curl -u username:password https://example.com/xyz/abc

from the mac terminal , I get my desired json format data.
But running the same command from java code , I get Unauthorised 401 error in console.
My code is :

    String username="myusername";
    String password="mypassword";
    String url="https://www.example.com/xyz/abc";
       String[] command = {"curl", "-u" ,"Accept:application/json", username, ":" , password , url};
        ProcessBuilder process = new ProcessBuilder(command);
        Process p;
        try
        {
            p = process.start();
             BufferedReader reader =  new BufferedReader(new InputStreamReader(p.getInputStream()));
                StringBuilder builder = new StringBuilder();
                String line = null;
                while ( (line = reader.readLine()) != null) {
                        builder.append(line);
                        builder.append(System.getProperty("line.separator"));
                }
                String result = builder.toString();
                System.out.print(result);

        }
        catch (IOException e)
        {   System.out.print("error");
            e.printStackTrace();
        }

I get Unauthorised 401 error and bunch of html tags .
It seems like a repetitive question, but I've tried all the approaches.
I know alternative is using http response method, but particularly I want to use curl commands.
Thanks in advance.

Body:
hey try this I had the same problem.
It worked in my terminal had the same error as yours.

String[] command = {"curl", "-u" , username+ ":" + password , url};