问:
Zend Framework: Controllers in separate directories
I'm quite new in Zend framework, but quickly learning. I've encountered the following problem, but I don't really know if my solution is good :)

I've created an application which uses widgets. Widget is a class which implements Widget_Interface and is executed by Widget_Manager.

Widgets can be loaded via WidgetController (which calls Widget_Manager, etc). Now the problem I encountered is: widgets can also be configured, and to make the code more transparent, I'd like a widget to have its own controller (currently, it is only a class). But the problem is, I'd like all widget configurations to be addressed via WidgetController, and then passed to specific widget controller.

An example: let's say I've got a widget named 'scrobbler'. Now when configuring it in the UI, I'd like to make Ajax request with updated settings. I could make a request like http://myapp.com/scrobbler/update-info/, so the framework would run ScrobblerController and I'd process the information from here on.
My idea is to make a request on http://myapp.com/widget/update/scrobbler/, so the framework runs WidgetController. WidgetController would then call ScrobblerController and pass other parameters.

I'm aware of _forward() function in Zend_Controller, but I'd like to have widget controllers and my application's controllers separated (let's say application controllers in /application/controllers and widget controllers in /application/controllers/widgets).

Is it possible to make this and what do I have to add to the Zend framework configuration? Hope I didn't complicate too much :)

Nice day

Edit:
Solved this using modular structure, and moved common classes into root directory.

答:
You coud probably utilize Controller helpers instead of controllers in this case. So let's say that WidgetController is responsible for updating all types of widgets. The updateAction would need to find information on which widget type you wish to configure, this is the scrobbler parameter. You would need to name this parameter so it can be accessed easily. This can be done by either adding a route or adding the name before scrobbler in the uri.

Solution 1: Add a route:

In Bootstrap:

```<code>public function __initRoutes () {
    $route = new Zend_Controller_Router_Route(
        'widget/update/:type',
        array (
            'controller' => 'widget',
            'action' => 'update'
        ),
        array (
            'type' => '[a-z_-]*'
        )
    );
    /* @var $fc Zend_Controller_Front */
    $fc = $this->bootstrap('FrontController')->getResource('FrontController');
    /* @var $router Zend_Controller_Router_Rewrite */
    $router = $fc->getRouter();
    $router->addRoute('update-widget', $route);
}
</code>```

Solution 2: Add the parameter name in the uri:

Make requests to /widget/update/type/widgetName instead.

Now, in the WidgetController::updateAction, you can fetch the widget to update using $this->_getParam('type').

So the code could look something like:

```<code>class WidgetController extends Zend_Controller_Action
{
  public function updateAction ()
  {
     $widgetName = $this->_getParam('type');
     $this->view->result = $this->_helper->Widgets->update($widgetName);
  }
}

class App_Controller_Helper_Widgets extends Zend_Controller_Action_Helper
{
  public function update($widgetName)
  {
     $widgetManager = new App_Model_WidgetManager();
     $widget = $widgetManager->load($widgetName);
     $widget->setOptions($this->getRequest()->getParams());
     return $widget->save();
  }
}
</code>```

Body:
You coud probably utilize Controller helpers instead of controllers in this case. So let's say that WidgetController is responsible for updating all types of widgets. The updateAction would need to find information on which widget type you wish to configure, this is the scrobbler parameter. You would need to name this parameter so it can be accessed easily. This can be done by either adding a route or adding the name before scrobbler in the uri.

Solution 1: Add a route:

In Bootstrap:

public function __initRoutes () {
    $route = new Zend_Controller_Router_Route(
        'widget/update/:type',
        array (
            'controller' => 'widget',
            'action' => 'update'
        ),
        array (
            'type' => '[a-z_-]*'
        )
    );
    /* @var $fc Zend_Controller_Front */
    $fc = $this->bootstrap('FrontController')->getResource('FrontController');
    /* @var $router Zend_Controller_Router_Rewrite */
    $router = $fc->getRouter();
    $router->addRoute('update-widget', $route);
}

Solution 2: Add the parameter name in the uri:

Make requests to /widget/update/type/widgetName instead.

Now, in the WidgetController::updateAction, you can fetch the widget to update using $this->_getParam('type').

So the code could look something like:

class WidgetController extends Zend_Controller_Action
{
  public function updateAction ()
  {
     $widgetName = $this->_getParam('type');
     $this->view->result = $this->_helper->Widgets->update($widgetName);
  }
}

class App_Controller_Helper_Widgets extends Zend_Controller_Action_Helper
{
  public function update($widgetName)
  {
     $widgetManager = new App_Model_WidgetManager();
     $widget = $widgetManager->load($widgetName);
     $widget->setOptions($this->getRequest()->getParams());
     return $widget->save();
  }
}


来源: stackexchange

问:
need to check this col-md(col-sm-4 col-md-4 col-lg-4) clarification
I need 3*3 service box for my website with responsive.But alignment is not proper.each box in 1st row differs in 2nd row and last box is moving to 4th row.so need code for 3*3 box type.</p>

```<code>       <div class="col-sm-4 col-md-4 col-lg-4">
                    <div class="serviceBox_2">
                        <i class="fa fa-bell"></i>
                        <h3>Broadband Services</h3>
                        <p>Integer ultrices scelerisque nulla fringilla.
      Praesent leo massa, ullamcorper venenatis tempor.</p>
                    </div>
                </div>
                <div class="col-sm-4 col-md-4 col-lg-4">
                    <div class="serviceBox_2">
                        <i class="fa fa-briefcase"></i>
                        <h3>Dedicated Leased Line</h3>
                        <p>Integer ultrices scelerisque nulla fringilla.
     Praesent leo massa, ullamcorper venenatis tempor.</p>
                    </div>
                </div>
                <div class="col-sm-4 col-md-4 col-lg-4">
                    <div class="serviceBox_2">
                        <i class="fa fa-rocket"></i>
                        <h3>Dark Fibre</h3>
                        <p>Integer ultrices scelerisque nulla fringilla.
       Praesent leo massa, ullamcorper venenatis tempor.</p>
                    </div>
                </div>
            </div>

                <div class="col-sm-4 col-md-4 col-lg-4">
                    <div class="serviceBox_2">
                        <i class="fa fa-rocket"></i>
                        <h3>CCTV Installation</h3>
                        <p>Integer ultrices scelerisque nulla fringilla.
     Praesent leo massa, ullamcorper venenatis tempor.</p>
                    </div>

            <div class="col-sm-12 col-sm-offset-12 col-xs-12 col-md-12">

                    <div class="serviceBox_2">
                        <i class="fa fa-rocket"></i>
                        <h3>CCTV Installation</h3>
                        <p>Integer ultrices scelerisque nulla fringilla.
     Praesent leo massa, ullamcorper venenatis tempor.</p>
                    </div>

                </div>

            </div>
</code>```

答:
You are closing the second to last div incorrectly, making the last div a child of it. Also, Bootstrap provides a row class which can be helpful when making just that, rows.

```<code><div class="container">
    <div class="row">
        <div class="col-sm-4 col-md-4 col-lg-4">
            <div class="serviceBox_2">
                <i class="fa fa-bell"></i>
                <h3>Broadband Services</h3>
                <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
            </div>
        </div>
        <div class="col-sm-4 col-md-4 col-lg-4">
            <div class="serviceBox_2">
                <i class="fa fa-briefcase"></i>
                <h3>Dedicated Leased Line</h3>
                <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
            </div>
        </div>
        <div class="col-sm-4 col-md-4 col-lg-4">
            <div class="serviceBox_2">
                <i class="fa fa-rocket"></i>
                <h3>Dark Fibre</h3>
                <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-4 col-md-4 col-lg-4">
            <div class="serviceBox_2">
                <i class="fa fa-rocket"></i>
                <h3>CCTV Installation</h3>
                <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
            </div>
        </div>
        <div class="col-sm-12 col-sm-offset-12 col-xs-12 col-md-12">
            <div class="serviceBox_2">
                <i class="fa fa-rocket"></i>
                <h3>CCTV Installation</h3>
                <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
            </div>
        </div>
    </div>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need 3*3 service box for my website with responsive.But alignment is not proper.each box in 1st row differs in 2nd row and last box is moving to 4th row.so need code for 3*3 box type.

Broadband Services

Integer ultrices scelerisque nulla fringilla.
      Praesent leo massa, ullamcorper venenatis tempor.

Dedicated Leased Line

Integer ultrices scelerisque nulla fringilla.
     Praesent leo massa, ullamcorper venenatis tempor.

Dark Fibre

Integer ultrices scelerisque nulla fringilla.
       Praesent leo massa, ullamcorper venenatis tempor.

CCTV Installation

Integer ultrices scelerisque nulla fringilla.
     Praesent leo massa, ullamcorper venenatis tempor.

CCTV Installation

Integer ultrices scelerisque nulla fringilla.
     Praesent leo massa, ullamcorper venenatis tempor.

Body:
You are closing the second to last div incorrectly, making the last div a child of it. Also, Bootstrap provides a row class which can be helpful when making just that, rows.

<div class="container">
    <div class="row">
        <div class="col-sm-4 col-md-4 col-lg-4">
            <div class="serviceBox_2">
                <i class="fa fa-bell"></i>
                <h3>Broadband Services</h3>
                <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
            </div>
        </div>
        <div class="col-sm-4 col-md-4 col-lg-4">
            <div class="serviceBox_2">
                <i class="fa fa-briefcase"></i>
                <h3>Dedicated Leased Line</h3>
                <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
            </div>
        </div>
        <div class="col-sm-4 col-md-4 col-lg-4">
            <div class="serviceBox_2">
                <i class="fa fa-rocket"></i>
                <h3>Dark Fibre</h3>
                <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-4 col-md-4 col-lg-4">
            <div class="serviceBox_2">
                <i class="fa fa-rocket"></i>
                <h3>CCTV Installation</h3>
                <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
            </div>
        </div>
        <div class="col-sm-12 col-sm-offset-12 col-xs-12 col-md-12">
            <div class="serviceBox_2">
                <i class="fa fa-rocket"></i>
                <h3>CCTV Installation</h3>
                <p>Integer ultrices scelerisque nulla fringilla. Praesent leo massa, ullamcorper venenatis tempor.</p>
            </div>
        </div>
    </div>
</div>


问:
Call a function once page load after button click
There is a scenario where I need a function like xyz() to be called once a button on page is clicked and page is loaded using javascript/jquery.
I can't call xyz() directly on  or inside document.ready() or  $(window).on('load', function ()).
I need the function to be called once a button is clicked and page has loaded completely.
Below is working code on page load but not my requirement

```<code><body onload="xyz();">
    <form id="form1" runat="server">
        <div id="vizContainer" style="width: 800px; height: 700px;">
        </div>
    </form>
</body>
</code>```

Now below is my required code on button click and it is not working

```<code><body>
        <form id="form1" runat="server">
            <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="functiongetdata()" />
            <div id="vizContainer" style="width: 800px; height: 700px;">
            </div>
        </form>
    </body>
 <script type="text/javascript">
        function functiongetdata() {
            xyz();
        }
    </script>
</code>```

答:
Approach 1:

On window load function, update a hidden field or add a flag variable and set true

```<code> var myWindowIsLoaded = false
 $(window).on('load', function (){
    myWindowIsLoaded = true;
 });
</code>```

And then on the button click check the value

```<code>function xyz(){
 if(myWindowIsLoaded){
   // Do your stuff
 }
}
</code>```

Approach 2:

Add the function in the button click event on window load

```<code>$(window).on('load', function (){
  $("#myButton").click(xyz);
});
</code>```

Body:
There is a scenario where I need a function like xyz() to be called once a button on page is clicked and page is loaded using javascript/jquery.
I can't call xyz() directly on  or inside document.ready() or  $(window).on('load', function ()).
I need the function to be called once a button is clicked and page has loaded completely.
Below is working code on page load but not my requirement

    <form id="form1" runat="server">

    </form>

Now below is my required code on button click and it is not working

        <form id="form1" runat="server">
            <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="functiongetdata()" />

        </form>

Body:
Approach 1:

On window load function, update a hidden field or add a flag variable and set true

 var myWindowIsLoaded = false
 $(window).on('load', function (){
    myWindowIsLoaded = true;
 });

And then on the button click check the value

function xyz(){
 if(myWindowIsLoaded){
   // Do your stuff
 }
}

Approach 2:

Add the function in the button click event on window load

$(window).on('load', function (){
  $("#myButton").click(xyz);
});


问:
Java Scanner String input
I'm writing a program that uses an Event class, which has in it an instance of a calendar, and a description of type String.  The method to create an event uses a Scanner to take in a month, day, year, hour, minute, and a description.  The problem I'm having is that the Scanner.next() method only returns the first word before a space.  So if the input is "My Birthday", the description of that instance of an Event is simply "My".

I did some research and found that people used Scanner.nextLine() for this issue, but when I try this, it just skips past where the input should go.  Here is what a section of my code looks like:

```<code>System.out.print("Please enter the event description: ");
String input = scan.nextLine();
e.setDescription(input);
System.out.println("Event description" + e.description);
e.time.set(year, month-1, day, hour, min);
addEvent(e);
System.out.println("Event: "+ e.time.getTime());
</code>```

And this is the output I get:

```<code>Please enter the event description: Event description
Event: Thu Mar 22 11:11:48 EDT 2012
</code>```

It skips past the space to input the description String, and as a result, the description (which is initially set to a blank space - " "), is never changed.

How can I fix this?

答:
```<code>    Scanner ss = new Scanner(System.in);
    System.out.print("Enter the your Name : ");
    // Below Statement used for getting String including sentence
    String s = ss.nextLine();
   // Below Statement used for return the first word in the sentence
    String s = ss.next();
</code>```

Title: Java Scanner String input

Body:
I'm writing a program that uses an Event class, which has in it an instance of a calendar, and a description of type String.  The method to create an event uses a Scanner to take in a month, day, year, hour, minute, and a description.  The problem I'm having is that the Scanner.next() method only returns the first word before a space.  So if the input is "My Birthday", the description of that instance of an Event is simply "My".

I did some research and found that people used Scanner.nextLine() for this issue, but when I try this, it just skips past where the input should go.  Here is what a section of my code looks like:

System.out.print("Please enter the event description: ");
String input = scan.nextLine();
e.setDescription(input);
System.out.println("Event description" + e.description);
e.time.set(year, month-1, day, hour, min);
addEvent(e);
System.out.println("Event: "+ e.time.getTime());

And this is the output I get:

Please enter the event description: Event description
Event: Thu Mar 22 11:11:48 EDT 2012

It skips past the space to input the description String, and as a result, the description (which is initially set to a blank space - " "), is never changed.

How can I fix this?


问:
Apache Zeppelin postgres Null Pointer Exception
I try to connect a query a remote postgres database -

```<code>%psql.sql

select * from my_schema.my_table limit 5
</code>```

I have updated the interpreter values but I still get the following error -

java.lang.NullPointerException    at
  org.apache.zeppelin.postgresql.PostgreSqlInterpreter.executeSql(PostgreSqlInterpreter.java:201)
    at
  org.apache.zeppelin.postgresql.PostgreSqlInterpreter.interpret(PostgreSqlInterpreter.java:288)
    at
  org.apache.zeppelin.interpreter.ClassloaderInterpreter.interpret(ClassloaderInterpreter.java:57)
    at
  org.apache.zeppelin.interpreter.LazyOpenInterpreter.interpret(LazyOpenInterpreter.java:93)
    at
  org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer$InterpretJob.jobRun(RemoteInterpreterServer.java:302)
    at org.apache.zeppelin.scheduler.Job.run(Job.java:171)  at
  org.apache.zeppelin.scheduler.FIFOScheduler$1.run(FIFOScheduler.java:139)
    at
  java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at
  java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

I tried accessing from shell but got an error -

Process exited with an error: 2 (Exit value: 2)

I suspect that it relates to the fact that it tries to get a password. However the same command + the password works on my terminal.

The other related issue is that the properties in the interpreter does not contain database name. I add it as postgresql.database but I am not sure if this property is used.

Please let me know if you have any idea how to solve it, Thanks!

答:
Some of your credentials might be wrong. I had the username typed incorrectly and got something similar:

java.lang.NullPointerException at
org.apache.zeppelin.postgresql.PostgreSqlInterpreter.executeSql(PostgreSqlInterpreter.java:202)

Body:
I try to connect a query a remote postgres database -

%psql.sql

select * from my_schema.my_table limit 5

I have updated the interpreter values but I still get the following error -

java.lang.NullPointerException    at
  org.apache.zeppelin.postgresql.PostgreSqlInterpreter.executeSql(PostgreSqlInterpreter.java:201)
    at
  org.apache.zeppelin.postgresql.PostgreSqlInterpreter.interpret(PostgreSqlInterpreter.java:288)
    at
  org.apache.zeppelin.interpreter.ClassloaderInterpreter.interpret(ClassloaderInterpreter.java:57)
    at
  org.apache.zeppelin.interpreter.LazyOpenInterpreter.interpret(LazyOpenInterpreter.java:93)
    at
  org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer$InterpretJob.jobRun(RemoteInterpreterServer.java:302)
    at org.apache.zeppelin.scheduler.Job.run(Job.java:171)  at
  org.apache.zeppelin.scheduler.FIFOScheduler$1.run(FIFOScheduler.java:139)
    at
  java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at
  java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

I tried accessing from shell but got an error -

Process exited with an error: 2 (Exit value: 2)

I suspect that it relates to the fact that it tries to get a password. However the same command + the password works on my terminal.

The other related issue is that the properties in the interpreter does not contain database name. I add it as postgresql.database but I am not sure if this property is used.

Please let me know if you have any idea how to solve it, Thanks!


问:
Running a Powershell Script on Windows Service Failure. Works when run manually but not when service fails. Advice needed
So I have been working on a script to essentially send an email when a Service fails. The script works just fine, as I've run it manually from PowerShell. I get the email and everything checks out.
I then add this to the service:
Service Recovery Options

I tell it to run Powershell by linking to the executable:

```<code>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
</code>```

And the execute the following script:

```<code>-command C:\Users\andreand\Desktop\Sendmail.ps1
</code>```

As mentioned, I tried this manually in PowerShell, and I got an error. If I append the PowerShell location before the -command it works. Like so:

```<code>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command C:\Users\andreand\Desktop\Sendmail.ps1
</code>```

So this works if I run it manually, but when the service fails, nothing happens.
I trigger a failure by doing /taskkill /F /PID pid, and I can see the service has stopped.

What am I missing? I feel like I am so close and it is frustrating!

答:
As Mark Wragg here suggested, the problem lies in that I encrypted the string with one user account, but trying to decrypt it with another. By not using encryption for the password, it works.

I am still trying to figure out if there is any way to keep the encryption and have this work.

Furthermore, I am now trying to embed the failed service in the email subject field, but I am unsure how to do this. I have seen the Get-Service Cmdlet, but that seems to fetch an entire list, where I would just need it to read back the service that failed. Any help on this is most welcome.

EDIT: I have now found solutions to both encrypting the password and retrieving a list of services.
To encrypt the password, I used an encryption key. It goes something like this:

```<code># Change this location as necessary.
PS C:\Users\andreand> $File = 'C:\SomeLocation\Key.txt'

PS C:\Users\andreand> [Byte[]] $Key = (1..16)

# The password for the mail account / SMTP client.
PS C:\Users\andreand> $Password = 'Passwordgoeshere' | ConvertTo-SecureString -AsPlainText -Force

PS C:\Users\andreand> $Password | ConvertFrom-SecureString -Key $Key | Out-File
$File
</code>```

After this, I input the following into my script to retrieve the encrypted key:

```<code>$File = 'C:\SomeLocation\Key.txt'
[Byte[]] $Key = (1..16)
$Password = Get-Content $File | ConvertTo-SecureString -Key $Key
</code>```

For retrieving the list of services, I used the Get-Service cmdlet, but with some filtering to find the services I wanted. Like so:

```<code>$Services = Get-Service | Where-Object {$_.DisplayName -like "ServiceName*"}
</code>```

Body:
So I have been working on a script to essentially send an email when a Service fails. The script works just fine, as I've run it manually from PowerShell. I get the email and everything checks out.
I then add this to the service:
Service Recovery Options

I tell it to run Powershell by linking to the executable:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

And the execute the following script:

-command C:\Users\andreand\Desktop\Sendmail.ps1

As mentioned, I tried this manually in PowerShell, and I got an error. If I append the PowerShell location before the -command it works. Like so:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command C:\Users\andreand\Desktop\Sendmail.ps1

So this works if I run it manually, but when the service fails, nothing happens.
I trigger a failure by doing /taskkill /F /PID pid, and I can see the service has stopped.

What am I missing? I feel like I am so close and it is frustrating!

Body:
As Mark Wragg here suggested, the problem lies in that I encrypted the string with one user account, but trying to decrypt it with another. By not using encryption for the password, it works.

I am still trying to figure out if there is any way to keep the encryption and have this work.

Furthermore, I am now trying to embed the failed service in the email subject field, but I am unsure how to do this. I have seen the Get-Service Cmdlet, but that seems to fetch an entire list, where I would just need it to read back the service that failed. Any help on this is most welcome.

EDIT: I have now found solutions to both encrypting the password and retrieving a list of services.
To encrypt the password, I used an encryption key. It goes something like this:

# Change this location as necessary.
PS C:\Users\andreand> $File = 'C:\SomeLocation\Key.txt'

PS C:\Users\andreand> [Byte[]] $Key = (1..16)

# The password for the mail account / SMTP client.
PS C:\Users\andreand> $Password = 'Passwordgoeshere' | ConvertTo-SecureString -AsPlainText -Force

PS C:\Users\andreand> $Password | ConvertFrom-SecureString -Key $Key | Out-File
$File

After this, I input the following into my script to retrieve the encrypted key:

$File = 'C:\SomeLocation\Key.txt'
[Byte[]] $Key = (1..16)
$Password = Get-Content $File | ConvertTo-SecureString -Key $Key

For retrieving the list of services, I used the Get-Service cmdlet, but with some filtering to find the services I wanted. Like so:

$Services = Get-Service | Where-Object {$_.DisplayName -like "ServiceName*"}


问:
Returning a list from an iterated object in Python
I need help creating a list of iterated values. In this example, I want to get all odd numbers in the range of x. Then make a list from it:

```<code>def x_list(x):
    for i in range(x):
        if x%2==0:
            return i
</code>```

Since return stops the function after iterating through the first object, I'm unable to get the rest of the values and create a list from it.
Could you advice what I should use instead of "return"?
Thank you.

答:
With range, you can specify a stepping.

Therefore, all you need to do is:

```<code>def oddlist(x):
    return list(range(1, x, 2))
</code>```

If you don't actually need a list, and just an iterable will do, you could omit the list generation:

```<code>def oddlist(x):
    return range(1, x, 2)
</code>```

Body:
I need help creating a list of iterated values. In this example, I want to get all odd numbers in the range of x. Then make a list from it:

def x_list(x):
    for i in range(x):
        if x%2==0:
            return i

Since return stops the function after iterating through the first object, I'm unable to get the rest of the values and create a list from it.
Could you advice what I should use instead of "return"?
Thank you.

Body:
With range, you can specify a stepping.

Therefore, all you need to do is:

def oddlist(x):
    return list(range(1, x, 2))

If you don't actually need a list, and just an iterable will do, you could omit the list generation:

def oddlist(x):
    return range(1, x, 2)


问:
window.location = window.location not work in IE7
To refresh the page I am using window.location = window.location it works fine with FireFox but not with IE7

any Idea??

Thanx

答:
To reload the page, the good solution is to use window.location.reload();

You say this pops up for confirmation? This is probably because the page you are on was called with POST data sent.

If you want thoses POST data to be sent again, you don't have an easy solution to avoid this confirmation (maybe using ajax you could do it.... you'll spend a lot of time doing this).

If you don't want to POST again the data, than you don't want to reload the page ! You only want to load the same URL.

The problem is, if you say to your browser, load this URL, it will do nothing because the URL you're speaking of is already loaded (for most browser, no URL change -> no page reload) !!

An easy way to get around this problem can be to call the same URL plus a random query string value. This way the URL you call is a new one.

To do this a really easy way :

```<code>window.location.search += '&' + Math.random();
</code>```

One problem with this solution is that your URL can become messy....

Depending on your needs and your URLs, you can probably find a way to make very little changes, just enough to make the browser reload the page.

ContentLicense: CC BY-SA 2.5

Body:
To reload the page, the good solution is to use window.location.reload();

You say this pops up for confirmation? This is probably because the page you are on was called with POST data sent.

If you want thoses POST data to be sent again, you don't have an easy solution to avoid this confirmation (maybe using ajax you could do it.... you'll spend a lot of time doing this).

If you don't want to POST again the data, than you don't want to reload the page ! You only want to load the same URL.

The problem is, if you say to your browser, load this URL, it will do nothing because the URL you're speaking of is already loaded (for most browser, no URL change -> no page reload) !!

An easy way to get around this problem can be to call the same URL plus a random query string value. This way the URL you call is a new one.

To do this a really easy way :

window.location.search += '&' + Math.random();

One problem with this solution is that your URL can become messy....

Depending on your needs and your URLs, you can probably find a way to make very little changes, just enough to make the browser reload the page.


问:
CURRENT_TIME format in esql
What is the default format of the function CURRENT_TIME in esql and how do we change it as per our requirements(24 hr or 12 hr formats)</p>

答:
Maybe whats missing is the information, how you can configure if you want to have 24h or 12h format. You can get this information from the same source @DaveZiegler mentioned:

h  | hour in am or pm (1-12)

hh | hour in am or pm (01-12)

H  | hour of day in 24 hour form (0-23)

HH | hour of day in 24 hour form (00-23)

There's a footnote for 24h format:

24-hour fields might result in an ambiguous time, if specified with a conflicting am/pm field.

So use h, hh, H or HH with the patterns listed in the documentation.

Title: CURRENT_TIME format in esql


问:
Getting a TypeError (not a function) Jquery/Javascript
I'm trying to make a super simple "see more.." link. I was doing it before with a button, but it didn't work very well on mobile, so I've changed it to a link, but I'm getting this error:
jquery-3.1.1.min.js:2 jQuery.Deferred exception: seeMore is not a function TypeError: seeMore is not a function

Here's the code. I reckon it's just a stupid syntax error somewhere.

```<code>$(document).ready(function(){
    var seeMore = document.getElementById('seeMore');

    seeMore.onclick=seeMore();

    function seeMore(){
        document.getElementById('infoText').innerHTML= 'More text';
    };

    function seeLess(){
        document.getElementById('infoText').innerHTML= 'Less text';
    };
});
</code>```

and here's the linked seeMore ID.

```<code><a href="#" id="seeMore">See More</a>
</code>```

What's going on here??

答:
You use the same name for a property and a function and therefore its not clear what you mean.

You could rename one variable.

Also when you assign seeMore() with the brackets you assign the return value of the function and not the function itself. You need to remove the brackets.

You could also use the events which jquery provide to easily support all browsers.

```<code>$(document).ready(function(){
    var seeMoreElement = document.getElementById('seeMore');

    function seeMore(){
        document.getElementById('infoText').innerHTML= 'More text';
    };

    function seeLess(){
        document.getElementById('infoText').innerHTML= 'Less text';
    };

    $(seeMoreElement).click(seeMore);
});
</code>```

Body:
I'm trying to make a super simple "see more.." link. I was doing it before with a button, but it didn't work very well on mobile, so I've changed it to a link, but I'm getting this error:
jquery-3.1.1.min.js:2 jQuery.Deferred exception: seeMore is not a function TypeError: seeMore is not a function

Here's the code. I reckon it's just a stupid syntax error somewhere.

$(document).ready(function(){
    var seeMore = document.getElementById('seeMore');

    seeMore.onclick=seeMore();

    function seeMore(){
        document.getElementById('infoText').innerHTML= 'More text';
    };

    function seeLess(){
        document.getElementById('infoText').innerHTML= 'Less text';
    };
});

and here's the linked seeMore ID.

See More

What's going on here??

Body:
You use the same name for a property and a function and therefore its not clear what you mean.

You could rename one variable.

Also when you assign seeMore() with the brackets you assign the return value of the function and not the function itself. You need to remove the brackets.

You could also use the events which jquery provide to easily support all browsers.

$(document).ready(function(){
    var seeMoreElement = document.getElementById('seeMore');

    function seeMore(){
        document.getElementById('infoText').innerHTML= 'More text';
    };

    function seeLess(){
        document.getElementById('infoText').innerHTML= 'Less text';
    };

    $(seeMoreElement).click(seeMore);
});


问:
How to copy a file open from open dialog to other location in vb.net
I have start a new application that converts video to image and then image to gif
every thing is ok if i put my video in side of the same folder but if i not put my video in the same folder of the project the ffmpeg its says no such file or directory. wen i click to chose my file with openfiledialog , how can i copy or move my chose video to the correct directory in this case C:\avitogifconverter\

I have try to move the file to other location but wen i try to move the file to a different location its say i can not find the directory but the directory exist. what i have miss here this is the code

This is my code

```<code>Imports System.Diagnostics
Imports System.ComponentModel
Imports System
Imports System.IO
Imports System.IO.Compression
Imports System.Windows.Forms
Imports System.Net

Public Class Form1
Dim fpsx = 10
Dim video = ""
Dim startInfo As New ProcessStartInfo("ffmpeg.exe")
Dim frame As Long 'individual frames
Dim tempdir As String = "C:\avitogifconverter\" ' images temp directory
Dim DestPath As String = "C:\avitogifconverter\"
Public Declare Auto Function FindWindowNullClassName Lib "user32.dll" Alias "FindWindow" (ByVal lpClassname As Integer, ByVal lpWindownName As String) As Integer
Dim Counter As Integer = 0

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    My.Computer.FileSystem.CreateDirectory(tempdir)
    TextBox1.Text = "exp:-->video.avi or webm or flv"
    TextBox1.Clear()
    TextBox2.Text = fpsx

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    fpsx = TextBox2.Text
    TextBox2.Text = fpsx

    Dim p As Process = Process.Start("cmd", "/k ffmpeg.exe -i " + TextBox1.Text + " -framerate 5/1 -filter:v fps=" + TextBox2.Text + " C:\avitogifconverter\out%02d.jpg")
    p.WaitForExit()

    If p.HasExited Then
        MsgBox("The Extraction Are Finish...")
    End If

End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs)

End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

    If (OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK) Then
        'TextBox1.Text = OpenFileDialog1.FileName
        'TextBox1.Text = System.IO.Path.GetFileName(OpenFileDialog1.FileName)
        TextBox1.Text = System.IO.Path.GetDirectoryName(OpenFileDialog1.FileName)
        Dim newdialog As New OpenFileDialog()
        If newdialog.ShowDialog() = DialogResult.OK Then
            System.IO.File.Copy(newdialog.FileName, tempdir)
            MessageBox.Show(System.IO.Path.GetDirectoryName(newdialog.FileName) & "\" & System.IO.Path.GetFileName(newdialog.FileName))
        End If
    End If
    If TextBox1.Text = Nothing Then
        Return
    End If
    If TextBox1.Text <> Nothing Then
        'My.Computer.FileSystem.CopyFile(TextBox1.Text, DestPath)
    End If

End Sub

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim args As String 'declare args
    args = " -i C:\avitogifconverter\out%02d.jpg -r 10 C:\avitogifconverter\out.gif "
    'args = " -i C:\avitogifconverter\out%02d.jpg -c:v libx264 -r 30 -pix_fmt yuv420p C:\avitogifconverter\out.mp4 "
    Dim proc As New Process
    Dim proci As New ProcessStartInfo
    proci.FileName = My.Application.Info.DirectoryPath & "\ffmpeg.exe"
    proci.Arguments = args
    proci.WindowStyle = ProcessWindowStyle.Hidden
    proci.CreateNoWindow = True
    proci.UseShellExecute = False
    proc.StartInfo = proci
    proc.Start()
    Do Until proc.HasExited = True
        Me.Text = "Saving"
    Loop
    Me.Text = "your video done"

    MsgBox("Done")
    Dim directoryName As String = "C:\avitogifconverter\"
    For Each deleteFile In Directory.GetFiles(directoryName, "*.jpg", SearchOption.TopDirectoryOnly)
        File.Delete(deleteFile)
    Next

    'IO.Directory.Delete(tempdir, True)
End Sub

Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
    Form2.Show()

End Sub
End Class
</code>```

答: I don't know why you use 2 OpenFileDialog, but anyway you don't use the System.IO.File.Copy method correctly. Both of the parameters have to be FILE PATHS. Your mistake is that you use the second parameter as DIRECTORY PATH

Body:
I have start a new application that converts video to image and then image to gif
every thing is ok if i put my video in side of the same folder but if i not put my video in the same folder of the project the ffmpeg its says no such file or directory. wen i click to chose my file with openfiledialog , how can i copy or move my chose video to the correct directory in this case C:\avitogifconverter\

I have try to move the file to other location but wen i try to move the file to a different location its say i can not find the directory but the directory exist. what i have miss here this is the code

This is my code

Imports System.Diagnostics
Imports System.ComponentModel
Imports System
Imports System.IO
Imports System.IO.Compression
Imports System.Windows.Forms
Imports System.Net

Public Class Form1
Dim fpsx = 10
Dim video = ""
Dim startInfo As New ProcessStartInfo("ffmpeg.exe")
Dim frame As Long 'individual frames
Dim tempdir As String = "C:\avitogifconverter\" ' images temp directory
Dim DestPath As String = "C:\avitogifconverter\"
Public Declare Auto Function FindWindowNullClassName Lib "user32.dll" Alias "FindWindow" (ByVal lpClassname As Integer, ByVal lpWindownName As String) As Integer
Dim Counter As Integer = 0

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    My.Computer.FileSystem.CreateDirectory(tempdir)
    TextBox1.Text = "exp:-->video.avi or webm or flv"
    TextBox1.Clear()
    TextBox2.Text = fpsx

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    fpsx = TextBox2.Text
    TextBox2.Text = fpsx

    Dim p As Process = Process.Start("cmd", "/k ffmpeg.exe -i " + TextBox1.Text + " -framerate 5/1 -filter:v fps=" + TextBox2.Text + " C:\avitogifconverter\out%02d.jpg")
    p.WaitForExit()

    If p.HasExited Then
        MsgBox("The Extraction Are Finish...")
    End If

End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs)

End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

    If (OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK) Then
        'TextBox1.Text = OpenFileDialog1.FileName
        'TextBox1.Text = System.IO.Path.GetFileName(OpenFileDialog1.FileName)
        TextBox1.Text = System.IO.Path.GetDirectoryName(OpenFileDialog1.FileName)
        Dim newdialog As New OpenFileDialog()
        If newdialog.ShowDialog() = DialogResult.OK Then
            System.IO.File.Copy(newdialog.FileName, tempdir)
            MessageBox.Show(System.IO.Path.GetDirectoryName(newdialog.FileName) & "\" & System.IO.Path.GetFileName(newdialog.FileName))
        End If
    End If
    If TextBox1.Text = Nothing Then
        Return
    End If
    If TextBox1.Text <> Nothing Then
        'My.Computer.FileSystem.CopyFile(TextBox1.Text, DestPath)
    End If

End Sub

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim args As String 'declare args
    args = " -i C:\avitogifconverter\out%02d.jpg -r 10 C:\avitogifconverter\out.gif "
    'args = " -i C:\avitogifconverter\out%02d.jpg -c:v libx264 -r 30 -pix_fmt yuv420p C:\avitogifconverter\out.mp4 "
    Dim proc As New Process
    Dim proci As New ProcessStartInfo
    proci.FileName = My.Application.Info.DirectoryPath & "\ffmpeg.exe"
    proci.Arguments = args
    proci.WindowStyle = ProcessWindowStyle.Hidden
    proci.CreateNoWindow = True
    proci.UseShellExecute = False
    proc.StartInfo = proci
    proc.Start()
    Do Until proc.HasExited = True
        Me.Text = "Saving"
    Loop
    Me.Text = "your video done"

    MsgBox("Done")
    Dim directoryName As String = "C:\avitogifconverter\"
    For Each deleteFile In Directory.GetFiles(directoryName, "*.jpg", SearchOption.TopDirectoryOnly)
        File.Delete(deleteFile)
    Next

    'IO.Directory.Delete(tempdir, True)
End Sub

Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
    Form2.Show()

End Sub
End Class


问:
Rails split sentence into separate words but substitute certain words
What the goal is

```<code><span>I</span>
<span>helped</span>
<span>the</span>
<span class="highlighted">Adidas</span>
<span class="highlighted">brand</span>
<span>rebuild</span>
<span>their</span>
<span>design</span>
<span>system</span>
</code>```

Got a Rails project I'm working on. I've got data that forms a sentence like so:

```<code>sentence = 'I helped Adidas rebuild their design system'
</code>```

I can separate the words with sentence.split(/\W+/) and I get:

```<code>[I] [helped] [Adidas] [rebuild] [their] [design] [system]
</code>```

But I would like to highlight the word Adidas by wrapping it in a class.

Sometimes that highlighted word can be a combination of words like Adidas brand

For that I tried doing:

```<code>sentence.sub(sentenceHighlight, "<span>#{sentenceHighlight}</span>")
</code>```

Which gives me:

```<code>I helped the <span>Adidas brand</span> rebuild their design system
</code>```

While that works fine I still need each of the words to be separate like in the example above.

Does anyone know how I can combine the two methods nicely in a clean code?

答:
You could do something like this:</p>

```<code>sentence = 'I helped Adidas brand rebuild their design system'
words  = ["Adidas", "brand"]

sentence = sentence.split(/\W+/)
sentence.map! do |word|
  words.include?(word) ? "<span class='highlight'>#{word}</span>" : "<span>#{word}</span>"
end

puts sentence
# =>
<span>I</span>
<span>helped</span>
<span class='highlight'>Adidas</span>
<span class='highlight'>brand</span>
<span>rebuild</span>
<span>their</span>
<span>design</span>
<span>system</span>
</code>```

Body:
What the goal is

I
helped
the
Adidas
brand
rebuild
their
design
system

Got a Rails project I'm working on. I've got data that forms a sentence like so:

sentence = 'I helped Adidas rebuild their design system'

I can separate the words with sentence.split(/\W+/) and I get:

[I] [helped] [Adidas] [rebuild] [their] [design] [system]

But I would like to highlight the word Adidas by wrapping it in a class.

Sometimes that highlighted word can be a combination of words like Adidas brand

For that I tried doing:

sentence.sub(sentenceHighlight, "#{sentenceHighlight}")

Which gives me:

I helped the Adidas brand rebuild their design system

While that works fine I still need each of the words to be separate like in the example above.

Does anyone know how I can combine the two methods nicely in a clean code?

Body:
You could do something like this:

sentence = 'I helped Adidas brand rebuild their design system'
words  = ["Adidas", "brand"]

sentence = sentence.split(/\W+/)
sentence.map! do |word|
  words.include?(word) ? "<span class='highlight'>#{word}</span>" : "<span>#{word}</span>"
end

puts sentence
# =>
<span>I</span>
<span>helped</span>
<span class='highlight'>Adidas</span>
<span class='highlight'>brand</span>
<span>rebuild</span>
<span>their</span>
<span>design</span>
<span>system</span>


问:
Unable to write or append data into csv in imacros
I'm extracting some data using imacros, and trying to append that data into a csv.
This is my code for extraction

```<code>'Gives me a numeric value(e.g  14)
TAG POS=1 TYPE=span ATTR=CLASS:proPriceField&&TXT:* EXTRACT=TXT
SET !EXTRACT EVAL("'{{!EXTRACT}}'.match(/[0-9,]+/);")

'Gives me a numeric value(e.g  2456)
TAG POS=1 TYPE=span ATTR=CLASS:sqrPriceField&&TXT:* EXTRACT=TXT
SET abc EVAL("'{{!EXTRACT}}'.match(/[0-9,]+/);")

'Gives me a text value(e.g "Kalyan")
TAG POS=1 TYPE=span ATTR=CLASS:localityFirst&&TXT:* EXTRACT=TXT

'Gives me lattiude from a link
TAG POS=2 TYPE=a ATTR=class:stop-propagation&&TXT:* EXTRACT=HTM
SET lat EVAL("'{{!EXTRACT}}'.match(/\?(lat=.+?)&/)[1];")

'Gives me longitude from a link
SET longt EVAL("var regex = /longt=(\\d+(?:\\.\\d+)?)/g; var str = '{{!EXTRACT}}';str.match(regex)[1];")

SAVEAS TYPE=!EXTRACT FOLDER=* FILE=temp.csv
</code>```

This is the link from where I'm extracting data.

I'm expecting data should be appended in the following format

```<code>ProPrice   SqrPrice  Locality    Lat      Longt
 14        2456       Kalyan    19.456    17.897
</code>```

But the above code gives error "reject is not defined, line: 20 (Error code: -1001)" while writing data in csv, Any suggestion on why is it happening. Any help would be much appreciated.Thanks

答:
I corrected your code a little:</p>

```<code>'Gives me a numeric value(e.g  14)
TAG POS=1 TYPE=span ATTR=CLASS:proPriceField&&TXT:* EXTRACT=TXT
SET ProPrice EVAL("'{{!EXTRACT}}'.match(/[0-9,]+/);")
SET !EXTRACT NULL

'Gives me a numeric value(e.g  2456)
TAG POS=1 TYPE=span ATTR=CLASS:sqrPriceField&&TXT:* EXTRACT=TXT
SET SqrPrice EVAL("'{{!EXTRACT}}'.match(/[0-9,]+/);")
SET !EXTRACT NULL

'Gives me a text value(e.g "Kalyan")
TAG POS=1 TYPE=span ATTR=CLASS:localityFirst&&TXT:* EXTRACT=TXT
SET Locality {{!EXTRACT}}
SET !EXTRACT NULL

'Gives me lattiude from a link
TAG POS=2 TYPE=a ATTR=class:stop-propagation&&TXT:* EXTRACT=HTM
SET lat EVAL("'{{!EXTRACT}}'.match(/\?(lat=.+?)&/)[1];")

'Gives me longitude from a link
SET longt EVAL("var regex = /longt=(\\d+(?:\\.\\d+)?)/g; var str = '{{!EXTRACT}}';str.match(regex)[1];")

SET !EXTRACT {{ProPrice}}[EXTRACT]{{SqrPrice}}[EXTRACT]{{Locality}}[EXTRACT]{{lat}}[EXTRACT]{{longt}}

SAVEAS TYPE=EXTRACT FOLDER=* FILE=temp.csv
</code>```

Body:
I'm extracting some data using imacros, and trying to append that data into a csv.
This is my code for extraction

'Gives me a numeric value(e.g  14)
TAG POS=1 TYPE=span ATTR=CLASS:proPriceField&&TXT:* EXTRACT=TXT
SET !EXTRACT EVAL("'{{!EXTRACT}}'.match(/[0-9,]+/);")

'Gives me a numeric value(e.g  2456)
TAG POS=1 TYPE=span ATTR=CLASS:sqrPriceField&&TXT:* EXTRACT=TXT
SET abc EVAL("'{{!EXTRACT}}'.match(/[0-9,]+/);")

'Gives me a text value(e.g "Kalyan")
TAG POS=1 TYPE=span ATTR=CLASS:localityFirst&&TXT:* EXTRACT=TXT

'Gives me lattiude from a link
TAG POS=2 TYPE=a ATTR=class:stop-propagation&&TXT:* EXTRACT=HTM
SET lat EVAL("'{{!EXTRACT}}'.match(/\?(lat=.+?)&/)[1];")

'Gives me longitude from a link
SET longt EVAL("var regex = /longt=(\\d+(?:\\.\\d+)?)/g; var str = '{{!EXTRACT}}';str.match(regex)[1];")

SAVEAS TYPE=!EXTRACT FOLDER=* FILE=temp.csv

This is the link from where I'm extracting data.

I'm expecting data should be appended in the following format

ProPrice   SqrPrice  Locality    Lat      Longt
 14        2456       Kalyan    19.456    17.897

But the above code gives error "reject is not defined, line: 20 (Error code: -1001)" while writing data in csv, Any suggestion on why is it happening. Any help would be much appreciated.Thanks

Body:
I corrected your code a little:

'Gives me a numeric value(e.g  14)
TAG POS=1 TYPE=span ATTR=CLASS:proPriceField&&TXT:* EXTRACT=TXT
SET ProPrice EVAL("'{{!EXTRACT}}'.match(/[0-9,]+/);")
SET !EXTRACT NULL

'Gives me a numeric value(e.g  2456)
TAG POS=1 TYPE=span ATTR=CLASS:sqrPriceField&&TXT:* EXTRACT=TXT
SET SqrPrice EVAL("'{{!EXTRACT}}'.match(/[0-9,]+/);")
SET !EXTRACT NULL

'Gives me a text value(e.g "Kalyan")
TAG POS=1 TYPE=span ATTR=CLASS:localityFirst&&TXT:* EXTRACT=TXT
SET Locality {{!EXTRACT}}
SET !EXTRACT NULL

'Gives me lattiude from a link
TAG POS=2 TYPE=a ATTR=class:stop-propagation&&TXT:* EXTRACT=HTM
SET lat EVAL("'{{!EXTRACT}}'.match(/\?(lat=.+?)&/)[1];")

'Gives me longitude from a link
SET longt EVAL("var regex = /longt=(\\d+(?:\\.\\d+)?)/g; var str = '{{!EXTRACT}}';str.match(regex)[1];")

SET !EXTRACT {{ProPrice}}[EXTRACT]{{SqrPrice}}[EXTRACT]{{Locality}}[EXTRACT]{{lat}}[EXTRACT]{{longt}}

SAVEAS TYPE=EXTRACT FOLDER=* FILE=temp.csv


问:
Connecting Processmaker 3.2 (bitnami installer) to sql server
How can I connect processmaker 3 to sql server database ?

It seems that mssql functions family deprecated from php but codes of processmaker did not updated yet !

what i did until now is explained here

答:
Finally I found a solution !
And since we owe to "open source" :) I posted an answer to processmaker forum

Best wishes !


问:
How do I remove JSON form JSON array with repeated key-value
I have a JSON as follows:

```<code>[{"name": "John", "id": 1},
 {"name": "Don", "id": 2},
 {"name": "Tom", "id": 3},
 {"name": "NewJohn", "id": 1},
 {"name": "Tim", "id": 4}]
</code>```

I want to first identify if key "id" has same value. If yes, I want to remove previous JSON with the same "id" so that I get following JSON with unique "id" values in the JSON Array.

```<code>[{"name": "Don", "id": 2},
 {"name": "Tom", "id": 3},
 {"name": "NewJohn", "id": 1},
 {"name": "Tim", "id": 4}]
</code>```

How do I achieve this in javascript?

答:
Using two for loop I delete the previous id property.

var data=[{"name": "John", "id": 1},
 {"name": "Don", "id": 2},
 {"name": "Tom", "id": 3},
 {"name": "NewJohn", "id": 1},
 {"name": "Tim", "id": 4}];

function deleteJsonProperty(dataJson){
for(var i=0;i<dataJson.length;i++){
  for(var z=i+1;z<dataJson.length;z++){
  if(dataJson[i].id===dataJson[z].id){
    delete dataJson[i].id;
  }
  }
}
  return dataJson;
}
console.log(deleteJsonProperty(data));```

Body:
I have a JSON as follows:

[{"name": "John", "id": 1},
 {"name": "Don", "id": 2},
 {"name": "Tom", "id": 3},
 {"name": "NewJohn", "id": 1},
 {"name": "Tim", "id": 4}]

I want to first identify if key "id" has same value. If yes, I want to remove previous JSON with the same "id" so that I get following JSON with unique "id" values in the JSON Array.

[{"name": "Don", "id": 2},
 {"name": "Tom", "id": 3},
 {"name": "NewJohn", "id": 1},
 {"name": "Tim", "id": 4}]

How do I achieve this in javascript?


问:
Grouping and remove from list
I have following type

```<code>public class Parameter
{
   public string Name {get;set;}
   public string PathType {get;set;}
}
</code>```

My parameter list like:

```<code>List<Parameter> params = new List<Parameter>();
params.Add(new Parameter{ Name ="A", PathType ="path" });
params.Add(new Parameter{ Name ="B", PathType ="query" });
params.Add(new Parameter{ Name ="C", PathType ="path" });
params.Add(new Parameter{ Name ="C", PathType ="query" });
params.Add(new Parameter{ Name ="D", PathType ="path" });
params.Add(new Parameter{ Name ="D", PathType ="query" });
params.Add(new Parameter{ Name ="D", PathType ="body" });
</code>```

I need to find parameters that have the same Name (like: C and D) where PathType equals path and query. Sorry for my English, it is a little bit difficult to explain. I want to find

```<code> Name ="C", PathType ="path"
 Name ="C", PathType ="query"
 Name ="D", PathType ="path"
 Name ="D", PathType ="query"
</code>```

Then remove all where PathType = "query". Finally result should be

```<code>Name ="A", PathType ="path"
Name ="B", PathType ="query"
Name ="C", PathType ="path"
Name ="D", PathType ="path"
Name ="D", PathType ="body"
</code>```

My code

```<code>var groupedParams = params.GroupBy(a => a.Name, StringComparer.InvariantCultureIgnoreCase).ToDictionary(t => t.Key);
foreach (var parameter in params) {
    if (groupedParams.ContainsKey(parameter.Name)) {
        var temp = groupedParams[parameter.Name];
        if (temp.Count(x => x.PathType.ToLower() == "path") == 1 && temp.Count(x => x.PathType.ToLower() == "query") == 1) {
            params.Remove(parameter);
        }
    }
}
</code>```

I need to group by name but remove only when there are path and query for that name.
Please suggest how can I do in in other way? Thanks

答:
Well, first of all, you can't use params as variable's name because it's C# instruction.

Next. As I understand you want to have cycles. Ok, as I noted above, you can't modify collection (papram in your case) inside foreach loop body. You can use something like this:

```<code>var groupedParams = _params.GroupBy(a => a.Name, StringComparer.InvariantCultureIgnoreCase).ToDictionary(t => t.Key);
int i = 0;
while (i != _params.Count)
{
    if (groupedParams.ContainsKey(parameter.Name))
    {
        var temp = groupedParams[parameter.Name];
        if (temp.Count(x => x.PathType.ToLower() == "path") == 1 && temp.Count(x => x.PathType.ToLower() == "query") == 1)
        {
            params.RemoveAt(i);
            continue;
        }
    }
    i++;
}
</code>```

I've just rename params to _params to make it more correct. If params is just Parametr[] replace _params.Count with _params.Length.

Title: Grouping and remove from list

Body:
I have following type

public class Parameter
{
   public string Name {get;set;}
   public string PathType {get;set;}
}

My parameter list like:

List<Parameter> params = new List<Parameter>();
params.Add(new Parameter{ Name ="A", PathType ="path" });
params.Add(new Parameter{ Name ="B", PathType ="query" });
params.Add(new Parameter{ Name ="C", PathType ="path" });
params.Add(new Parameter{ Name ="C", PathType ="query" });
params.Add(new Parameter{ Name ="D", PathType ="path" });
params.Add(new Parameter{ Name ="D", PathType ="query" });
params.Add(new Parameter{ Name ="D", PathType ="body" });

I need to find parameters that have the same Name (like: C and D) where PathType equals path and query. Sorry for my English, it is a little bit difficult to explain. I want to find

 Name ="C", PathType ="path"
 Name ="C", PathType ="query"
 Name ="D", PathType ="path"
 Name ="D", PathType ="query"

Then remove all where PathType = "query". Finally result should be

Name ="A", PathType ="path"
Name ="B", PathType ="query"
Name ="C", PathType ="path"
Name ="D", PathType ="path"
Name ="D", PathType ="body"

My code

var groupedParams = params.GroupBy(a => a.Name, StringComparer.InvariantCultureIgnoreCase).ToDictionary(t => t.Key);
foreach (var parameter in params) {
    if (groupedParams.ContainsKey(parameter.Name)) {
        var temp = groupedParams[parameter.Name];
        if (temp.Count(x => x.PathType.ToLower() == "path") == 1 && temp.Count(x => x.PathType.ToLower() == "query") == 1) {
            params.Remove(parameter);
        }
    }
}

I need to group by name but remove only when there are path and query for that name.
Please suggest how can I do in in other way? Thanks

Body:
Well, first of all, you can't use params as variable's name because it's C# instruction.

Next. As I understand you want to have cycles. Ok, as I noted above, you can't modify collection (papram in your case) inside foreach loop body. You can use something like this:

var groupedParams = _params.GroupBy(a => a.Name, StringComparer.InvariantCultureIgnoreCase).ToDictionary(t => t.Key);
int i = 0;
while (i != _params.Count)
{
    if (groupedParams.ContainsKey(parameter.Name))
    {
        var temp = groupedParams[parameter.Name];
        if (temp.Count(x => x.PathType.ToLower() == "path") == 1 && temp.Count(x => x.PathType.ToLower() == "query") == 1)
        {
            params.RemoveAt(i);
            continue;
        }
    }
    i++;
}

I've just rename params to _params to make it more correct. If params is just Parametr[] replace _params.Count with _params.Length.


问:
Updating ObservableCollection bound to Pivot crashes for SelectedIndex >= 2 (wp7)
I have an observableCollection bound to a pivot control in my UI. When I try to update the collection (clear() items and recreate) everything works fine unless the selectedIndex of the pivot control is bigger or equal to 2.

In that case I get an ArgumentOutOfRange exception when I try to call Add() to the observable collection. It is very strange.

I tried creating a new observable collection and then Add() items there, this seems to work but I doesn't refresh the UI unless I call my update function twice.

What can be wrong? Is this a bug?

答:
To try and save load and performacne overhead, the framework only loads the currently displayed pivot and the ones either side. The other items are delay loaded when the neighbouring item is displayed. As a consequence of this you can experience issues when trying to set the SelectedItem to an item which hasn't been loaded or the page hasn't finished loading fully.

If you can share some code to demonstrate what you're trying to do we may be able to provide some more specific help.


问:
Remove Server Response Header IIS7
Is there any way to remove "Server" response header from IIS7? There are some articles showing that using HttpModules we can achieve the same thing. This will be helpful if we don't have admin right to server. Also I don't want to write ISAPI filter.

I have admin rights to my server. So I don't want to do the above stuff. So, please help me to do the same.

答:
In IIS 10, we use a similar solution to Drew's approach, i.e.:

```<code>using System;
using System.Web;

namespace Common.Web.Modules.Http
{
    /// <summary>
    /// Sets custom headers in all requests (e.g. "Server" header) or simply remove some.
    /// </summary>
    public class CustomHeaderModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.PreSendRequestHeaders += OnPreSendRequestHeaders;
        }

        public void Dispose() { }

        /// <summary>
        /// Event handler that implements the desired behavior for the PreSendRequestHeaders event,
        /// that occurs just before ASP.NET sends HTTP headers to the client.
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnPreSendRequestHeaders(object sender, EventArgs e)
        {
            //HttpContext.Current.Response.Headers.Remove("Server");
            HttpContext.Current.Response.Headers.Set("Server", "MyServer");
        }
    }
}
</code>```

And obviously add a reference to that dll in your project(s) and also the module in the config(s) you want:

<system.webServer>
    <modules>

      <add name="CustomHeaderModule" type="Common.Web.Modules.Http.CustomHeaderModule" />
    </modules>
</system.webServer>```

IMPORTANT NOTE1: This solution needs an application pool set as integrated;

IMPORTANT NOTE2: All responses within the web app will be affected by this (css and js included);

OwnerDisplayName: ram

LastEditorDisplayName: ram

Title: Remove Server Response Header IIS7

Body:
In IIS 10, we use a similar solution to Drew's approach, i.e.:

using System;
using System.Web;

namespace Common.Web.Modules.Http
{
    /// <summary>
    /// Sets custom headers in all requests (e.g. "Server" header) or simply remove some.
    /// </summary>
    public class CustomHeaderModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.PreSendRequestHeaders += OnPreSendRequestHeaders;
        }

        public void Dispose() { }

        /// <summary>
        /// Event handler that implements the desired behavior for the PreSendRequestHeaders event,
        /// that occurs just before ASP.NET sends HTTP headers to the client.
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnPreSendRequestHeaders(object sender, EventArgs e)
        {
            //HttpContext.Current.Response.Headers.Remove("Server");
            HttpContext.Current.Response.Headers.Set("Server", "MyServer");
        }
    }
}

And obviously add a reference to that dll in your project(s) and also the module in the config(s) you want:

<system.webServer>
    <modules>
      <!--Use http module to remove/customize IIS "Server" header-->
      <add name="CustomHeaderModule" type="Common.Web.Modules.Http.CustomHeaderModule" />
    </modules>
</system.webServer>

IMPORTANT NOTE1: This solution needs an application pool set as integrated;

IMPORTANT NOTE2: All responses within the web app will be affected by this (css and js included);


问:
HTML input not updating value
I have a very strange problem (at least to me).
I dynamically create textboxes, and it works fine. But the problem is when I try to write in those, if I check the html code, values that I write do not appear. I have no idea why this is happening or how to work arround this.
Here is my code example.

```<code><ul class="ml4 js-sortable-buttons list flex flex-column list-reset" data-disabled="false" id="page-content">
    <li class="p1 mb1 blue bg-white" id="id"><input type="text" class="textbox" /></li>
</ul>
<div class="center py2 ml4">
    <div class="js-add-textbox-button button blue bg-white" >add textbox</div>
    <div class="show_html_button blue bg-white">show html</div>
</div>

<!-- <script src="../src/html.sortable.js"></script> -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="html.sortable.min.js"></script>
<script  type="text/javascript">
        sortable('.js-sortable-buttons', {
            forcePlaceholderSize: true,
            items: 'li',
            placeholderClass: 'border border-white mb1'

        });
        // buttons to add items and reload the list
        // separately to showcase issue without reload
        document.querySelector('.js-add-textbox-button').addEventListener('click', function () {
            doc = new DOMParser().parseFromString(`<li class="p1 mb1 blue bg-white"><input type="text" class="textbox"></li>`, "text/html").body.firstChild;
            document.querySelector('.js-sortable-buttons').appendChild(doc);
            sortable('.js-sortable-buttons');
            window.stop();
        });
</script>

    <script  type="text/javascript">
        $(".show_html_button").click(function () {
            var optionTexts = $("#page-content").clone(true);
            alert(optionTexts.html());
        });
</script>
</code>```

Any help would be greatly appreciated.

答:
You are missing reference to html5Sortable.
https://cdnjs.com/libraries/html5sortable

        sortable('.js-sortable-buttons', {
            forcePlaceholderSize: true,
            items: 'li',
            placeholderClass: 'border border-white mb1'

        });
        // buttons to add items and reload the list
        // separately to showcase issue without reload
        document.querySelector('.js-add-textbox-button').addEventListener('click', function () {
            doc = new DOMParser().parseFromString(`<li class="p1 mb1 blue bg-white"><input type="text" class="textbox"></li>`, "text/html").body.firstChild;
            document.querySelector('.js-sortable-buttons').appendChild(doc);
            sortable('.js-sortable-buttons');
            window.stop();
        });

        $(".show_html_button").click(function () {
            var optionTexts = $("#page-content").clone(true);
            alert(optionTexts.html());
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html5sortable/0.6.1/html.sortable.min.js"></script>

<ul class="ml4 js-sortable-buttons list flex flex-column list-reset" data-disabled="false" id="page-content">
    <li class="p1 mb1 blue bg-white" id="id"><input type="text" class="textbox" /></li>
</ul>
<div class="center py2 ml4">
    <div class="js-add-textbox-button button blue bg-white" >add textbox</div>
    <div class="show_html_button blue bg-white">show html</div>
</div></code>```

Title: HTML input not updating value

Body:
I have a very strange problem (at least to me).
I dynamically create textboxes, and it works fine. But the problem is when I try to write in those, if I check the html code, values that I write do not appear. I have no idea why this is happening or how to work arround this.
Here is my code example.

<input type="text" class="textbox" />

add textbox

show html

Any help would be greatly appreciated.

Body:
You are missing reference to html5Sortable.
https://cdnjs.com/libraries/html5sortable

        sortable('.js-sortable-buttons', {
            forcePlaceholderSize: true,
            items: 'li',
            placeholderClass: 'border border-white mb1'

        });
        // buttons to add items and reload the list
        // separately to showcase issue without reload
        document.querySelector('.js-add-textbox-button').addEventListener('click', function () {
            doc = new DOMParser().parseFromString(`<li class="p1 mb1 blue bg-white"><input type="text" class="textbox"></li>`, "text/html").body.firstChild;
            document.querySelector('.js-sortable-buttons').appendChild(doc);
            sortable('.js-sortable-buttons');
            window.stop();
        });

        $(".show_html_button").click(function () {
            var optionTexts = $("#page-content").clone(true);
            alert(optionTexts.html());
        });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html5sortable/0.6.1/html.sortable.min.js"></script>

<ul class="ml4 js-sortable-buttons list flex flex-column list-reset" data-disabled="false" id="page-content">
    <li class="p1 mb1 blue bg-white" id="id"><input type="text" class="textbox" /></li>
</ul>
<div class="center py2 ml4">
    <div class="js-add-textbox-button button blue bg-white" >add textbox</div>
    <div class="show_html_button blue bg-white">show html</div>
</div>


问:
AJAX HTTP-POST-Request - Saving JSON responses
I want to make a HTTP-POST-Request with AJAX to call a JSON API. So, the API should return a response in JSON. I can see on the console of the API, that the request is successful. But the problem is, that no data or status is returned, or that I can't use it with JQuery. Here is my function:

```<code>$.post("http://api-adress/controller",
    {
            email: input_mail,
            password: input_pw
    },
    function(data, status){
        alert(data);
        alert(status);
    }, 'json');
</code>```

I guess the problem is that the response from the Server does not get saved in the variables data and status correctly.

答:
I would suggest to change a little bit your code like below:

```<code>var dataString = {
     email: input_mail,
     password: input_pw
}

    $.post("http://api-adress/controller", dataString, function (result) {

})
      .done(function (result) {
           //Here is your result. You must parseJSON if it is json format
           var data = jQuery.parseJSON(result);

       })
       .fail(function () {
              //use this if you need it
       })
</code>```

Also make sure that you get the response through firebug in console tab. You can check there what you post, what you get etc.

Body:
I want to make a HTTP-POST-Request with AJAX to call a JSON API. So, the API should return a response in JSON. I can see on the console of the API, that the request is successful. But the problem is, that no data or status is returned, or that I can't use it with JQuery. Here is my function:

$.post("http://api-adress/controller",
    {
            email: input_mail,
            password: input_pw
    },
    function(data, status){
        alert(data);
        alert(status);
    }, 'json');

I guess the problem is that the response from the Server does not get saved in the variables data and status correctly.

Body:
I would suggest to change a little bit your code like below:

var dataString = {
     email: input_mail,
     password: input_pw
}

    $.post("http://api-adress/controller", dataString, function (result) {

})
      .done(function (result) {
           //Here is your result. You must parseJSON if it is json format
           var data = jQuery.parseJSON(result);

       })
       .fail(function () {
              //use this if you need it
       })

Also make sure that you get the response through firebug in console tab. You can check there what you post, what you get etc.


问:
Only allow certain characters to be entered in database
I was checking for an answer to only accept certain type of characters and ignoring some.

I found a link in stack itself, here

But, even though that prevents from entering the data in text box, anyone with a little knowledge of how to inspect the content and delete the pattern from client side will allow it to enter any detail it wants and send to database.

Is there any way I can prevent it for my website? I don't want certain characters like space, semicolon, etc.

Frontend in html & php
Backend in MySQL

答:
First of all,
You can define a type for each column in your database, for example, if you set type as integer - you won't be able to insert anything else.

Let us assume you're looking to "filter" or manipulate strings in your database - I Would make a regex to replace any unwanted character from the string and the insert it into database.


问:
Jquery button don't append elements with no errors at the console
I have this html form:

```<code>         <div class="col-sm-4 rounded" style="background-color: #D3D3D3">
          <div class="row clonedInput" id="clonedInput1">
          <div class="col-sm-6">
              <label for="diagnosis_data">Medication</label>
                <fieldset class="form-group">
                  <select class="form-control select" name="diagnosis_data" id="diagnosis_data">
                    <option value="choose">Select</option>
                  </select>
                </fieldset>
            <!-- End class="col-sm-6" -->
            </div>
            <div class="col-sm-6">
              <label for="patient_weight">Quantity</label>
                <fieldset class="form-group">
                  <input type="number" class="form-control" name="patient_weight" id="patient_weight">
                </fieldset>
            <!-- End class="col-sm-6" -->
            </div>
            <!-- End class="col-sm-6" -->
          </div>
          <div class="actions pull-right">
            <button class="btn btn-danger clone">Add More</button>
            <button class="btn btn-danger remove">Remove</button>
          </div>
</code>```

And this jQuery Script from this link here:

```<code><script>
  $(document).ready(function()
  {
    $("button.clone").on("click", clone);

    $("button.remove").on("click", remove);
  })
    var regex = /^(.+?)(\d+)$/i;
    var cloneIndex = $(".clonedInput").length;
    function clone(){
        $(this).parents(".clonedInput").clone()
            .appendTo(".rounded")
            .attr("id", "clonedInput" +  cloneIndex)
            .find("*")
            .each(function() {
                var id = this.id || "";
                var match = id.match(regex) || [];
                if (match.length == 3) {
                    this.id = match[1] + (cloneIndex);
                }
            })
            .on('click', 'button.clone', clone)
            .on('click', 'button.remove', remove);
        cloneIndex++;
    }
    function remove(){
        $(this).parents(".clonedInput").remove();
    }

  </script>
</code>```

But of course with changes to html but nothing happens when I click on each of the buttons, even no errors at the console. Here is my fiddle.

I am using jQuery 3.2.1

EDIT 1

I tried this script:

```<code>$("button.clone").on("click", function()
{
   $('.clonedInput').clone().insertAfter('.clonedInput')
});
</code>```

it works but there is 2 problems:

ID of each element is not incrementing;

If I had 2 elements and clicked on the button they will be 4, then 8, then...

EDIT 2

I tried this and the problem number 2 is gone:

```<code>$("button.clone").on("click", function()
{
  $('#clonedInput1').clone().insertAfter('#clonedInput1')
});
</code>```

Now I still have to increment the id so I can send the data later using Ajax. Here is my updated fiddle.

答:
You are missing the parent div. As you are doing in clone() :
$(this).parents(".clonedInput").clone()

But in your html
 is not parent of <button class="btn btn-danger clone">Add More</button>.

Here is the updated fiddle - https://jsfiddle.net/b9L4k8mL/2/

Body:
I have this html form:

              Medication
                <fieldset class="form-group">
                  <select class="form-control select" name="diagnosis_data" id="diagnosis_data">
                    <option value="choose">Select</option>
                  </select>
                </fieldset>

              Quantity
                <fieldset class="form-group">
                  <input type="number" class="form-control" name="patient_weight" id="patient_weight">
                </fieldset>

            <button class="btn btn-danger clone">Add More</button>
            <button class="btn btn-danger remove">Remove</button>

And this jQuery Script from this link here:

But of course with changes to html but nothing happens when I click on each of the buttons, even no errors at the console. Here is my fiddle.

I am using jQuery 3.2.1

EDIT 1

I tried this script:

$("button.clone").on("click", function()
{
   $('.clonedInput').clone().insertAfter('.clonedInput')
});

it works but there is 2 problems:

ID of each element is not incrementing;

If I had 2 elements and clicked on the button they will be 4, then 8, then...

EDIT 2

I tried this and the problem number 2 is gone:

$("button.clone").on("click", function()
{
  $('#clonedInput1').clone().insertAfter('#clonedInput1')
});

Now I still have to increment the id so I can send the data later using Ajax. Here is my updated fiddle.

Body:
You are missing the parent div. As you are doing in clone() :
$(this).parents(".clonedInput").clone()

But in your html <div class="clonedInput" id="clonedInput1"> is not parent of <button class="btn btn-danger clone">Add More</button>.

Here is the updated fiddle - https://jsfiddle.net/b9L4k8mL/2/


问:
type mismatch in kotlin
I'm newbie to Kotlin language and Object Oriented Programming, so I wonder why  there's a wrong type of instance of the class inherited from class Fragment() in android. These are my codes

Fragment.kt

```<code> class MyFragment: Fragment() {
 //do something
 }
</code>```

MainActivity.kt

```<code>class MainActivity : AppCompatActivity() {
val fm : Fragment? = MyFragment()
...
}
</code>```

Why fm return MyFragment type, not Fragment? ??
Thank you

答:
I'm so silly that I import 2 different packages for Fragment()

The solution is that 2 files must be imported android.app.Fragment

Title: type mismatch in kotlin

Body:
I'm newbie to Kotlin language and Object Oriented Programming, so I wonder why  there's a wrong type of instance of the class inherited from class Fragment() in android. These are my codes

Fragment.kt

 class MyFragment: Fragment() {
 //do something
 }

MainActivity.kt

class MainActivity : AppCompatActivity() {
val fm : Fragment? = MyFragment()
...
}

Why fm return MyFragment type, not Fragment? ??
Thank you


问:
issue with FILE
I'm getting the folowing error for below code,
"1506-221 (S) Initializer must be a valid constant expression"

```<code>FILE          *fp[] = {stdout, dump_f};
</code>```

is this acceptable? what is the proper way to achive this?

答: If that is a global, then C does not support initializing it with a function call. If stdout is a macro (as suggested initially) for a function call, then you won't be able to use it to initialize a global.

OwnerDisplayName: Thi

Title: issue with FILE

Body:
I'm getting the folowing error for below code,
"1506-221 (S) Initializer must be a valid constant expression"

FILE          *fp[] = {stdout, dump_f};

is this acceptable? what is the proper way to achive this?

LastEditorDisplayName: strager

OwnerDisplayName: MSN


问:
jetty websocket server: Send customer status code based on application logic
I am writing a Websocket server using Jetty.

My handler code:

```<code>public class WebSocketServerHandler {

    @OnWebSocketClose
    public void onClose(int statusCode, String reason) {
        System.out.println("Close: statusCode=" + statusCode + ", reason=" + reason);

    }

    @OnWebSocketError
    public void onError(Throwable t) {
    }

    @OnWebSocketConnect
    public void onConnect(Session session) {

    }

    @OnWebSocketMessage
    public void onMessage(Session session, String message) {
    }

    @OnWebSocketMessage
    public void onBinaryMethod(Session session, byte data[], int offset, int length) {

    }
}
</code>```

One of my requirement is to send custom status code based on business logic insde onBinaryMethod

e.g: Send 1001 as status code for timeout(Jetty already support this)

I am not sure where to set these status codes. I have tried following but that doesn't seems to work.

```<code>Session().getUpgradeResponse().setStatusCode();
</code>```

答:
WebSockets

Here is the RFC regarding the status codes of WebSocket.

During the communication with the socket You are not supposed to send such information in status codes. Send a message instead with the information which is needed by the client.

If you happen to be interested in closing codes you can supply this information on the Session object as follows:

```<code>session.close(new CloseReason(YOUR_NUMBER, "Your reason"));
</code>```

REST

If You rely on those codes use REST services, there are a lot of options there:

Throw a specific exception

Use response builder and return the response

Inject the context

I think the easiest way to achieve Your goal is to use setStatus(int):

```<code>@Context
HttpServletResponse response;

@Path("/method")
public void onBinaryMethod() {
    int statusCode = 200;
    //SOME CODE
    response.setStatus(statusCode);
}
</code>```

Here is a nice answer listing a lot of possible solutions:

https://stackoverflow.com/a/22869076/4823977

Body:
I am writing a Websocket server using Jetty.

My handler code:

public class WebSocketServerHandler {

    @OnWebSocketClose
    public void onClose(int statusCode, String reason) {
        System.out.println("Close: statusCode=" + statusCode + ", reason=" + reason);

    }

    @OnWebSocketError
    public void onError(Throwable t) {
    }

    @OnWebSocketConnect
    public void onConnect(Session session) {

    }

    @OnWebSocketMessage
    public void onMessage(Session session, String message) {
    }

    @OnWebSocketMessage
    public void onBinaryMethod(Session session, byte data[], int offset, int length) {

    }
}

One of my requirement is to send custom status code based on business logic insde onBinaryMethod

e.g: Send 1001 as status code for timeout(Jetty already support this)

I am not sure where to set these status codes. I have tried following but that doesn't seems to work.

Session().getUpgradeResponse().setStatusCode();

Body:
WebSockets

Here is the RFC regarding the status codes of WebSocket.

During the communication with the socket You are not supposed to send such information in status codes. Send a message instead with the information which is needed by the client.

If you happen to be interested in closing codes you can supply this information on the Session object as follows:

session.close(new CloseReason(YOUR_NUMBER, "Your reason"));

REST

If You rely on those codes use REST services, there are a lot of options there:

Throw a specific exception

Use response builder and return the response

Inject the context

I think the easiest way to achieve Your goal is to use setStatus(int):

@Context
HttpServletResponse response;

@Path("/method")
public void onBinaryMethod() {
    int statusCode = 200;
    //SOME CODE
    response.setStatus(statusCode);
}

Here is a nice answer listing a lot of possible solutions:

https://stackoverflow.com/a/22869076/4823977


问:
Fullscreen image preview doesn't resize vertically
I've created a simple system to preview images on my website. The preview opens in a fullscreen view but the image should resize both horizontally and vertically. It does resize horizontally but it fails completely when I am trying to resize it vertically.

Here's the fiddle:

Fiddle

I'd appreciate some help with this. Vertical resizing seems to work when I give fullscreenImageContainer 100% height. The problem is that then the close button won't be located at the top right of the image.

答:
There are 4 properties you need to apply / tweak. max-width, max-height, width and height

width: auto; adjusts the width to maintain the original aspect ratio - i.e. no stretching

height: auto; adjusts the width to maintain the original aspect ratio

max-width: 90vw; ensures that the object or preview div will never exceed 90% of the screen width.

max-height: 90vh; ensures that the object or preview div will never exceed 90% of the screen height.

With these four combined, the object will always be fully in view and you will not need to scroll the screen.

Working example:
(open in full screen and try to resize vertically or horizontally to see the effect)

body {
  background: #111;
  margin: auto;
  padding: 0;
  text-align: center;
}

.adjust {
  width: auto;
  height: auto;
  max-width: 90vw;
  max-height: 90vh;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img class="adjust" src="https://unsplash.it/2600/2600"></code>```

Body:
There are 4 properties you need to apply / tweak. max-width, max-height, width and height

width: auto; adjusts the width to maintain the original aspect ratio - i.e. no stretching

height: auto; adjusts the width to maintain the original aspect ratio

max-width: 90vw; ensures that the object or preview div will never exceed 90% of the screen width.

max-height: 90vh; ensures that the object or preview div will never exceed 90% of the screen height.

With these four combined, the object will always be fully in view and you will not need to scroll the screen.

Working example:
(open in full screen and try to resize vertically or horizontally to see the effect)

body {
  background: #111;
  margin: auto;
  padding: 0;
  text-align: center;
}

.adjust {
  width: auto;
  height: auto;
  max-width: 90vw;
  max-height: 90vh;
  margin: 0 auto;
}

<img class="adjust" src="https://unsplash.it/2600/2600">


问:
how can we show/hide div tags using value of radio buttons in jquery or javascript?
hi i am very new to jquery and i am working on show and hide div tags using values of radio buttons. here is my HTML.

    <input type="radio" name="vehicleList" id="two" onclick="fuelList()" value="1" />Two Wheeler

    <input type="radio" name="vehicleList" id="four" onclick="fuelList()" value="2" />Four Wheeler

    <input type="radio" name="TwoWheeler" value="6" />Electric

    <input type="radio" name="TwoWheeler" value="7" />Petrol

    <input type="radio" name="FourWheeler" value="1" />Electric

    <input type="radio" name="FourWheeler" value="2" />Petrol

    <input type="radio" name="FourWheeler" value="3" />Diesel

    <input type="radio" name="FourWheeler" value="4" />CNG

    <input type="radio" name="FourWheeler" value="5" />LPG

```

now i need help in writing a jquery code for showing the div tag with id = "two wheeler" when radio button value = 1 and div tag with id = "four wheeler" when radio button value = 2.

thnaks in advance.

sorry for anyone who couldnt understand my question.

答:
Below is simple JQuery code that will help you to achieve your requirement:

$("input[name='vehicleList']").on('click', function() {
  if ($(this).val() == 1) {
    $('#TwoWheeler').show();
    $('#FourWheeler').hide();
  } else {
    $('#TwoWheeler').hide();
    $('#FourWheeler').show();
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#TwoWheeler,
#FourWheeler {
  display: none;
}

#OwnVehicle label,
#TwoWheeler label,
#FourWheeler label {
  cursor: pointer;
}</code>```

        <input type="radio" name="vehicleList" id="two" value="1" />Two Wheeler

        <input type="radio" name="vehicleList" id="four" value="2" />Four Wheeler

        <input type="radio" name="TwoWheeler" value="6" />Electric

        <input type="radio" name="TwoWheeler" value="7" />Petrol

        <input type="radio" name="FourWheeler" value="1" />Electric

        <input type="radio" name="FourWheeler" value="2" />Petrol

        <input type="radio" name="FourWheeler" value="3" />Diesel

        <input type="radio" name="FourWheeler" value="4" />CNG

        <input type="radio" name="FourWheeler" value="5" />LPG

```

Body:
hi i am very new to jquery and i am working on show and hide div tags using values of radio buttons. here is my HTML.

    <input type="radio" name="vehicleList" id="two" onclick="fuelList()" value="1" />Two Wheeler

    <input type="radio" name="vehicleList" id="four" onclick="fuelList()" value="2" />Four Wheeler

    <input type="radio" name="TwoWheeler" value="6" />Electric

    <input type="radio" name="TwoWheeler" value="7" />Petrol

    <input type="radio" name="FourWheeler" value="1" />Electric

    <input type="radio" name="FourWheeler" value="2" />Petrol

    <input type="radio" name="FourWheeler" value="3" />Diesel

    <input type="radio" name="FourWheeler" value="4" />CNG

    <input type="radio" name="FourWheeler" value="5" />LPG

now i need help in writing a jquery code for showing the div tag with id = "two wheeler" when radio button value = 1 and div tag with id = "four wheeler" when radio button value = 2.

thnaks in advance.

sorry for anyone who couldnt understand my question.

Body:
Below is simple JQuery code that will help you to achieve your requirement:

$("input[name='vehicleList']").on('click', function() {
  if ($(this).val() == 1) {
    $('#TwoWheeler').show();
    $('#FourWheeler').hide();
  } else {
    $('#TwoWheeler').hide();
    $('#FourWheeler').show();
  }
});

#TwoWheeler,
#FourWheeler {
  display: none;
}

#OwnVehicle label,
#TwoWheeler label,
#FourWheeler label {
  cursor: pointer;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="OwnVehicle">
  <label>
        <input type="radio" name="vehicleList" id="two" value="1" />Two Wheeler
    </label>
  <label>
        <input type="radio" name="vehicleList" id="four" value="2" />Four Wheeler
    </label>
</div>

<div id="TwoWheeler">
  <label>
        <input type="radio" name="TwoWheeler" value="6" />Electric
    </label>
  <label>
        <input type="radio" name="TwoWheeler" value="7" />Petrol
    </label>
</div>
<div id="FourWheeler">
  <label>
        <input type="radio" name="FourWheeler" value="1" />Electric
    </label>
  <label>
        <input type="radio" name="FourWheeler" value="2" />Petrol
    </label>
  <label>
        <input type="radio" name="FourWheeler" value="3" />Diesel
    </label>
  <label>
        <input type="radio" name="FourWheeler" value="4" />CNG
    </label>
  <label>
        <input type="radio" name="FourWheeler" value="5" />LPG
    </label>
</div>


问:
Can't install Couchbase sync gateway
Hey I'm trying to install Couchbase Sync Gateway in my iOS app but it doesn't work.
I am trying many but not sync or connect with Couchbase Server.

if you guys Know then tell me proper method or way to do that.

thanks

答:
The Couchbase Sync Gateway is installed on your database server, where it can connect to a particular bucket of Couchbase. What you're looking to install on your iOS app is the CouchbaseLite library. You can easily install it via CocoaPods.
For reference, here is a GIT application with the Couchbase Lite already configured --> https://github.com/couchbase/couchbase-lite-ios
Try if you can connect to your sync gateway from there. That should give you a fair idea. Let me know if there are any other problems going forward.</p>

Title: Can't install Couchbase sync gateway


问:
Not able to generate HTML reports of code coverage from Clover Maven plugin
Trying to integrate Clover maven plugin to get the code coverage of my project.

After I build my project with mvn clean install, target folder looks like below

But I am looking for code coverage with HTML reports (Which will give us the code coverage with package wise, class wise views)

Will the line <generateHtml>true</generateHtml> does it ?, if yes, something wrong in my configuration.

How can I get HTML reports out of Clover maven plugin?

Below is the pom.xml code

```<code><build>
         <plugins>
            <plugin>
        <groupId>com.atlassian.maven.plugins</groupId>
        <artifactId>maven-clover2-plugin</artifactId>
        <configuration>
        <!-- <targetPercentage>80%</targetPercentage> -->
        <generateHtml>true</generateHtml>
          <generatePdf>true</generatePdf>
          <generateXml>true</generateXml>
        </configuration>
        <executions>
          <execution>
             <phase>verify</phase>
            <goals>
               <goal>instrument</goal>
              <goal>check</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
        </plugins>
    </build>
    <reporting>
    <plugins>
      <plugin>
        <groupId>com.atlassian.maven.plugins</groupId>
        <artifactId>maven-clover2-plugin</artifactId>
        <configuration>
        <generateHtml>true</generateHtml>
          <generatePdf>true</generatePdf>
          <generateXml>true</generateXml>
        </configuration>
      </plugin>
    </plugins>
  </reporting>
</code>```

答:
Please use mvn clean install clover2:clover command ad see if you get the html report generated in target/site/clover/index.html file.

The clover2:clover goal should instrument your test classes, execute the test cases and record the code coverage information.

Body:
Trying to integrate Clover maven plugin to get the code coverage of my project.

After I build my project with mvn clean install, target folder looks like below

But I am looking for code coverage with HTML reports (Which will give us the code coverage with package wise, class wise views)

Will the line <generateHtml>true</generateHtml> does it ?, if yes, something wrong in my configuration.

How can I get HTML reports out of Clover maven plugin?

Below is the pom.xml code

<build>
         <plugins>
            <plugin>
        <groupId>com.atlassian.maven.plugins</groupId>
        <artifactId>maven-clover2-plugin</artifactId>
        <configuration>

        <generateHtml>true</generateHtml>
          <generatePdf>true</generatePdf>
          <generateXml>true</generateXml>
        </configuration>
        <executions>
          <execution>
             <phase>verify</phase>
            <goals>
               <goal>instrument</goal>
              <goal>check</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
        </plugins>
    </build>
    <reporting>
    <plugins>
      <plugin>
        <groupId>com.atlassian.maven.plugins</groupId>
        <artifactId>maven-clover2-plugin</artifactId>
        <configuration>
        <generateHtml>true</generateHtml>
          <generatePdf>true</generatePdf>
          <generateXml>true</generateXml>
        </configuration>
      </plugin>
    </plugins>
  </reporting>


问:
Calculating modbus RTU 3.5 character time
am new to Modbus and developing an application using Modbus RTU. I would like to know how to find out the RTU message frame separation time. In the Modbus RTU specification, It mentions 3.5 chars time, but there is no more data about how i can decide this intervals. and wat are the steps to calculate the separation time?</p>

答: Modbus RTU use 11-bit char, regardless using parity or not. The formula should be : 11 * 1000000 / ( baud_rate ) for one char time, this applies for baud rate <= 19200 bps. For baud rate > 19200 bps, fixed time is used, which are 1750 micro seconds for 3.5 char time, and 750 micro seconds for 1.5 char time</p>


问:
mvn command is not recognized as an internal or external command
I am getting the mvn command not recognized as an internal or external command.

I have setup the M2_HOME, JAVA_HOME and added %M2_HOME%/bin to the path variable. All are system variables. Still getting the same problem.

Echoing the variables showing me the correct paths.

Path to Maven: C:\apache-maven-3.1.0\apache-maven-3.1.0

M2_HOME:C:\apache-maven-3.1.0\apache-maven-3.1.0

PATH: Other things,C:\Program Files (x86)\Java\jdk1.7.0_40\bin,C:\apache-maven-3.1.0\apache-maven-3.1.0\bin

and I have restarted my computer twice.

答:
I faced this problem which kept me busy and buggy for quiet sometime. I was facing the problem (mvn not recognized) after setting up all required environment variables absolutely correctly. So by going by one of the response here, I switched to another version of maven and that fixed the problem.

Not being completely convinced why it worked this way, I then unzipped the problematic-version and updated env-vars which made it work.

The problem was when I initially extracted file from the zip, I modified the directory structure a bit. When you extract the zip, say apache-maven-X.x.x-bin.zip, it creates the folder structure as - "apache-maven-3.5.0-bin\apache-maven-3.5.0..."

In my first attempt I had modified this structure by deleting apache-maven-3.5.0-bin folder and bringing apache-maven-3.5.0 structure one folder up. This was causing the problem.


问:
Claims based Authentication with JAVA based STS?
We have a java based STS service .We would like to use this STS for claims based authentication provided by WIF . Can someone provide some insight into how this can be acheieved ? All the examples I have come across use C# based STS and C# based RP . In my case the RP can be C# but the STS has to be in Java .Specifically,I would be interested in knowing how SAML requested is passed to the STS and the format of claims passed backed to the RP .

Thanks,
Somnath

答:
It depends what protocols your Java STS supports for requesting tokens.

In principle, if your Java STS implements the token request protocols from public standards WS-Trust & WS-Federation, and issues SAML 1.1 or SAML 2.0 tokens, a C# RP using WIF should be able to interoperate with it.

However, if your STS depends on some other request protocol such as SAML 2.0p then WIF doesn't currently support this directly. I believe ADFS does, however, and so there may well be a solution using ADFS as an intermediate STS federating with your Java-based STS in this case.


问:
Writing a query without using sub-query
I have two tables, A and B.

They are joined by a common field called id. Table B also has a field post_code and a date attached to that post_code, meaning the first time that post_code was entered into the database.

I need to select the latest post code and join it to a row on table A WITHOUT a sub-query.

I've got a solution with a sub-query but it's taking far too long

TIA

答:
You can try using APPLY</p>

```<code>Create Table #A(Id int)

Create Table #B(Id int, AId int, PostCode VARCHAR(10), DateAdded DATE)

Insert into #A
    Values(1),(2)

Insert into #B
    Values(1,1,'NW1', GETDATE()-100),
          (2,1,'S20', GETDATE()-200)

Select *
From #A A
    CROSS APPLY(SELECT TOP 1 B.*
                FROM #B B
                WHERE A.Id = B.AId
                ORDER BY DateAdded DESC) Latest
</code>```

Title: Writing a query without using sub-query

Body:
You can try using APPLY

Create Table #A(Id int)

Create Table #B(Id int, AId int, PostCode VARCHAR(10), DateAdded DATE)

Insert into #A
    Values(1),(2)

Insert into #B
    Values(1,1,'NW1', GETDATE()-100),
          (2,1,'S20', GETDATE()-200)

Select *
From #A A
    CROSS APPLY(SELECT TOP 1 B.*
                FROM #B B
                WHERE A.Id = B.AId
                ORDER BY DateAdded DESC) Latest