问:
An INSERT EXEC statement cannot be nested. Dealing with error
Not duplicate. The problem here is it has different structure. and I have some restrictions of what I can change and what I can't. Here I have exact example, which other tickets don't. OPENROWSET cannot be applied either, because test1 loops through all dbs (using       EXEC sp_MSforeachdb @sql). And I can't use it, because in OPENROWSET you have to specify from which db you are running procedure

Suppose I have these two SPs:

```<code>create procedure test1
@ProcName  varchar(155)
as
begin

if OBJECT_ID('tempdb..#testt') is not null drop table #testt
create table #testt1(a int, b int)

insert #testt1
exec @ProcName

select * from #testt1
end

create procedure test2
as
begin

declare @sql varchar(155)

if OBJECT_ID('tempdb..#testt2') is not null drop table #testt2
create table #testt2(a int, b int)

select @sql = 'select 1 as a,2 as b'

insert #testt2
exec (@sql)

select * from #testt2

end
</code>```

when I run exec test1 @ProcName = 'Test2', it returns error:

An INSERT EXEC statement cannot be nested.

The problem here is that I can't stop using insert exec in test2. And test1 should have @ProcName as a variable

What is the least painless way to resolve this issue?

答: Putting insert statement inside test2 procedure solved problem

Body:
Not duplicate. The problem here is it has different structure. and I have some restrictions of what I can change and what I can't. Here I have exact example, which other tickets don't. OPENROWSET cannot be applied either, because test1 loops through all dbs (using       EXEC sp_MSforeachdb @sql). And I can't use it, because in OPENROWSET you have to specify from which db you are running procedure

Suppose I have these two SPs:

create procedure test1
@ProcName  varchar(155)
as
begin

if OBJECT_ID('tempdb..#testt') is not null drop table #testt
create table #testt1(a int, b int)

insert #testt1
exec @ProcName

select * from #testt1
end

create procedure test2
as
begin

declare @sql varchar(155)

if OBJECT_ID('tempdb..#testt2') is not null drop table #testt2
create table #testt2(a int, b int)

select @sql = 'select 1 as a,2 as b'

insert #testt2
exec (@sql)

select * from #testt2

end

when I run exec test1 @ProcName = 'Test2', it returns error:

An INSERT EXEC statement cannot be nested.

The problem here is that I can't stop using insert exec in test2. And test1 should have @ProcName as a variable

What is the least painless way to resolve this issue?


来源: stackexchange

问:
Angular 2 http GET for json file returns 404
I'm doing a POC to prove I have communication between the back end and front end in Angular Universal. I've got a JSON file in the back end called heroes.json that I want to retrieve from the front end service ModelService in model.service.ts.

I have this folder structure:

Within model.service.ts (front end) I want to create an http request to get some data in a method called getStuff().

I have this in model.service.ts:

```<code>// domain/feature service
@Injectable()
export class ModelService {
  private heroesUrl = "http://localhost:4000/src/backend/heroes.json"; // URL to JSON file
   // This is only one example of one Model depending on your domain
  constructor(public api: ApiService, public cacheService: CacheService, private http: Http) {

  }

  public getStuff(): Observable<any[]> {
        return this.http.get(this.heroesUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }

    private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
  }

    private handleError (error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || "";
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ""} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

    // domain/feature service
    @Injectable()
    export class ModelService {
      private heroesUrl = "http://localhost:4000/src/backend/heroes.json"; // URL to JSON file
       // This is only one example of one Model depending on your domain
      constructor(public api: ApiService, public cacheService: CacheService, private http: Http) {

      }

      public getStuff(): Observable<any[]> {
            return this.http.get(this.heroesUrl)
                        .map(this.extractData)
                        .catch(this.handleError);
      }

        private extractData(res: Response) {
        let body = res.json();
        return body.data || { };
      }

        private handleError (error: Response | any) {
        // In a real world app, we might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {
          const body = error.json() || "";
          const err = body.error || JSON.stringify(body);
          errMsg = `${error.status} - ${error.statusText || ""} ${err}`;
        } else {
          errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
      }
</code>```

From a front end component I am calling the ModelService.getHeroes:

```<code>export class HomeComponent {

      public data: any = {};
      constructor(public modelService: ModelService) {
        // we need the data synchronously for the client to set the server response
        // we create another method so we have more control for testing
        this.universalInit();
      }

      public universalInit() {

        this.modelService.getStuff().subscribe((data) => {
          this.data = data;
        });
      }
</code>```

I'm getting this error:

```<code>GET /src/backend/heroes.json 404 3.698 ms - 46
404 -  {"status":404,"message":"No Content"}
EXCEPTION: 404 -  {"status":404,"message":"No Content"}

/private/var/root/vepo/node_modules/rxjs/Subscriber.js:227
            throw err;
            ^
404 -  {"status":404,"message":"No Content"}
[nodemon] app crashed - waiting for file changes before starting...
</code>```

So my url private heroesUrl = "http://localhost:4000/src/backend/heroes.json"; // URL to JSON file in the service is wrong. Given that folder structure, what would the url be? Because the actual running project, the output, is in dist:

So I'm not sure what to put in ModelService.heroesUrl. What string value should ModelService.heroesUrl have?

答:
I put my the same file places.json to "assets" folder
and after set the url like:

```<code>places = this.http.request("http://localhost:4200/assets/places.json")
</code>```

hope this info will helpful for somebody.

ContentLicense: CC BY-SA 3.0

Body:
I'm doing a POC to prove I have communication between the back end and front end in Angular Universal. I've got a JSON file in the back end called heroes.json that I want to retrieve from the front end service ModelService in model.service.ts.

I have this folder structure:

Within model.service.ts (front end) I want to create an http request to get some data in a method called getStuff().

I have this in model.service.ts:

// domain/feature service
@Injectable()
export class ModelService {
  private heroesUrl = "http://localhost:4000/src/backend/heroes.json"; // URL to JSON file
   // This is only one example of one Model depending on your domain
  constructor(public api: ApiService, public cacheService: CacheService, private http: Http) {

  }

  public getStuff(): Observable<any[]> {
        return this.http.get(this.heroesUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }

    private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
  }

    private handleError (error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || "";
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ""} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

    // domain/feature service
    @Injectable()
    export class ModelService {
      private heroesUrl = "http://localhost:4000/src/backend/heroes.json"; // URL to JSON file
       // This is only one example of one Model depending on your domain
      constructor(public api: ApiService, public cacheService: CacheService, private http: Http) {

      }

      public getStuff(): Observable<any[]> {
            return this.http.get(this.heroesUrl)
                        .map(this.extractData)
                        .catch(this.handleError);
      }

        private extractData(res: Response) {
        let body = res.json();
        return body.data || { };
      }

        private handleError (error: Response | any) {
        // In a real world app, we might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {
          const body = error.json() || "";
          const err = body.error || JSON.stringify(body);
          errMsg = `${error.status} - ${error.statusText || ""} ${err}`;
        } else {
          errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
      }

From a front end component I am calling the ModelService.getHeroes:

export class HomeComponent {

      public data: any = {};
      constructor(public modelService: ModelService) {
        // we need the data synchronously for the client to set the server response
        // we create another method so we have more control for testing
        this.universalInit();
      }

      public universalInit() {

        this.modelService.getStuff().subscribe((data) => {
          this.data = data;
        });
      }

I'm getting this error:

GET /src/backend/heroes.json 404 3.698 ms - 46
404 -  {"status":404,"message":"No Content"}
EXCEPTION: 404 -  {"status":404,"message":"No Content"}

/private/var/root/vepo/node_modules/rxjs/Subscriber.js:227
            throw err;
            ^
404 -  {"status":404,"message":"No Content"}
[nodemon] app crashed - waiting for file changes before starting...

So my url private heroesUrl = "http://localhost:4000/src/backend/heroes.json"; // URL to JSON file in the service is wrong. Given that folder structure, what would the url be? Because the actual running project, the output, is in dist:

So I'm not sure what to put in ModelService.heroesUrl. What string value should ModelService.heroesUrl have?

Body:
I put my the same file places.json to "assets" folder
and after set the url like:

places = this.http.request("http://localhost:4200/assets/places.json")

hope this info will helpful for somebody.


问:
How to detect and track the foot using ARKIt and vision framework?
I wants to virtually add foot ball and detect and tracking the foot so that we can simulate the kick to the ball.

Can any one please suggest the way achieve it in iOS?

答: I think you'll have to have your own CoreML model that identify where a foot is in an image, and pass it the frames captured by the camera and identify where there is a foot. ARKit doesn't do that and there's no foot recognition built in iOS 11</p>


问:
Retrieve and Rank IBM
In IBM Rank and Retrieve, is it possible to use your own Solr Cluster to save on expenses? If so, how?
I am creating a chatbot and require Retrieve and Rank for the same. The IBM free service seems to have only a 50MB limit to the solr cluster. Is there any way to bypass this?</p>

答: It is possible to use the rank portion of the Retrieve and Rank portion as a standalone learning-to-rank component.  However, this requires having to generate all your own features on top of Solr.  The feature generation part of the Retrieve and Rank service is only available in IBM's Solr Cluster...so it can't really be used with your own Solr Cluster.

Title: Retrieve and Rank IBM


问:
Python Semaphore: I Need Negative Initial Value
Python's semaphore doesn't support negative initial values. How, then, do I make a thread wait until 8 other threads have done something? If Semophore supported negative initial values, I could have just set it to -8, and have each thread increment the value by 1, until we have a 0, which unblocks the waiting thread.

I can manually increment a global counter inside a critical section, then use a conditional variable, but I want to see if there are other suggestions.

答:
Surely it's late for an answer, but it can come handy to someone else.

If you want to wait for 8 different threads to do something, you can just wait 8 times.
You initialize a semaphore in 0 with

s = threading.Semaphore(0)

and then

```<code>for _ in range(8):
    s.acquire()
</code>```

will do the job.

Full example:

import threading
import time

NUM_THREADS = 4

s = threading.Semaphore(0)

def thread_function(i):
    print("start of thread", i)
    time.sleep(1)
    s.release()
    print("end of thread", i)

def main_thread():
    print("start of main thread")

    threads = [
        threading.Thread(target=thread_function, args=(i, ))
        for i
        in range(NUM_THREADS)
    ]

    [t.start() for t in threads]

    [s.acquire() for _ in range(NUM_THREADS)]

    print("end of main thread")

main_thread()
```
<p>Possible output:</p>
```start of main thread
start of thread 0
start of thread 1
start of thread 2
start of thread 3
end of thread 0
end of thread 2
end of thread 1
end of thread 3
end of main thread
```

Body:
Surely it's late for an answer, but it can come handy to someone else.

If you want to wait for 8 different threads to do something, you can just wait 8 times.
You initialize a semaphore in 0 with

s = threading.Semaphore(0)

and then

for _ in range(8):
    s.acquire()

will do the job.

Full example:

import threading
import time

NUM_THREADS = 4

s = threading.Semaphore(0)

def thread_function(i):
    print("start of thread", i)
    time.sleep(1)
    s.release()
    print("end of thread", i)

def main_thread():
    print("start of main thread")

    threads = [
        threading.Thread(target=thread_function, args=(i, ))
        for i
        in range(NUM_THREADS)
    ]

    [t.start() for t in threads]

    [s.acquire() for _ in range(NUM_THREADS)]

    print("end of main thread")

main_thread()

Possible output:

start of main thread
start of thread 0
start of thread 1
start of thread 2
start of thread 3
end of thread 0
end of thread 2
end of thread 1
end of thread 3
end of main thread

ContentLicense: CC BY-SA 4.0


问:
How to send a Asp label value( from server side) from popup window to parent window dropdownlist
Trying to send label value from popupwindow to parent window drop down list  </p>

答:
I got it by using, (Changed to client side)
popup window code:

```<code><script type="text/javascript">
             function updateParent(test) {
            var oVal = test;
            window.opener.updateParent(oVal);
            window.top.close();
        }
    </script>
</code>```

Parent window code:

```<code>function updateParent(oVal) {
            var region = oVal;
            $('#ddlreg option:contains(' + region + ')').each(function () {
                if ($(this).text() == region) {
                    $(this).attr('selected', 'selected');
                    return false;
                }
                return true;
            });
        }
</code>```

Body:
I got it by using, (Changed to client side)
popup window code:

<script type="text/javascript">
             function updateParent(test) {
            var oVal = test;
            window.opener.updateParent(oVal);
            window.top.close();
        }
    </script>

Parent window code:

function updateParent(oVal) {
            var region = oVal;
            $('#ddlreg option:contains(' + region + ')').each(function () {
                if ($(this).text() == region) {
                    $(this).attr('selected', 'selected');
                    return false;
                }
                return true;
            });
        }


问:
Does Clojure Ring create a thread for each request?
I am making a Messenger bot and I am using Ring as my http framework.

Sometime I want to apply delays between messages sent by the bot. My expectation would be that it is safe to use Thread/sleep because this will make the active thread sleep and not the entire server. Is that so, or should I resort to clojure/core.async?

This is the code I would be writing without async:

```<code>  (match [reply]

    ; The bot wants to send a message (text, images, videos etc.) after n milliseconds
    [{:message message :delay delay}]
    (do
      (Thread/sleep interval delay)
      (facebook/send-message sender-id message))
    ; More code would follow...
</code>```

A link to Ring code where its behaviour in this sense is clear would be appreciated, as well as any other with explanation on the matter.

答:
Ring is the wrong thing to ask this question about: ring is not an http server, but rather an abstraction over http servers. Ring itself does not have a fixed threading model: all it really cares about is that you have a function from request to response.

What really makes this decision is which ring adapter you use. By far the most common is ring-jetty-adapter, which is a jetty http handler that delegates to your function through ring. And jetty does indeed have a single thread for each request, so that you can sleep in one thread without impacting others (but as noted in another answer, threads are not free, so you don't want to do a ton of this regularly).

But there are other ring handlers with different threading models. For example, aleph includes a ring adapter based on netty, which uses java.nio for non-blocking IO in a small, limited threadpool; in that case, sleeping on a "request thread" is very disruptive.

Body:
I am making a Messenger bot and I am using Ring as my http framework.

Sometime I want to apply delays between messages sent by the bot. My expectation would be that it is safe to use Thread/sleep because this will make the active thread sleep and not the entire server. Is that so, or should I resort to clojure/core.async?

This is the code I would be writing without async:

  (match [reply]

    ; The bot wants to send a message (text, images, videos etc.) after n milliseconds
    [{:message message :delay delay}]
    (do
      (Thread/sleep interval delay)
      (facebook/send-message sender-id message))
    ; More code would follow...

A link to Ring code where its behaviour in this sense is clear would be appreciated, as well as any other with explanation on the matter.


问:
Select element with div and class and data attribute
How do I select a element using it's element type (Div), a class (spaceEvent) and a data attribute (data-event-id)?

here is an example of a element

```<code><div class="spaceEvent" data-event-id=112>
</code>```

and I want to find this element so that I can search for stuff inside it?

my guess would be something like

```<code>$("div.spaceEvent").find("[event-id=112]")
</code>```

but I'm not sure!

答:
You can use:

$('div.spaceEvent[data-event-id="112"]');

$('div.spaceEvent').filter('[data-event-id="112"]');

The find() function searches the children, not itself. More details here.

Body:
How do I select a element using it's element type (Div), a class (spaceEvent) and a data attribute (data-event-id)?

here is an example of a element

and I want to find this element so that I can search for stuff inside it?

my guess would be something like

$("div.spaceEvent").find("[event-id=112]")

but I'm not sure!


问:
javascript code from external file can not be executed in Cordova app
I want to load an external javascript (without jquery or others) into my Corodova/Phonegapp app (Visual Studio 2015, Cordova CLI 6.1.1) when the app is actually ready and online (I check that in the original code, but did not enter it in the example below). Ultimately this external javascript will be the google maps javascript api. However since I ran into some problems I first tryed with my own little javascript file (external_file.js).

While debugging I can see that the  tag is writen into the original code of my app, but I can not access the loaded code (function external_function() is not available ). I tryed with the ripple emulator as well as with my android 5.1.1 device.

All my functions work on a "normal" html file without cordova. Also when I try to load the javascript file locally (from scripts/external_file.js) I can access the functions located inside the file.

I search quite some time for a solution, but did not find anything usefull:

Andreas Linnert had a similar problem in 2013, but no answer is given there.

psycrow117 wanted to load the googel maps api with  tags (as given in the Google Maps Javascript API Example). However I would like to do that with a function

rolinger did not load the cordova-plugin-whitelist (which I do)

FabianE and KRIZTE describe the same problem. I actually use the solution by Blauharley and e-satis with Jason Livesay to load the external script. However the problem does not seem to be solved in that post, too.

I know that there is the cordova-plugin-googlemaps to load the native environment. Let's just say I do not want to do that for now. If there is no other solution I will have to...

Since my functions work with a "normal" html file and I can also load a local script file corretly, I think I forgot to set something correctly to be able to execute the external code.

I set the Content-Security-Policy to

<meta http-equiv="Content-Security-Policy" content="default-src: 'self' https://myhost https://maps.google.com 'unsafe-inline' 'unsafe-eval'">
<meta http-equiv="Content-Security-Policy" content="script-src: 'self' https://myhost https://maps.google.com 'unsafe-inline' 'unsafe-eval'">```
</div>
</div>
</p>

<p>I also entered the <code>cordova-plugin-whitelist</code> parameters</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<access origin="https://*.googleapis.com" />
<access origin="https://myhost" />
<access origin="*" />
<allow-navigation href="https://*.googleapis.com" />
<allow-navigation href="https://myhost" />
<allow-navigation href="*" />
<allow-intent href="https://*.googleapis.com" />
<allow-intent href="https://myhost" />
<allow-intent href="*" /></code>```

But somehow that does not seem to work, too.

Does anyone have a solution to be able to execute the code after loading the external file?

Later the google maps javascript api needs to be asyncron, but that's a nother issue then.

index.html

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">

    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">

    <meta http-equiv="Content-Security-Policy" content="default-src: 'self' https://myhost https://maps.google.com 'unsafe-inline' 'unsafe-eval'">
    <meta http-equiv="Content-Security-Policy" content="script-src: 'self' https://myhost https://maps.google.com 'unsafe-inline' 'unsafe-eval'">
    <link rel="stylesheet" type="text/css" href="css/index.css">
    <title>Testapp</title>

Testapp

        <button id="loadexternal_button">load external file</button>
        <button id="isloaded_button">is loaded?</button>

```
</div>
</div>
</p>

<h2>index.css</h2>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.app {
    background-color:white;
}

#map{
    height: 400px;
    width: 400px;
    border:1px solid white;
}</code>```

index.js

(function () {
    "use strict";

    function onDeviceReady() {

        // Event Listener for Buttons: https://stackoverflow.com/a/31892530/2381164
        document.getElementById('isloaded_button').addEventListener('click', function () { checkLoadedFile(); }, false);
        document.getElementById('loadexternal_button').addEventListener('click', function () { loadJS('https://myhost/external_file.js', hasloaded(), document.body);
    }, false);
    };

    // https://stackoverflow.com/a/950146/2381164
    function loadJS(url, implementationCode, location) {

        var scriptTag = document.createElement('script');
        scriptTag.src = url;

        scriptTag.onload = implementationCode;
        scriptTag.onreadystatechange = implementationCode;

        location.appendChild(scriptTag);
    };

    // Change color of div when script is loaded
    function hasloaded() {
        var mapElement = document.getElementById('map');
        mapElement.setAttribute('style', 'border:1px solid yellow');
    }
    // Change background-color of div when file is loaded propperly
    function checkLoadedFile() {
        var mapElement = document.getElementById('map');

        if (typeof external_function === 'function') {
            mapElement.setAttribute('style', 'background-color: green;');
        } else {
            mapElement.setAttribute('style', 'background-color: red;');
        }
    }
    // Load when App is ready
    document.addEventListener('deviceready', onDeviceReady.bind(this), false);
})();```
</div>
</div>
</p>

<h2>external_file.js</h2>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function external_function() {
    var mapElement = document.getElementById('map');
    mapElement.setAttribute('style', 'background-color: orange;');
}</code>```

答:
This is the security policy meta i am currently using:

```<code><meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval; media-src *">
</code>```

It currently accepts everything I throw at it! ...please keep in mind that using

content="default-src *;

is not 100% safe as it will run scripts from any location (local or online), but as long as you have

script-src 'self'

in your security meta... the problems you are currently facing while executing external scripts should be a thing of the past!

Body:
I want to load an external javascript (without jquery or others) into my Corodova/Phonegapp app (Visual Studio 2015, Cordova CLI 6.1.1) when the app is actually ready and online (I check that in the original code, but did not enter it in the example below). Ultimately this external javascript will be the google maps javascript api. However since I ran into some problems I first tryed with my own little javascript file (external_file.js).

While debugging I can see that the  tag is writen into the original code of my app, but I can not access the loaded code (function external_function() is not available ). I tryed with the ripple emulator as well as with my android 5.1.1 device.

All my functions work on a "normal" html file without cordova. Also when I try to load the javascript file locally (from scripts/external_file.js) I can access the functions located inside the file.

I search quite some time for a solution, but did not find anything usefull:

Andreas Linnert had a similar problem in 2013, but no answer is given there.

psycrow117 wanted to load the googel maps api with  tags (as given in the Google Maps Javascript API Example). However I would like to do that with a function

rolinger did not load the cordova-plugin-whitelist (which I do)

FabianE and KRIZTE describe the same problem. I actually use the solution by Blauharley and e-satis with Jason Livesay to load the external script. However the problem does not seem to be solved in that post, too.

I know that there is the cordova-plugin-googlemaps to load the native environment. Let's just say I do not want to do that for now. If there is no other solution I will have to...

Since my functions work with a "normal" html file and I can also load a local script file corretly, I think I forgot to set something correctly to be able to execute the external code.

I set the Content-Security-Policy to

<meta http-equiv="Content-Security-Policy" content="default-src: 'self' https://myhost https://maps.google.com 'unsafe-inline' 'unsafe-eval'">
<meta http-equiv="Content-Security-Policy" content="script-src: 'self' https://myhost https://maps.google.com 'unsafe-inline' 'unsafe-eval'">

I also entered the cordova-plugin-whitelist parameters

<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<access origin="https://*.googleapis.com" />
<access origin="https://myhost" />
<access origin="*" />
<allow-navigation href="https://*.googleapis.com" />
<allow-navigation href="https://myhost" />
<allow-navigation href="*" />
<allow-intent href="https://*.googleapis.com" />
<allow-intent href="https://myhost" />
<allow-intent href="*" />

But somehow that does not seem to work, too.

Does anyone have a solution to be able to execute the code after loading the external file?

Later the google maps javascript api needs to be asyncron, but that's a nother issue then.

index.html

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">

    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">

    <meta http-equiv="Content-Security-Policy" content="default-src: 'self' https://myhost https://maps.google.com 'unsafe-inline' 'unsafe-eval'">
    <meta http-equiv="Content-Security-Policy" content="script-src: 'self' https://myhost https://maps.google.com 'unsafe-inline' 'unsafe-eval'">
    <link rel="stylesheet" type="text/css" href="css/index.css">
    <title>Testapp</title>

Testapp

        <button id="loadexternal_button">load external file</button>
        <button id="isloaded_button">is loaded?</button>

index.css

.app {
    background-color:white;
}

#map{
    height: 400px;
    width: 400px;
    border:1px solid white;
}

index.js

(function () {
    "use strict";

    function onDeviceReady() {

        // Event Listener for Buttons: https://stackoverflow.com/a/31892530/2381164
        document.getElementById('isloaded_button').addEventListener('click', function () { checkLoadedFile(); }, false);
        document.getElementById('loadexternal_button').addEventListener('click', function () { loadJS('https://myhost/external_file.js', hasloaded(), document.body);
    }, false);
    };

    // https://stackoverflow.com/a/950146/2381164
    function loadJS(url, implementationCode, location) {

        var scriptTag = document.createElement('script');
        scriptTag.src = url;

        scriptTag.onload = implementationCode;
        scriptTag.onreadystatechange = implementationCode;

        location.appendChild(scriptTag);
    };

    // Change color of div when script is loaded
    function hasloaded() {
        var mapElement = document.getElementById('map');
        mapElement.setAttribute('style', 'border:1px solid yellow');
    }
    // Change background-color of div when file is loaded propperly
    function checkLoadedFile() {
        var mapElement = document.getElementById('map');

        if (typeof external_function === 'function') {
            mapElement.setAttribute('style', 'background-color: green;');
        } else {
            mapElement.setAttribute('style', 'background-color: red;');
        }
    }
    // Load when App is ready
    document.addEventListener('deviceready', onDeviceReady.bind(this), false);
})();

external_file.js

function external_function() {
    var mapElement = document.getElementById('map');
    mapElement.setAttribute('style', 'background-color: orange;');
}

Body:
This is the security policy meta i am currently using:

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval; media-src *">

It currently accepts everything I throw at it! ...please keep in mind that using

content="default-src *;

is not 100% safe as it will run scripts from any location (local or online), but as long as you have

script-src 'self'

in your security meta... the problems you are currently facing while executing external scripts should be a thing of the past!


问:
How to 'wait' for two observables in RxJS
In my app i have something like:

```<code>this._personService.getName(id)
      .concat(this._documentService.getDocument())
      .subscribe((response) => {
                  console.log(response)
                  this.showForm()
       });

 //Output:
 // [getnameResult]
 // [getDocumentResult]

 // I want:
 // [getnameResult][getDocumentResult]
</code>```

Then i get two separated results, first of the _personService and then the _documentService. How can I wait for both results before call this.showForm() to finish an then manipulate the results of each one.

答:
Last Update: Mar, 2022.

RxJS v7: combineLatestWith

From reactiveX documentation:

Whenever any input Observable emits a value, it computes a formula using the latest values from all the inputs, then emits the output of that formula.

```<code>// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();

name$.pipe(
        combineLatestWith($document)
      )
      .subscribe(([name, document]) => {
           this.name = name;
           this.document = pair.document;
           this.showForm();
       })
</code>```

(Deprecated) RxJS v6 combineLatest()

From reactiveX documentation:

Whenever any input Observable emits a value, it computes a formula using the latest values from all the inputs, then emits the output of that formula.

(Update: Feb, 2021):

```<code>// Deprecated (RxJS v6)
// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();

name$.combineLatest(document$, (name, document) => {name, document})
    .subscribe(pair => {
           this.name = pair.name;
           this.document = pair.document;
           this.showForm();
       })
</code>```

(alternate syntax): combineLatest(observables)

```<code>// Deprecated (RxJS v6)
// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();

combineLatest(name$, document$, (name, document) => ({name, document}))
    .subscribe(pair => {
           this.name = pair.name;
           this.document = pair.document;
           this.showForm();
       })
</code>```

zip vs combineLatest

(Update: Oct, 2018)
I previously suggested the use of zip method. However, for some use cases, combineLatest has a few advantages over zip. So it is important to understand the differences.

CombineLatest emits the latest emitted values from observables. While zip method emits the emitted items in sequence order.

For example if observable #1 emits its 3rd item and observable #2 has emitted its 5th item. The result using zip method will be the 3rd emitted values of both observables.

In this situation the result using combineLatest will be the 5th and 3rd. which feels more natural.

Observable.zip(observables)

(Original answer: Jul, 2017) Observable.zip method is explained in reactiveX documentation:

Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each of its input Observables.

```<code>// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();

Observable
    .zip(name$, document$, (name: string, document: string) => ({name, document}))
    .subscribe(pair => {
           this.name = pair.name;
           this.document = pair.document;
           this.showForm();
       })
</code>```

a side note (applies for both methods)

The last parameter, where we have provided a function, (name: string, document: string) => ({name, document}) is optional. You can skip it, or do more complex operations:

If the latest parameter is a function, this function is used to compute the created value from the input values. Otherwise, an array of the input values is returned.

So if you skip the last part, you get an array:

```<code>// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();

Observable
    .zip(name$, document$)
    .subscribe(pair => {
           this.name = pair['0'];
           this.document = pair['1'];
           this.showForm();
       })
</code>```

Body:
In my app i have something like:

this._personService.getName(id)
      .concat(this._documentService.getDocument())
      .subscribe((response) => {
                  console.log(response)
                  this.showForm()
       });

 //Output:
 // [getnameResult]
 // [getDocumentResult]

 // I want:
 // [getnameResult][getDocumentResult]

Then i get two separated results, first of the _personService and then the _documentService. How can I wait for both results before call this.showForm() to finish an then manipulate the results of each one.

Body:
Last Update: Mar, 2022.

RxJS v7: combineLatestWith

From reactiveX documentation:

Whenever any input Observable emits a value, it computes a formula using the latest values from all the inputs, then emits the output of that formula.

// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();

name$.pipe(
        combineLatestWith($document)
      )
      .subscribe(([name, document]) => {
           this.name = name;
           this.document = pair.document;
           this.showForm();
       })

(Deprecated) RxJS v6 combineLatest()

From reactiveX documentation:

Whenever any input Observable emits a value, it computes a formula using the latest values from all the inputs, then emits the output of that formula.

(Update: Feb, 2021):

// Deprecated (RxJS v6)
// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();

name$.combineLatest(document$, (name, document) => {name, document})
    .subscribe(pair => {
           this.name = pair.name;
           this.document = pair.document;
           this.showForm();
       })

(alternate syntax): combineLatest(observables)

// Deprecated (RxJS v6)
// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();

combineLatest(name$, document$, (name, document) => ({name, document}))
    .subscribe(pair => {
           this.name = pair.name;
           this.document = pair.document;
           this.showForm();
       })

zip vs combineLatest

(Update: Oct, 2018)
I previously suggested the use of zip method. However, for some use cases, combineLatest has a few advantages over zip. So it is important to understand the differences.

CombineLatest emits the latest emitted values from observables. While zip method emits the emitted items in sequence order.

For example if observable #1 emits its 3rd item and observable #2 has emitted its 5th item. The result using zip method will be the 3rd emitted values of both observables.

In this situation the result using combineLatest will be the 5th and 3rd. which feels more natural.

Observable.zip(observables)

(Original answer: Jul, 2017) Observable.zip method is explained in reactiveX documentation:

Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each of its input Observables.

// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();

Observable
    .zip(name$, document$, (name: string, document: string) => ({name, document}))
    .subscribe(pair => {
           this.name = pair.name;
           this.document = pair.document;
           this.showForm();
       })

a side note (applies for both methods)

The last parameter, where we have provided a function, (name: string, document: string) => ({name, document}) is optional. You can skip it, or do more complex operations:

If the latest parameter is a function, this function is used to compute the created value from the input values. Otherwise, an array of the input values is returned.

So if you skip the last part, you get an array:

// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();

Observable
    .zip(name$, document$)
    .subscribe(pair => {
           this.name = pair['0'];
           this.document = pair['1'];
           this.showForm();
       })


问:
How to retain original color of Image on rotation using java
I have a java application that receives image files. I want to rotate them using the exif information.

Here on StackOverflow, i found two different approaches, in both cases I start with an BufferedImage:

```<code>        BufferedImage image=ImageIO.read(sourceFile.getInputStream());
</code>```

The first solution is coming from this post.

```<code>        ImageTransformer.ImageInformation imageInformation=ImageTransformer.readImageInformation(sourceFile.getInputStream());
        AffineTransform tranform=ImageTransformer.getExifTransformation(imageInformation);
        image=ImageTransformer.transformImage(image,tranform);
</code>```

The second one was also recommended in some post here, using Thumbnailator:

```<code>BufferedImage image = Thumbnails.of(sourceFile.getInputStream()).scale(1).asBufferedImage();
</code>```

Both ways do properly rotate my image. But also both solutions change the coloring, which i do not want. I will attache two files, the "white" one is the original file with wrong rotation. This is exactly what I achieve when I comment out both rotation codes.

The other, the red one, is the one with proper rotation, but wrong color.

How can I have the original color with just changing the rotation?

答:
Ive been trying to allign the center of the image with the center of the frame and I did not find a good way of doing it but Ive managed to rotate the image without losing its properties:

```<code>import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;

public class Rotate extends JComponent {
    // Attributes
    private String route = null;
    private double degree = 0.0;

    // Constructor
    public Rotate(String route, double degree) {
        this.setRoute(route);
        this.setDegree(degree);
    }

    // Create a bufferedImage for the given route
    private BufferedImage getBufferedImage() {
        Image image = null;
        try {
            image = ImageIO.read(new File(getRoute()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return (BufferedImage) image;
    }

    // Paint the image
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        AffineTransform at = AffineTransform.getRotateInstance(Math.toRadians(getDegree()));
        g2.setTransform(at);
        // Here I tried to calculate you must add the coordenates to start
        // drawing the image in your frame
        g2.drawImage(getBufferedImage(), 0, 0, null);
    }

    public double getDiagonal() {
        return Math.hypot(getBufferedImage().getWidth(), getBufferedImage().getHeight());
    }

    public String getRoute() {
        return route;
    }

    public void setRoute(String route) {
        this.route = route;
    }

    public double getDegree() {
        return degree;
    }

    public void setDegree(double degree) {
        this.degree = degree;
    }

}
</code>```

For testing it:

```<code>import java.awt.Container;

import javax.swing.JFrame;

public class ImageRotation {

    public static void main(String[] args) {
        // The route of the image and the degrees of rotation
        String route = "C:\\Users\\Public\\Pictures\\Sample Pictures\\download.jpg";
        double degrees = 30;
        // Frame to display the image
        JFrame jf = new JFrame("Image Rotated");
        // Introduce the route and degrees
        Rotate tl = new Rotate(route, degrees);
        // Set the size of the frame
        int hyp = (int) tl.getDiagonal();
        jf.setSize(hyp, hyp);
        // Print the rotated image in the frame
        Container cp = jf.getContentPane();
        cp.add(tl);
        // Display
        jf.setVisible(true);
    }
}
</code>```

Body:
I have a java application that receives image files. I want to rotate them using the exif information.

Here on StackOverflow, i found two different approaches, in both cases I start with an BufferedImage:

        BufferedImage image=ImageIO.read(sourceFile.getInputStream());

The first solution is coming from this post.

        ImageTransformer.ImageInformation imageInformation=ImageTransformer.readImageInformation(sourceFile.getInputStream());
        AffineTransform tranform=ImageTransformer.getExifTransformation(imageInformation);
        image=ImageTransformer.transformImage(image,tranform);

The second one was also recommended in some post here, using Thumbnailator:

BufferedImage image = Thumbnails.of(sourceFile.getInputStream()).scale(1).asBufferedImage();

Both ways do properly rotate my image. But also both solutions change the coloring, which i do not want. I will attache two files, the "white" one is the original file with wrong rotation. This is exactly what I achieve when I comment out both rotation codes.

The other, the red one, is the one with proper rotation, but wrong color.

How can I have the original color with just changing the rotation?

Body:
Ive been trying to allign the center of the image with the center of the frame and I did not find a good way of doing it but Ive managed to rotate the image without losing its properties:

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;

public class Rotate extends JComponent {
    // Attributes
    private String route = null;
    private double degree = 0.0;

    // Constructor
    public Rotate(String route, double degree) {
        this.setRoute(route);
        this.setDegree(degree);
    }

    // Create a bufferedImage for the given route
    private BufferedImage getBufferedImage() {
        Image image = null;
        try {
            image = ImageIO.read(new File(getRoute()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return (BufferedImage) image;
    }

    // Paint the image
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        AffineTransform at = AffineTransform.getRotateInstance(Math.toRadians(getDegree()));
        g2.setTransform(at);
        // Here I tried to calculate you must add the coordenates to start
        // drawing the image in your frame
        g2.drawImage(getBufferedImage(), 0, 0, null);
    }

    public double getDiagonal() {
        return Math.hypot(getBufferedImage().getWidth(), getBufferedImage().getHeight());
    }

    public String getRoute() {
        return route;
    }

    public void setRoute(String route) {
        this.route = route;
    }

    public double getDegree() {
        return degree;
    }

    public void setDegree(double degree) {
        this.degree = degree;
    }

}

For testing it:

import java.awt.Container;

import javax.swing.JFrame;

public class ImageRotation {

    public static void main(String[] args) {
        // The route of the image and the degrees of rotation
        String route = "C:\\Users\\Public\\Pictures\\Sample Pictures\\download.jpg";
        double degrees = 30;
        // Frame to display the image
        JFrame jf = new JFrame("Image Rotated");
        // Introduce the route and degrees
        Rotate tl = new Rotate(route, degrees);
        // Set the size of the frame
        int hyp = (int) tl.getDiagonal();
        jf.setSize(hyp, hyp);
        // Print the rotated image in the frame
        Container cp = jf.getContentPane();
        cp.add(tl);
        // Display
        jf.setVisible(true);
    }
}


问:
Creating anomaly detection using machine learning
I'm very impressed from the new x-pack ML of the elastic stack. It seems their technique learns data patterns over time and can predict anomalies in multiple domains.

Zoomed in:

I was wondering what approach and network topology could be used, in order to create a similar feature. Is it fair to assume that since x-pack works on time series data, RNN would be a good start?

Interested in your opinions and references.

答:
From what I read, I'd be surprised if they're using neural networks. Here's how they say they detect anomalies:

Detect outliers in a population by building a profile of a “typical” user or machine to know when one starts to stray from the pack.

Doing anomaly detection like that requires nothing more than a statistical test of whether or not observed behavior is within 2-3 standard deviations of the expected behavior.

If you want to use neural networks for some reason, you could go with CNNs, RNNs, or attention-only networks. Google recently showed that you don't need RNNs or CNNs to do state-of-the-art translation.


问:
JDOM.Element.getChild(String) is returning unexpected results
According to the API at jdom.org, the semantics of getChild(String name):

This returns the first child element within this element with the given local name and belonging to no namespace. If no elements exist for the specified name and namespace, null is returned.

Therefore, if I have an XML structure like:

```<code><?xml version="1.0" encoding="UTF-8"?>
<lvl1>
    <lvl2>
        <lvl3/>
    </lvl2>
</lvl1>
</code>```

I have a JDOM Element which is currently pointing to <lvl1>. I should be able to make the following call:

```<code>Element lvl3 = lvl1Element.getChild("lvl3");
</code>```

and lvl3 should have non-null.

However, I'm finding that lvl3 is actually null.  Am I missing something?

Here is a sample code snippet that should work:

```<code>import java.io.StringReader;
import org.jdom.*;
public static void main(String[] args){
    Document doc = new SAXBuilder().build(new StringReader("path to file"));
    Element lvl1Element = doc.getRootElement();
    Element lvl3Element = lvl1Element.getChild("lvl3"); //is null. Why?
}
</code>```

答:
You've just said it....

This returns the first child element
  within this element with the given
  local name...

Basically, on lvl1, your first child is lvl2. I haven't used JDOM to help further. My suggestion is to go to lvl2 and retrieve lvl3.

ContentLicense: CC BY-SA 2.5

Body:
According to the API at jdom.org, the semantics of getChild(String name):

This returns the first child element within this element with the given local name and belonging to no namespace. If no elements exist for the specified name and namespace, null is returned.

Therefore, if I have an XML structure like:

<?xml version="1.0" encoding="UTF-8"?>
<lvl1>
    <lvl2>
        <lvl3/>
    </lvl2>
</lvl1>

I have a JDOM Element which is currently pointing to <lvl1>. I should be able to make the following call:

Element lvl3 = lvl1Element.getChild("lvl3");

and lvl3 should have non-null.

However, I'm finding that lvl3 is actually null.  Am I missing something?

Here is a sample code snippet that should work:

import java.io.StringReader;
import org.jdom.*;
public static void main(String[] args){
    Document doc = new SAXBuilder().build(new StringReader("path to file"));
    Element lvl1Element = doc.getRootElement();
    Element lvl3Element = lvl1Element.getChild("lvl3"); //is null. Why?
}


问:
Allow user access to one directory in a S3 Bucket
I searched through existing questions and couldnt find an answer.

I want to restrict access to one directory S3 bucket to some user. For example, I have the directory my-bucket/test/123. I put a few images to this directory. Other users should not have access to this directory.
Then I created Bucket policy:

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "AddPerm",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::123456789000:user/some-user"
        },
        "Action": "s3:*",
        "Resource": "arn:aws:s3:::my-bucket/test/123/*"
    }
]
}
</code>```

But when I tried to open file in browser, I recieved "Access Denied" message.

I tried to use Deny effect and NotPrincipal. In this case, the files are available to other users.
Please help!

答:
You also need bucket listing permissions on the root prefix (folder) as described in this AWS doc Writing IAM Policies: Grant Access to User-Specific Folders in an Amazon S3 Bucket:

Although David should have access to only his home folder, he requires
  additional permissions so that he can navigate to his folder in the
  Amazon S3 console. David needs permission to list objects at the root
  level of the my-company bucket and in the home/ folder.

Body:
I searched through existing questions and couldnt find an answer.

I want to restrict access to one directory S3 bucket to some user. For example, I have the directory my-bucket/test/123. I put a few images to this directory. Other users should not have access to this directory.
Then I created Bucket policy:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "AddPerm",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::123456789000:user/some-user"
        },
        "Action": "s3:*",
        "Resource": "arn:aws:s3:::my-bucket/test/123/*"
    }
]
}

But when I tried to open file in browser, I recieved "Access Denied" message.

I tried to use Deny effect and NotPrincipal. In this case, the files are available to other users.
Please help!


问:
R, sqldf and avg for ratio average
Why do the two commands yield different results when using sqldf in R?

```<code>sqldf('select species,
    avg([Petal.Width]/[Petal.Length])
    as petalratio from iris group by species')

sqldf('select species,
    ([Petal.Width]/[Petal.Length])
    as petalratio from iris group by species')
</code>```

Being that the goal is to find the average of the ratios for each of the 3 species.

答:
```<code>select species,
avg([Petal.Width]/[Petal.Length]) as petalratio
from iris
group by species
</code>```

This query outputs the average per species as you are using an aggregate function avg.

```<code>select species,
([Petal.Width]/[Petal.Length]) as petalratio
from iris
group by species
</code>```

This query randomly outputs one row per species as you aren't using an aggregate function. This isn't allowed in most databases, but allowed in SQLite, which is the default database sqldf uses.

You should use the first query with avg as that is what you are trying to do.

Title: R, sqldf and avg for ratio average

Body:
Why do the two commands yield different results when using sqldf in R?

sqldf('select species,
    avg([Petal.Width]/[Petal.Length])
    as petalratio from iris group by species')

sqldf('select species,
    ([Petal.Width]/[Petal.Length])
    as petalratio from iris group by species')

Being that the goal is to find the average of the ratios for each of the 3 species.

Body:
select species,
avg([Petal.Width]/[Petal.Length]) as petalratio
from iris
group by species

This query outputs the average per species as you are using an aggregate function avg.

select species,
([Petal.Width]/[Petal.Length]) as petalratio
from iris
group by species

This query randomly outputs one row per species as you aren't using an aggregate function. This isn't allowed in most databases, but allowed in SQLite, which is the default database sqldf uses.

You should use the first query with avg as that is what you are trying to do.


答:
Use forEach to loop through every items of the data.games array and  then simply add the name property using game.name = game.id[0].

const data = {
  "games" : [
      { "id":["1"] },
      { "id":["2"] },
      { "id":["3"] },
      { "id":["4"] },
      { "id":["5"] },
      { "id":["6"] }
   ]
};

data.games.forEach(game => game.name = game.id[0]);

console.log(data);```

Title: Add new attribute to JSON?

Body:
I have JSON data and I want to update items on it.

How can I add a name attribute to ALL id's in controller ?

{
  "games" : [
      { "id":["1"] },
      { "id":["2"] },
      { "id":["3"] },
      { "id":["4"] },
      { "id":["5"] },
      { "id":["6"] }
   ]
}

Should be :

{
  "games" : [
      { "id":["1"],"name":"1" },
      { "id":["2"],"name":"2" },
      { "id":["3"],"name":"3" },
      { "id":["4"],"name":"4" },
      { "id":["5"],"name":"5" },
      { "id":["6"],"name":"6" }
   ]
}

for (var i = 1; i <= games.length; i++) {
    games[].name = i;
}


问:
How to set elevation to Bottom navigation
So by the support V25. We have new component called Bottom navigation.

Follow the Design guidelines, the Bottom Navigation's elevation should be 8dp (https://material.io/guidelines/components/bottom-navigation.html#bottom-navigation-specs)

But I can't set the elevation to it.

Any suggestion, example would be appreciated. Thank you!

UPDATE XML CODE

```<code><RelativeLayout
  android:layout_width="match_parent"
  android:layout_height="match_parent">

<android.support.design.widget.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:elevation="8dp"
    app:elevation="8dp"
    app:itemBackground="@color/colorPrimary"
    app:itemIconTint="@drawable/bottom_nav_color_state"
    app:itemTextColor="@drawable/bottom_nav_color_state"
    app:menu="@menu/bottom_navigation_main"/>

<FrameLayout
    android:id="@+id/contentFrame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/bottom_navigation"
    android:background="#EDEDED"/>
</code>```

答:
I had the same issue and to have a @android:color/white as OP suggested was not acceptable in my case. So since we "can't" get shadow with elevation and custom background we need to hack it.

My approach is adding a shadow view inside the frame layout to "mimic" elevation.

```<code><RelativeLayout
  android:layout_width="match_parent"
  android:layout_height="match_parent">

<android.support.design.widget.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:elevation="8dp"
    app:elevation="8dp"
    app:itemBackground="@color/colorPrimary"
    app:itemIconTint="@drawable/bottom_nav_color_state"
    app:itemTextColor="@drawable/bottom_nav_color_state"
    app:menu="@menu/bottom_navigation_main"/>

<FrameLayout
    android:id="@+id/contentFrame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/bottom_navigation"
    android:background="#EDEDED"/>

    <some.kind.of.pager.or.other.content.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <View
        android:id="@+id/shadow_view"
        android:layout_width="match_parent"
        android:layout_height="4dp"
        android:layout_gravity="bottom"
        android:background="@drawable/shadow_gradient" />

</FrameLayout>
</code>```

where the background of the shadow view is nothing more than a shape gradient that is positioned over all other just above the bottom nav view, something like:

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:angle="90"
        android:endColor="@android:color/transparent"
        android:startColor="#8f000000" />
</shape>
</code>```

Hope this helps someone.

Body:
So by the support V25. We have new component called Bottom navigation.

Follow the Design guidelines, the Bottom Navigation's elevation should be 8dp (https://material.io/guidelines/components/bottom-navigation.html#bottom-navigation-specs)

But I can't set the elevation to it.

Any suggestion, example would be appreciated. Thank you!

UPDATE XML CODE

<RelativeLayout
  android:layout_width="match_parent"
  android:layout_height="match_parent">

<android.support.design.widget.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:elevation="8dp"
    app:elevation="8dp"
    app:itemBackground="@color/colorPrimary"
    app:itemIconTint="@drawable/bottom_nav_color_state"
    app:itemTextColor="@drawable/bottom_nav_color_state"
    app:menu="@menu/bottom_navigation_main"/>

<FrameLayout
    android:id="@+id/contentFrame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/bottom_navigation"
    android:background="#EDEDED"/>

Body:
I had the same issue and to have a @android:color/white as OP suggested was not acceptable in my case. So since we "can't" get shadow with elevation and custom background we need to hack it.

My approach is adding a shadow view inside the frame layout to "mimic" elevation.

<RelativeLayout
  android:layout_width="match_parent"
  android:layout_height="match_parent">

<android.support.design.widget.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:elevation="8dp"
    app:elevation="8dp"
    app:itemBackground="@color/colorPrimary"
    app:itemIconTint="@drawable/bottom_nav_color_state"
    app:itemTextColor="@drawable/bottom_nav_color_state"
    app:menu="@menu/bottom_navigation_main"/>

<FrameLayout
    android:id="@+id/contentFrame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/bottom_navigation"
    android:background="#EDEDED"/>

    <some.kind.of.pager.or.other.content.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <View
        android:id="@+id/shadow_view"
        android:layout_width="match_parent"
        android:layout_height="4dp"
        android:layout_gravity="bottom"
        android:background="@drawable/shadow_gradient" />

</FrameLayout>

where the background of the shadow view is nothing more than a shape gradient that is positioned over all other just above the bottom nav view, something like:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:angle="90"
        android:endColor="@android:color/transparent"
        android:startColor="#8f000000" />
</shape>

Hope this helps someone.


问:
How to delete the canvas from Tkinter after shown the window
I want to create a line in the Tkinter and after changing the height I need to delete the previous line and create a new line with the new height, this is a repeated process.

To this, I read the tutorial of the Tkinter of python and I think the After method might be useful. So, I write my idea but it is not a good method and I cannot create it. Also, I searched about a Shown event in the Tkinter, but I did not find the Shown event in the Tkinter for the window.

Here is my suggested code:

```<code>from tkinter import *
from tkinter import messagebox
import numpy as np
import random
window = Tk()
window.geometry("600x400+650+200")
window.resizable(0, 0)
window.title("Ball Balancing Game - QLearning")

canvas = Canvas()

def uptodate():
    canvas.delete(line1)
    line1 = canvas.create_line(100, 200, 500, h)

# for i in range(len(h) - 1):
#     for j in range(len(h) - 1):
#
#         line1 = canvas.create_line(100, h[i], 500, h[j])
#         line2 = canvas.create_line(100, h[i+1], 500, h[j+1])
#         # lines = canvas.create_line(0,0,600,400)
#         # balls = canvas.create_oval(200, 150, 230, 110, outline="gray", fill="gray", width=6)
#         canvas.pack(fill=BOTH, expand=1)
#         canvas.delete(line1)
#         window.update()
#         window.after()
#         canvas.delete(lines)
#         canvas.update()
#         lines.destroy()
#         i = w.create_line(xy, fill="red")

line = canvas.create_line(100, 200, 500, 200)
canvas.pack(fill=BOTH, expand=1)
window.after(1000, uptodate())
window.mainloop()
</code>```

答:
Don't need to delete, you can update all of lines:</p>

```<code>import tkinter as tk
import random
import numpy as np

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.frame = tk.Frame(self, background="bisque")
        self.frame.pack(side="top", fill="both", expand=True)
        self.canvas = tk.Canvas(self.frame)
        self.line = self.canvas.create_line(100, 100, 300, 200, fill="blue")
        self.canvas.pack(side="top", fill="both", expand=True)
        self.draw_line()

    def remove_line(self, line):
        self.canvas.delete(line)

    def get_h(self):
        h1 = [-1, -0.86, -0.71, -0.57, -0.43, -0.29, -0.14, 0, 0.14, 0.29,0.43, 0.57, 0.71, 0.86, 1]
        map_h = np.linspace(100, 300, 15)
        map_h = np.around(map_h, 3)
        map_h = map_h.tolist()
        rnd_h1 = map_h[h1.index(random.choice(h1))]
        rnd_h2 = map_h[h1.index(random.choice(h1))]

        return rnd_h1, rnd_h2

   def draw_line(self):
        rnd_h1, rnd_h2 = self.get_h()
        self.canvas.coords(self.line, 100, rnd_h1, 300, rnd_h2)
        self.after(1000, self.draw_line)

app = App()
app.mainloop()
</code>```

Body:
I want to create a line in the Tkinter and after changing the height I need to delete the previous line and create a new line with the new height, this is a repeated process.

To this, I read the tutorial of the Tkinter of python and I think the After method might be useful. So, I write my idea but it is not a good method and I cannot create it. Also, I searched about a Shown event in the Tkinter, but I did not find the Shown event in the Tkinter for the window.

Here is my suggested code:

from tkinter import *
from tkinter import messagebox
import numpy as np
import random
window = Tk()
window.geometry("600x400+650+200")
window.resizable(0, 0)
window.title("Ball Balancing Game - QLearning")

canvas = Canvas()

def uptodate():
    canvas.delete(line1)
    line1 = canvas.create_line(100, 200, 500, h)

# for i in range(len(h) - 1):
#     for j in range(len(h) - 1):
#
#         line1 = canvas.create_line(100, h[i], 500, h[j])
#         line2 = canvas.create_line(100, h[i+1], 500, h[j+1])
#         # lines = canvas.create_line(0,0,600,400)
#         # balls = canvas.create_oval(200, 150, 230, 110, outline="gray", fill="gray", width=6)
#         canvas.pack(fill=BOTH, expand=1)
#         canvas.delete(line1)
#         window.update()
#         window.after()
#         canvas.delete(lines)
#         canvas.update()
#         lines.destroy()
#         i = w.create_line(xy, fill="red")

line = canvas.create_line(100, 200, 500, 200)
canvas.pack(fill=BOTH, expand=1)
window.after(1000, uptodate())
window.mainloop()

Body:
Don't need to delete, you can update all of lines:

import tkinter as tk
import random
import numpy as np

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.frame = tk.Frame(self, background="bisque")
        self.frame.pack(side="top", fill="both", expand=True)
        self.canvas = tk.Canvas(self.frame)
        self.line = self.canvas.create_line(100, 100, 300, 200, fill="blue")
        self.canvas.pack(side="top", fill="both", expand=True)
        self.draw_line()

    def remove_line(self, line):
        self.canvas.delete(line)

    def get_h(self):
        h1 = [-1, -0.86, -0.71, -0.57, -0.43, -0.29, -0.14, 0, 0.14, 0.29,0.43, 0.57, 0.71, 0.86, 1]
        map_h = np.linspace(100, 300, 15)
        map_h = np.around(map_h, 3)
        map_h = map_h.tolist()
        rnd_h1 = map_h[h1.index(random.choice(h1))]
        rnd_h2 = map_h[h1.index(random.choice(h1))]

        return rnd_h1, rnd_h2

   def draw_line(self):
        rnd_h1, rnd_h2 = self.get_h()
        self.canvas.coords(self.line, 100, rnd_h1, 300, rnd_h2)
        self.after(1000, self.draw_line)

app = App()
app.mainloop()


问:
Not able to read InputStream from RS232 Bluetooth module
I am trying to read values from a weighing machine connected to bluetooth module(M143 RS232 Bluetooth Serial Adapter purchased from eBay).I am able to connect the device and i am getting Socket object.But the InputStream is blocking and not able to read data from the stream(inputstream.available() is always returns zero).There is no issue when i write something to the OutputStream.I tried using BufferedReader but no change.Following is the code i tried.

```<code>InputStream inputStream = socket.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
   total.append(line).append('\n');
}
//code is not reaching here it is blocking in the while loop
if(outputStream!=null){
  outputStream.flush();
  outputStream.close();
}
</code>```

答:
Are you opening sockets for connection in different threads. There should be 3 threads for connection. This is valid for non-Bluetooth LE. Bluetooth Connectitivty

Connection Thread

Accept Thread

Connected Thread

If you use these threads, you will be able to get data using connected thread and you can pass data to main thread using handler, callback or BroadcastReceiver. I use all three of them seamlessly.

If you wish to check whether it works or not, download Bluetooth Terminal app from Play Store. It exactly uses Threads and Handler to display data. You can find one of the Bluetooth Terminal source code too. One of them is open source.

For BLE you can try this link. There are working samples associated with guides.
If you want to be sure your BT device works, download a BT terminal program pc or/and Android and test your device.

Body:
I am trying to read values from a weighing machine connected to bluetooth module(M143 RS232 Bluetooth Serial Adapter purchased from eBay).I am able to connect the device and i am getting Socket object.But the InputStream is blocking and not able to read data from the stream(inputstream.available() is always returns zero).There is no issue when i write something to the OutputStream.I tried using BufferedReader but no change.Following is the code i tried.

InputStream inputStream = socket.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
   total.append(line).append('\n');
}
//code is not reaching here it is blocking in the while loop
if(outputStream!=null){
  outputStream.flush();
  outputStream.close();
}


问:
MFiles API setting propertyValue
I'm working with MFiles API...

I want to pass a propertyDef to a propertyValue...

This code is working... but I have to create the MFiles object first.

```<code> ObjectVersionAndProperties objVersion =
 mFilesStructure.MFileVault.ObjectOperations.CreateNewObject(objTypeID,
 propValues);

 var testPropValues = new PropertyValues();
 testPropValues = FilesStructure.MFileVault.ObjectPropertyOperations.GetProperties(objVersion.ObjVer);

  var testPropValue = new PropertyValue();
  testPropValue = testPropValues.SearchForProperty(typeClientID);
</code>```

it work fine "testPropValue" has all the property set correctly espacially the DataType... but don't want to create the MFiles at first...

This should do the same, in my opinion but doesn't

```<code>var test = new PropertyDef();
test = mFilesStructure.MFileVault.PropertyDefOperations.GetPropertyDef(typeClientID);
var testPropValue = new PropertyValue();
testPropValue.PropertyDef = test.ID;
</code>```

the properties doesn't setup correctly...

Any one can help

Best regards,

Steph

答:
I just stumbled across this looking for something else and thought I might help.

You actually have it a little backwards. The creation of the new object is actually the last step in the process. You need to create a collection of PropertyValues() by creating each individual PropertyValue() and then adding them to the collection.

So something like this:

```<code>    public static PropertyValue GetPropertyValue(int propertyDefId, object value)
    {
        //resolve property def by ID
        PropertyDef propertyDef = Vault.PropertyDefOperations.GetPropertyDef(propertyDefId);

        //create the property value with prop def ID and value
        return GetPropertyValue(propertyDefId, propertyDef.DataType, value);
    }

    public static PropertyValue GetPropertyValue(int propertyDefId, MFDataType dataType, object value)
    {
        PropertyValue propertyValue = new PropertyValue();
        propertyValue.PropertyDef = propertyDefId;
        propertyValue.TypedValue.SetValue(dataType, value);

        return propertyValue;
    }

    public static ObjectVersionAndProperties CreateDocument(PropertyValues propertyValues, string filepath, Vault vault)
    {
        // Create the Source File object from the filepath.
        SourceObjectFile sourceFile = new SourceObjectFile();
        sourceFile.SourceFilePath = filepath;
        sourceFile.Extension = Path.GetExtension(filepath).TrimStart('.');
        sourceFile.Title = Path.GetFileNameWithoutExtension(filepath).TrimEnd('.');

        // Create the document object.
        return vault.ObjectOperations.CreateNewSFDObject((int)MFBuiltInObjectType.MFBuiltInObjectTypeDocument,
            propertyValues, sourceFile, true);
    }
</code>```

Once you set up the above functions you could call them like:

```<code>     //If the document doesn't exist, go ahead and create a new one
     //creat and add all the properties
     PropertyValues props = new PropertyValues();
     //class
     props.Add(-1, HelperMF.GetClassPropertyValue(classId, env.Vault));
     //job
     int jobId = env.Vault.ValueListItemOperations.GetValueListItemByDisplayID(Structure.ObjType.Job.ID, jobDisplayId).ID;
     props.Add(-1, HelperMF.GetPropertyValue(Properties.Job.ID, jobId, env.Vault));
     //estimates
     props.Add(-1, HelperMF.GetPropertyValueFromListOfDisplayIds(env.Vault, Properties.Estimate.ID,
                      MFDataType.MFDatatypeMultiSelectLookup, Structure.ObjType.Estimate.ID, estimateDisplayIds));
     //Add the relationship to the return doc that was uploaded
     props.Add(-1, HelperMF.GetPropertyValue(Properties.Document.ID, movingDocId, env.Vault));

     //create the new object in the vault
     ObjectVersionAndProperties newDoc = HelperMF.CreateDocument(props, docDownloadPath, env.Vault);
</code>```

I use a lot of help functions and classes but you should get the gist from my samples. Also, I would highly recommend you use the M-Files community website for research as they have a lot of code samples there geared specifically for M-Files.

https://community.m-files.com/

Also, if you don't already, use the API documentation as it also includes code samples.

http://www.m-files.com/api/documentation/2015.2/

Hopefully this helps,
Mike

Title: MFiles API setting propertyValue

Body:
I'm working with MFiles API...

I want to pass a propertyDef to a propertyValue...

This code is working... but I have to create the MFiles object first.

 ObjectVersionAndProperties objVersion =
 mFilesStructure.MFileVault.ObjectOperations.CreateNewObject(objTypeID,
 propValues);

 var testPropValues = new PropertyValues();
 testPropValues = FilesStructure.MFileVault.ObjectPropertyOperations.GetProperties(objVersion.ObjVer);

  var testPropValue = new PropertyValue();
  testPropValue = testPropValues.SearchForProperty(typeClientID);

it work fine "testPropValue" has all the property set correctly espacially the DataType... but don't want to create the MFiles at first...

This should do the same, in my opinion but doesn't

var test = new PropertyDef();
test = mFilesStructure.MFileVault.PropertyDefOperations.GetPropertyDef(typeClientID);
var testPropValue = new PropertyValue();
testPropValue.PropertyDef = test.ID;

the properties doesn't setup correctly...

Any one can help

Best regards,

Steph

Body:
I just stumbled across this looking for something else and thought I might help.

You actually have it a little backwards. The creation of the new object is actually the last step in the process. You need to create a collection of PropertyValues() by creating each individual PropertyValue() and then adding them to the collection.

So something like this:

    public static PropertyValue GetPropertyValue(int propertyDefId, object value)
    {
        //resolve property def by ID
        PropertyDef propertyDef = Vault.PropertyDefOperations.GetPropertyDef(propertyDefId);

        //create the property value with prop def ID and value
        return GetPropertyValue(propertyDefId, propertyDef.DataType, value);
    }

    public static PropertyValue GetPropertyValue(int propertyDefId, MFDataType dataType, object value)
    {
        PropertyValue propertyValue = new PropertyValue();
        propertyValue.PropertyDef = propertyDefId;
        propertyValue.TypedValue.SetValue(dataType, value);

        return propertyValue;
    }

    public static ObjectVersionAndProperties CreateDocument(PropertyValues propertyValues, string filepath, Vault vault)
    {
        // Create the Source File object from the filepath.
        SourceObjectFile sourceFile = new SourceObjectFile();
        sourceFile.SourceFilePath = filepath;
        sourceFile.Extension = Path.GetExtension(filepath).TrimStart('.');
        sourceFile.Title = Path.GetFileNameWithoutExtension(filepath).TrimEnd('.');

        // Create the document object.
        return vault.ObjectOperations.CreateNewSFDObject((int)MFBuiltInObjectType.MFBuiltInObjectTypeDocument,
            propertyValues, sourceFile, true);
    }

Once you set up the above functions you could call them like:

     //If the document doesn't exist, go ahead and create a new one
     //creat and add all the properties
     PropertyValues props = new PropertyValues();
     //class
     props.Add(-1, HelperMF.GetClassPropertyValue(classId, env.Vault));
     //job
     int jobId = env.Vault.ValueListItemOperations.GetValueListItemByDisplayID(Structure.ObjType.Job.ID, jobDisplayId).ID;
     props.Add(-1, HelperMF.GetPropertyValue(Properties.Job.ID, jobId, env.Vault));
     //estimates
     props.Add(-1, HelperMF.GetPropertyValueFromListOfDisplayIds(env.Vault, Properties.Estimate.ID,
                      MFDataType.MFDatatypeMultiSelectLookup, Structure.ObjType.Estimate.ID, estimateDisplayIds));
     //Add the relationship to the return doc that was uploaded
     props.Add(-1, HelperMF.GetPropertyValue(Properties.Document.ID, movingDocId, env.Vault));

     //create the new object in the vault
     ObjectVersionAndProperties newDoc = HelperMF.CreateDocument(props, docDownloadPath, env.Vault);

I use a lot of help functions and classes but you should get the gist from my samples. Also, I would highly recommend you use the M-Files community website for research as they have a lot of code samples there geared specifically for M-Files.

https://community.m-files.com/

Also, if you don't already, use the API documentation as it also includes code samples.

http://www.m-files.com/api/documentation/2015.2/

Hopefully this helps,
Mike


问:
Does Maven Central still not use CDN for distribution?
I read articles from 3 years back highlighting why Jcenter is a better option over Maven Central, one of the primary reasons being the HTTPS transfer as a result of distribution via a CDN. Maven Central had HTTP, does the Maven repository still use HTTP?

It would make sense for them to upgrade to HTTPS, matching their competition (despite other areas where Jcenter excels). Have they done this yet?

Additionally, I'd like to ask why using a CDN enhances security. How does Maven Central distribute its libraries if not via a CDN?

Many thanks in advance.

答:
HTTPS and CDN are two orthogonal concerns of a distribution repository, and  JCenter and Maven Central have both.

We (JFrog) did many experiments with CDNs (including Fastly, that Maven Central uses), and went with the widest and fastest there is on the market today – Akamai. It means that your downloads will be served from servers closer to you, and the downloads will be faster.

But the differences aren't limited to CDN and presence or lacking of HTTPS. For example, the existence of additional metadata, like the maintainer, release notes, license information, and more is critical for a modern distribution repository, and the ability to be the owner of your package while making it available via 'canonical' repositories is also a huge advantage for open-source developers.

I am with JFrog, the company behind bintray, jcenter and artifactory, see my profile for details and links.


问:
Where is the best place to store an RTCPeerConnection object in a React/Redux app?
RTCPeerConnection is an object with certain methods that when called mutate the object (for example, setLocalDescription, addIceCandidate). These methods get called based on received signaling from the other side of a WebRTC connection (like when you receive an offer, or an ice candidate).

Therefore, this object does not seem well-suited for being in a redux store, since the developer doesn't at a first approximation have control over the mutations, and in a redux reducer you can't just create a copy of an RTCPeerConnection as this would eliminate your previous webRTC session.

However, in a WebRTC app that uses React, perhaps different components need access to the RTCPeerConnection object (for instance, maybe it is instantiated on mount of the top level component in the app, but then in some UI component like a modal deep in the tree that accepts a call, you want to call a method on RTCPeerConnection to create an answer to the webRTC offer that was received. Or maybe a deeply nested component needs to initiate a call). Is it the case that the only solution is to pass the object as props down the component tree? Is there no way to use redux with a complex object like this?

UPDATE: considering the answer below about using middleware for handling socket.io, let me reframe my original question: would it make sense, if I have an RTCPeerConnection object as state in a top-level component, to build middleware that that handles dispatch calls that ultimately must receive some way some how a reference to the original RTCPeerConnection to make a method call such as setRemoteDescription?

答:
The standard place for "socket"-like connection objects (websockets, Firebase, etc) in a Redux app is in a middleware.  Any part of the application that needs to tell the socket to do something can dispatch an action that is intercepted by the middleware, and the middleware can dispatch actions to update the state in response to received messages.

There's dozens of existing examples of middleware for various sockets in the Middleware - Sockets and Adapters section of my Redux addons catalog.

update

Here's a quick example of what an RTC middleware might look like.  The code is completely untested, but this should illustrate the idea:

```<code>function createRtcMiddleware() {
    return (store) => {
        let rtcPeerConnection = null;

        return (next) => action => {
            switch(action.type) {
                case "RTC_CONNECTION_CREATE": {
                    const {rtcConfig} = action;
                    rtcPeerConnection = new RTCPeerConnection(rtcConfig);

                    rtcPeerConnection.somecallback = () => {
                        // maybe dispatch a Redux action in response to
                        // a received message
                    };

                    // Do not pass the action down the pipeline, since only
                    // this middleware cares about it
                    return;
                }
                case "RTC_CONNECTION_SET_DESCRIPTION": {
                    if(rtcPeerConnection) {
                        rtcPeerConnection.setDescription(action.description);
                    }

                    return;
                }
            }

            // If we don't care about it, pass it down the pipeline
            return next(action);
        }
    }
}
</code>```

Body:
The standard place for "socket"-like connection objects (websockets, Firebase, etc) in a Redux app is in a middleware.  Any part of the application that needs to tell the socket to do something can dispatch an action that is intercepted by the middleware, and the middleware can dispatch actions to update the state in response to received messages.

There's dozens of existing examples of middleware for various sockets in the Middleware - Sockets and Adapters section of my Redux addons catalog.

update

Here's a quick example of what an RTC middleware might look like.  The code is completely untested, but this should illustrate the idea:

function createRtcMiddleware() {
    return (store) => {
        let rtcPeerConnection = null;

        return (next) => action => {
            switch(action.type) {
                case "RTC_CONNECTION_CREATE": {
                    const {rtcConfig} = action;
                    rtcPeerConnection = new RTCPeerConnection(rtcConfig);

                    rtcPeerConnection.somecallback = () => {
                        // maybe dispatch a Redux action in response to
                        // a received message
                    };

                    // Do not pass the action down the pipeline, since only
                    // this middleware cares about it
                    return;
                }
                case "RTC_CONNECTION_SET_DESCRIPTION": {
                    if(rtcPeerConnection) {
                        rtcPeerConnection.setDescription(action.description);
                    }

                    return;
                }
            }

            // If we don't care about it, pass it down the pipeline
            return next(action);
        }
    }
}


问:
How to use keyboard keys in background when application is minimized in JAVA
I am working in JAVA application which requires that
- Get all the keys which is pressed by user in separate txt file.
- Get the keys in background when Application is minimized.

I have no idea how to do this currently I am Working in following Code.

```<code>public class KeyChecker1 extends JFrame
{
    public static JLabel keyLabel = new JLabel("Hit any key");

    public KeyChecker1()
    {
        super("Hit a Key");
        KeyMonitor1 monitor = new KeyMonitor1(this);
        addKeyListener(monitor);

        setFocusable(true);
        setVisible(true);
    }
    public static void main(String[] arguments)
    {
        new KeyChecker1();
    }
}
class KeyMonitor1 extends KeyAdapter
{
    KeyChecker1 display;
    public static Thread t1key, t2;
    KeyMonitor1(KeyChecker1 display)
    {
        this.display = display;

    }
    public void keyPressed(final KeyEvent event)
    {

        t1key = new Thread()
        {
             @Override
             public void run()
             {
                try
                {
                    boolean caps_lock = Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
                    switch (event.getKeyCode())
                    {
                        case KeyEvent.VK_F1:
                            System.out.print("[F1]");
                            break;
                        case KeyEvent.VK_F2:
                            System.out.print("[F2]");
                            break;
                        case KeyEvent.VK_F3:
                            System.out.print("[F3]");
                            break;
                        case KeyEvent.VK_F4:
                            System.out.print("[F4]");
                            break;
                        case KeyEvent.VK_F5:
                            System.out.print("[F5]");
                            break;
                        case KeyEvent.VK_F6:
                            System.out.print("[F6]");
                            break;
                        case KeyEvent.VK_F7:
                            System.out.print("[F7]");
                            break;
                        case KeyEvent.VK_F8:
                            System.out.print("[F8]");
                            break;
                        case KeyEvent.VK_F9:
                            System.out.print("[F9]");
                            break;
                        case KeyEvent.VK_F10:
                            System.out.print("[F10]");
                            break;
                                 .
                                 .
                                 .
                      }
                }
                catch (Exception ex)
                {
                    Logger.getLogger(Dashboard.class.getName()).log(Level.SEVERE, null, ex);
                }
             }
          };
          t1key.start();
    }
}
</code>```

It working well when application is running but I want to Run the same functionality when the application is running in background (Minimized).

Please help me for this.

Thanks in advance.

答: To answer the question, it is not possible using pure Java.  You must implement platform dependent keyboard and mouse hooks using operating system specific API's (like the infamous SetWindowsHookEx on Windows) and then convert the native platform dependent data back to something Java can understand.  To simplify this process, I created https://github.com/kwhat/jnativehook as part of my graduate thesis because I needed to solve this issue in a portable way for my undergraduate thesis.</p>

Body:
I am working in JAVA application which requires that
- Get all the keys which is pressed by user in separate txt file.
- Get the keys in background when Application is minimized.

I have no idea how to do this currently I am Working in following Code.

public class KeyChecker1 extends JFrame
{
    public static JLabel keyLabel = new JLabel("Hit any key");

    public KeyChecker1()
    {
        super("Hit a Key");
        KeyMonitor1 monitor = new KeyMonitor1(this);
        addKeyListener(monitor);

        setFocusable(true);
        setVisible(true);
    }
    public static void main(String[] arguments)
    {
        new KeyChecker1();
    }
}
class KeyMonitor1 extends KeyAdapter
{
    KeyChecker1 display;
    public static Thread t1key, t2;
    KeyMonitor1(KeyChecker1 display)
    {
        this.display = display;

    }
    public void keyPressed(final KeyEvent event)
    {

        t1key = new Thread()
        {
             @Override
             public void run()
             {
                try
                {
                    boolean caps_lock = Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
                    switch (event.getKeyCode())
                    {
                        case KeyEvent.VK_F1:
                            System.out.print("[F1]");
                            break;
                        case KeyEvent.VK_F2:
                            System.out.print("[F2]");
                            break;
                        case KeyEvent.VK_F3:
                            System.out.print("[F3]");
                            break;
                        case KeyEvent.VK_F4:
                            System.out.print("[F4]");
                            break;
                        case KeyEvent.VK_F5:
                            System.out.print("[F5]");
                            break;
                        case KeyEvent.VK_F6:
                            System.out.print("[F6]");
                            break;
                        case KeyEvent.VK_F7:
                            System.out.print("[F7]");
                            break;
                        case KeyEvent.VK_F8:
                            System.out.print("[F8]");
                            break;
                        case KeyEvent.VK_F9:
                            System.out.print("[F9]");
                            break;
                        case KeyEvent.VK_F10:
                            System.out.print("[F10]");
                            break;
                                 .
                                 .
                                 .
                      }
                }
                catch (Exception ex)
                {
                    Logger.getLogger(Dashboard.class.getName()).log(Level.SEVERE, null, ex);
                }
             }
          };
          t1key.start();
    }
}

It working well when application is running but I want to Run the same functionality when the application is running in background (Minimized).

Please help me for this.

Thanks in advance.