问:
EasyHook and communication
Using EasyHook I have set up the following structure:

APP <--> Interface <--> DLL

I am trying to run some code inside the injected DLL when I press a button in the APP.

I managed to get the DLL to send messages outside using this code:

```<code>((EntryPoint)HookRuntimeInfo.Callback).Interface.WriteLine("");
</code>```

But how can I actually make code run inside the injected DLL?

答:
You need to configure a bi-directional IPC interface. There are a range of different ways to implement this. What follows is one example using .NET Remoting.

First take a look at the EasyHook remote file monitor tutorial as a starting point for creating your interface to send messages from the DLL back to APP, i.e. APP <- interface <- DLL.

To allow messages from APP -> interface -> DLL, a new channel needs to be configured within the DLL IEntryPoint constructor: e.g.

```<code>    #region Allow client event handlers (bi-directional IPC)
    // Attempt to create a IpcServerChannel so that any event handlers on the client will function correctly
    System.Collections.IDictionary properties = new System.Collections.Hashtable();
    properties["name"] = channelName;
    properties["portName"] = channelName + Guid.NewGuid().ToString("N"); // random portName so no conflict with existing channels of channelName

    System.Runtime.Remoting.Channels.BinaryServerFormatterSinkProvider binaryProv = new System.Runtime.Remoting.Channels.BinaryServerFormatterSinkProvider();
    binaryProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;

    System.Runtime.Remoting.Channels.Ipc.IpcServerChannel _clientServerChannel = new System.Runtime.Remoting.Channels.Ipc.IpcServerChannel(properties, binaryProv);
        System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel(_clientServerChannel, false);
    #endregion
</code>```

To implement the IPC from APP -> interface -> DLL take a look at the Disconnect method and Disconnected event within the "Client-side events" of the Direct3DHook project, CaptureInterface.Disconnect, CaptureInterface.Disconnected and  ClientCaptureInterfaceEventProxy.Disconnected, all in CaptureInterface.cs. In addition to the interface class, this approach also uses a client event proxy class that inherits from MarshalByRefObject and allows an event handler to be called elsewhere in your DLL in response to the APP calling a method. You will need to take a good look at the code linked, there are some additional points of interest that need to be considered (such as event handler lifetime), the interface implements a wrapper around each event to trigger it in a "Safe" manner.

Finally the handler for the Disconnected event is attached within the DLL's IEntryPoint Run method:

```<code>    _interface.Disconnected += _clientEventProxy.DisconnectedProxyHandler;

    _clientEventProxy.Disconnected += () =>
            {
                // This code in the DLL will run when APP calls CaptureInterface.Disconnect
            };
</code>```

Title: EasyHook and communication

Body:
Using EasyHook I have set up the following structure:

APP <--> Interface <--> DLL

I am trying to run some code inside the injected DLL when I press a button in the APP.

I managed to get the DLL to send messages outside using this code:

((EntryPoint)HookRuntimeInfo.Callback).Interface.WriteLine("");

But how can I actually make code run inside the injected DLL?

Body:
You need to configure a bi-directional IPC interface. There are a range of different ways to implement this. What follows is one example using .NET Remoting.

First take a look at the EasyHook remote file monitor tutorial as a starting point for creating your interface to send messages from the DLL back to APP, i.e. APP <- interface <- DLL.

To allow messages from APP -> interface -> DLL, a new channel needs to be configured within the DLL IEntryPoint constructor: e.g.

    #region Allow client event handlers (bi-directional IPC)
    // Attempt to create a IpcServerChannel so that any event handlers on the client will function correctly
    System.Collections.IDictionary properties = new System.Collections.Hashtable();
    properties["name"] = channelName;
    properties["portName"] = channelName + Guid.NewGuid().ToString("N"); // random portName so no conflict with existing channels of channelName

    System.Runtime.Remoting.Channels.BinaryServerFormatterSinkProvider binaryProv = new System.Runtime.Remoting.Channels.BinaryServerFormatterSinkProvider();
    binaryProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;

    System.Runtime.Remoting.Channels.Ipc.IpcServerChannel _clientServerChannel = new System.Runtime.Remoting.Channels.Ipc.IpcServerChannel(properties, binaryProv);
        System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel(_clientServerChannel, false);
    #endregion

To implement the IPC from APP -> interface -> DLL take a look at the Disconnect method and Disconnected event within the "Client-side events" of the Direct3DHook project, CaptureInterface.Disconnect, CaptureInterface.Disconnected and  ClientCaptureInterfaceEventProxy.Disconnected, all in CaptureInterface.cs. In addition to the interface class, this approach also uses a client event proxy class that inherits from MarshalByRefObject and allows an event handler to be called elsewhere in your DLL in response to the APP calling a method. You will need to take a good look at the code linked, there are some additional points of interest that need to be considered (such as event handler lifetime), the interface implements a wrapper around each event to trigger it in a "Safe" manner.

Finally the handler for the Disconnected event is attached within the DLL's IEntryPoint Run method:

    _interface.Disconnected += _clientEventProxy.DisconnectedProxyHandler;

    _clientEventProxy.Disconnected += () =>
            {
                // This code in the DLL will run when APP calls CaptureInterface.Disconnect
            };


来源: stackexchange

问:
Which is the Postgres version
I have a doubt about my version of Postgres installed in my environment.

This is my os: CentOS Linux release 7.3.1611 (Core)
In /usr/ I can see: pgsql-9.4/ folder.

But when I do: select version(); I get:

```<code>PostgreSQL 9.2.18 on x86_64-redhat-linux-gnu, compiled by gcc (GCC) 4.8.5
20150623 (Red Hat 4.8.5-11), 64-bit
</code>```

So, what version do I have?

答:
You may of course have more than one instance of Postgresql. Try this sql to show your current instance location in case there is more than one</p>

```<code>SHOW data_directory;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Which is the Postgres version

Body:
I have a doubt about my version of Postgres installed in my environment.

This is my os: CentOS Linux release 7.3.1611 (Core)
In /usr/ I can see: pgsql-9.4/ folder.

But when I do: select version(); I get:

PostgreSQL 9.2.18 on x86_64-redhat-linux-gnu, compiled by gcc (GCC) 4.8.5
20150623 (Red Hat 4.8.5-11), 64-bit

So, what version do I have?

Body:
You may of course have more than one instance of Postgresql. Try this sql to show your current instance location in case there is more than one

SHOW data_directory;


问:
Collapse ui bootsrap navbar in angularjs on clicking menu list item
I followed the solution at Angular UI, Bootstrap Navbar Collapse and Javascript and used an ng-click on the list items to make sure the menu collapses when a menu item is clicked (otherwise it just stays open) on mobile devices.

However, I noticed that in the large screen view there is a flicker effect on the menu when the list items are clicked because a menu collapse toggle is triggered.

to fix that, I am using the following function in my controller to ensure that the click even is triggered only on the mobile view:

```<code>$scope.toggleCollapse = function(){
    if($window.innerWidth < 768){
       $scope.navbarCollapsed = !$scope.navbarCollapsed
    }
}
</code>```

But I am pretty sure that it is bad practice to have the screen size used like that inside the controller.

How can I achieve this in a more angularjs best-practice way?

答:
I know you asked this two years ago, so you've probably figured out a better way by now, but I found your question while I was trying to solve the same problem. I was surprised that this isn't built into the library.

```<code>    <div class="collapse navbar-collapse" uib-collapse="isNavCollapsed">
        <ul class="nav navbar-nav">
            <li><a ng-click="home()">Link 1</a></li>
            <li><a ng-click="home()">Link 2</a></li>
        </ul>
    </div>

angular.module('ui.bootstrap.demo', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('CollapseDemoCtrl', function ($scope) {
  $scope.isNavCollapsed = true;
  $scope.isCollapsed = false;
  $scope.isCollapsedHorizontal = false;
  $scope.home = function() {
    if(!$scope.isNavCollapsed){
      $scope.isNavCollapsed = true;
    }
    //$location.url('/'); you get the idea
  }
});
</code>```

Here it is in Plunker

Body:
I followed the solution at Angular UI, Bootstrap Navbar Collapse and Javascript and used an ng-click on the list items to make sure the menu collapses when a menu item is clicked (otherwise it just stays open) on mobile devices.

However, I noticed that in the large screen view there is a flicker effect on the menu when the list items are clicked because a menu collapse toggle is triggered.

to fix that, I am using the following function in my controller to ensure that the click even is triggered only on the mobile view:

$scope.toggleCollapse = function(){
    if($window.innerWidth < 768){
       $scope.navbarCollapsed = !$scope.navbarCollapsed
    }
}

But I am pretty sure that it is bad practice to have the screen size used like that inside the controller.

How can I achieve this in a more angularjs best-practice way?

Body:
I know you asked this two years ago, so you've probably figured out a better way by now, but I found your question while I was trying to solve the same problem. I was surprised that this isn't built into the library.

    <div class="collapse navbar-collapse" uib-collapse="isNavCollapsed">
        <ul class="nav navbar-nav">
            <li><a ng-click="home()">Link 1</a></li>
            <li><a ng-click="home()">Link 2</a></li>
        </ul>
    </div>

angular.module('ui.bootstrap.demo', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('CollapseDemoCtrl', function ($scope) {
  $scope.isNavCollapsed = true;
  $scope.isCollapsed = false;
  $scope.isCollapsedHorizontal = false;
  $scope.home = function() {
    if(!$scope.isNavCollapsed){
      $scope.isNavCollapsed = true;
    }
    //$location.url('/'); you get the idea
  }
});

Here it is in Plunker


Title: Merge two multidimensional lists into one list in Python

Body:
I have two lists:

a_list =
[['2017-06-03 23:01:49', 0], ['2017-06-03 23:02:49', 712.32], ['2017-06-03 23:03:49', 501.21].......]

b_list =
[['2017-06-03 23:01:49', 100.01], ['2017-06-03 23:02:49', 50.01], ['2017-06-03 23:03:49', 521.79].......]

I need to merge a_list with b_list so it becomes:

combined_list =
[['2017-06-03 23:01:49', 0, 100,01], ['2017-06-03 23:02:49', 712.32, 50.01], ['2017-06-03 23:03:49', 501.21, 521.79].......]

How would I achieve this?

Body:
You can use zip() and unpack your data all along with a list comprehension like this example:

a = [['2017-06-03 23:01:49', 0],
 ['2017-06-03 23:02:49', 712.32],
 ['2017-06-03 23:03:49', 501.21]]

b = [['2017-06-03 23:01:49', 100.01],
 ['2017-06-03 23:02:49', 50.01],
 ['2017-06-03 23:03:49', 521.79]]

final = [[k,v,j] for (k,v),(_,j) in zip(a, b)]
print(final)

Output:

[['2017-06-03 23:01:49', 0, 100.01],
 ['2017-06-03 23:02:49', 712.32, 50.01],
 ['2017-06-03 23:03:49', 501.21, 521.79]]


问:
Accessing PHP page downloads file instead of processing / parsing PHP
When I moved my website from one host to another, this error started happening: http://eldwa.com/

This is the code of the htaccess

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php56” package as the default “PHP” programming language.
<IfModule mime_module>
  AddType application/x-httpd-ea-php56 .php .php5 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit```

答: You actually need to contact your hosting service provider with the issue as they have the root access of the server and they will be able to fix the issue for you.</p>


问:
Cannot open an html file from python in a web browser - notepad opens instead
In python I am trying to plot a graph with the pygal package

```<code>import pygal  # First import pygal
bar_chart = pygal.Bar()
bar_chart.add('Fibonacci', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
bar_chart.add('Padovan', [1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12])
bar_chart.render_in_browser()
</code>```

Unfortunately, it always opens the HTML file, but not an HTML page in the browser window. I read many posts and I see that people had similar issues in the past. I did not find a solution that works. I also tried to open it via the webbrowser module, but that also opens the HTML file in notepad.

```<code>url='file://C:/Users/User1/AppData/Local/Temp/tmpsblpwtpr.html'
webbrowser.open(url)
</code>```

Anyone any thoughts?

答:
As noted in the Python documentation for webbrowser.open, this function isn't a reliable way to open a local file in a browser:

Note that on some platforms, trying to open a filename using this function, may work and start the operating system’s associated program. However, this is neither supported nor portable.

The issue here is how webbrowser.open (Python 2.7 source code) decides which program to use to open the url/file. When webbrowser is imported in, it stores a list of strings corresponding to browsers (_tryorder). The first item in this list (and the first browser used) is a operation-system-specific default browser, followed by other browsers that the module has detected.

The default browser attempts to use a generic command that will call the user's default internet browser. Depending on your operating system (and possibly your default browser), this may or may not work in opening the file. For example, when I tested it on MacOs with Chrome as the default browser, a(n already opened) Chrome window appeared, but the file did not open (nor did any new tab). However, in Ubuntu with Firefox as the default, the file was opened in the browser.

In Windows, the "default browser" opens the file using os.startfile(), which the Python documentation says "acts like double-clicking the file in Windows Explorer". As pycoder's answer mentions, it is likely that the associated program for .html files on your computer is notepad. If this is the case, changing the default program for opening .html files to your web browser should solve this issue.

However, it may be possible to open the file in a web browser without having to change any settings. You can instead try opening it through one of the other browsers listed for webbrowser._tryorder (although it should be noted that the source code (in both 2.7 and 3.6) does not seem to support Chrome on Windows). It should look something like this (although with different browser names):

```<code>>>> webbrowser._tryorder
['MacOSX', 'chrome', 'firefox', 'safari']
</code>```

Once you have this list, you can pick the browser you wish to use (in this example, Firefox) and then use the following code (replacing the index in _tryorder as appropriate):

```<code>browser = webbrowser.get(webbrowser._tryorder[2])
browser.open(url)
</code>```

The above code succeeded in opening a local .html file in the web browser when I tested it using MacOs (Firefox and Chrome) and Ubuntu (just Firefox). I can't guarantee it will work on Windows or with different browsers, but it seems probable that it would (all of the non-default Windows browsers appear to be called through subprocess.Popen, so they should work as long as it is possible to open the file in the browser from the Windows command line).

Body:
In python I am trying to plot a graph with the pygal package

import pygal  # First import pygal
bar_chart = pygal.Bar()
bar_chart.add('Fibonacci', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
bar_chart.add('Padovan', [1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12])
bar_chart.render_in_browser()

Unfortunately, it always opens the HTML file, but not an HTML page in the browser window. I read many posts and I see that people had similar issues in the past. I did not find a solution that works. I also tried to open it via the webbrowser module, but that also opens the HTML file in notepad.

url='file://C:/Users/User1/AppData/Local/Temp/tmpsblpwtpr.html'
webbrowser.open(url)

Anyone any thoughts?

Body:
As noted in the Python documentation for webbrowser.open, this function isn't a reliable way to open a local file in a browser:

Note that on some platforms, trying to open a filename using this function, may work and start the operating system’s associated program. However, this is neither supported nor portable.

The issue here is how webbrowser.open (Python 2.7 source code) decides which program to use to open the url/file. When webbrowser is imported in, it stores a list of strings corresponding to browsers (_tryorder). The first item in this list (and the first browser used) is a operation-system-specific default browser, followed by other browsers that the module has detected.

The default browser attempts to use a generic command that will call the user's default internet browser. Depending on your operating system (and possibly your default browser), this may or may not work in opening the file. For example, when I tested it on MacOs with Chrome as the default browser, a(n already opened) Chrome window appeared, but the file did not open (nor did any new tab). However, in Ubuntu with Firefox as the default, the file was opened in the browser.

In Windows, the "default browser" opens the file using os.startfile(), which the Python documentation says "acts like double-clicking the file in Windows Explorer". As pycoder's answer mentions, it is likely that the associated program for .html files on your computer is notepad. If this is the case, changing the default program for opening .html files to your web browser should solve this issue.

However, it may be possible to open the file in a web browser without having to change any settings. You can instead try opening it through one of the other browsers listed for webbrowser._tryorder (although it should be noted that the source code (in both 2.7 and 3.6) does not seem to support Chrome on Windows). It should look something like this (although with different browser names):

>>> webbrowser._tryorder
['MacOSX', 'chrome', 'firefox', 'safari']

Once you have this list, you can pick the browser you wish to use (in this example, Firefox) and then use the following code (replacing the index in _tryorder as appropriate):

browser = webbrowser.get(webbrowser._tryorder[2])
browser.open(url)

The above code succeeded in opening a local .html file in the web browser when I tested it using MacOs (Firefox and Chrome) and Ubuntu (just Firefox). I can't guarantee it will work on Windows or with different browsers, but it seems probable that it would (all of the non-default Windows browsers appear to be called through subprocess.Popen, so they should work as long as it is possible to open the file in the browser from the Windows command line).


问:
How can I convert an int number from decimal to binary?
How can I convert an int number from decimal to binary. For example:

```<code>int x=10; // radix 10
</code>```

How can I make another integer has the binary representation of x, such as:

```<code>int y=1010; // radix 2
</code>```

by using c only?

答:
String s = Integer.toBinaryString(10);

http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html

Body:
How can I convert an int number from decimal to binary. For example:

int x=10; // radix 10

How can I make another integer has the binary representation of x, such as:

int y=1010; // radix 2

by using c only?

ContentLicense: CC BY-SA 2.5


问:
Microsoft Azure - Deploying ASP.NET solution - Path too long error
First, I'd like to explain that I tried the suggestions offered here:Path too long error when building a windows azure service. None of these solutions seem to work for my situation.

To summarize, I'm simply trying to to deploy an ASP.NET web forms app to my already-established Azure web app service. I see the following error:

Copying file packages\Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.2.2.0\Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.2.2.0.nupkg to C:\Users\stevieray8450\AppData\Local\Temp\WebSitePublish\FrankiesDiscountAutos1-982367110\obj\Debug\Package\PackageTmp\packages\Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.2.2.0\Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.2.2.0.nupkg failed. The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.  FrankiesDiscountAutos1      0

The path is ridiculously long, as you can see. Are there any other suggestions? Much appreciated!

答:
I encountered this issue before. And I resolved it
by setting the _CSRUN_STATE_DIRECTORY to a shorter path, say “C:\A” for example. It is also in you mentioned SO thread. We also can get more detail information from this document. If you have't tried this, please have a try.

Note: Make sure that you close Visual Studio and shutdown the development fabric by using the “csrun /devfabric:shutdown” command I mentioned above or by clicking “exit” on the Windows Azure the tray icon.


问:
How to sort data of txt file in Python
I have devices.txt file that looks like this:

```<code>tw004:Galaxy S5:Samsung:Mobilni telefon:5
tw002:Galaxy S6:Samsung:Mobilni telefon:1
tw001:Huawei P8:Huawei:Mobilni telefon:4
tw003:Huawei P9:Huawei:Mobilni telefon:3
</code>```

Now, I have code like this, and I have to chose how to sort devices in table (for example sort them by code from tw001 to tw004 or sort them by producer's name from A to Z)

```<code>def formatheader():
        print(
    "Code |    Name    |  Producer  |       Description       |  Quantity   |\n"
    "-----+------------+------------+-------------------------+-------------|")

def sortbycode():
    devices = open('devices.txt', 'r')
    formatheader()
    for i in devices:
        devices = i.strip("\n").split(":")
        print("{0:5}|{1:13}|{2:15}|{3:18}|{4:5}".format(
            devices[0],
            devices[1],
            devices[2],
            devices[3],
            devices[4]))
    print()
</code>```

How to do that?

答:
You can use the .sort method of lists:

```<code>devices.sort()
# or if you want to sort by another field, use a key function
devices.sort(key=lambda x:int(x[4])) # sort by integer value of quantity
</code>```

You should use a different variable name in the for loop to avoid messing with devices. And, if you want to sort by another column, you will need to do the splitting each line of devices into a list before you loop over and print them. You may need two loops (the original for loop to print, and a while loop to process each line ready to sort)

Side note: for this use case, using .strip() without any arguments would be safer, as that will catch leading/trailing whitespace, as well as removing '\r\n' style line endings (if the file so happens to have them).

Also, since you know the list for each row will always be the same format, you could use .format(*devices) to unpack the list to arguments, which may be shorter or neater.

Title: How to sort data of txt file in Python

Body:
I have devices.txt file that looks like this:

tw004:Galaxy S5:Samsung:Mobilni telefon:5
tw002:Galaxy S6:Samsung:Mobilni telefon:1
tw001:Huawei P8:Huawei:Mobilni telefon:4
tw003:Huawei P9:Huawei:Mobilni telefon:3

Now, I have code like this, and I have to chose how to sort devices in table (for example sort them by code from tw001 to tw004 or sort them by producer's name from A to Z)

def formatheader():
        print(
    "Code |    Name    |  Producer  |       Description       |  Quantity   |\n"
    "-----+------------+------------+-------------------------+-------------|")

def sortbycode():
    devices = open('devices.txt', 'r')
    formatheader()
    for i in devices:
        devices = i.strip("\n").split(":")
        print("{0:5}|{1:13}|{2:15}|{3:18}|{4:5}".format(
            devices[0],
            devices[1],
            devices[2],
            devices[3],
            devices[4]))
    print()

How to do that?

Body:
You can use the .sort method of lists:

devices.sort()
# or if you want to sort by another field, use a key function
devices.sort(key=lambda x:int(x[4])) # sort by integer value of quantity

You should use a different variable name in the for loop to avoid messing with devices. And, if you want to sort by another column, you will need to do the splitting each line of devices into a list before you loop over and print them. You may need two loops (the original for loop to print, and a while loop to process each line ready to sort)

Side note: for this use case, using .strip() without any arguments would be safer, as that will catch leading/trailing whitespace, as well as removing '\r\n' style line endings (if the file so happens to have them).

Also, since you know the list for each row will always be the same format, you could use .format(*devices) to unpack the list to arguments, which may be shorter or neater.


问:
Best way of adding SNMP support to your own application on Debian
I am working on Debian and I have this server we want to monitor.

The application is ours and there are around a hundred real-time counters we want to export for monitoring purposes, graphs and alarms.

I've been looking at the Debian way of doing this because we do use Debian packaging to install the app, and Debian uses snmpd daemon, based on net-snmp, to export SNMP.
So far every approach I've seen looks very complicated, from recompiling snmpd to load a dynamic library into it, and compiling a form of subagent that replicates what snmpd does.

While all of those options make me think I should go for something else than SNMP I don't want to give up that early and I was wondering if anybody has found a feasible implementation.

Ideally it should be coded in C or C++ as the app is in C++, but I'm open to wrappers or other kind of suggestions.

答: net-snmp supports both the smux and agentx agent extension protocols, allowing sub-agents to live in different processes. They also have a tutorial on writing AgentX subagents in C.</p>


问:
Movement of rectangle with tot function
How can I make this rectangle move from the top left down to the bottom right?

```<code>clear all
close all
clc
n=10;
h=1;
for t=0:n-1
    clf;
    axis([0 sum(1:n) 0 sum(1:n)]);
    axis manual
    tot = sum(0:t);
    patch([tot tot+(t+1)*h tot+(t+1)*h tot],[tot tot tot+(t+1)*h tot+(t+1)*h],...
        [2 6 3 7],'EdgeColor','none','FaceAlpha',(1-(t+1)*.7/n));
    pause(1/6)
end
</code>```

Also, try to use this function somewhere.
sum(1:t)-tot-(t+1)*h

答:
You could compute the Y location for patch function differently, but from your current code, the simplest change will be to reverse the Y axis direction:</p>

```<code>axis ij; % put this before patch
</code>```

Title: Movement of rectangle with tot function

Body:
How can I make this rectangle move from the top left down to the bottom right?

clear all
close all
clc
n=10;
h=1;
for t=0:n-1
    clf;
    axis([0 sum(1:n) 0 sum(1:n)]);
    axis manual
    tot = sum(0:t);
    patch([tot tot+(t+1)*h tot+(t+1)*h tot],[tot tot tot+(t+1)*h tot+(t+1)*h],...
        [2 6 3 7],'EdgeColor','none','FaceAlpha',(1-(t+1)*.7/n));
    pause(1/6)
end

Also, try to use this function somewhere.
sum(1:t)-tot-(t+1)*h

Body:
You could compute the Y location for patch function differently, but from your current code, the simplest change will be to reverse the Y axis direction:

axis ij; % put this before patch


问:
No 'Access-Control-Allow-Origin' Angular 4 app
I am trying to access this address:
http://52.208.91.209:3000/?paging=1

Accessing manually works fine.
Accessing via an Angular 4 request returns:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

I have googled it for a few hours and did not find a solution.

The only "solution" I have found is using Allow-Control-Allow-Origin plugin.

The address I am trying to access is not mine.

I am just trying to work with it.

I have even read about proxies when using ng serve with angular CLI but didnt fully understand.

All of the solutions I saw are simply a response headers problem on the server side. However, This is NOT my server so I cannot configure it.

Any help would be appreciated. Thank you.

答:
You can change your frontend JavaScript code to instead make the request through a public proxy.

To try that, change your code to use the following URL:

```<code>https://cors-anywhere.herokuapp.com/http://52.208.91.209:3000/?paging=1
</code>```

That’ll cause the request to go to https://cors-anywhere.herokuapp.com, a open CORS proxy that sends the request on to the http://52.208.91.209:3000/?paging=1 URL you want.

That proxy gets the response, takes it and adds the Access-Control-Allow-Origin response header to it, and then finally passes that back to your requesting frontend code as the response.

So in the end because the browser sees a response with the Access-Control-Allow-Origin response header, the browser allows your frontend JavaScript code to access the response.

Or use the code from https://github.com/Rob--W/cors-anywhere/ or such to set up your own proxy.

You need a proxy in this case because http://52.208.91.209:3000/?paging=1 itself doesn’t send the Access-Control-Allow-Origin response header—and in that case your browser will not allow your frontend JavaScript code to access a response from that server cross-origin.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has more details.

Body:
You can change your frontend JavaScript code to instead make the request through a public proxy.

To try that, change your code to use the following URL:

https://cors-anywhere.herokuapp.com/http://52.208.91.209:3000/?paging=1

That’ll cause the request to go to https://cors-anywhere.herokuapp.com, a open CORS proxy that sends the request on to the http://52.208.91.209:3000/?paging=1 URL you want.

That proxy gets the response, takes it and adds the Access-Control-Allow-Origin response header to it, and then finally passes that back to your requesting frontend code as the response.

So in the end because the browser sees a response with the Access-Control-Allow-Origin response header, the browser allows your frontend JavaScript code to access the response.

Or use the code from https://github.com/Rob--W/cors-anywhere/ or such to set up your own proxy.

You need a proxy in this case because http://52.208.91.209:3000/?paging=1 itself doesn’t send the Access-Control-Allow-Origin response header—and in that case your browser will not allow your frontend JavaScript code to access a response from that server cross-origin.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has more details.


问:
Values pf pandas data frame columns as list
I am creating a data frame from dictionary in a list like below :

```<code>[{'points': [-9.3613566605198262, 4.0910018605047171, -9.3473134841172731, 4.0960021770649475], 'uid': 0},
 {'points': [-9.4687215264026712, 4.0132947848279499, -9.3641925245477857, 4.0159059337303784], 'uid': 1},
</code>```

The above is a list called l1

For data frame:

```<code>df = pd.DataFrame.from_records(l1)
</code>```

This creates following df:

```<code>   points                                          uid
0  [-9.3613566605198262, 4.09100186050......]      0
1  [-9.4687215264026712, 4.01329478482......]      1
</code>```

I want to know how to remove the list format/ square brackets from the points column, and it should contain simple comma separated values.

Also, How to limit the decimal place only to 2 digits?

I tried the following, but it doesn't works.

```<code>np.round(df, 2)
</code>```

and

```<code>df.round({'points':2})
</code>```

expected df

```<code>   points                      uid
0  -9.36, 4.09, -9.34, 4.09    0
1  -9.46, 4.01, -9.36, 4.01    1
</code>```

答:
Try this way:

```<code>df = pd.DataFrame.from_records(l1)
df['points'] = [', '.join(str(e) for e in [round(i, 2) for i in j])
                                 for j in df['points']]
df
</code>```

df will be:

```<code>    points                  uid
0   -9.36, 4.09, -9.35, 4.1 0
1   -9.47, 4.01, -9.36, 4.02    1
</code>```

Body:
I am creating a data frame from dictionary in a list like below :

[{'points': [-9.3613566605198262, 4.0910018605047171, -9.3473134841172731, 4.0960021770649475], 'uid': 0},
 {'points': [-9.4687215264026712, 4.0132947848279499, -9.3641925245477857, 4.0159059337303784], 'uid': 1},

The above is a list called l1

For data frame:

df = pd.DataFrame.from_records(l1)

This creates following df:

   points                                          uid
0  [-9.3613566605198262, 4.09100186050......]      0
1  [-9.4687215264026712, 4.01329478482......]      1

I want to know how to remove the list format/ square brackets from the points column, and it should contain simple comma separated values.

Also, How to limit the decimal place only to 2 digits?

I tried the following, but it doesn't works.

np.round(df, 2)

and

df.round({'points':2})

expected df

   points                      uid
0  -9.36, 4.09, -9.34, 4.09    0
1  -9.46, 4.01, -9.36, 4.01    1

Body:
Try this way:

df = pd.DataFrame.from_records(l1)
df['points'] = [', '.join(str(e) for e in [round(i, 2) for i in j])
                                 for j in df['points']]
df

df will be:

    points                  uid
0   -9.36, 4.09, -9.35, 4.1 0
1   -9.47, 4.01, -9.36, 4.02    1


问:
How to add Tensorboard to a Tensorflow estimator process
I have taken the supplied Abalone example and made sure I have understood it.... Well I think I do. But as another estimator project I am working on is producing total garbage - I have tried to add tensor board, so I can understand what is going on.

The Base code is https://www.tensorflow.org/extend/estimators

I had added a Session and a writer

```<code>    # Set model params
    model_params = {"learning_rate": 0.01}
    with  tf.Session ()   as  sess:
        # Instantiate Estimator
        nn = tf.contrib.learn.Estimator(model_fn=model_fn, params=model_params)
        writer  =  tf.summary.FileWriter ( '/tmp/ab_tf' ,  sess.graph)
        nn.fit(x=training_set.data, y=training_set.target, steps=5000)
        # Score accuracy
        ev = nn.evaluate(x=test_set.data, y=test_set.target, steps=1)

And added 1 line in the model_fn function so it looks like this...

def model_fn(features, targets, mode, params):
  """Model function for Estimator."""

  # Connect the first hidden layer to input layer
  # (features) with relu activation
  first_hidden_layer = tf.contrib.layers.relu(features, 49)

  # Connect the second hidden layer to first hidden layer with relu
  second_hidden_layer = tf.contrib.layers.relu(first_hidden_layer, 49)

  # Connect the output layer to second hidden layer (no activation fn)
  output_layer = tf.contrib.layers.linear(second_hidden_layer, 1)

  # Reshape output layer to 1-dim Tensor to return predictions
  predictions = tf.reshape(output_layer, [-1])
  predictions_dict = {"ages": predictions}

  # Calculate loss using mean squared error
  loss = tf.losses.mean_squared_error(targets, predictions)

  # Calculate root mean squared error as additional eval metric
  eval_metric_ops = {
      "rmse": tf.metrics.root_mean_squared_error(
          tf.cast(targets, tf.float64), predictions)
  }

  train_op = tf.contrib.layers.optimize_loss(
      loss=loss,
      global_step=tf.contrib.framework.get_global_step(),
      learning_rate=params["learning_rate"],
      optimizer="SGD")

  tf.summary.scalar('Loss',loss)

  return model_fn_lib.ModelFnOps(
      mode=mode,
      predictions=predictions_dict,
      loss=loss,
      train_op=train_op,
      eval_metric_ops=eval_metric_ops)
</code>```

Finally added a

```<code>writer.close()
</code>```

When I run the code ... I get a data file in the /tmp/ab_tf, this file is NOT null. But it also is only 139 bytes in size ... which implies nothing is being written....

When I open this with tensor board - there is no data.

What am I doing wrong ?

Appreciate any input ...

答:
I was trying to do exactly the same thing as you. I finally figured out that you need to pass model_dir as a parameter to the class constructor like this:

```<code># Instantiate Estimator
nn = tf.contrib.learn.Estimator(model_fn=model_fn,
        params=model_params,
        model_dir=FLAGS.log_dir)
</code>```

You can see this documented in the TensorFlow API here: https://www.tensorflow.org/api_docs/python/tf/contrib/learn/Estimator

Body:
I have taken the supplied Abalone example and made sure I have understood it.... Well I think I do. But as another estimator project I am working on is producing total garbage - I have tried to add tensor board, so I can understand what is going on.

The Base code is https://www.tensorflow.org/extend/estimators

I had added a Session and a writer

    # Set model params
    model_params = {"learning_rate": 0.01}
    with  tf.Session ()   as  sess:
        # Instantiate Estimator
        nn = tf.contrib.learn.Estimator(model_fn=model_fn, params=model_params)
        writer  =  tf.summary.FileWriter ( '/tmp/ab_tf' ,  sess.graph)
        nn.fit(x=training_set.data, y=training_set.target, steps=5000)
        # Score accuracy
        ev = nn.evaluate(x=test_set.data, y=test_set.target, steps=1)

And added 1 line in the model_fn function so it looks like this...

def model_fn(features, targets, mode, params):
  """Model function for Estimator."""

  # Connect the first hidden layer to input layer
  # (features) with relu activation
  first_hidden_layer = tf.contrib.layers.relu(features, 49)

  # Connect the second hidden layer to first hidden layer with relu
  second_hidden_layer = tf.contrib.layers.relu(first_hidden_layer, 49)

  # Connect the output layer to second hidden layer (no activation fn)
  output_layer = tf.contrib.layers.linear(second_hidden_layer, 1)

  # Reshape output layer to 1-dim Tensor to return predictions
  predictions = tf.reshape(output_layer, [-1])
  predictions_dict = {"ages": predictions}

  # Calculate loss using mean squared error
  loss = tf.losses.mean_squared_error(targets, predictions)

  # Calculate root mean squared error as additional eval metric
  eval_metric_ops = {
      "rmse": tf.metrics.root_mean_squared_error(
          tf.cast(targets, tf.float64), predictions)
  }

  train_op = tf.contrib.layers.optimize_loss(
      loss=loss,
      global_step=tf.contrib.framework.get_global_step(),
      learning_rate=params["learning_rate"],
      optimizer="SGD")

  tf.summary.scalar('Loss',loss)

  return model_fn_lib.ModelFnOps(
      mode=mode,
      predictions=predictions_dict,
      loss=loss,
      train_op=train_op,
      eval_metric_ops=eval_metric_ops)

Finally added a

writer.close()

When I run the code ... I get a data file in the /tmp/ab_tf, this file is NOT null. But it also is only 139 bytes in size ... which implies nothing is being written....

When I open this with tensor board - there is no data.

What am I doing wrong ?

Appreciate any input ...

Body:
I was trying to do exactly the same thing as you. I finally figured out that you need to pass model_dir as a parameter to the class constructor like this:

# Instantiate Estimator
nn = tf.contrib.learn.Estimator(model_fn=model_fn,
        params=model_params,
        model_dir=FLAGS.log_dir)

You can see this documented in the TensorFlow API here: https://www.tensorflow.org/api_docs/python/tf/contrib/learn/Estimator

ContentLicense: CC BY-SA 4.0


问:
Button function call does not work?
I want a webpage that has something like this:

Welcome

[textbox] [textbox] [Multiply!]

Enter a value to multiply.

represented by this html code:

window.onload = function begin() {
  document.getElementById("demo").innerHTML = "Welcome";
}

function multiply(var1, var2) {
  document.getElementById('multiply').innerHTML = var1 * var2
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body onload="onload();">
  <p id='demo'> </p>

  <form>
    <input type='number' name=num1>
    <input type='number' name=num2>
    <button onclick=multiply(num1, num2)> Multiply! </button>
  </form>

  <p id='multiply'> Enter a value to multiply. </p>

</body></code>```

答:
You lack " in onclick, and I changed the script. I also removed unnecessary elements. Just add them back in your codes

EDIT

I returned the <form> tag and added the type="button" attribute to prevent the form from submitting. Thanks to @Patrick Roberts and @Nick Tirrell for the information

function multiply() {
  var num1 = document.getElementById("num1").value;
  var num2 = document.getElementById("num2").value;
  document.getElementById('multiply').innerHTML = num1 * num2
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <input id="num1" type='number'>
  <input id="num2" type='number'>
  <button type="button" onclick="multiply()"> Multiply! </button>
  <p id='multiply'> Enter a value to multiply. </p>
</form></code>```

Title: Button function call does not work?

Body:
I want a webpage that has something like this:

Welcome

[textbox] [textbox] [Multiply!]

Enter a value to multiply.

represented by this html code:

window.onload = function begin() {
  document.getElementById("demo").innerHTML = "Welcome";
}

function multiply(var1, var2) {
  document.getElementById('multiply').innerHTML = var1 * var2
}

  <form>
    <input type='number' name=num1>
    <input type='number' name=num2>
    <button onclick=multiply(num1, num2)> Multiply! </button>
  </form>

 Enter a value to multiply.

Body:
You lack " in onclick, and I changed the script. I also removed unnecessary elements. Just add them back in your codes

EDIT

I returned the <form> tag and added the type="button" attribute to prevent the form from submitting. Thanks to @Patrick Roberts and @Nick Tirrell for the information

function multiply() {
  var num1 = document.getElementById("num1").value;
  var num2 = document.getElementById("num2").value;
  document.getElementById('multiply').innerHTML = num1 * num2
}

<form>
  <input id="num1" type='number'>
  <input id="num2" type='number'>
  <button type="button" onclick="multiply()"> Multiply! </button>
  <p id='multiply'> Enter a value to multiply. </p>
</form>


问:
How two components communicate, in angular 2?
I wrote two components, as follows:

DynSelectionComponent.ts (generic select tag, because the select tag does not support multi-select, filter, so this component uses ng2-selet).

user-list.component.ts (this component corresponds to the html template using DynSelectionComponent, and provides a collection for DynSelectionComponent shown as option).

DynSelectionComponent.ts

```<code>import { Component, OnInit, ViewEncapsulation, Input, SimpleChanges } from '@angular/core';

@Component({
    selector: 'dyn-selection',
    template: `
    <ng-select [allowClear]="true"
                [items]="items"
                [disabled]="disabled"
                (data)="refreshValue($event)"
                (selected)="selected($event)"
                (removed)="removed($event)"
                (typed)="typed($event)"
                [placeholder]="placeholder">
    </ng-select>
    `,
})

export class DynSelectionComponent implements OnInit {
    @Input() inputItems: any[];//The other components are passed over the collection

    private value: any = {};
    private disabled: boolean = false;
    private placeholder: string = '';
    items: Array<any> = [];

    ngOnChanges(changes: SimpleChanges) {
        let newItems: any[] = [];
        for (let propName in changes) {
            if (propName == 'inputItems') {
                this.inputItems.forEach((compay: { companyId: string, companyName: string }) => {
                    newItems.push({
                        id: compay.companyId,
                        text: `${compay.companyName}`
                    });
                });
                this.items = newItems;
            }
        }
    }

    public selected(value: any): void {
        console.log('Selected value is: ', value);
    }
    public removed(value: any): void {
        console.log('Removed value is: ', value);
    }
    public typed(value: any): void {
        console.log('New search input: ', value);
    }
    public refreshValue(value: any): void {
        this.value = value;
    }
}
</code>```

user-list.html(This file uses DynSelectionComponent)

```<code><dyn-selection [inputItems]='companies' name="companyId" id="companyId"></dyn-selection>
</code>```

user-list.component.ts(This component assigns a value for the companies property)

```<code>getCompanies(){
    var url = "/api/company/queryCompany";
    this.httpPlus.post(url, {
        data:"c"
    }).subscribe((data: any) => {
        this.companies = data.data;
    }, (err)=> {
        this.companies = [];
    });
}
</code>```

This time, user-list.html file can normally use DynSelectionComponent component, the normal display companies collection.

However, when  triggers the onchange event, how does the user-list.component.ts component get the modified value of companyId ?

What should I do ? Thank you for your reply.

答:
DynSelectionComponent.ts Add the following code

```<code>@Output("ValueOnChange")
ValueOnChange:EventEmitter<SelectItem> = new EventEmitter<SelectItem>();
</code>```

When the ng2-select value changes:

```<code>public refreshValue(value: any): void {
    this.ValueOnChange.emit(value);
}
</code>```

receiver: user-list.html（binding ValueOnChange event）

```<code><dyn-selection [inputItems]='companies' (companyIdChange)="ValueOnChange($event)"></dyn-selection>
</code>```

receiver: user-list.component.ts

```<code>ValueOnChange(company: SelectItem){
    console.log("The received value is: " + company.id);
}
</code>```

Body:
I wrote two components, as follows:

DynSelectionComponent.ts (generic select tag, because the select tag does not support multi-select, filter, so this component uses ng2-selet).

user-list.component.ts (this component corresponds to the html template using DynSelectionComponent, and provides a collection for DynSelectionComponent shown as option).

DynSelectionComponent.ts

import { Component, OnInit, ViewEncapsulation, Input, SimpleChanges } from '@angular/core';

@Component({
    selector: 'dyn-selection',
    template: `
    <ng-select [allowClear]="true"
                [items]="items"
                [disabled]="disabled"
                (data)="refreshValue($event)"
                (selected)="selected($event)"
                (removed)="removed($event)"
                (typed)="typed($event)"
                [placeholder]="placeholder">
    </ng-select>
    `,
})

export class DynSelectionComponent implements OnInit {
    @Input() inputItems: any[];//The other components are passed over the collection

    private value: any = {};
    private disabled: boolean = false;
    private placeholder: string = '';
    items: Array<any> = [];

    ngOnChanges(changes: SimpleChanges) {
        let newItems: any[] = [];
        for (let propName in changes) {
            if (propName == 'inputItems') {
                this.inputItems.forEach((compay: { companyId: string, companyName: string }) => {
                    newItems.push({
                        id: compay.companyId,
                        text: `${compay.companyName}`
                    });
                });
                this.items = newItems;
            }
        }
    }

    public selected(value: any): void {
        console.log('Selected value is: ', value);
    }
    public removed(value: any): void {
        console.log('Removed value is: ', value);
    }
    public typed(value: any): void {
        console.log('New search input: ', value);
    }
    public refreshValue(value: any): void {
        this.value = value;
    }
}

user-list.html(This file uses DynSelectionComponent)

<dyn-selection [inputItems]='companies' name="companyId" id="companyId"></dyn-selection>

user-list.component.ts(This component assigns a value for the companies property)

getCompanies(){
    var url = "/api/company/queryCompany";
    this.httpPlus.post(url, {
        data:"c"
    }).subscribe((data: any) => {
        this.companies = data.data;
    }, (err)=> {
        this.companies = [];
    });
}

This time, user-list.html file can normally use DynSelectionComponent component, the normal display companies collection.

However, when  triggers the onchange event, how does the user-list.component.ts component get the modified value of companyId ?

What should I do ? Thank you for your reply.

Body:
DynSelectionComponent.ts Add the following code

@Output("ValueOnChange")
ValueOnChange:EventEmitter<SelectItem> = new EventEmitter<SelectItem>();

When the ng2-select value changes:

public refreshValue(value: any): void {
    this.ValueOnChange.emit(value);
}

receiver: user-list.html（binding ValueOnChange event）

<dyn-selection [inputItems]='companies' (companyIdChange)="ValueOnChange($event)"></dyn-selection>

receiver: user-list.component.ts

ValueOnChange(company: SelectItem){
    console.log("The received value is: " + company.id);
}


问:
Why Objective-C doesn't support method overloading?
Objective-C doesn't support methods overloading.

Why?

Is it doable but Apple decided not implement it? or it is not doable due the dynamic nature of Objective-C?

I have the impression that method overloading can be done on compiled languages (Java, C#) and can't be done on interpreted languages (Ruby, Python).

Holds some true?

答:
The distinction that's relevant here is not between compiled and interpreted languages, but between statically typed (Java, C#) and dynamically typed (Ruby, Python, Objective-C). In a dynamically typed language, type information is very often not known until runtime. At runtime, all objects are statically typed as id in Objective-C.

Additionally, a core idea in dynamically typed OO languages is that you should not care what type an object is as long as it responds to the messages you want to send. So overloading based on type would fly right in the face of that.


问:
Gives ORA-01841: (full) year must be between -4713 and +9999, and not be 0 on Oracle select statement from on .net application
```<code>string vDate="2017/06/08";
OracleCommand cmd= new OracleCommand();
OracleParamater pDate= new OracleParameter("pDate",OracleDbType.Varchar2);
pDate.Direction=ParameterDirection.Input;
pDate.Value= vDate;
cmd.Parameters.Add(pDate);
cmd.CommandText="select * from testtable where joinDate<=to_date(:pDate, 'YYYY/MM/DD')";
cmd.CommandType=CommandType.Text;
DataSet ds= new DataSet();
OracleDataAdapter adp= new OracleDataAdapter(); //Please assume that db is connected successfully.
adp.fill(ds);
</code>```

joinDate type is of Date.

When application execute the query it is giving ora-01841 error. I tried with  OracleDBType.Date too, assigning vDate as DateTime type. How do I fix this issue?

Your help would be highly appreciated.

答: I think instead of new OracleParameter("pDate",OracleDbType.Varchar2) it should be OracleParameter("pDate",OracleDbType.date);

Body:
string vDate="2017/06/08";
OracleCommand cmd= new OracleCommand();
OracleParamater pDate= new OracleParameter("pDate",OracleDbType.Varchar2);
pDate.Direction=ParameterDirection.Input;
pDate.Value= vDate;
cmd.Parameters.Add(pDate);
cmd.CommandText="select * from testtable where joinDate<=to_date(:pDate, 'YYYY/MM/DD')";
cmd.CommandType=CommandType.Text;
DataSet ds= new DataSet();
OracleDataAdapter adp= new OracleDataAdapter(); //Please assume that db is connected successfully.
adp.fill(ds);

joinDate type is of Date.

When application execute the query it is giving ora-01841 error. I tried with  OracleDBType.Date too, assigning vDate as DateTime type. How do I fix this issue?

Your help would be highly appreciated.


问:
RecurringJob or BackgroundJob + loop for infinite task
I'm wondering to use Hangfire to program an update task. I want this task to be executed every time. So when the task finish I want to execute it again.

I don't know if the best method to use is RecurringJob or use a loop and a BackgroundJob for it.

What do you recommend me? Are there any other options?

答:
You can use RecurringJob which triggers every x minutes or x hours (based on your requirement - can set CRON expression) , which will trigger the task/work after every such interval. This you need to use in conjunction with DisableConcurrentExecution attribute, so that multiple instances of same task are not triggered, also this attributes makes sure once your first instance is completely, then only second one will be processed.

Alternatively, you can use BackGroundJob to enqueue a task/job but this does the processing of job only one time. So you need to write some code to check this Jobs status and re-enqueue the same job again, once the first is completed. In this approach you need to write some code to do that.

I would suggest the best way is to use RecurringJob.AddOrUpdate in conjunction with DisableConcurrentExecution


问:
Updating parameters in a javascript function using element ID
I'm trying to update the parameters of a function based on a an element ID. The below code works as intended since the ID parameters are hardcoded.

```<code>window.setInterval(function() {
    $('#result').text(collision_(
        $('#task1'), $('#task2'), $('#task3'), $('#task4')
    ));
}, 200);
</code>```

When I try to compile the parameters dynamically the function isn't working.

```<code>window.setInterval(function() {
    function workerTasks() {
        var task = document.getElementById("worker1").children;
        var tasks = [];
        for (i = 0; i <= task.length - 1; i++) {
            tasks.push($("#" + task[i].id))
        }
        return tasks;
    }

    $('#result').text(collision_(tasks));
}, 200);
</code>```

Any help would be greatly appreciated!

UPDATED CODE BELOW ---------

I'm pairing this with draggable collision functions that are driven off of the true or false response - but I'm still not able to indicate the array from 'workerTasks' to be used by 'collision_'.

```<code>$(document).ready(function(){
      setInterval(function() {
        $('#result').text(collision_(workerTasks()));
            console.log(tasks);
      }, 200);
    });

    function workerTasks() {
      var tasks = '';
      $('#worker1 [id^=task]').each(function(i){
        var comma = $('#worker1 [id^=task]').length == i ? '' : ',';
        tasks += $('#' + $(this).attr('id'))  + comma;
      });
      return tasks;
    }

                    function collision_() {
                            if (arguments.length > 1) {
                                    for (var x = 0; x < arguments.length; x++) {
                                            for (var y = 1; y < arguments.length; y++) {
                                                    if (x == y) {
                                                            continue;
                                                    }
                                                    if (collision(arguments[x], arguments[y])) {
                                                            return true;
                                                    }
                                            }
                                    }
                                    return false;
                            }
                    }

                    function collision($div1, $div2) {
                        var x1 = $div1.offset().left;
                        var y1 = $div1.offset().top;
                        var h1 = $div1.outerHeight(true);
                        var w1 = $div1.outerWidth(false);
                        var b1 = y1 + h1;
                        var r1 = x1 + w1;
                        var x2 = $div2.offset().left;
                        var y2 = $div2.offset().top;
                        var h2 = $div2.outerHeight(true);
                        var w2 = $div2.outerWidth(false);
                        var b2 = y2 + h2;
                        var r2 = x2 + w2;

                        if (b1 < y2 || y1 > b2 || r1 < x2 || x1> r2) return false;
                        return true;
                        }
</code>```

答:
Ok I'll post my answer to solve this code issue even if I believe there is no need for all this code if you just showing function_ content

1st: I don't prefer mixing jquery with pure js

2nd: There is no mean to save tasks as an array while function_ not accept array as a parameter

So your code should be something like this

```<code>$(document).ready(function(){
  setInterval(function() {
    $('#result').text(function_(workerTasks()));
  }, 200);
});
function workerTasks() {
  var tasks = '';
  $('#worker1 [id^=task]').each(function(i){
    var comma = $('#worker1 [id^=task]').length == i ? '' : ',';
    tasks += $('#' + $(this).attr('id'))  + comma;
  });
  return tasks;
}
</code>```

Update: After edited the question with the collision and collision_ functions .. See the next demo

$(document).ready(function(){
  setInterval(function() {
    $('#result').text(collision_(workerTasks()));
  }, 200);

  $('button').on('click' , function(){
    $(this).closest('div').remove();
  });
});
function workerTasks() {
  var tasks = [];
  $('#worker1 [id^=task]').each(function(i){
    tasks.push($('#' + $(this).attr('id')));
  });
  return tasks;
}
function collision_(objArr) {
  if (objArr.length > 1) {
    for (var x = 0; x < objArr.length; x++) {
      for (var y = 1; y < objArr.length; y++) {
        if (x == y) {
           continue;
        }
        if (collision(objArr[x], objArr[y])) {
             return true;
        }
      }
    }
  }else{
    return false;
  }
}

function collision($div1, $div2) {
  var x1 = $div1.offset().left;
  var y1 = $div1.offset().top;
  var h1 = $div1.outerHeight(true);
  var w1 = $div1.outerWidth(false);
  var b1 = y1 + h1;
  var r1 = x1 + w1;
  var x2 = $div2.offset().left;
  var y2 = $div2.offset().top;
  var h2 = $div2.outerHeight(true);
  var w2 = $div2.outerWidth(false);
  var b2 = y2 + h2;
  var r2 = x2 + w2;

  if (b1 < y2 || y1 > b2 || r1 < x2 || x1> r2){
    return false;
  }else{
    return true;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="worker1">
  <div id="task1">Task 1 <button>X</button></div>
  <div id="task2">Task 2 <button>X</button></div>
  <div id="task3">Task 3 <button>X</button></div>
  <div id="task4">Task 4 <button>X</button></div>
</div>
<div id="result"></div></code>```

$(document).ready(function(){
  setInterval(function() {
    $('#result').text(collision_(workerTasks()));
  }, 200);

  $('button').on('click' , function(){
    $(this).closest('div').remove();
  });
});
function workerTasks() {
  var tasks = [];
  $('#worker1 [id^=task]').each(function(i){
    tasks.push('#' + $(this).attr('id'));
  });
  return tasks;
}
function collision_(objArr) {
  if (objArr.length > 1) {
    for (var x = 0; x < objArr.length; x++) {
      for (var y = 1; y < objArr.length; y++) {
        if (x !== y) {
          if (collision(objArr[x], objArr[y])) {
               return true;
          }
        }else{
          return false;
        }
      }
    }
  }else{
    return false;
  }
}

function collision($div1, $div2) {
  var x1 = $($div1).offset().left;
  var y1 = $($div1).offset().top;
  var h1 = $($div1).outerHeight(true);
  var w1 = $($div1).outerWidth(false);
  var b1 = y1 + h1;
  var r1 = x1 + w1;
  var x2 = $($div2).offset().left;
  var y2 = $($div2).offset().top;
  var h2 = $($div2).outerHeight(true);
  var w2 = $($div2).outerWidth(false);
  var b2 = y2 + h2;
  var r2 = x2 + w2;

  if (b1 < y2 || y1 > b2 || r1 < x2 || x1> r2){
    return false;
  }else{
    return true;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="worker1">
  <div id="task1">Task 1 <button>X</button></div>
  <div id="task2">Task 2 <button>X</button></div>
  <div id="task3">Task 3 <button>X</button></div>
  <div id="task4">Task 4 <button>X</button></div>
</div>
<div id="result"></div></code>```

Body:
I'm trying to update the parameters of a function based on a an element ID. The below code works as intended since the ID parameters are hardcoded.

window.setInterval(function() {
    $('#result').text(collision_(
        $('#task1'), $('#task2'), $('#task3'), $('#task4')
    ));
}, 200);

When I try to compile the parameters dynamically the function isn't working.

window.setInterval(function() {
    function workerTasks() {
        var task = document.getElementById("worker1").children;
        var tasks = [];
        for (i = 0; i <= task.length - 1; i++) {
            tasks.push($("#" + task[i].id))
        }
        return tasks;
    }

    $('#result').text(collision_(tasks));
}, 200);

Any help would be greatly appreciated!

UPDATED CODE BELOW ---------

I'm pairing this with draggable collision functions that are driven off of the true or false response - but I'm still not able to indicate the array from 'workerTasks' to be used by 'collision_'.

$(document).ready(function(){
      setInterval(function() {
        $('#result').text(collision_(workerTasks()));
            console.log(tasks);
      }, 200);
    });

    function workerTasks() {
      var tasks = '';
      $('#worker1 [id^=task]').each(function(i){
        var comma = $('#worker1 [id^=task]').length == i ? '' : ',';
        tasks += $('#' + $(this).attr('id'))  + comma;
      });
      return tasks;
    }

                    function collision_() {
                            if (arguments.length > 1) {
                                    for (var x = 0; x < arguments.length; x++) {
                                            for (var y = 1; y < arguments.length; y++) {
                                                    if (x == y) {
                                                            continue;
                                                    }
                                                    if (collision(arguments[x], arguments[y])) {
                                                            return true;
                                                    }
                                            }
                                    }
                                    return false;
                            }
                    }

                    function collision($div1, $div2) {
                        var x1 = $div1.offset().left;
                        var y1 = $div1.offset().top;
                        var h1 = $div1.outerHeight(true);
                        var w1 = $div1.outerWidth(false);
                        var b1 = y1 + h1;
                        var r1 = x1 + w1;
                        var x2 = $div2.offset().left;
                        var y2 = $div2.offset().top;
                        var h2 = $div2.outerHeight(true);
                        var w2 = $div2.outerWidth(false);
                        var b2 = y2 + h2;
                        var r2 = x2 + w2;

                        if (b1 < y2 || y1 > b2 || r1 < x2 || x1> r2) return false;
                        return true;
                        }

Body:
Ok I'll post my answer to solve this code issue even if I believe there is no need for all this code if you just showing function_ content

1st: I don't prefer mixing jquery with pure js

2nd: There is no mean to save tasks as an array while function_ not accept array as a parameter

So your code should be something like this

$(document).ready(function(){
  setInterval(function() {
    $('#result').text(function_(workerTasks()));
  }, 200);
});
function workerTasks() {
  var tasks = '';
  $('#worker1 [id^=task]').each(function(i){
    var comma = $('#worker1 [id^=task]').length == i ? '' : ',';
    tasks += $('#' + $(this).attr('id'))  + comma;
  });
  return tasks;
}

Update: After edited the question with the collision and collision_ functions .. See the next demo

$(document).ready(function(){
  setInterval(function() {
    $('#result').text(collision_(workerTasks()));
  }, 200);

  $('button').on('click' , function(){
    $(this).closest('div').remove();
  });
});
function workerTasks() {
  var tasks = [];
  $('#worker1 [id^=task]').each(function(i){
    tasks.push($('#' + $(this).attr('id')));
  });
  return tasks;
}
function collision_(objArr) {
  if (objArr.length > 1) {
    for (var x = 0; x < objArr.length; x++) {
      for (var y = 1; y < objArr.length; y++) {
        if (x == y) {
           continue;
        }
        if (collision(objArr[x], objArr[y])) {
             return true;
        }
      }
    }
  }else{
    return false;
  }
}

function collision($div1, $div2) {
  var x1 = $div1.offset().left;
  var y1 = $div1.offset().top;
  var h1 = $div1.outerHeight(true);
  var w1 = $div1.outerWidth(false);
  var b1 = y1 + h1;
  var r1 = x1 + w1;
  var x2 = $div2.offset().left;
  var y2 = $div2.offset().top;
  var h2 = $div2.outerHeight(true);
  var w2 = $div2.outerWidth(false);
  var b2 = y2 + h2;
  var r2 = x2 + w2;

  if (b1 < y2 || y1 > b2 || r1 < x2 || x1> r2){
    return false;
  }else{
    return true;
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="worker1">
  <div id="task1">Task 1 <button>X</button></div>
  <div id="task2">Task 2 <button>X</button></div>
  <div id="task3">Task 3 <button>X</button></div>
  <div id="task4">Task 4 <button>X</button></div>
</div>
<div id="result"></div>

$(document).ready(function(){
  setInterval(function() {
    $('#result').text(collision_(workerTasks()));
  }, 200);

  $('button').on('click' , function(){
    $(this).closest('div').remove();
  });
});
function workerTasks() {
  var tasks = [];
  $('#worker1 [id^=task]').each(function(i){
    tasks.push('#' + $(this).attr('id'));
  });
  return tasks;
}
function collision_(objArr) {
  if (objArr.length > 1) {
    for (var x = 0; x < objArr.length; x++) {
      for (var y = 1; y < objArr.length; y++) {
        if (x !== y) {
          if (collision(objArr[x], objArr[y])) {
               return true;
          }
        }else{
          return false;
        }
      }
    }
  }else{
    return false;
  }
}

function collision($div1, $div2) {
  var x1 = $($div1).offset().left;
  var y1 = $($div1).offset().top;
  var h1 = $($div1).outerHeight(true);
  var w1 = $($div1).outerWidth(false);
  var b1 = y1 + h1;
  var r1 = x1 + w1;
  var x2 = $($div2).offset().left;
  var y2 = $($div2).offset().top;
  var h2 = $($div2).outerHeight(true);
  var w2 = $($div2).outerWidth(false);
  var b2 = y2 + h2;
  var r2 = x2 + w2;

  if (b1 < y2 || y1 > b2 || r1 < x2 || x1> r2){
    return false;
  }else{
    return true;
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="worker1">
  <div id="task1">Task 1 <button>X</button></div>
  <div id="task2">Task 2 <button>X</button></div>
  <div id="task3">Task 3 <button>X</button></div>
  <div id="task4">Task 4 <button>X</button></div>
</div>
<div id="result"></div>


问:
Meteorjs server side call
I have a task like this:

Create a meterojs app. This app should provide an ability for users to add messages (without explicit server side call) and to remove it (only using server side call).

I'm a newbie with meteorjs and i dont understand how can an entity be put to the collection without a server side call.

Is there any way to do this?

答:
it's an odd task, but it works like this: Meteor maintains a client-side "mini mongo" that

houses the data published from the server

allows mongo-like queries on that data

allows CRUD operations that sync with mongo behind the scenes

let's say you define a collection, messages, in a file that is served to both the client and the server:

```<code>Messages = new Mongo.Collection('messages');
</code>```

Meteor will:

if not already created, create a mongo collection called 'messages' in the database

create a minimongo collection called 'messages' on the client

define a symbol, 'Messages', on both the client and the server that has the typical mongo functions (e.g. find(), findOne(), insert(), etc)

by default, any operations you make client-side will be reflected server-side, behind the scenes. thus, your user can add a message without an explicit server-side call (i.e. its implicit).

that data will actually exist in the real mongo database. so now you have the ability, from the server, to delete it. if there is an active publish on that collection, the client will be updated with that deletion.

Title: Meteorjs server side call

Body:
it's an odd task, but it works like this: Meteor maintains a client-side "mini mongo" that

houses the data published from the server

allows mongo-like queries on that data

allows CRUD operations that sync with mongo behind the scenes

let's say you define a collection, messages, in a file that is served to both the client and the server:

Messages = new Mongo.Collection('messages');

Meteor will:

if not already created, create a mongo collection called 'messages' in the database

create a minimongo collection called 'messages' on the client

define a symbol, 'Messages', on both the client and the server that has the typical mongo functions (e.g. find(), findOne(), insert(), etc)

by default, any operations you make client-side will be reflected server-side, behind the scenes. thus, your user can add a message without an explicit server-side call (i.e. its implicit).

that data will actually exist in the real mongo database. so now you have the ability, from the server, to delete it. if there is an active publish on that collection, the client will be updated with that deletion.


答:
give each input an id attribute then use that to get the value(s) to multiply, e.g. document.getElementById("my-id-1").value.  Also, use a basic

```<code>doc.getElementById("my-button").addEventListener('click', function(evt) {
    //do your thing.
});
</code>```

Title: Button function call does not work?

Body:
give each input an id attribute then use that to get the value(s) to multiply, e.g. document.getElementById("my-id-1").value.  Also, use a basic

doc.getElementById("my-button").addEventListener('click', function(evt) {
    //do your thing.
});


问:
SQL - confused with aggregate
I currently have this query:

```<code>select
  customers.emailaddress,
  MAX(orders.orderdate) as "last order"
from orders
join customers
  on orders.customerID = customers.customerID
group by customers.emailaddress
</code>```

Which gives me the emails, and the last order date. With the 'Orders' table, there is a field named 'PaymentTotal', how can I get this based on the value returned by MAX(orders.orderdate)? (ie am trying to get the amount of the last order per email)

答:
```<code>select c.EmailAddress, om.MaxOrderDate, o.PaymentTotal
from (
    select CustomerID, MAX(orders.orderdate) as MaxOrderDate
    from orders
    group by CustomerID
) om
inner join orders o on om.CustomerID = o.CustomerID
    and om.MaxOrderDate = o.orderdate
inner join customers c on o.customerID = c.customerID
</code>```

Title: SQL - confused with aggregate

Body:
I currently have this query:

select
  customers.emailaddress,
  MAX(orders.orderdate) as "last order"
from orders
join customers
  on orders.customerID = customers.customerID
group by customers.emailaddress

Which gives me the emails, and the last order date. With the 'Orders' table, there is a field named 'PaymentTotal', how can I get this based on the value returned by MAX(orders.orderdate)? (ie am trying to get the amount of the last order per email)


问:
WindowLevel for UITextField's custom input view
Hope to find a workaround on setting windowLevel for my custom inputView.

Scenario: Using PKHUD in the project. It's window level is UIWindowLevelNormal + 1.0. I can change this if needed. I'm showing a custom input view for my textfields. Everything works fine except only when I want to show PKHUD loading indicator, UIAlertController & Custom InputView in the same place.

Showing progress indicator while making server api call when the user entered the content in textfield and tapped "GO". I'm not resigning the keyboard.

So, once I get an error from server, hiding the PKHUD & showing the UIAlertController. But, UIAlertController shows behind my custom keyboard. Any help would be appreciated showing the UIAlertController before the custom keyboard input view without resigning it.

答:
I didn't find a workaround. But, I got an advice from an expert. He said to not mess with a WindowLevel. Keyboard is a top level window and Apple made it there for a reason.

So, whenever we show a progress indicator or alert, we must resign the keyboard and invoke again if it is needed.


问:
Is there a way to forward old logs to Splunk with a new index?
I have logs that were already forwarded to an index (A). I have zipped up the logs and saved them. I noticed that index A had a very low retention period, so I was losing logs in Splunk before I could do my analysis. I created a new index (B) with a longer retention period and want to forward the old zipped logs to this new index. I changed the config and restarted splunk forwarder. I don't see the unzipped logs being forwarded to the new index. Am I missing something? Is there an easy way to do this? I don't mind copying my log data to a new file. I tried that and it didn't work.</p>

答:
In my opinion, you don't need to create a new index.

First you need to Change a retirement and archiving policy

Then you can Restore archived indexed data.
In this step, you can ask splunk to reindex the "Thaw" logs and keep it for as long as you want.


问:
Add models to java classpath
How can I add below OpenNLP models to my java web application classpath ? I just copied the "en-parser-chunking.bin" file to my java web application src folder. But it gives me the class not found exception. What is the correct way to add this file to my classpath in tomcat 9 ?

Open NLP Tools Models

答:
If using Maven, create a folder structure under src/main/resources/ that reflects the package of the class you are using to load the model. For example, src/main/resources/mycompany/myapp/.

You will be able to load the model using this code:

```<code>InputStream modelIn = this.getClass().getResourceAsStream("en-parser-chunking.bin");
model = new ParserModel(modelIn);
            modelIn.close();
</code>```

You can find more information on Apache OpenNLP Documentation, more specifically in the Parser API docs.

Title: Add models to java classpath

Body:
If using Maven, create a folder structure under src/main/resources/ that reflects the package of the class you are using to load the model. For example, src/main/resources/mycompany/myapp/.

You will be able to load the model using this code:

InputStream modelIn = this.getClass().getResourceAsStream("en-parser-chunking.bin");
model = new ParserModel(modelIn);
            modelIn.close();

You can find more information on Apache OpenNLP Documentation, more specifically in the Parser API docs.


问:
match and originalkey to resize Image in lambda function
I'm working with lambda function to resize the upload image in my s3 bucket, I'm encountering few problems with the following code, Can anyone explain what is "const match"  and  "originalKey" I tried several combination . none helped me.

```<code> 'use strict';
 const AWS = require('aws-sdk');
 const S3 = new AWS.S3({
 accessKeyId: "xxxxxxxxxxxx",
 secretAccessKey: "yyyyyyyyyyy",
region: "us-east-1",
signatureVersion: 'v4',
});

const Sharp = require('sharp');
const BUCKET = "patientimg";
const URL = "https://s3.ap-south-1.amazonaws.com";
exports.handler = function(event, context, callback) {
const key = event.Records[0].s3.object.key;
const match = key.match(/(\d+)x(\d+)\/(.*)/);
const width =10;
const height =10;
const originalKey ="ImageName";

S3.getObject({Bucket: BUCKET, Key: originalKey}).promise()
.then(data => Sharp(data.Body)
 .resize(width, height)
  .toFormat('png')
    .toBuffer()
 )
 .then(buffer => S3.putObject({
   Body: buffer,
    Bucket: BUCKET,
     ContentType: "image/png",
       Key: key,
        }).promise()
    )
.then(() => callback(null, {
   statusCode: '301',
    headers: {'location': "${URL}/${key}"},
      body: "",
  })
)
 .catch(err => callback(err))
}
</code>```

output:

error occured in match[1], match[2] and match[3]

Thanks in advance.....

答:
This code assumes the uploaded object key matches a specific pattern /(\d+)x(\d+)\/(.*)/, which means:

```<code>\d+ 1 or more digits - match[1]
x a literal x
\d+ 1 or more digits - match[2]
\/ a literal slash
.* zero or more of any character - match[3]
</code>```

If your object key doesn't match this pattern, the code would break.

Body:
I'm working with lambda function to resize the upload image in my s3 bucket, I'm encountering few problems with the following code, Can anyone explain what is "const match"  and  "originalKey" I tried several combination . none helped me.

 'use strict';
 const AWS = require('aws-sdk');
 const S3 = new AWS.S3({
 accessKeyId: "xxxxxxxxxxxx",
 secretAccessKey: "yyyyyyyyyyy",
region: "us-east-1",
signatureVersion: 'v4',
});

const Sharp = require('sharp');
const BUCKET = "patientimg";
const URL = "https://s3.ap-south-1.amazonaws.com";
exports.handler = function(event, context, callback) {
const key = event.Records[0].s3.object.key;
const match = key.match(/(\d+)x(\d+)\/(.*)/);
const width =10;
const height =10;
const originalKey ="ImageName";

S3.getObject({Bucket: BUCKET, Key: originalKey}).promise()
.then(data => Sharp(data.Body)
 .resize(width, height)
  .toFormat('png')
    .toBuffer()
 )
 .then(buffer => S3.putObject({
   Body: buffer,
    Bucket: BUCKET,
     ContentType: "image/png",
       Key: key,
        }).promise()
    )
.then(() => callback(null, {
   statusCode: '301',
    headers: {'location': "${URL}/${key}"},
      body: "",
  })
)
 .catch(err => callback(err))
}

output:

error occured in match[1], match[2] and match[3]

Thanks in advance.....

Body:
This code assumes the uploaded object key matches a specific pattern /(\d+)x(\d+)\/(.*)/, which means:

\d+ 1 or more digits - match[1]
x a literal x
\d+ 1 or more digits - match[2]
\/ a literal slash
.* zero or more of any character - match[3]

If your object key doesn't match this pattern, the code would break.


问:
How to edit Database file?
I want to change the database at:

```<code>/data/data/com.android.provider.settings/databases/settings.db
</code>```

I can create new databases with:

```<code>final String MY_DB_NAME = "Test";
final String MY_DB_TABLE = "Autos";

SQLiteDatabase myDB = null;

myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);
myDB.execSQL("CREATE TABLE IF NOT EXISTS " + MY_DB_TABLE + " (_id integer primary key autoincrement, name varchar(100))");

myDB.execSQL("INSERT INTO " + MY_DB_TABLE + " (name)" + " VALUES ('Audi TT');");
myDB.execSQL("INSERT INTO " + MY_DB_TABLE + " (name)" + " VALUES ('Honda Civic');");
</code>```

Now, that creates only the name, how can I add the value?

Thanks in advance

答:
You have to use getWritableDatabase() to get hold of SQLiteDatabase object. using this object you can do db operations using execSQL.

I usually have all db operations in a seperate class which extends from SQLiteOpenHelper

Title: How to edit Database file?

Body:
I want to change the database at:

/data/data/com.android.provider.settings/databases/settings.db

I can create new databases with:

final String MY_DB_NAME = "Test";
final String MY_DB_TABLE = "Autos";

SQLiteDatabase myDB = null;

myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);
myDB.execSQL("CREATE TABLE IF NOT EXISTS " + MY_DB_TABLE + " (_id integer primary key autoincrement, name varchar(100))");

myDB.execSQL("INSERT INTO " + MY_DB_TABLE + " (name)" + " VALUES ('Audi TT');");
myDB.execSQL("INSERT INTO " + MY_DB_TABLE + " (name)" + " VALUES ('Honda Civic');");

Now, that creates only the name, how can I add the value?

Thanks in advance


问:
insert <button> to the end of layer styled text-overflow:ellipsis
I'm trying to add [read more] button to multiple line ellipsis layer.

```<code><p class="description">this is long text.this is long text. <button type="button">expand</button></p>

.description {
  width: 300px;
  text-overflow: ellipsis;
  display: -webkit-box;
  overflow: hidden;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.description button {
  margin: 0; padding: 0 0 0 10px;
  background-color: transparent; border-width: 0; outline-width: 0;
  font-size: 14px; color: #3f8f7b;
}
</code>```

https://jsfiddle.net/redhork7/symuzrmt/

the result should be like,

```<code>this is long text.this is long text.this is long text.this is long text.
this is long text.this is long text.this is long text.this is long text.
this is long text.this is long text.this is long text...   [more button]
</code>```

is it possible?

答:
The button needs to be at the right margin of the last line or it can be below the text block? If yes, put it outside the text element

 but

if you need it to be at the bottom right corner, you can set the text content as position:relative and the button as position:absolute /right:0 /bottom:0 , however this way the button is going to overlap the characters at the end of the box.

Body:
I'm trying to add [read more] button to multiple line ellipsis layer.

this is long text.this is long text. <button type="button">expand</button>

.description {
  width: 300px;
  text-overflow: ellipsis;
  display: -webkit-box;
  overflow: hidden;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.description button {
  margin: 0; padding: 0 0 0 10px;
  background-color: transparent; border-width: 0; outline-width: 0;
  font-size: 14px; color: #3f8f7b;
}

https://jsfiddle.net/redhork7/symuzrmt/

the result should be like,

this is long text.this is long text.this is long text.this is long text.
this is long text.this is long text.this is long text.this is long text.
this is long text.this is long text.this is long text...   [more button]

is it possible?


问:
Perform swipe on screen using AccessibilityService
I want to perform swipe on screen using accessibility service.
i tried this but this only perform a single touch.
i know it is possible because when enable my service on device it says this service can perform swipe,touch,pinch etc.</p>

```<code>Point position=new Point(100,10);
GestureDescription.Builder builder = new GestureDescription.Builder();
Path p = new Path();
p.moveTo(position.x, position.y);
builder.addStroke(new GestureDescription.StrokeDescription(p, 100L, 50L));
GestureDescription gesture = builder.build();
boolean isDispatched =    dispatchGesture(gesture,gestureResultCallback,null);
</code>```

答:
I think you have multiple problems.  How you're building your gesture is a little off, and the number of pixels you have to move for it to be a swipe is bigger than you think!  I would calculate this based on screen size, rather than a specific number of pixels.  I think of a typical swipe gesture as about half the screen, originating from one side to the other, right in the middle height wise.

I set up a silly little "onAccessibilityEvent" listener, that on my Nexus 6 bounces back and forth between home screen 1 and home screen two.  You have to have two home screens set up obviously to see it in action.

```<code>@Override
public void onAccessibilityEvent(AccessibilityEvent event) {

    switch (event.getEventType()) {
        case AccessibilityEvent.TYPE_ANNOUNCEMENT:
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {

                DisplayMetrics displayMetrics = getResources().getDisplayMetrics();

                int middleYValue = displayMetrics.heightPixels / 2;
                final int leftSideOfScreen = displayMetrics.widthPixels / 4;
                final int rightSizeOfScreen = leftSideOfScreen * 3;
                GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
                Path path = new Path();

                if (event.getText() != null && event.getText().toString().contains("1")) {
                    //Swipe left
                    path.moveTo(rightSizeOfScreen, middleYValue);
                    path.lineTo(leftSideOfScreen, middleYValue);
                } else {
                    //Swipe right
                    path.moveTo(leftSideOfScreen, middleYValue);
                    path.lineTo(rightSizeOfScreen, middleYValue);
                }

                gestureBuilder.addStroke(new GestureDescription.StrokeDescription(path, 100, 50));
                dispatchGesture(gestureBuilder.build(), new GestureResultCallback() {
                    @Override
                    public void onCompleted(GestureDescription gestureDescription) {
                        Log.w("Gesture Completed");
                        super.onCompleted(gestureDescription);
                    }
                }, null);
            }

        default: {
            break;
        }
    }
}
</code>```

Also important is the accessibility configuration info, check out my config xml file

```<code><accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/accessibility_service_description"
android:accessibilityEventTypes="typeAllMask"
android:accessibilityFlags="flagReportViewIds"
android:canRetrieveWindowContent="true"
android:canRequestTouchExplorationMode="true"
android:accessibilityFeedbackType="feedbackSpoken"
android:notificationTimeout="100"
android:settingsActivity="com.moba11y.basicaccessibilityservice.SettingsActivity"
android:canPerformGestures="true"
/>
</code>```

EDIT:

To support swiping up or down you just need to change your path arguments.

```<code>final int height = displayMetrics.heightPixels;
final int top = height * .25;
final int mid = height * .5;
final int bottom = height * .75;
final int midX = displayMetrics.widthPixels / 2;

if(swipeUp) {
    path.moveTo(midX, bottom);
    path.lineTo(midX, top);
} else {
    path.moveTo(midX, top);
    path.lineTo(midX, bottom);
}
</code>```

Body:
I want to perform swipe on screen using accessibility service.
i tried this but this only perform a single touch.
i know it is possible because when enable my service on device it says this service can perform swipe,touch,pinch etc.

Point position=new Point(100,10);
GestureDescription.Builder builder = new GestureDescription.Builder();
Path p = new Path();
p.moveTo(position.x, position.y);
builder.addStroke(new GestureDescription.StrokeDescription(p, 100L, 50L));
GestureDescription gesture = builder.build();
boolean isDispatched =    dispatchGesture(gesture,gestureResultCallback,null);

Body:
I think you have multiple problems.  How you're building your gesture is a little off, and the number of pixels you have to move for it to be a swipe is bigger than you think!  I would calculate this based on screen size, rather than a specific number of pixels.  I think of a typical swipe gesture as about half the screen, originating from one side to the other, right in the middle height wise.

I set up a silly little "onAccessibilityEvent" listener, that on my Nexus 6 bounces back and forth between home screen 1 and home screen two.  You have to have two home screens set up obviously to see it in action.

@Override
public void onAccessibilityEvent(AccessibilityEvent event) {

    switch (event.getEventType()) {
        case AccessibilityEvent.TYPE_ANNOUNCEMENT:
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {

                DisplayMetrics displayMetrics = getResources().getDisplayMetrics();

                int middleYValue = displayMetrics.heightPixels / 2;
                final int leftSideOfScreen = displayMetrics.widthPixels / 4;
                final int rightSizeOfScreen = leftSideOfScreen * 3;
                GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
                Path path = new Path();

                if (event.getText() != null && event.getText().toString().contains("1")) {
                    //Swipe left
                    path.moveTo(rightSizeOfScreen, middleYValue);
                    path.lineTo(leftSideOfScreen, middleYValue);
                } else {
                    //Swipe right
                    path.moveTo(leftSideOfScreen, middleYValue);
                    path.lineTo(rightSizeOfScreen, middleYValue);
                }

                gestureBuilder.addStroke(new GestureDescription.StrokeDescription(path, 100, 50));
                dispatchGesture(gestureBuilder.build(), new GestureResultCallback() {
                    @Override
                    public void onCompleted(GestureDescription gestureDescription) {
                        Log.w("Gesture Completed");
                        super.onCompleted(gestureDescription);
                    }
                }, null);
            }

        default: {
            break;
        }
    }
}

Also important is the accessibility configuration info, check out my config xml file

<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/accessibility_service_description"
android:accessibilityEventTypes="typeAllMask"
android:accessibilityFlags="flagReportViewIds"
android:canRetrieveWindowContent="true"
android:canRequestTouchExplorationMode="true"
android:accessibilityFeedbackType="feedbackSpoken"
android:notificationTimeout="100"
android:settingsActivity="com.moba11y.basicaccessibilityservice.SettingsActivity"
android:canPerformGestures="true"
/>

EDIT:

To support swiping up or down you just need to change your path arguments.

final int height = displayMetrics.heightPixels;
final int top = height * .25;
final int mid = height * .5;
final int bottom = height * .75;
final int midX = displayMetrics.widthPixels / 2;

if(swipeUp) {
    path.moveTo(midX, bottom);
    path.lineTo(midX, top);
} else {
    path.moveTo(midX, top);
    path.lineTo(midX, bottom);
}


问:
Call a stored procedure from a select statement in a stored procedure
I have a SQL Server 2016 database with a table that stores an XML file. What I want to do if possible is to call another stored procedure and pass in the ApplicationID value.

My code is

```<code>select
    RecID,
    nref.value('APPLICATION_ID[1]','varchar(max)') ApplicationID ,
    nref.value('FY[1]','varchar(max)') FY
into
    ADMIN_stagingTable
from
    [ADMIN_Grant_Exporter_Files_XML]
cross apply
    XMLData.nodes('PROJECTS[1]/row[1]') as R(nref)
where
    nref.value('ORG_DUNS[1]', 'varchar(max)') = '183710748'
</code>```

I'm currently storing it into a staging table. Is there a better way than looping the result set?

```<code>SELECT @APPLICATION_ID = ApplicationID
FROM ADMIN_stagingTable

EXECUTE  [Parse_Exporter] @APPLICATION_ID
</code>```

答:
try using function.
you can put the script of the SP in a function and then you can call it
name the function fn_Parse_Exporter

and use like this

```<code>SELECT *, dbo.fn_Parse_Exporter(ApplicationID)
FROM My_Table
</code>```

Body:
I have a SQL Server 2016 database with a table that stores an XML file. What I want to do if possible is to call another stored procedure and pass in the ApplicationID value.

My code is

select
    RecID,
    nref.value('APPLICATION_ID[1]','varchar(max)') ApplicationID ,
    nref.value('FY[1]','varchar(max)') FY
into
    ADMIN_stagingTable
from
    [ADMIN_Grant_Exporter_Files_XML]
cross apply
    XMLData.nodes('PROJECTS[1]/row[1]') as R(nref)
where
    nref.value('ORG_DUNS[1]', 'varchar(max)') = '183710748'

I'm currently storing it into a staging table. Is there a better way than looping the result set?

SELECT @APPLICATION_ID = ApplicationID
FROM ADMIN_stagingTable

EXECUTE  [Parse_Exporter] @APPLICATION_ID

Body:
try using function.
you can put the script of the SP in a function and then you can call it
name the function fn_Parse_Exporter

and use like this

SELECT *, dbo.fn_Parse_Exporter(ApplicationID)
FROM My_Table


问:
call method using onclick event in invokeelementmethod() and insertadjacentHTML()
I'm trying to call getInput() method in save button via onclick event. But this generates following error:

```<code>Uncaught TypeError: this.getInput is not a function at HTMLButtonElement.onclick ((index):1)
</code>```

I want to call getInput() method. I also tried to call getInput() without this. Any suggestions will be appreciated.

```<code>this.renderer.invokeElementMethod(this.inputYT.nativeElement, "insertAdjacentHTML", ["beforeend", "<button onclick = 'this.getInput()' type = 'button' class = 'btn btn-success' style = 'position: relative; top: -50px; right: 6px; float: right' >Save</button>"]);
</code>```

full code:

```<code>import { Component, Input, Output, ElementRef, ViewChild, Renderer } from "angular2/core";
import {Video} from "./video";

@Component(
{
selector: "playlist",
templateUrl: "app/ts/playlist.component.html",
inputs: ["videos"]
})
export class Playlist
{
iframe: HTMLIFrameElement;
div: HTMLDivElement = document.getElementsByTagName("div")[0];
input: HTMLInputElement;
videoCode: string[];
@ViewChild("inputDiv") inputYT: ElementRef;
constructor(private renderer: Renderer)
{
}
getInput()
{
    this.videoCode = this.input.value.split("=", 2);
    this.videoCode = this.input.value.split("&", 2);
}
addVideos()
{
    if(this.input)
        return;
    this.renderer.invokeElementMethod(this.inputYT.nativeElement, "insertAdjacentHTML", ["beforebegin", "<script src = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>"]);
    this.input = document.createElement("input");
    this.renderer.invokeElementMethod(this.inputYT.nativeElement, "insertAdjacentHTML", ["beforeend", "<input type = 'text' class = 'form-control input-lg' id = 'inputText' style = 'margin: 10px 0px; width: 100%;' placeholder = 'Paste youtube video link here'/>"]);
    this.renderer.invokeElementMethod(this.inputYT.nativeElement, "insertAdjacentHTML", ["beforeend", "<button onclick = 'this.getInput()' type = 'button' class = 'btn btn-success' style = 'position: relative; top: -50px; right: 6px; float: right'>Save</button>"]);
}
onSelect(vid: Video)
{
    if(this.iframe)
        this.div.removeChild(this.iframe);
    this.iframe = document.createElement("iframe");
    this.iframe.setAttribute("width", "800");
    this.iframe.setAttribute("height", "500");
    this.iframe.setAttribute("src", "https://www.youtube.com/embed/" + vid.link);
    this.div.appendChild(this.iframe);
}
}
</code>```

答:
Add onclick event like this -

(click)="getInput ()"

Body:
I'm trying to call getInput() method in save button via onclick event. But this generates following error:

Uncaught TypeError: this.getInput is not a function at HTMLButtonElement.onclick ((index):1)

I want to call getInput() method. I also tried to call getInput() without this. Any suggestions will be appreciated.

this.renderer.invokeElementMethod(this.inputYT.nativeElement, "insertAdjacentHTML", ["beforeend", "<button onclick = 'this.getInput()' type = 'button' class = 'btn btn-success' style = 'position: relative; top: -50px; right: 6px; float: right' >Save</button>"]);

full code:

import { Component, Input, Output, ElementRef, ViewChild, Renderer } from "angular2/core";
import {Video} from "./video";

@Component(
{
selector: "playlist",
templateUrl: "app/ts/playlist.component.html",
inputs: ["videos"]
})
export class Playlist
{
iframe: HTMLIFrameElement;
div: HTMLDivElement = document.getElementsByTagName("div")[0];
input: HTMLInputElement;
videoCode: string[];
@ViewChild("inputDiv") inputYT: ElementRef;
constructor(private renderer: Renderer)
{
}
getInput()
{
    this.videoCode = this.input.value.split("=", 2);
    this.videoCode = this.input.value.split("&", 2);
}
addVideos()
{
    if(this.input)
        return;
    this.renderer.invokeElementMethod(this.inputYT.nativeElement, "insertAdjacentHTML", ["beforebegin", ""]);
    this.input = document.createElement("input");
    this.renderer.invokeElementMethod(this.inputYT.nativeElement, "insertAdjacentHTML", ["beforeend", "<input type = 'text' class = 'form-control input-lg' id = 'inputText' style = 'margin: 10px 0px; width: 100%;' placeholder = 'Paste youtube video link here'/>"]);
    this.renderer.invokeElementMethod(this.inputYT.nativeElement, "insertAdjacentHTML", ["beforeend", "<button onclick = 'this.getInput()' type = 'button' class = 'btn btn-success' style = 'position: relative; top: -50px; right: 6px; float: right'>Save</button>"]);
}
onSelect(vid: Video)
{
    if(this.iframe)
        this.div.removeChild(this.iframe);
    this.iframe = document.createElement("iframe");
    this.iframe.setAttribute("width", "800");
    this.iframe.setAttribute("height", "500");
    this.iframe.setAttribute("src", "https://www.youtube.com/embed/" + vid.link);
    this.div.appendChild(this.iframe);
}
}