问:
Go synchronization and concurrency model
I'm a new Go learner, and I'm following gobyexample.com to learn the basics. When I reach the "closing channels" section, the tutorial inserts this code snippet (I'll remove original comments):

    package main

    import "fmt"

    func main() {
        jobs := make(chan int, 5)
        done := make(chan bool)

       go func() {
           for {
               j, more := <-jobs
               if more {
                   fmt.Println("received job", j)
               } else {
                   fmt.Println("received all jobs")
                   done <- true
                   return
               }
           }
       }()

       for j := 1; j <= 18; j++ {
           jobs <- j
           fmt.Println("sent job", j)
       }
       close(jobs)
       fmt.Println("sent all jobs")

       <-done
    }
```

<p>The original code was setting a 3 instead of a 18 in the job sender loop.</p>

<p>Executing this code in play.golang.org it is what I don't fully understand. It always outputs the following:</p>

```sent job 1
sent job 2
sent job 3
sent job 4
sent job 5
received job 1
received job 2
received job 3
received job 4
received job 5
received job 6
sent job 6
sent job 7
sent job 8
sent job 9
sent job 10
sent job 11
sent job 12
received job 7
received job 8
received job 9
received job 10
received job 11
received job 12
received job 13
sent job 13
sent job 14
sent job 15
sent job 16
sent job 17
sent job 18
sent all jobs
received job 14
received job 15
received job 16
received job 17
received job 18
received all jobs
```

So I understand that the "queue" of a channel (I'm aware this terminology is not the most accurate, but for the purpose of learning myself it is what I understand about what a channel is) is of size 5 so the first 10 log messages are fine for me.

But how can be the message 6 and 13 be output their reception prior than their actual sending? How can be 7 messages sent in a row, if the channel size is 5? What am I missing from this?

答:
Goroutines run concurrently, therefore they also print to stdout concurrently (i.e. out-of-order). Moreover, fmt.Print APIs are buffered, so your prints are not actually prited immediately as they are called. This happens also in other languages. </p>

<p>This is why you cannot derive the real concurrent execution of goroutines from the messages in stdout. </p>

Body:
I'm a new Go learner, and I'm following gobyexample.com to learn the basics. When I reach the "closing channels" section, the tutorial inserts this code snippet (I'll remove original comments):

    package main

    import "fmt"

    func main() {
        jobs := make(chan int, 5)
        done := make(chan bool)

       go func() {
           for {
               j, more := <-jobs
               if more {
                   fmt.Println("received job", j)
               } else {
                   fmt.Println("received all jobs")
                   done <- true
                   return
               }
           }
       }()

       for j := 1; j <= 18; j++ {
           jobs <- j
           fmt.Println("sent job", j)
       }
       close(jobs)
       fmt.Println("sent all jobs")

       <-done
    }

The original code was setting a 3 instead of a 18 in the job sender loop.

Executing this code in play.golang.org it is what I don't fully understand. It always outputs the following:

sent job 1
sent job 2
sent job 3
sent job 4
sent job 5
received job 1
received job 2
received job 3
received job 4
received job 5
received job 6
sent job 6
sent job 7
sent job 8
sent job 9
sent job 10
sent job 11
sent job 12
received job 7
received job 8
received job 9
received job 10
received job 11
received job 12
received job 13
sent job 13
sent job 14
sent job 15
sent job 16
sent job 17
sent job 18
sent all jobs
received job 14
received job 15
received job 16
received job 17
received job 18
received all jobs

So I understand that the "queue" of a channel (I'm aware this terminology is not the most accurate, but for the purpose of learning myself it is what I understand about what a channel is) is of size 5 so the first 10 log messages are fine for me.

But how can be the message 6 and 13 be output their reception prior than their actual sending? How can be 7 messages sent in a row, if the channel size is 5? What am I missing from this?

Body:
Goroutines run concurrently, therefore they also print to stdout concurrently (i.e. out-of-order). Moreover, fmt.Print APIs are buffered, so your prints are not actually prited immediately as they are called. This happens also in other languages.

This is why you cannot derive the real concurrent execution of goroutines from the messages in stdout.


来源: stackexchange

问:
Can i use a 32 Bit ODBC Driver for my 64 Bit app
I have a Win32 application that makes ODBC-Connections. We connect using SQLDriverConnect()
which displays a dialog to select the data source. In the x64-Version the Dialog shows and offers 2 different 32 Bit MS ACCESS Drivers. When i select one of these, in the 32 Bit version i would see a open file dialog to select a .mdb file. In the 64 Bit version the call to SQLDriverConnect() at this point returns with -1.

SQLError() returns: "[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"

Is it in general possible to use a 32 Bit ODBC Driver from a 64-Bit executable? Why are these driver shown? As far as i can find there is no 64 Bit MS Access OBDC driver so far. What can i do?

答:
Well, I don't know why SQLDriverConnect() works the way you describe it, but perhaps this Blog post from Microsoft

http://blogs.msdn.com/b/psssql/archive/2010/01/21/how-to-get-a-x64-version-of-jet.aspx

can help you a little bit.

Seems there will be no native 64 bit ODBC driver for MS Access in near future, but those ACE components mentioned there may be an alternative.

ContentLicense: CC BY-SA 3.0


问:
Corrupted Textures with OpenGL 4.1 on Mac OS
I am trying to draw textures with OpenGL 4.1 shader language.
It works absolutely fine on Windows, so I'm quite positive there is no problem in shader or coordinates.
On Mac, However, the textures are corrupted like on the picture:

If you'll notice - there are two small textures looks ok. The unique about them is that one is 16 and second is 32 pixels wide (Power of 2). Therefore it must be something in configuration or pixel storage. It can't be that textures which are not power of 2 are not supported, since they were on legacy openGL context (Not GLSL). Here is example of my texture generating:

```<code>    unsigned char* pixels = convertedImage->m_pixelbufs.at(0);
    GLuint imageDepth = convertedImage->GetBitsPerPixel() == 24 ? GL_RGB : GL_RGBA;

    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, convertedImage->GetWidth(), convertedImage->GetHeight(), 0, imageDepth, GL_UNSIGNED_BYTE, pixels);

    glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
    glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
    glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
    glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    glBindTexture(GL_TEXTURE_2D, 0);
</code>```

I tried to play with other glPixelStorei parameters but textures were always corrupted. Any clue?

答: The issue was in the other place. There was an old piece of code checking the extension GL_ARB_texture_non_power_of_two before actually extracting PNG file into memory and acting accordingly. On windows, despite the fact that it was moved to core answer was - TRUE, therefore behavior was as expected. On mac, since it moved to cere the answer was - FALSE, so the behavior was wrong.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to draw textures with OpenGL 4.1 shader language.
It works absolutely fine on Windows, so I'm quite positive there is no problem in shader or coordinates.
On Mac, However, the textures are corrupted like on the picture:

If you'll notice - there are two small textures looks ok. The unique about them is that one is 16 and second is 32 pixels wide (Power of 2). Therefore it must be something in configuration or pixel storage. It can't be that textures which are not power of 2 are not supported, since they were on legacy openGL context (Not GLSL). Here is example of my texture generating:

    unsigned char* pixels = convertedImage->m_pixelbufs.at(0);
    GLuint imageDepth = convertedImage->GetBitsPerPixel() == 24 ? GL_RGB : GL_RGBA;

    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, convertedImage->GetWidth(), convertedImage->GetHeight(), 0, imageDepth, GL_UNSIGNED_BYTE, pixels);

    glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
    glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
    glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
    glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    glBindTexture(GL_TEXTURE_2D, 0);

I tried to play with other glPixelStorei parameters but textures were always corrupted. Any clue?


问:
Azure DevOps Agent Pool Security
I am having a hard time understanding how the Agent Pool security for a Team Project works or is populated. I think I am missing a basic construct.

I would like to grant the following access rights at the Project Level:

Contributors - role: User

  Project Mini Administrators (custom group) - role: Administrator

Here is what I did:
From Project settings, I clicked on Agent Pools and then the Security button.
I added the two above referenced groups.

If I then click on one of the Agent Pools listed on this screen and select Security, I can see that Inheritance is on but my new groups are not listed for the selected Pool.

What am I missing? If a Contributor or Project Mini Administrator go to a Build Definition in the Team Project and attempt to drop down the Agent list, they do not see any of the Agents; as if they had no security to the Agents. If I manually add the to all of the Agents individually, they things work as expected. Its almost as if the inheritance chain from the Agent Pool Security to the Agent is not propagating.

答: I provided feedback for this problem on Microsoft's Developer Community site. Microsoft confirmed that this was an issue and is working on a fix.</p>

Title: Azure DevOps Agent Pool Security


问:
search a structure element in map
i am new to C++(also english).
i want to search {1,2,3} in the map and if it exists , print TRUE on screen
but i can not
my code comes below
can you help me?</p>

```<code>#include <iostream>
#include <map>
#include <iterator>
#define PKT_UNIT_MAX_LEN  10000
using namespace std;

struct PKT_UNIT
{
int len;
unsigned int checksum;
unsigned char data[PKT_UNIT_MAX_LEN];

};

int main()
{
 map<int,PKT_UNIT> maharan;
 maharan.insert(pair<int,PKT_UNIT>(1,{1,2,3}));

 map<int,PKT_UNIT> ::iterator it;
 it=maharan.begin();

 for(it=maharan.begin(); it != maharan.end(); it++ )
 {

  if (maharan.find(it)!=maharan.end())
  {
   if (it->second.len==1 && it->second.checksum==2 && it->second.data==3)
   cout<<"TRUE"<<endl;

  }

return 0;
}
</code>```

答:
map::find takes something comparable to the key_type, not the mapped_type, and certainly not an iterator. Searching for the value is not what std::map is designed to support. You can instead use the generic searching algorithms.

```<code>bool operator==(const PKT_UNIT& lhs, const PKT_UNIT& rhs)
{
    return (lhs.len == rhs.len)
        && (lhs.checksum == rhs.checksum)
        && std::equal(lhs.data, lhs.data + lhs.len, rhs.data);
}

int main()
{
    PKT_UNIT needle{1,2,3};
    std::map<int,PKT_UNIT> maharan;
    maharan.insert(pair<int,PKT_UNIT>(1,needle));

    auto it = std::find_if(maharan.begin(), maharan.end(), [&needle](auto & item){ return item.second == needle; });
    if (it != maharan.end())
    {
        std::cout << "TRUE";
    }

    return 0;
}
</code>```

Title: search a structure element in map

Body:
i am new to C++(also english).
i want to search {1,2,3} in the map and if it exists , print TRUE on screen
but i can not
my code comes below
can you help me?

#include <iostream>
#include <map>
#include <iterator>
#define PKT_UNIT_MAX_LEN  10000
using namespace std;

struct PKT_UNIT
{
int len;
unsigned int checksum;
unsigned char data[PKT_UNIT_MAX_LEN];

};

int main()
{
 map<int,PKT_UNIT> maharan;
 maharan.insert(pair<int,PKT_UNIT>(1,{1,2,3}));

 map<int,PKT_UNIT> ::iterator it;
 it=maharan.begin();

 for(it=maharan.begin(); it != maharan.end(); it++ )
 {

  if (maharan.find(it)!=maharan.end())
  {
   if (it->second.len==1 && it->second.checksum==2 && it->second.data==3)
   cout<<"TRUE"<<endl;

  }

return 0;
}

Body:
map::find takes something comparable to the key_type, not the mapped_type, and certainly not an iterator. Searching for the value is not what std::map is designed to support. You can instead use the generic searching algorithms.

bool operator==(const PKT_UNIT& lhs, const PKT_UNIT& rhs)
{
    return (lhs.len == rhs.len)
        && (lhs.checksum == rhs.checksum)
        && std::equal(lhs.data, lhs.data + lhs.len, rhs.data);
}

int main()
{
    PKT_UNIT needle{1,2,3};
    std::map<int,PKT_UNIT> maharan;
    maharan.insert(pair<int,PKT_UNIT>(1,needle));

    auto it = std::find_if(maharan.begin(), maharan.end(), [&needle](auto & item){ return item.second == needle; });
    if (it != maharan.end())
    {
        std::cout << "TRUE";
    }

    return 0;
}


问:
Minimal addition-chain exponentiation
I know it has been proven NP-complete, and that's ok. I'm currently solving it with branch and bound where I set the initial upper limit at the number of multiplications it would take the normal binary square/multiply algorithm, and it does give the right answers, but I'm not satisfied with the running time (it can take several seconds for numbers around 200). This being an NP-complete problem, I'm not expecting anything spectacular; but there are often tricks to get the Actual Time under control somewhat.

Are there faster ways to do this in practice? If so, what are they?

答: I'm late to the party but in Handbook of Elliptic and Hyperelliptic Curve Cryptography there is a chapter "9.2 Fixed exponent" which also discusses various kinds addition chains.</p>

Title: Minimal addition-chain exponentiation


问:
Is there a way to get html footer on bottom of any page?
I'm building my own website for a project. I have an event page where I show all upcoming events. Every time you add an event, the page will get bigger. ATM, the footer is in the middle of the page because there are not enough events.

The problem is, I want the footer to be on the bottom of the screen, unless the page is bigger than the screen. If the page is bigger than the screen, the footer should be on the bottom of the page.

I tried to use height: 100% or height: 100vh but they put the height on "fit to screen", so if there are for example 20 events (bigger than the screen), the footer will be stuck on the bottom of the screen and the events will go through the footer.

The page now looks like this:

and the table is build up like this:

      Date/Time
      Event

            #_EVENTDATES
            #_EVENTTIMES

            #_EVENTLINK
            {has_location}
#_LOCATIONNAME, #_LOCATIONTOWN #_LOCATIONSTATE{/has_location}

```

答:
Have a look at this: https://www.freecodecamp.org/news/how-to-keep-your-footer-where-it-belongs-59c6aa05c59c

Summary:

use a page-container around everything on the page

set its minimum height to 100% of the viewport height (vh). As it is relative, its child elements can be set with absolute position based on it later.

content-wrap has a bottom padding that is the height of the footer, ensuring that exactly enough space is left for the footer inside the container they are both in.

wrapping div is used here that would contain all other page content.

set footer to absolute, sticking to the bottom: 0 of the page-container it is within.

HTML:

```<code> <body>
       <div id="page-container">
            <div id="content-wrap">
                  <!-- all other page content -->
            </div>
            <footer id="footer"></footer>
       </div>
 </body>
</code>```

CSS:

```<code> #page-container {  position: relative;  min-height: 100vh;}

 #content-wrap {  padding-bottom: 2.5rem;    /* Footer height */}

 #footer {  position: absolute;  bottom: 0;  width: 100%;  height: 2.5rem;            /* Footer height */}
</code>```

Body:
Have a look at this: https://www.freecodecamp.org/news/how-to-keep-your-footer-where-it-belongs-59c6aa05c59c

Summary:

use a page-container around everything on the page

set its minimum height to 100% of the viewport height (vh). As it is relative, its child elements can be set with absolute position based on it later.

content-wrap has a bottom padding that is the height of the footer, ensuring that exactly enough space is left for the footer inside the container they are both in.

wrapping div is used here that would contain all other page content.

set footer to absolute, sticking to the bottom: 0 of the page-container it is within.

HTML:

 <body>
       <div id="page-container">
            <div id="content-wrap">
                  <!-- all other page content -->
            </div>
            <footer id="footer"></footer>
       </div>
 </body>

CSS:

 #page-container {  position: relative;  min-height: 100vh;}

 #content-wrap {  padding-bottom: 2.5rem;    /* Footer height */}

 #footer {  position: absolute;  bottom: 0;  width: 100%;  height: 2.5rem;            /* Footer height */}


问:
How to pass different set of data to train and test without splitting a dataframe. (python)?
I have gone through multiple questions that help divide your dataframe into train and test, with scikit, without etc.

But my question is I have 2 different csvs ( 2 different dataframes from different years). I want to use one as train and other as test?

How to do so for LinearRegression / any model?

答:
Load the datasets individually.

Make sure they are in the same format of rows and columns (features).

Use the train set to fit the model.

Use the test set to predict the output after training.

# Load the data
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')

# Split features and value
# when trying to predict column "target"
X_train, y_train = train.drop("target"), train["target"]
X_test, y_test = test.drop("target"), test["target"]

# Fit (train) model
reg = LinearRegression()
reg.fit(X_train, y_train)

# Predict
pred = reg.predict(X_test)

# Score
accuracy = reg.socre(X_test, y_test)
```


问:
PowerShell Compilation to .exe
I have a PowerShell script that uses PowerShell 3 to perform REST API calls. The script works as intended in PowerShell 3, however, REST API calls are not supported in PowerShell 2. Unfortunately the users of the script all have PowerShell 2. Is there any way to compile the PowerShell script to an .exe such that the users of the .exe do not require a PowerShell 3 installation? I tried PS2EXE but it did not work when testing on a machine with PowerShell 2. Are there any compilers for PS that have this capability?</p>

答:
Take a look at PrimalScript or PowerShell Studio if the users need to run the script from the command-line. Both of those tools will output an exe that includes the runtime so the target environment won't have to have PowerShell v3.

If your users don't have to run the script from the shell, you could wrap it in a web GUI using System Frontier. Then they could run it from any modern browser without needing a specific PowerShell run-time on their machines.

Title: PowerShell Compilation to .exe


问:
USB device for Android
I have a usb device that I have been using in windows OS. I am to connect that device to an Android Tablet. Can you suggest some API for developing my programs to communicate over the USB device using Android Operating system.
Thank you so much for your interest</p>

答:
I think you can only do this on a rooted phone, and it is a complicated and "unsafe" process.

You can check this other post in stackoverflow forums where other references are mentioned. Some people have managed to do this but with rooted phone and some tricks, and also some projects are mentioned that were considering USB connection as a future goal, even though such development might not have been yet achieved. The link is: Android apps, communicating with a device plugged in the USB port

Title: USB device for Android


问:
is it possible to run virtualbox inside a docker container
I tried running the container in privileged mode, but still the vboxdrv cannot be loaded.

I get

```<code>WARNING: The vboxdrv kernel module is not loaded. Either there is no module
     available for the current kernel (3.11.0-22-generic) or it failed to
     load. Please recompile the kernel module and install it by

       sudo /etc/init.d/vboxdrv setup

     You will not be able to start VMs until this problem is fixed.
</code>```

答:
2019:

Virtualbox version: 6.0

Docker version: 18.09.6

Ubuntu 18.04

The key is to use a docker image that has systemd running. I chose jrei/systemd-ubuntu see here.

```<code>    docker run -d --privileged \
    --name systemd-ubuntu --network=host \
    --device /dev/vboxdrv:/dev/vboxdrv \
    -v /sys/fs/cgroup:/sys/fs/cgroup:ro \
    -v /tmp:/tmp -it jrei/systemd-ubuntu
</code>```

Inside the container I ran:

```<code>    apt update
    apt -y install wget
    apt -y install gnupg2
    apt -y install systemd
    apt -y install software-properties-common
    wget -q https://www.virtualbox.org/download/oracle_vbox_2016.asc -O- | apt-key add -
    wget -q https://www.virtualbox.org/download/oracle_vbox.asc -O- | apt-key add -
    add-apt-repository "deb https://download.virtualbox.org/virtualbox/debian bionic contrib"
    apt update
    apt -y install virtualbox-6.0
</code>```

Enjoy :-)

Body:
I tried running the container in privileged mode, but still the vboxdrv cannot be loaded.

I get

WARNING: The vboxdrv kernel module is not loaded. Either there is no module
     available for the current kernel (3.11.0-22-generic) or it failed to
     load. Please recompile the kernel module and install it by

       sudo /etc/init.d/vboxdrv setup

     You will not be able to start VMs until this problem is fixed.

Body:
2019:

Virtualbox version: 6.0

Docker version: 18.09.6

Ubuntu 18.04

The key is to use a docker image that has systemd running. I chose jrei/systemd-ubuntu see here.

    docker run -d --privileged \
    --name systemd-ubuntu --network=host \
    --device /dev/vboxdrv:/dev/vboxdrv \
    -v /sys/fs/cgroup:/sys/fs/cgroup:ro \
    -v /tmp:/tmp -it jrei/systemd-ubuntu

Inside the container I ran:

    apt update
    apt -y install wget
    apt -y install gnupg2
    apt -y install systemd
    apt -y install software-properties-common
    wget -q https://www.virtualbox.org/download/oracle_vbox_2016.asc -O- | apt-key add -
    wget -q https://www.virtualbox.org/download/oracle_vbox.asc -O- | apt-key add -
    add-apt-repository "deb https://download.virtualbox.org/virtualbox/debian bionic contrib"
    apt update
    apt -y install virtualbox-6.0

Enjoy :-)


问:
Call method between independent components using BehaviorSubject in Angular 4+
What is the best practices for calling a method between independent (no parent-child relation) components? I have a look at several samples on the web i.e. but some of them use BehaviorSubject, some of them Observable, and some of them lack of completing observables with ngOnDestroy() method. There is an example usage on How to execute a function from another component that is NOT a sibling of the first component? that I can apply to my Angular7 project successfully, but I think there is a better approach using BehaviorSubject without any missed point. Any idea? </p>

答:
Definitely the best-practice approach is to use a shared service as is mentioned in the article. You don't necessarily have to use a BehaviorSubject. You could use regular Subjects if you want, or even more classic getters and setters if that's more familiar to you (although I highly recommend embracing the reactive approach using RxJS).

Services are typically created as singletons, so you will have the issue with long-running Observables unless you put in some custom logic for it (for example, create a method in the service for unsubscribing and call that method on either of the component's onDestroy hook).

I may be misunderstanding your question, but if you're concerned about exposing BehaviorSubjects, you can always wrap them in an Observable and just expose the Obsevable:

```<code>private myBehaviorSubject = new BehaviorSubject<boolean>(false);
myObservable = this.myBehaviorSubject.asObservable()
</code>```

Hopefully that answered your question.

Body:
Definitely the best-practice approach is to use a shared service as is mentioned in the article. You don't necessarily have to use a BehaviorSubject. You could use regular Subjects if you want, or even more classic getters and setters if that's more familiar to you (although I highly recommend embracing the reactive approach using RxJS).

Services are typically created as singletons, so you will have the issue with long-running Observables unless you put in some custom logic for it (for example, create a method in the service for unsubscribing and call that method on either of the component's onDestroy hook).

I may be misunderstanding your question, but if you're concerned about exposing BehaviorSubjects, you can always wrap them in an Observable and just expose the Obsevable:

private myBehaviorSubject = new BehaviorSubject<boolean>(false);
myObservable = this.myBehaviorSubject.asObservable()

Hopefully that answered your question.


问:
How to make CSS hover tooltip display auto position(Top,Right,Bottom,Left) inside of a table
I am using bootstrap4 and custom CSS,I want to display a tooltip on td element and position it top or right or bottom or left up to the positon of td element  ? Here you can find my classes with a HTML file and a CSS file that make it's position always on top.

Here I enclose my code link to you:
Here is my Codepen.

Below you will find my code which does not provide the right solution.

This is some HTML code:

```<code><div class="container">
    <div class="col-6">
        <table class="table table-responsive">
            <tr>
                <td class="CellWithComment">
                    S
                    <span class="CellComment">
                        010620190528113002
                        <br>
                            55555
                        <br>
                        2019-05-2804:25:37
                    </span>
                <td>
                <td class="CellWithComment">
                    S
                    <span class="CellComment">
                        010620190528113002
                        <br>
                            55555
                        </br>
                        2019-05-2804:25:37
                    </span>
                <td>
            </tr>
        </table>
    </div>
</div>
</code>```

This is my CSS:

```<code>.CellWithComment {
 position: relative;
 }

.CellComment {
visibility: hidden;
background-color: black;
color: #fff;
text-align: left;
border-radius: 6px;
padding: 3px 7px;
position: absolute;
z-index: 1908;
bottom: 100%;
margin-left: -92px;
}
.CellComment::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: black transparent transparent transparent;
}

.CellWithComment:hover span.CellComment {
 visibility: visible;
 }
</code>```

答:
If you want something fancy, you need to use javascript. Here is what I came up with:

First of all. You're HTML is incorrect, where you never finish the  with 	 but instead adding another . I had to fix that before I moved on with adding more code:

https://codepen.io/anon/pen/WBKzZB

```<code>.CellWithComment:last-child > .CellComment {
  transform: translateX(-100%);
  background-color: #cc00cc;
}

tr:last-child > .CellWithComment > .CellComment {
  transform: translateY(-100%);
  background-color: #00cccc;
}

tr:last-child > .CellWithComment:last-child  > .CellComment {
  transform: translate(-100%, -100%);
  background-image: linear-gradient(20deg, #00cccc 50%, #cc00cc 51%);
}
</code>```

I added a background-color so it's easier to see my idea behind my solution.

Body:
I am using bootstrap4 and custom CSS,I want to display a tooltip on td element and position it top or right or bottom or left up to the positon of td element  ? Here you can find my classes with a HTML file and a CSS file that make it's position always on top.

Here I enclose my code link to you:
Here is my Codepen.

Below you will find my code which does not provide the right solution.

This is some HTML code:

                    S

                        010620190528113002

                            55555

                        2019-05-2804:25:37

                    S

                        010620190528113002

                            55555

                        2019-05-2804:25:37

This is my CSS:

.CellWithComment {
 position: relative;
 }

.CellComment {
visibility: hidden;
background-color: black;
color: #fff;
text-align: left;
border-radius: 6px;
padding: 3px 7px;
position: absolute;
z-index: 1908;
bottom: 100%;
margin-left: -92px;
}
.CellComment::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: black transparent transparent transparent;
}

.CellWithComment:hover span.CellComment {
 visibility: visible;
 }

Body:
If you want something fancy, you need to use javascript. Here is what I came up with:

First of all. You're HTML is incorrect, where you never finish the <td> with </td> but instead adding another <td>. I had to fix that before I moved on with adding more code:

https://codepen.io/anon/pen/WBKzZB

.CellWithComment:last-child > .CellComment {
  transform: translateX(-100%);
  background-color: #cc00cc;
}

tr:last-child > .CellWithComment > .CellComment {
  transform: translateY(-100%);
  background-color: #00cccc;
}

tr:last-child > .CellWithComment:last-child  > .CellComment {
  transform: translate(-100%, -100%);
  background-image: linear-gradient(20deg, #00cccc 50%, #cc00cc 51%);
}

I added a background-color so it's easier to see my idea behind my solution.


问:
change most significant bit of an 8 bit binary to 0 and get the decimal value of first seven bits only
I have a binary number and i want to get the decimal value of only the seven bits and not include the 8th bit. How do i go about this in java.

eg. 130 as binary => 10000010, I only need 00000010 =>2 ,ie, change only the most significant bit to 0.

Please help.

Body:
  byte b =10;
  byte result  = (byte) (b & 127);

Under the cover it would be

    00001010 //10 in dec
AND 01111111 // our mask ,127 in dec
  = 00001010 //10

another example

    10000001 //129 in dec
AND 01111111 // our mask ,127 in dec
  = 00000001 //1


问:
How to put ruby-watir code into a defined method?
I wanted to write a program with ruby (watir). To keep the code clear and compact I wanted to put code into a method, which is getting called every time the code needs to be run. But calling the method throws an error and I really don't know how to solve this problem.

I tried to define/create the browser under the method (google) but that did not work either. I am a newbie to ruby and I have no idea how to fix this because the error says that the browser is undefined. If I run the code without the method, but browser.goto "google.com" instead everything works fine.

```<code>require 'watir'

browser = Watir::Browser.new :chrome

def google
  browser.goto "google.com"
end

google
</code>```

I expect, that chrome is getting opened and the page "google.com" is getting navigated to. But instead I'm getting this error:

undefined local variable or method `browser' for main:Object (NameError)

答:
When you write your code inside the method, it has it's scope, so pass the browser variable, it would</p>

```<code>require 'watir'

browser = Watir::Browser.new :chrome

def google browser
  browser.goto "google.com"
end

google browser
</code>```

Body:
I wanted to write a program with ruby (watir). To keep the code clear and compact I wanted to put code into a method, which is getting called every time the code needs to be run. But calling the method throws an error and I really don't know how to solve this problem.

I tried to define/create the browser under the method (google) but that did not work either. I am a newbie to ruby and I have no idea how to fix this because the error says that the browser is undefined. If I run the code without the method, but browser.goto "google.com" instead everything works fine.

require 'watir'

browser = Watir::Browser.new :chrome

def google
  browser.goto "google.com"
end

google

I expect, that chrome is getting opened and the page "google.com" is getting navigated to. But instead I'm getting this error:

undefined local variable or method `browser' for main:Object (NameError)

Body:
When you write your code inside the method, it has it's scope, so pass the browser variable, it would

require 'watir'

browser = Watir::Browser.new :chrome

def google browser
  browser.goto "google.com"
end

google browser


问:
ffmpeg command to copy raw data into MP4 hangs and never finishes
I am running an ffmpeg command to copy raw H.265 data into an MP4 file and the command never completes. The file isn't large, just 10 seconds worth of data. Here's the command I'm running:

```<code>$ ffmpeg -rtsp_transport tcp -i rtsp://user:pass@71.185.124.195:554/c1/b1558830329/e1558830339/replay/ -vcodec copy -y test_clip.mp4
</code>```

I then get output like this:

```<code>ffmpeg version 3.4.6-0ubuntu0.18.04.1 Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 7 (Ubuntu 7.3.0-16ubuntu3)
  configuration: --prefix=/usr --extra-version=0ubuntu0.18.04.1 --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --enable-gpl --disable-stripping --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librubberband --enable-librsvg --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libopencv --enable-libx264 --enable-shared
  libavutil      55. 78.100 / 55. 78.100
  libavcodec     57.107.100 / 57.107.100
  libavformat    57. 83.100 / 57. 83.100
  libavdevice    57. 10.100 / 57. 10.100
  libavfilter     6.107.100 /  6.107.100
  libavresample   3.  7.  0 /  3.  7.  0
  libswscale      4.  8.100 /  4.  8.100
  libswresample   2.  9.100 /  2.  9.100
  libpostproc    54.  7.100 / 54.  7.100
Guessed Channel Layout for Input Stream #0.1 : mono
Input #0, rtsp, from 'rtsp://user:pass@71.85.104.195:554/c1/b1558830329/e1558830339/replay/':
  Metadata:
    title           : ONVIF RTSP Server
  Duration: N/A, start: 0.000000, bitrate: N/A
    Stream #0:0: Video: h264 (High), yuvj420p(pc, bt709, progressive), 1920x1080, 30 fps, 30 tbr, 90k tbn, 60 tbc
    Stream #0:1: Audio: pcm_mulaw, 8000 Hz, mono, s16, 64 kb/s
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
  Stream #0:1 -> #0:1 (pcm_mulaw (native) -> aac (native))
Press [q] to stop, [?] for help
[aac @ 0x55b71ce31900] Too many bits 8832.000000 > 6144 per frame requested, clamping to max
Output #0, mp4, to 'test_clip.mp4':
  Metadata:
    title           : ONVIF RTSP Server
    encoder         : Lavf57.83.100
    Stream #0:0: Video: h264 (High) (avc1 / 0x31637661), yuvj420p(pc, bt709, progressive), 1920x1080, q=2-31, 30 fps, 30 tbr, 90k tbn, 90k tbc
    Stream #0:1: Audio: aac (LC) (mp4a / 0x6134706D), 8000 Hz, mono, fltp, 48 kb/s
    Metadata:
      encoder         : Lavc57.107.100 aac
[mp4 @ 0x55b71ce17e00] Non-monotonous DTS in output stream 0:0; previous: 18000, current: 3000; changing to 18001. This may result in incorrect timestamps in the output file.
[mp4 @ 0x55b71ce17e00] Non-monotonous DTS in output stream 0:0; previous: 18001, current: 6000; changing to 18002. This may result in incorrect timestamps in the output file.
[mp4 @ 0x55b71ce17e00] Non-monotonous DTS in output stream 0:0; previous: 18002, current: 9000; changing to 18003. This may result in incorrect timestamps in the output file.
[mp4 @ 0x55b71ce17e00] Non-monotonous DTS in output stream 0:0; previous: 18003, current: 12000; changing to 18004. This may result in incorrect timestamps in the output file.
[mp4 @ 0x55b71ce17e00] Non-monotonous DTS in output stream 0:0; previous: 18004, current: 15000; changing to 18005. This may result in incorrect timestamps in the output file.
[mp4 @ 0x55b71ce17e00] Non-monotonous DTS in output stream 0:0; previous: 18005, current: 18000; changing to 18006. This may result in incorrect timestamps in the output file.
frame=   44 fps=0.0 q=-1.0 size=     256kB time=00:00:01.43 bitrate=1463.4kbits/frame=   60 fps= 57 q=-1.0 size=     512kB time=00:00:01.96 bitrate=2132.9kbits/frame=   76 fps= 48 q=-1.0 size=     768kB time=00:00:02.50 bitrate=2516.7kbits/frame=   92 fps= 44 q=-1.0 size=    1024kB time=00:00:03.03 bitrate=2765.6kbits/frame=  108 fps= 41 q=-1.0 size=    1024kB time=00:00:03.56 bitrate=2352.0kbits/[NULL @ 0x55b71cdfa540] SEI type 5 size 2208 truncated at 1944
frame=  123 fps= 39 q=-1.0 size=    1280kB time=00:00:04.06 bitrate=2578.6kbits/frame=  139 fps= 38 q=-1.0 size=    1536kB time=00:00:04.60 bitrate=2735.5kbits/frame=  155 fps= 37 q=-1.0 size=    1536kB time=00:00:05.13 bitrate=2451.3kbits/frame=  171 fps= 36 q=-1.0 size=    1792kB time=00:00:05.66 bitrate=2590.7kbits/frame=  187 fps= 36 q=-1.0 size=    2048kB time=00:00:06.20 bitrate=2706.1kbits/frame=  203 fps= 35 q=-1.0 size=    2304kB time=00:00:06.73 bitrate=2803.2kbits/frame=  219 fps= 35 q=-1.0 size=    2304kB time=00:00:07.26 bitrate=2597.4kbits/frame=  235 fps= 34 q=-1.0 size=    2560kB time=00:00:07.80 bitrate=2688.7kbits/frame=  246 fps= 33 q=-1.0 size=    2560kB time=00:00:08.16 bitrate=2568.0kbits/frame=  267 fps= 34 q=-1.0 size=    3072kB time=00:00:08.86 bitrate=2838.3kbits/frame=  282 fps= 34 q=-1.0 size=    3072kB time=00:00:09.36 bitrate=2686.8kbits/frame=  298 fps= 33 q=-1.0 size=    3328kB time=00:00:09.90 bitrate=2753.9kbits/frame=  314 fps= 33 q=-1.0 size=    3328kB time=00:00:10.43 bitrate=2613.1kbits/^Cspeed=1.11x
</code>```

The command never completes and I need to kill it using Ctrl-C.

I have also tried adding the options -nostdin -loglevel error and appending this to the end of the command: > /dev/null 2>&1 < /dev/null but to no avail.

I am testing the above since it mimics the actual code I'm developing which utilizes a Python package that wraps calls to ffmpeg. The Python code below works well on a laptop but hangs on EC2 (both are Ubuntu 18.04):

```<code>import argparse
import datetime
import ffmpeg

# ------------------------------------------------------------------------------
if __name__ == "__main__":

    # USAGE
    # $ python collect_and_store.py --rtsp rtsp://user:pass1@71.85.125.110:554 \
    #       --duration 30 --count 10

    # construct the argument parser and parse the arguments
    args_parser = argparse.ArgumentParser()
    args_parser.add_argument("--rtsp",
                             required=True,
                             type=str,
                             help="RTSP URL for video stream")
    args_parser.add_argument("--duration",
                             required=True,
                             type=int,
                             help="duration of saved clips (in seconds)")
    args_parser.add_argument("--count",
                             required=True,
                             type=int,
                             help="number of clips to save")
    args = vars(args_parser.parse_args())

    # sanity check for some of the arguments
    if not args["rtsp"].lower().startswith("rtsp://"):
        raise ValueError("Invalid input URL -- only RTSP supported")

    seconds_per_clip = args["duration"]
    start = int(datetime.datetime.now().strftime("%s"))
    end = start + seconds_per_clip
    number_of_files_to_collect = args["count"]

    while number_of_files_to_collect > 0:

        # build URL with start and end times
        # NOTE URL is for Uniview RTSP, add options for other camera types
        url = args["rtsp"] + f"/c1/b{start}/e{end}/replay/"

        # file where we'll write clip data
        temp_file = f"clip_b{start}_e{end}.mp4"

        # create the equivalent of the ffmpeg command:
        # $ ffmpeg -i <rtsp_url> -vcodec copy -y -rtsp_transport tcp <output_mp4>
        stream = ffmpeg.input(url)
        stream = ffmpeg.output(stream, temp_file,
                               **{"codec:v": "copy",
                                  "rtsp_transport": "tcp",
                                  "y": None
                                  }
                               )
        ffmpeg.run(stream)

        print(f"\n\nMP4 file created: {temp_file}")

        number_of_files_to_collect -= 1
        start = end + 1
        end = start + seconds_per_clip
</code>```

答:
I was able to get past this by including a duration time parameter (-t) to the ffmpeg command. So in this example instead of specifying the start and end time within the RTSP URL I included only the start time, and used the duration as the argument to ffmpeg via the -t option. The command line version for a 10-second clip looks like so:

```<code>$ ffmpeg -rtsp_transport tcp -i rtsp://user:pass@71.185.124.195:554/c1/b1558830329/replay/ -t 00:00:10 -vcodec copy -y test_clip.mp4
</code>```

My Python script with the equivalent call to ffmpeg is now this:

```<code>import argparse
import datetime

import ffmpeg

# ------------------------------------------------------------------------------
if __name__ == "__main__":

    # USAGE
    # $ python collect_and_store.py --rtsp rtsp://user:pass1@71.85.125.110:554 \
    #       --duration 30 --count 10

    # construct the argument parser and parse the arguments
    args_parser = argparse.ArgumentParser()
    args_parser.add_argument("--rtsp",
                             required=True,
                             type=str,
                             help="RTSP URL for video stream")
    args_parser.add_argument("--duration",
                             required=True,
                             type=int,
                             help="duration of saved clips (in seconds)")
    args_parser.add_argument("--count",
                             required=True,
                             type=int,
                             help="number of clips to save")
    args = vars(args_parser.parse_args())

    # sanity check for some of the arguments
    if not args["rtsp"].lower().startswith("rtsp://"):
        raise ValueError("Invalid input URL -- only RTSP supported")

    seconds_per_clip = args["duration"]
    start = int(datetime.datetime.now().strftime("%s"))
    end = start + seconds_per_clip
    number_of_files_to_collect = args["count"]

    while number_of_files_to_collect > 0:

        # build URL with start and end times
        # NOTE URL is for Uniview RTSP, add options for other camera types
        url = args["rtsp"] + f"/c1/b{start}/replay/"
        # url = args["rtsp"] + f"/c1/b{start}/e{end}/replay/"

        # file where we'll write clip data
        temp_file = f"clip_b{start}_e{end}.mp4"

        # create the equivalent of the ffmpeg command:
        # $ ffmpeg -i <rtsp_url> -vcodec copy -y -rtsp_transport tcp <output_mp4>
        stream = ffmpeg.input(url)
        stream = ffmpeg.output(stream, temp_file,
                               **{"codec:v": "copy",
                                  "rtsp_transport": "tcp",
                                  "t": f"00:00:{str(seconds_per_clip).zfill(2)}",
                                  "y": None
                                  }
                               )
        ffmpeg.run(stream)

        print(f"\n\nMP4 file created: {temp_file}")

        number_of_files_to_collect -= 1
        start += seconds_per_clip
        end += seconds_per_clip
</code>```

Body:
I am running an ffmpeg command to copy raw H.265 data into an MP4 file and the command never completes. The file isn't large, just 10 seconds worth of data. Here's the command I'm running:

$ ffmpeg -rtsp_transport tcp -i rtsp://user:pass@71.185.124.195:554/c1/b1558830329/e1558830339/replay/ -vcodec copy -y test_clip.mp4

I then get output like this:

ffmpeg version 3.4.6-0ubuntu0.18.04.1 Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 7 (Ubuntu 7.3.0-16ubuntu3)
  configuration: --prefix=/usr --extra-version=0ubuntu0.18.04.1 --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --enable-gpl --disable-stripping --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librubberband --enable-librsvg --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libopencv --enable-libx264 --enable-shared
  libavutil      55. 78.100 / 55. 78.100
  libavcodec     57.107.100 / 57.107.100
  libavformat    57. 83.100 / 57. 83.100
  libavdevice    57. 10.100 / 57. 10.100
  libavfilter     6.107.100 /  6.107.100
  libavresample   3.  7.  0 /  3.  7.  0
  libswscale      4.  8.100 /  4.  8.100
  libswresample   2.  9.100 /  2.  9.100
  libpostproc    54.  7.100 / 54.  7.100
Guessed Channel Layout for Input Stream #0.1 : mono
Input #0, rtsp, from 'rtsp://user:pass@71.85.104.195:554/c1/b1558830329/e1558830339/replay/':
  Metadata:
    title           : ONVIF RTSP Server
  Duration: N/A, start: 0.000000, bitrate: N/A
    Stream #0:0: Video: h264 (High), yuvj420p(pc, bt709, progressive), 1920x1080, 30 fps, 30 tbr, 90k tbn, 60 tbc
    Stream #0:1: Audio: pcm_mulaw, 8000 Hz, mono, s16, 64 kb/s
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
  Stream #0:1 -> #0:1 (pcm_mulaw (native) -> aac (native))
Press [q] to stop, [?] for help
[aac @ 0x55b71ce31900] Too many bits 8832.000000 > 6144 per frame requested, clamping to max
Output #0, mp4, to 'test_clip.mp4':
  Metadata:
    title           : ONVIF RTSP Server
    encoder         : Lavf57.83.100
    Stream #0:0: Video: h264 (High) (avc1 / 0x31637661), yuvj420p(pc, bt709, progressive), 1920x1080, q=2-31, 30 fps, 30 tbr, 90k tbn, 90k tbc
    Stream #0:1: Audio: aac (LC) (mp4a / 0x6134706D), 8000 Hz, mono, fltp, 48 kb/s
    Metadata:
      encoder         : Lavc57.107.100 aac
[mp4 @ 0x55b71ce17e00] Non-monotonous DTS in output stream 0:0; previous: 18000, current: 3000; changing to 18001. This may result in incorrect timestamps in the output file.
[mp4 @ 0x55b71ce17e00] Non-monotonous DTS in output stream 0:0; previous: 18001, current: 6000; changing to 18002. This may result in incorrect timestamps in the output file.
[mp4 @ 0x55b71ce17e00] Non-monotonous DTS in output stream 0:0; previous: 18002, current: 9000; changing to 18003. This may result in incorrect timestamps in the output file.
[mp4 @ 0x55b71ce17e00] Non-monotonous DTS in output stream 0:0; previous: 18003, current: 12000; changing to 18004. This may result in incorrect timestamps in the output file.
[mp4 @ 0x55b71ce17e00] Non-monotonous DTS in output stream 0:0; previous: 18004, current: 15000; changing to 18005. This may result in incorrect timestamps in the output file.
[mp4 @ 0x55b71ce17e00] Non-monotonous DTS in output stream 0:0; previous: 18005, current: 18000; changing to 18006. This may result in incorrect timestamps in the output file.
frame=   44 fps=0.0 q=-1.0 size=     256kB time=00:00:01.43 bitrate=1463.4kbits/frame=   60 fps= 57 q=-1.0 size=     512kB time=00:00:01.96 bitrate=2132.9kbits/frame=   76 fps= 48 q=-1.0 size=     768kB time=00:00:02.50 bitrate=2516.7kbits/frame=   92 fps= 44 q=-1.0 size=    1024kB time=00:00:03.03 bitrate=2765.6kbits/frame=  108 fps= 41 q=-1.0 size=    1024kB time=00:00:03.56 bitrate=2352.0kbits/[NULL @ 0x55b71cdfa540] SEI type 5 size 2208 truncated at 1944
frame=  123 fps= 39 q=-1.0 size=    1280kB time=00:00:04.06 bitrate=2578.6kbits/frame=  139 fps= 38 q=-1.0 size=    1536kB time=00:00:04.60 bitrate=2735.5kbits/frame=  155 fps= 37 q=-1.0 size=    1536kB time=00:00:05.13 bitrate=2451.3kbits/frame=  171 fps= 36 q=-1.0 size=    1792kB time=00:00:05.66 bitrate=2590.7kbits/frame=  187 fps= 36 q=-1.0 size=    2048kB time=00:00:06.20 bitrate=2706.1kbits/frame=  203 fps= 35 q=-1.0 size=    2304kB time=00:00:06.73 bitrate=2803.2kbits/frame=  219 fps= 35 q=-1.0 size=    2304kB time=00:00:07.26 bitrate=2597.4kbits/frame=  235 fps= 34 q=-1.0 size=    2560kB time=00:00:07.80 bitrate=2688.7kbits/frame=  246 fps= 33 q=-1.0 size=    2560kB time=00:00:08.16 bitrate=2568.0kbits/frame=  267 fps= 34 q=-1.0 size=    3072kB time=00:00:08.86 bitrate=2838.3kbits/frame=  282 fps= 34 q=-1.0 size=    3072kB time=00:00:09.36 bitrate=2686.8kbits/frame=  298 fps= 33 q=-1.0 size=    3328kB time=00:00:09.90 bitrate=2753.9kbits/frame=  314 fps= 33 q=-1.0 size=    3328kB time=00:00:10.43 bitrate=2613.1kbits/^Cspeed=1.11x

The command never completes and I need to kill it using Ctrl-C.

I have also tried adding the options -nostdin -loglevel error and appending this to the end of the command: > /dev/null 2>&1 < /dev/null but to no avail.

I am testing the above since it mimics the actual code I'm developing which utilizes a Python package that wraps calls to ffmpeg. The Python code below works well on a laptop but hangs on EC2 (both are Ubuntu 18.04):

import argparse
import datetime
import ffmpeg

# ------------------------------------------------------------------------------
if __name__ == "__main__":

    # USAGE
    # $ python collect_and_store.py --rtsp rtsp://user:pass1@71.85.125.110:554 \
    #       --duration 30 --count 10

    # construct the argument parser and parse the arguments
    args_parser = argparse.ArgumentParser()
    args_parser.add_argument("--rtsp",
                             required=True,
                             type=str,
                             help="RTSP URL for video stream")
    args_parser.add_argument("--duration",
                             required=True,
                             type=int,
                             help="duration of saved clips (in seconds)")
    args_parser.add_argument("--count",
                             required=True,
                             type=int,
                             help="number of clips to save")
    args = vars(args_parser.parse_args())

    # sanity check for some of the arguments
    if not args["rtsp"].lower().startswith("rtsp://"):
        raise ValueError("Invalid input URL -- only RTSP supported")

    seconds_per_clip = args["duration"]
    start = int(datetime.datetime.now().strftime("%s"))
    end = start + seconds_per_clip
    number_of_files_to_collect = args["count"]

    while number_of_files_to_collect > 0:

        # build URL with start and end times
        # NOTE URL is for Uniview RTSP, add options for other camera types
        url = args["rtsp"] + f"/c1/b{start}/e{end}/replay/"

        # file where we'll write clip data
        temp_file = f"clip_b{start}_e{end}.mp4"

        # create the equivalent of the ffmpeg command:
        # $ ffmpeg -i <rtsp_url> -vcodec copy -y -rtsp_transport tcp <output_mp4>
        stream = ffmpeg.input(url)
        stream = ffmpeg.output(stream, temp_file,
                               **{"codec:v": "copy",
                                  "rtsp_transport": "tcp",
                                  "y": None
                                  }
                               )
        ffmpeg.run(stream)

        print(f"\n\nMP4 file created: {temp_file}")

        number_of_files_to_collect -= 1
        start = end + 1
        end = start + seconds_per_clip

Body:
I was able to get past this by including a duration time parameter (-t) to the ffmpeg command. So in this example instead of specifying the start and end time within the RTSP URL I included only the start time, and used the duration as the argument to ffmpeg via the -t option. The command line version for a 10-second clip looks like so:

$ ffmpeg -rtsp_transport tcp -i rtsp://user:pass@71.185.124.195:554/c1/b1558830329/replay/ -t 00:00:10 -vcodec copy -y test_clip.mp4

My Python script with the equivalent call to ffmpeg is now this:

import argparse
import datetime

import ffmpeg

# ------------------------------------------------------------------------------
if __name__ == "__main__":

    # USAGE
    # $ python collect_and_store.py --rtsp rtsp://user:pass1@71.85.125.110:554 \
    #       --duration 30 --count 10

    # construct the argument parser and parse the arguments
    args_parser = argparse.ArgumentParser()
    args_parser.add_argument("--rtsp",
                             required=True,
                             type=str,
                             help="RTSP URL for video stream")
    args_parser.add_argument("--duration",
                             required=True,
                             type=int,
                             help="duration of saved clips (in seconds)")
    args_parser.add_argument("--count",
                             required=True,
                             type=int,
                             help="number of clips to save")
    args = vars(args_parser.parse_args())

    # sanity check for some of the arguments
    if not args["rtsp"].lower().startswith("rtsp://"):
        raise ValueError("Invalid input URL -- only RTSP supported")

    seconds_per_clip = args["duration"]
    start = int(datetime.datetime.now().strftime("%s"))
    end = start + seconds_per_clip
    number_of_files_to_collect = args["count"]

    while number_of_files_to_collect > 0:

        # build URL with start and end times
        # NOTE URL is for Uniview RTSP, add options for other camera types
        url = args["rtsp"] + f"/c1/b{start}/replay/"
        # url = args["rtsp"] + f"/c1/b{start}/e{end}/replay/"

        # file where we'll write clip data
        temp_file = f"clip_b{start}_e{end}.mp4"

        # create the equivalent of the ffmpeg command:
        # $ ffmpeg -i <rtsp_url> -vcodec copy -y -rtsp_transport tcp <output_mp4>
        stream = ffmpeg.input(url)
        stream = ffmpeg.output(stream, temp_file,
                               **{"codec:v": "copy",
                                  "rtsp_transport": "tcp",
                                  "t": f"00:00:{str(seconds_per_clip).zfill(2)}",
                                  "y": None
                                  }
                               )
        ffmpeg.run(stream)

        print(f"\n\nMP4 file created: {temp_file}")

        number_of_files_to_collect -= 1
        start += seconds_per_clip
        end += seconds_per_clip


问:
turning a list of numpy.ndarray to a matrix in order to perform multiplication
i have vectors of this form :

```<code>test=np.linspace(0,1,10)
</code>```

i want to stack them horizontally in order to make a matrix .
problem is that i define them in a loop so the first stack is between an empty matrix and the first column vector , which gives the following error:

```<code>ValueError: all the input arrays must have same number of dimensions
</code>```

bottom line - i have a for loop that with every iteration creates a vector p1 and i want to add it to a final matrix of the form :
[p1 p2 p3 p4] which i could then do matrix operations on such as multiplying by the transposed etc

Body:
i have vectors of this form :

test=np.linspace(0,1,10)

i want to stack them horizontally in order to make a matrix .
problem is that i define them in a loop so the first stack is between an empty matrix and the first column vector , which gives the following error:

ValueError: all the input arrays must have same number of dimensions

bottom line - i have a for loop that with every iteration creates a vector p1 and i want to add it to a final matrix of the form :
[p1 p2 p3 p4] which i could then do matrix operations on such as multiplying by the transposed etc

Body:
If you've got a list of 1D arrays that you want horizontally stacked, you could convert them all to column first, but it's probably easier to just vertically stack them and then transpose:

In [6]: vector_list = [np.linspace(0, 1, 10) for _ in range(3)]

In [7]: np.vstack(vector_list).T
Out[7]:
array([[0.        , 0.        , 0.        ],
       [0.11111111, 0.11111111, 0.11111111],
       [0.22222222, 0.22222222, 0.22222222],
       [0.33333333, 0.33333333, 0.33333333],
       [0.44444444, 0.44444444, 0.44444444],
       [0.55555556, 0.55555556, 0.55555556],
       [0.66666667, 0.66666667, 0.66666667],
       [0.77777778, 0.77777778, 0.77777778],
       [0.88888889, 0.88888889, 0.88888889],
       [1.        , 1.        , 1.        ]])


问:
How to intercept and save to a variable the output streaming of a command in node.js?
I have this script that properly run synchronously the ls command and output the result to the terminal. How can I intercept the result and save it to a variable?

```<code>const cp = require('child_process');
const result = cp.spawnSync(
    'ls',
    ['-l', '/usr'],
    { stdio: [process.stdin, process.stdout, process.stdout] }
);
</code>```

If I try this, as suggested by https://stackoverflow.com/a/30617874/693271

```<code>result.stdout.on('data', function (chunk) {
    console.log(chunk);
});
</code>```

I get

```<code>result.stdout.on('data', function (chunk) {
              ^
TypeError: Cannot read property 'on' of null
</code>```

The difference is that is about spawnSync and not about spawn

答:
By looking at the docs we can see that the result of spawnSync returns an object containing a key called stdout, which is a Buffer. You do not have to listen to events since you're calling the synchronous version of the spawn - the process will wait for the command to finish executing before resuming and then returns the result.

So in your case, the result of your ls -l /usr command can be read with result.stdout.toString(). You also need to keep the default config for stdio in the options.

Body:
I have this script that properly run synchronously the ls command and output the result to the terminal. How can I intercept the result and save it to a variable?

const cp = require('child_process');
const result = cp.spawnSync(
    'ls',
    ['-l', '/usr'],
    { stdio: [process.stdin, process.stdout, process.stdout] }
);

If I try this, as suggested by https://stackoverflow.com/a/30617874/693271

result.stdout.on('data', function (chunk) {
    console.log(chunk);
});

I get

result.stdout.on('data', function (chunk) {
              ^
TypeError: Cannot read property 'on' of null

The difference is that is about spawnSync and not about spawn


问:
Ports allowed for an application
Can an application use two different ports simultaneously?</p>

答: yes , if and only if it is not already occupied </p>

Title: Ports allowed for an application


问:
Reading an incoming/received Lora frame with I-Cube End-node sample code
I'm using the ST I-Cube End-node sample code (in C) embedded on the B-L072Z-LRWAN1 discovery kit board and transmitting a LoRaWAN packet to my End-node device.
I'm seeing that the packet has been received by the end device because it prints:

"PACKET RECEIVED ON PORT 1"

But I don't know how or where the received packet is stored.

How can I print and access the packet data/payload that I have transmitted to my node?

Appreciate the help!

答:
A function with the signature void LORA_RxData(lora_AppData_t *AppData) has been declared and defined wherein the lora_AppData_t contains the downlink LoRaWAN payload.

The available member variables are:

message buffer: AppData->Buff

Size of the message buffer: AppData->BuffSize

Port of the received message: AppData->Port

This all can be found in the files lora.h and lora.c. These files contain ST's implemenentation of the LoRaMac-node

The function is defined with __weak so you can define your own LORA_RxData to process the data on your own terms. If you don't redefine it it will use the default.


问:
multiple variable in python regex
I have seen several related posts and several forums to find an answer for my question, but nothing has come up to what I need.

I am trying to use variable instead of hard-coded values in regex which search for either word in a line.

However i am able to get desired result if i don't use variable.

```<code><http://www.somesite.com/software/sub/a1#Msoffice>
<http://www.somesite.com/software/sub1/a1#vlc>
<http://www.somesite.com/software/sub2/a2#dell>
<http://www.somesite.com/software/sub3/a3#Notepad>

re.search(r"\#Msoffice|#vlc|#Notepad", line)
</code>```

This regex will return the line which has #Msoffice OR #vlc OR #Notepad.

I tried defining a single variable using re.escape and that worked absolutely fine. However i have tried many combination using | and , (pipe and comma) but no success.

Is there any way i can specify #Msoffice , #vlc and #Notepad in different variables and so later i can change those ?

Thanks in advance!!

答:
```<code>import re

lines = ["<http://www.somesite.com/software/sub/a1#Msoffice>",
                "<http://www.somesite.com/software/sub1/a1#vlc>",
                "<http://www.somesite.com/software/sub2/a2#dell>",
                "<http://www.somesite.com/software/sub3/a3#Notepad>"]

for line in lines:
    if re.search(r'\b(?:\#{}|\#{}|\#{})\b'.format('Msoffice', 'vlc', 'Notepad'), line):
        print(line)
</code>```

<p>Output : </p>

```<code><http://www.somesite.com/software/sub/a1#Msoffice>
<http://www.somesite.com/software/sub1/a1#vlc>
<http://www.somesite.com/software/sub3/a3#Notepad>

</code>```

Title: multiple variable in python regex

Body:
I have seen several related posts and several forums to find an answer for my question, but nothing has come up to what I need.

I am trying to use variable instead of hard-coded values in regex which search for either word in a line.

However i am able to get desired result if i don't use variable.

<http://www.somesite.com/software/sub/a1#Msoffice>
<http://www.somesite.com/software/sub1/a1#vlc>
<http://www.somesite.com/software/sub2/a2#dell>
<http://www.somesite.com/software/sub3/a3#Notepad>

re.search(r"\#Msoffice|#vlc|#Notepad", line)

This regex will return the line which has #Msoffice OR #vlc OR #Notepad.

I tried defining a single variable using re.escape and that worked absolutely fine. However i have tried many combination using | and , (pipe and comma) but no success.

Is there any way i can specify #Msoffice , #vlc and #Notepad in different variables and so later i can change those ?

Thanks in advance!!

Body:
import re

lines = ["<http://www.somesite.com/software/sub/a1#Msoffice>",
                "<http://www.somesite.com/software/sub1/a1#vlc>",
                "<http://www.somesite.com/software/sub2/a2#dell>",
                "<http://www.somesite.com/software/sub3/a3#Notepad>"]

for line in lines:
    if re.search(r'\b(?:\#{}|\#{}|\#{})\b'.format('Msoffice', 'vlc', 'Notepad'), line):
        print(line)

Output :

<http://www.somesite.com/software/sub/a1#Msoffice>
<http://www.somesite.com/software/sub1/a1#vlc>
<http://www.somesite.com/software/sub3/a3#Notepad>


问:
How to implement the Debug trait for struct that has a trait object member?
My goal is printing the contents of struct that has trait object member but I can't find how to tell Rust compiler that the member also implements other traits like Display or Debug.

For example, in the following program, I want to print the structure of S2 (and S1 for comparison) but I get stuck in the implementation of fmt.

trait Tr {}

impl Tr for usize {}

impl Tr for String {}

#[derive(Debug)]
struct S1 {
    member: Box,
}

struct S2 {
    member: Box
,
}

impl std::fmt::Debug for S2 {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        // ??
        Ok(())
    }
}

fn main() {
    let s1 = S1 {
        member: Box::new(String::from("abc")),
    };

    println!("{:?}", s1);

    let s2 = S2 {
        member: Box::new(String::from("abc")),
    };

    println!("{:?}", s2);
}
```

<p>My desired output of this program is</p>

<pre class="lang-none prettyprint-override"><code>S1 { member: "abc" }
S2 { member: "abc" }
</code>```

Is it possible to implement Debug for a struct like S2?

(Rust version: 1.35)

答:
Is it possible to implement Debug for a struct like S2?

Yes you can, and this is clearly pointed out in the Book

You need to implement the Debug trait for your S2 like following:

```<code>trait MyTrait {}
impl MyTrait for usize {}
impl MyTrait for String {}

trait MyTraitWritable: MyTrait + Debug {}
impl MyTraitWritable for usize {}
impl MyTraitWritable for String {}

impl std::fmt::Debug for S2 {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(fmt, "S2 {{ member: {:?} }}", self.member)
    }
}
</code>```

Playground

Body:
My goal is printing the contents of struct that has trait object member but I can't find how to tell Rust compiler that the member also implements other traits like Display or Debug.

For example, in the following program, I want to print the structure of S2 (and S1 for comparison) but I get stuck in the implementation of fmt.

trait Tr {}

impl Tr for usize {}

impl Tr for String {}

#[derive(Debug)]
struct S1 {
    member: Box,
}

struct S2 {
    member: Box
,
}

impl std::fmt::Debug for S2 {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        // ??
        Ok(())
    }
}

fn main() {
    let s1 = S1 {
        member: Box::new(String::from("abc")),
    };

    println!("{:?}", s1);

    let s2 = S2 {
        member: Box::new(String::from("abc")),
    };

    println!("{:?}", s2);
}

My desired output of this program is

S1 { member: "abc" }
S2 { member: "abc" }

Is it possible to implement Debug for a struct like S2?

(Rust version: 1.35)

Body:
Is it possible to implement Debug for a struct like S2?

Yes you can, and this is clearly pointed out in the Book

You need to implement the Debug trait for your S2 like following:

trait MyTrait {}
impl MyTrait for usize {}
impl MyTrait for String {}

trait MyTraitWritable: MyTrait + Debug {}
impl MyTraitWritable for usize {}
impl MyTraitWritable for String {}

impl std::fmt::Debug for S2 {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(fmt, "S2 {{ member: {:?} }}", self.member)
    }
}

Playground


问:
How to configure fetch base url on deployment in docker for react app?
I have a React app with fetches from an API in it. I have a dockerfile that works.

How do I configure the base url for all fetches in production?

In the end I will deploy my React app on Azure App Services.
I used the tag proxy in package.json, but this is only for development.
An Example fetch looks like this: (before "/evaluations" the base url has to be placed)

```<code>    fetch(`/evaluations?onlyactiveones=true`, this.credentials)
        .then(response => response.text())
        .then(data => {
            this.setState({ evaluations: data });
            console.log(data);
        });
</code>```

答:
Looks like you are making fetch calls to relative url. So by default it will make call to your domain as base url. For example in this case, http://yourdomain.com/evluations, but most likely you want to make call to http://someotherdomain.com/api/evaluations. In order to do that you need to configure reverse proxy in your azure web site (or any other hosting server)

In azure website you can configure reverse proxy as suggested in the following link:
 https://ppolyzos.com/2015/10/26/reverse-proxy-functionality-in-azure-web-sites/

Body:
I have a React app with fetches from an API in it. I have a dockerfile that works.

How do I configure the base url for all fetches in production?

In the end I will deploy my React app on Azure App Services.
I used the tag proxy in package.json, but this is only for development.
An Example fetch looks like this: (before "/evaluations" the base url has to be placed)

    fetch(`/evaluations?onlyactiveones=true`, this.credentials)
        .then(response => response.text())
        .then(data => {
            this.setState({ evaluations: data });
            console.log(data);
        });


问:
WPF 4.0 SpellCheck issue loading Custom Dictionaries
Has anyone used a custom dictionary into WPF 4.0?
I am having an issue getting the Custom Dictionaries to work in my WPF project.
I have been trying to follow the example msdn offers but have made no progress.

http://msdn.microsoft.com/en-us/library/system.windows.controls.spellcheck.customdictionaries.aspx

```<code>glossary.Definition.SpellCheck.IsEnabled = true;
Uri uri = new Uri(@"pack://application:,,,/Prog.Proj;component/dictionary.lex");
glossary.Definition.SpellCheck.CustomDictionaries.Add(uri);
</code>```

Due to the nature of my work sub folders have been renamed.

My .lex file is set as a resource file.

EDIT

I am able to get this to work only if I set it up in a separate button event after the page has already loaded.  It seems that something is preventing the 'Speller' property of CustomDictionariesSources to load until after a postback?  If anyone knows anything on this please post your insight.

FINAL EDIT

My desired text box was within a grid which had a enabled disabled flag that was set deep within the code.  Another link commented below talks towards this point.  Another issue faced is my page is rendered by parts depending on user selection.  To create consistent behavior I am loading my spellcheck as a last step each time my textbox would be loaded/re-loaded.

I created a context menut extension to allow users to either take a suggestion or add to a custom dictionary.  I am then submitting my custom dictionary into the registry based on current user.  I found this direction to be very user friendly and easy to implement.  To retrieve the items back I need to create a temporary file, pack the uri for that file then after loading the custom dictionary I deleted the file.

If this helps you implement your custom spell check or if you have questions please let me know!

答: In my case the problem was fixed by changing the Build Action on my custom.lex file from None to Resource

Body:
Has anyone used a custom dictionary into WPF 4.0?
I am having an issue getting the Custom Dictionaries to work in my WPF project.
I have been trying to follow the example msdn offers but have made no progress.

http://msdn.microsoft.com/en-us/library/system.windows.controls.spellcheck.customdictionaries.aspx

glossary.Definition.SpellCheck.IsEnabled = true;
Uri uri = new Uri(@"pack://application:,,,/Prog.Proj;component/dictionary.lex");
glossary.Definition.SpellCheck.CustomDictionaries.Add(uri);

Due to the nature of my work sub folders have been renamed.

My .lex file is set as a resource file.

EDIT

I am able to get this to work only if I set it up in a separate button event after the page has already loaded.  It seems that something is preventing the 'Speller' property of CustomDictionariesSources to load until after a postback?  If anyone knows anything on this please post your insight.

FINAL EDIT

My desired text box was within a grid which had a enabled disabled flag that was set deep within the code.  Another link commented below talks towards this point.  Another issue faced is my page is rendered by parts depending on user selection.  To create consistent behavior I am loading my spellcheck as a last step each time my textbox would be loaded/re-loaded.

I created a context menut extension to allow users to either take a suggestion or add to a custom dictionary.  I am then submitting my custom dictionary into the registry based on current user.  I found this direction to be very user friendly and easy to implement.  To retrieve the items back I need to create a temporary file, pack the uri for that file then after loading the custom dictionary I deleted the file.

If this helps you implement your custom spell check or if you have questions please let me know!


问:
SQL query to get all records with certain parent IDs and two additional conditions
So I am working on a table which stores different bus routes. Each route can go through different locations (StationId) and the order in which it goes through each of them is determined by the column StationOrder.

The table looks like this:

```<code>RouteId | StationId | StationOrder |
------------------------------------
1       | 1         | 2
1       | 2         | 3
1       | 4         | 1
3       | 1         | 1
3       | 2         | 3
3       | 3         | 2
</code>```

What I know is the routes that I'm interested in. In this case those are routes with id 1 and 3. I also know which is the starting Station, StationId 1 what I need to select is all StationIds which have StationOrder number higher than the StationOrder number for StationId 1.

I would show what I've tried so far but basically, since the table contains more routes than just two those I know how to select the desired routes:

```<code>SELECT RS.StationId FROM RouteStations AS RS
WHERE RS.RouteId IN (1,3)
</code>```

But when it comes to the second part where I need to select all StationIds with StationOrder number higher than the StationOrder number for StationId 1 for each route my SQL knowledge comes short.

答:
If the routeId is not important, then remove it from the inline view...</p>

```<code>SELECT a.*
FROM routes a
JOIN (
        SELECT  routeId
        ,       stationId
        ,       max(stationOrder) maxOrder
        FROM routes
        WHERE stationId = 1
        GROUP BY routeId
        ,        stationId
        ) b ON a.routeId = b.routeId
WHERE a.stationOrder > b.maxOrder
</code>```

Body:
So I am working on a table which stores different bus routes. Each route can go through different locations (StationId) and the order in which it goes through each of them is determined by the column StationOrder.

The table looks like this:

RouteId | StationId | StationOrder |
------------------------------------
1       | 1         | 2
1       | 2         | 3
1       | 4         | 1
3       | 1         | 1
3       | 2         | 3
3       | 3         | 2

What I know is the routes that I'm interested in. In this case those are routes with id 1 and 3. I also know which is the starting Station, StationId 1 what I need to select is all StationIds which have StationOrder number higher than the StationOrder number for StationId 1.

I would show what I've tried so far but basically, since the table contains more routes than just two those I know how to select the desired routes:

SELECT RS.StationId FROM RouteStations AS RS
WHERE RS.RouteId IN (1,3)

But when it comes to the second part where I need to select all StationIds with StationOrder number higher than the StationOrder number for StationId 1 for each route my SQL knowledge comes short.

Body:
If the routeId is not important, then remove it from the inline view...

SELECT a.*
FROM routes a
JOIN (
        SELECT  routeId
        ,       stationId
        ,       max(stationOrder) maxOrder
        FROM routes
        WHERE stationId = 1
        GROUP BY routeId
        ,        stationId
        ) b ON a.routeId = b.routeId
WHERE a.stationOrder > b.maxOrder


问:
Does Google Actions Support Websockets?
I am trying to build a Rocket Chat Google Action and one of the major advantage of RC is it's Realtime API's however they require Websocket to get access. I know that Dialogflow can be used for Websocket's but does Google Actions support it?

I am using Dialogflow along with Firebase as backend for my Action.

答:
Actions on Google is a platform for stateless applications running through a REST API call. In this model, the user sends one request to your server and they get back one response.

Actions on Google itself doesn't support web sockets, but you are able to define a cloud function like Firebase to do advanced fulfillment. While you may be able to get web sockets to work in your function, you'd still need to adjust the Action's conversational flow to work in a request/response fashion instead of listening to web sockets continually.

Title: Does Google Actions Support Websockets?


问:
Display data with whereRaw clause
This question is about how do I display the return data in the datatables from 2019-04-01 only.

I tried the whereRaw clause but it doesn't work on how I want it to be.

Here is the code:

```<code> case 'total_bets':
                $data = $user->bets()->with(['team', 'match' => function($query)
                    {
                        $query->select('id', 'name', 'status', 'team_winner');
                    }, 'league' => function($query)
                    {
                        $query->select('id', 'name', 'status', 'betting_status', 'league_winner');
                    }])->whereRaw("date(bets.created_at) >= '2019-04-01'")->orderBy('updated_at', 'desc');

                return \Datatables::of($data)->addColumn('potential_winnings', function (\App\Bet $bet) use($user)
                })->make(true);
</code>```

Any ideas how to deal with this? Thanks.

答:
You can use Laravel's Carbon library for same.
In you controller, add Carbon library using:

```<code>use Carbon\Carbon;
</code>```

Eg.

```<code>$date = Carbon::create(2019, 4, 1, 0, 0, 0, '{what-ever-timezone}');
$data = $user->bets()->with(['team', 'match' => function($query) use ($date)
                    {
                        $query->select('id', 'name', 'status', 'team_winner');
                    }, 'league' => function($query)
                    {
                        $query->select('id', 'name', 'status', 'betting_status', 'league_winner');
                    }])->where('bets.created_at', '>=', $date)->orderBy('updated_at', 'desc');

                return \Datatables::of($data)->addColumn('potential_winnings', function (\App\Bet $bet) use($user)
                })->make(true);
</code>```

Title: Display data with whereRaw clause

Body:
This question is about how do I display the return data in the datatables from 2019-04-01 only.

I tried the whereRaw clause but it doesn't work on how I want it to be.

Here is the code:

 case 'total_bets':
                $data = $user->bets()->with(['team', 'match' => function($query)
                    {
                        $query->select('id', 'name', 'status', 'team_winner');
                    }, 'league' => function($query)
                    {
                        $query->select('id', 'name', 'status', 'betting_status', 'league_winner');
                    }])->whereRaw("date(bets.created_at) >= '2019-04-01'")->orderBy('updated_at', 'desc');

                return \Datatables::of($data)->addColumn('potential_winnings', function (\App\Bet $bet) use($user)
                })->make(true);

Any ideas how to deal with this? Thanks.

Body:
You can use Laravel's Carbon library for same.
In you controller, add Carbon library using:

use Carbon\Carbon;

Eg.

$date = Carbon::create(2019, 4, 1, 0, 0, 0, '{what-ever-timezone}');
$data = $user->bets()->with(['team', 'match' => function($query) use ($date)
                    {
                        $query->select('id', 'name', 'status', 'team_winner');
                    }, 'league' => function($query)
                    {
                        $query->select('id', 'name', 'status', 'betting_status', 'league_winner');
                    }])->where('bets.created_at', '>=', $date)->orderBy('updated_at', 'desc');

                return \Datatables::of($data)->addColumn('potential_winnings', function (\App\Bet $bet) use($user)
                })->make(true);


问:
How to fix the "undefined" return from my mongoose/mongodb search function
I'm attempting to get the result from mongodb and then pass it to a const, but getting return vale of "undfined" where did I go wrong?

I made sure that the code works without the return and prints to console and made sure the data set is present in my mongodb.

```<code>const mongoose = require('mongoose');

function search(query) {
  const search = db.collection('spells').find({
    "name": query
  }).then(function(cursor) {
    cursor.forEach(function(spell) {
      console.log(spell);
      return spell;
    });
  });
}

mongoose.connect('mongodb://localhost/dnd', {
  useNewUrlParser: true
});

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("Connected to DB" + "\n");

});

console.log(search("Blight"));
</code>```

when the above is ran I get the following outputs on command line

undefined

Connected to DB

Then it prints the following which is the data in Mongodb

```<code>{ _id: 5ced1ce8aa89b60a7c2e34de,
  name: 'Blight',
  level: 4,
  school: 'N',
  time: [ { number: 1, unit: 'action' } ],
  range: { type: 'point', distance: { type: 'feet', amount: 30 } },
  components: { v: true, s: true },
  duration: [ { type: 'instant' } ],
  classes:
   { fromClassList: [ [Object], [Object], [Object], [Object] ],
     fromSubclass:
      [ [Object], [Object], [Object], [Object], [Object], [Object] ] },
  source: 'PHB',
  entries:
   [ 'Necromantic energy washes over a creature of your choice that you can see within range, draining moisture and vitality from it. The target must make a Constitution saving throw. The target takes {@dice 8d8} necrotic damage on a failed save, or half as much damage on a succ
essful one. This spell has no effect on undead or constructs.',
     'If you target a plant creature or a magical plant, it makes the saving throw with disadvantage, and the spell deals maximum damage to it.',
     'If you target a nonmagical plant that isn\'t a creature, such as a tree or shrub, it doesn\'t make a saving throw, it simply withers and dies.' ],
  entriesHigherLevel:
   [ { type: 'entries', name: 'At Higher Levels', entries: [Array] } ],
  page: 219,
  damageInflict: [ 'necrotic' ],
  savingThrow: [ 'constitution' ] }
</code>```

I want to be able to get the data via the return and not inside the function.

答:
After getting some advice from avu in freenode/#Node.js, I looked into promises and came up with this sloution.</p>

```<code>const mongoose = require('mongoose');

function search(query) {
  return new Promise(function(resolve) {
      const findspell = db.collection('spells').find({
        "name": query
      }).then(function(cursor) {
        cursor.forEach(function(spell) {
          resolve(spell)
        });
      });
    });
  }

  mongoose.connect('mongodb://localhost/dnd', {
    useNewUrlParser: true
  });

  const db = mongoose.connection;

  db.on('error', console.error.bind(console, 'connection error:'));
  db.once('open', function() {
    console.log("Connected to DB" + "\n");

  });

  search("Blight").then(console.log(response)});
</code>```

Body:
I'm attempting to get the result from mongodb and then pass it to a const, but getting return vale of "undfined" where did I go wrong?

I made sure that the code works without the return and prints to console and made sure the data set is present in my mongodb.

const mongoose = require('mongoose');

function search(query) {
  const search = db.collection('spells').find({
    "name": query
  }).then(function(cursor) {
    cursor.forEach(function(spell) {
      console.log(spell);
      return spell;
    });
  });
}

mongoose.connect('mongodb://localhost/dnd', {
  useNewUrlParser: true
});

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("Connected to DB" + "\n");

});

console.log(search("Blight"));

when the above is ran I get the following outputs on command line

undefined

Connected to DB

Then it prints the following which is the data in Mongodb

{ _id: 5ced1ce8aa89b60a7c2e34de,
  name: 'Blight',
  level: 4,
  school: 'N',
  time: [ { number: 1, unit: 'action' } ],
  range: { type: 'point', distance: { type: 'feet', amount: 30 } },
  components: { v: true, s: true },
  duration: [ { type: 'instant' } ],
  classes:
   { fromClassList: [ [Object], [Object], [Object], [Object] ],
     fromSubclass:
      [ [Object], [Object], [Object], [Object], [Object], [Object] ] },
  source: 'PHB',
  entries:
   [ 'Necromantic energy washes over a creature of your choice that you can see within range, draining moisture and vitality from it. The target must make a Constitution saving throw. The target takes {@dice 8d8} necrotic damage on a failed save, or half as much damage on a succ
essful one. This spell has no effect on undead or constructs.',
     'If you target a plant creature or a magical plant, it makes the saving throw with disadvantage, and the spell deals maximum damage to it.',
     'If you target a nonmagical plant that isn\'t a creature, such as a tree or shrub, it doesn\'t make a saving throw, it simply withers and dies.' ],
  entriesHigherLevel:
   [ { type: 'entries', name: 'At Higher Levels', entries: [Array] } ],
  page: 219,
  damageInflict: [ 'necrotic' ],
  savingThrow: [ 'constitution' ] }

I want to be able to get the data via the return and not inside the function.

Body:
After getting some advice from avu in freenode/#Node.js, I looked into promises and came up with this sloution.

const mongoose = require('mongoose');

function search(query) {
  return new Promise(function(resolve) {
      const findspell = db.collection('spells').find({
        "name": query
      }).then(function(cursor) {
        cursor.forEach(function(spell) {
          resolve(spell)
        });
      });
    });
  }

  mongoose.connect('mongodb://localhost/dnd', {
    useNewUrlParser: true
  });

  const db = mongoose.connection;

  db.on('error', console.error.bind(console, 'connection error:'));
  db.once('open', function() {
    console.log("Connected to DB" + "\n");

  });

  search("Blight").then(console.log(response)});


问:
Problem with direction sensitive image-data
I´m new here, so please be kind and teach me if I did not provide all the information you need :)

I need to detect objects by object detection. Everything works fine for most of my object classes, but there is a problem:

I have some objects that are sensitive to their direction on the image. More precisely: I have objects that are aligned as "to the right" or "to the left" and should be recognized as such.

I already know that TensorFlow reflects the images randomly - which destroys my alignment, because left is right and right left. I come to this conclusion because all other objects are detected in a good amount and quality.

Therefore I want to "forbid" TensorFlow to mirror the images and only to rotate them instead.

I have already searched the Python classes and identified the function "tf.image.flip_left_right" which does the mirroring.

Now I don't know which of the many many files and places, where this method is called, I have to change (none of the scripts are mine, they all come natively with TensorFlow!)

Here are the scripts the method was called:

```<code>...\models\research\object_detection\core\preprocessor.py (1 hit)

...\models\research\object_detection\core\__pycache__\preprocessor.cpython-36.pyc (1 hit)

...\models\research\object_detection\training\events.out.tfevents.1559030641.R233689 (60 hits)

...\models\research\object_detection\training\graph.pbtxt (24 hits)

...above that: 36 Hits in every model.ckpt-XXXXX.meta-file
</code>```

(which I dont think they are important for this problem?)

Has anyone had any experience with it and can give me any advice?

EDIT: I´m using TF in version 1.13

答:
You should have a .config file somewhere which defines the augmentation applied to your images. See for example this file.

Just remove random_horizontal_flip {} and you are done.

Body:
I´m new here, so please be kind and teach me if I did not provide all the information you need :)

I need to detect objects by object detection. Everything works fine for most of my object classes, but there is a problem:

I have some objects that are sensitive to their direction on the image. More precisely: I have objects that are aligned as "to the right" or "to the left" and should be recognized as such.

I already know that TensorFlow reflects the images randomly - which destroys my alignment, because left is right and right left. I come to this conclusion because all other objects are detected in a good amount and quality.

Therefore I want to "forbid" TensorFlow to mirror the images and only to rotate them instead.

I have already searched the Python classes and identified the function "tf.image.flip_left_right" which does the mirroring.

Now I don't know which of the many many files and places, where this method is called, I have to change (none of the scripts are mine, they all come natively with TensorFlow!)

Here are the scripts the method was called:

...\models\research\object_detection\core\preprocessor.py (1 hit)

...\models\research\object_detection\core\__pycache__\preprocessor.cpython-36.pyc (1 hit)

...\models\research\object_detection\training\events.out.tfevents.1559030641.R233689 (60 hits)

...\models\research\object_detection\training\graph.pbtxt (24 hits)

...above that: 36 Hits in every model.ckpt-XXXXX.meta-file

(which I dont think they are important for this problem?)

Has anyone had any experience with it and can give me any advice?

EDIT: I´m using TF in version 1.13


答:
In general, yes.  Just open two sockets.

Of course there may be a firewall present and the firewall may not be configured to allow the application to use both ports.  But most any firewall should support the ability to configure a range (or multiple distinct ranges) of ports as accessible to a given application.

Title: Ports allowed for an application

Body: Can an application use two different ports simultaneously?


问:
Why is this result?
Is that about stack? I think the last *p++ is undefined. *p++ means *(p++) or *p;p++;?

void test123()
{

    char s[] = "123", * p;
    p = s;
    // 1 2 3
    cout << *p++ << endl;
    cout << *p++ << endl;
    cout << *p++ << endl;

}
void test321()
{
    char s[] = "123", * p;
    p = s;
    //321
    cout << *p++ << *p++ << *p++ << endl;

}
int main(void)
{
    cout << "123:" << endl;
    test123();
    cout << "123:" << endl;
    test321();
    cout << "hello world" << endl;
    return 0;
}
```

I think the result is undefined.

答:
*p++ means *(p++) and *p;p++, because they are the same.

First ++ has a higher precedence over *, so it's computed first. Then dereferencement happens. In both cases. The thing is that p++ returns the value before the increment, as explained in the C++ standard.

Finally, as it was said int he comments, in C++17, the evaluation order was improved so that test321 behavior is well-defined. In C++11 it is indeed not.

The fact that p points to \0 is also well defined in C++17 (it would also point to the same value in C++11 because you have 4 characters, not just 3). Even with an additional ++, it would still be well-defined, unless you dereference the value. But just pointing to the end of an array is well defined as well and is why vectors can work.

Title: Why is this result?

Body:
Is that about stack? I think the last *p++ is undefined. *p++ means *(p++) or *p;p++;?

void test123()
{

    char s[] = "123", * p;
    p = s;
    // 1 2 3
    cout << *p++ << endl;
    cout << *p++ << endl;
    cout << *p++ << endl;

}
void test321()
{
    char s[] = "123", * p;
    p = s;
    //321
    cout << *p++ << *p++ << *p++ << endl;

}
int main(void)
{
    cout << "123:" << endl;
    test123();
    cout << "123:" << endl;
    test321();
    cout << "hello world" << endl;
    return 0;
}

I think the result is undefined.


问:
Ethereum: calling smart contract functions from Restful APIs
I am having an Ethereum Smart Contract and deployed on Ropsten TestNet network. Is there any way to call those functions using rest API? If yes please explain. If no, Please let me know how do Pre-sale of ICO works? because I believe pre-sale works similar to this.

The concepts I know says: When presale happens. The owner/organization of ICO handles it using their website. They sell the coins at a dicounted price during pre-sale by calling the functions themselves on their website.

In the case of Exchange, the ERC20 standard have its own methods such as transfer, balanceOf. They use the ERC20 standard methods of smart contract to communicate and perform transactions.

If I am wrong please correct me.

Any help/suggestion would be appreciated.
Thanks.

答: Cindercloud has APIs designed specifically for this.</p>