问:
How to make an element spin with js and css transitions without variables
I have a website, and I want an element to spin around 360 degrees once when it is clicked. The only way I have heard of to rotate a div element is the CSS transform property. I have tried some different things, like

```<code>    backward.classList.add("notrans");
    backward.style.transform = "rotateZ(0deg)";
    backward.classList.remove("notrans");
    backward.style.transform = "rotateZ(-360deg)";
</code>```

where the notrans class makes the element have a transition time of 0 seconds, and

```<code>backward.style.transition = "0s";
backward.style.transform = "rotateZ(0deg)";
backward.style.transition = transtime;
backward.style.transform = "rotateZ(360deg)";
</code>```

Here is the source code I am using right now:

var backward = document.getElementById("backward");

var Backward = function() {bgm.currentTime -= 10;
    backward.classList.add("notrans");
    backward.style.transform = "rotateZ(0deg)";
    backward.classList.remove("notrans");
    backward.style.transform = "rotateZ(-360deg)";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>:root {
--color: black;
--hovercolor: white;
--backcolor: white;
--hoverbackcolor: black;
--transtime: 0.5s;
}

#controls {
position: absolute;
left: 0;
top: 45%;
width: 100%;
height: 30%;
font-size: 250%;
border: 1px solid var(--color);
border-radius: 20px;
overflow: hidden;
padding: 0;
background-color: var(--color);
}

.cp {
  height: 25%;
  width: 0;
  overflow: hidden;
  background-color: black;
}

.controls {
  position: absolute;
  top: 0;
  width: 25%;
  height: 100%;
  border: 1px solid var(--color);
  background-color: var(--backcolor);
  color: var(--color);
  line-height: 75%;
  transform: rotateZ(0deg);
  border-radius: 0;
  transition: color var(--transtime), background-color var(--transtime);
  text-align: center;
  padding: 5%;
}

.controls:hover {
  background-color: var(--hoverbackcolor);
  color: var(--hovercolor);
}

#pause {
  left: 25%;
  line-height: 100%;
}

#backward {
  left: 0;
  line-height: 100%;
}

#autoskip {
  right: 0;
}

#forward {
  right: 25%;
  line-height: 100%;
}

#autoskip {
  line-height: 150%;
}

#skipline {
  position: absolute;
  left: 0;
  top: 47.5%;
  background-color: red;
  height: 5%;
  width: 100%;
  transform: rotateZ(-45deg);
  transition: var(--transtime);
}</code>```

<!DOCTYPE html>

↺

| |

↻

⏩

```

As you can see, the Backward button is not spinning when you press it.

Any help?

FYI: There is a lot of extra stuff in the code snippet, like CSS variables, but those are necessary.

答:
Do you want this behaviour?

var spinner = document.querySelector("#spinner");
document.querySelector("button").onclick = function() {
  spinner.style.animationName = "example";
  setTimeout(function() {
    spinner.style.animationName = "";
  }, 4000);
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#spinner {
  width: 100px;
  height: 100px;
  display: flex;
  flex-wrap: wrap;
  background-color: red;
  border-radius: 50%;
  overflow: hidden;
  animation-duration: 4s;
  position: relative;
  justify-content: center;
  align-items: center;
}

#spinner div {
  width: 50%;
  height: 50%;
}

#spinner button {
  position: absolute;
  cursor: pointer;
}

.blue {
  background-color: blue;
}

.green {
  background-color: green;
}

.red {
  background-color: red;
}

.yellow {
  background-color: yellow;
}

@keyframes example {
  0%   {transform: rotate(0deg)}
  100% {transform: rotate(360deg)}
}</code>```

  <button>Spin</button>

```

Body:
I have a website, and I want an element to spin around 360 degrees once when it is clicked. The only way I have heard of to rotate a div element is the CSS transform property. I have tried some different things, like

    backward.classList.add("notrans");
    backward.style.transform = "rotateZ(0deg)";
    backward.classList.remove("notrans");
    backward.style.transform = "rotateZ(-360deg)";

where the notrans class makes the element have a transition time of 0 seconds, and

backward.style.transition = "0s";
backward.style.transform = "rotateZ(0deg)";
backward.style.transition = transtime;
backward.style.transform = "rotateZ(360deg)";

Here is the source code I am using right now:

var backward = document.getElementById("backward");

var Backward = function() {bgm.currentTime -= 10;
    backward.classList.add("notrans");
    backward.style.transform = "rotateZ(0deg)";
    backward.classList.remove("notrans");
    backward.style.transform = "rotateZ(-360deg)";
}

:root {
--color: black;
--hovercolor: white;
--backcolor: white;
--hoverbackcolor: black;
--transtime: 0.5s;
}

#controls {
position: absolute;
left: 0;
top: 45%;
width: 100%;
height: 30%;
font-size: 250%;
border: 1px solid var(--color);
border-radius: 20px;
overflow: hidden;
padding: 0;
background-color: var(--color);
}

.cp {
  height: 25%;
  width: 0;
  overflow: hidden;
  background-color: black;
}

.controls {
  position: absolute;
  top: 0;
  width: 25%;
  height: 100%;
  border: 1px solid var(--color);
  background-color: var(--backcolor);
  color: var(--color);
  line-height: 75%;
  transform: rotateZ(0deg);
  border-radius: 0;
  transition: color var(--transtime), background-color var(--transtime);
  text-align: center;
  padding: 5%;
}

.controls:hover {
  background-color: var(--hoverbackcolor);
  color: var(--hovercolor);
}

#pause {
  left: 25%;
  line-height: 100%;
}

#backward {
  left: 0;
  line-height: 100%;
}

#autoskip {
  right: 0;
}

#forward {
  right: 25%;
  line-height: 100%;
}

#autoskip {
  line-height: 150%;
}

#skipline {
  position: absolute;
  left: 0;
  top: 47.5%;
  background-color: red;
  height: 5%;
  width: 100%;
  transform: rotateZ(-45deg);
  transition: var(--transtime);
}

<!DOCTYPE html>

↺

| |

↻

⏩

As you can see, the Backward button is not spinning when you press it.

Any help?

FYI: There is a lot of extra stuff in the code snippet, like CSS variables, but those are necessary.

Body:
Do you want this behaviour?

var spinner = document.querySelector("#spinner");
document.querySelector("button").onclick = function() {
  spinner.style.animationName = "example";
  setTimeout(function() {
    spinner.style.animationName = "";
  }, 4000);
};

#spinner {
  width: 100px;
  height: 100px;
  display: flex;
  flex-wrap: wrap;
  background-color: red;
  border-radius: 50%;
  overflow: hidden;
  animation-duration: 4s;
  position: relative;
  justify-content: center;
  align-items: center;
}

#spinner div {
  width: 50%;
  height: 50%;
}

#spinner button {
  position: absolute;
  cursor: pointer;
}

.blue {
  background-color: blue;
}

.green {
  background-color: green;
}

.red {
  background-color: red;
}

.yellow {
  background-color: yellow;
}

@keyframes example {
  0%   {transform: rotate(0deg)}
  100% {transform: rotate(360deg)}
}

<div id="spinner">
  <div class="blue"></div>
  <div class="red"></div>
  <div class="green"></div>
  <div class="yellow"></div>
  <button>Spin</button>
</div>


来源: stackexchange

问:
Comparison method violates its general contract! (elements duplicated in collection during sort)
I know there are many topics with same subject, but this case seems to me a bit different and not well-documented in javadocs. Here is the code:

```<code>Random random = new Random(0);

var list = new ArrayList<>();
for (int i = 0; i < 60; i++) {
    list.add(random.nextInt());
}

list.sort((x, y) -> {
    int sum = list.stream().reduce(0, Integer::sum);

    System.out.println(sum);

    return Integer.compare(x + sum, y + sum);
});
</code>```

The result is exception:

```<code>-1303811196
-1303811196
.....
-1303811196
-1303811196
-1303811196
-1364558868
-1569607140
-1836181454
-2014724660
-2023409163
-2094470032
-2128134715
2107317277
2107317277
Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
    at java.base/java.util.TimSort.mergeLo(TimSort.java:781)
    at java.base/java.util.TimSort.mergeAt(TimSort.java:518)
    at java.base/java.util.TimSort.mergeCollapse(TimSort.java:448)
    at java.base/java.util.TimSort.sort(TimSort.java:245)
    at java.base/java.util.Arrays.sort(Arrays.java:1516)
    at java.base/java.util.ArrayList.sort(ArrayList.java:1717)
    at HomeWork6_4.Company.main(Company.java:131)
</code>```

So it seems like, it's not possible to rely on collection during sorting, because its in dirty state. Is that behavior documented somewhere?

答:
Let us debug by logging what the Comparator is doing internally. For that, I am adding a special logging method to track the results of the comparator. Please check the code below

```<code>public static void main(String[] args) {
    Random random = new Random(0);

    var list = new ArrayList<Integer>();

    for (int i = 0; i < 60; i++) {
        list.add(random.nextInt());
    }
    list.sort(logging((x, y) -> {
        int sum = list.stream().reduce(0, Integer::sum);
        return Integer.compare(x + sum, y + sum);
    }));
}

public static Comparator<Integer> logging(Comparator<Integer> c) {
    return (Integer a, Integer b)-> {
        int r = c.compare(a, b);
        System.err.printf("%7d  %7d => %2d%n", a, b, r);
        return r;
    };
}
</code>```

The behaviour of Comparator for two inputs (T a, T b) is following

```<code>(i) returns  less than 0 ,  means a<b
(ii)returns 0 , means a==b
(iii)return greater than 0 , means a>b
</code>```

If any comparator doesn't satisfy these rules, we say the comparator is broken.
Now let's pay close attention to what the comparator is logging

```<code>-723955400  -1155484576 => -1  // broken (a>b but comparator Integer.compare(a+sum,b+sum) returned less than 0)
1033096058  -723955400 =>  1   // broken
1033096058  -1155484576 => -1
1033096058  -723955400 =>  1
-1690734402  1033096058 =>  1. // broken
</code>```

This shows that the specific comparator you used Integer.compare(a+sum, b+sum) has overflown and resulted in the inconsistent result when you apply against the list elements. When such a broken comparator is used sort(c) throws such Exception.

ContentLicense: CC BY-SA 4.0

Body:
I know there are many topics with same subject, but this case seems to me a bit different and not well-documented in javadocs. Here is the code:

Random random = new Random(0);

var list = new ArrayList<>();
for (int i = 0; i < 60; i++) {
    list.add(random.nextInt());
}

list.sort((x, y) -> {
    int sum = list.stream().reduce(0, Integer::sum);

    System.out.println(sum);

    return Integer.compare(x + sum, y + sum);
});

The result is exception:

-1303811196
-1303811196
.....
-1303811196
-1303811196
-1303811196
-1364558868
-1569607140
-1836181454
-2014724660
-2023409163
-2094470032
-2128134715
2107317277
2107317277
Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
    at java.base/java.util.TimSort.mergeLo(TimSort.java:781)
    at java.base/java.util.TimSort.mergeAt(TimSort.java:518)
    at java.base/java.util.TimSort.mergeCollapse(TimSort.java:448)
    at java.base/java.util.TimSort.sort(TimSort.java:245)
    at java.base/java.util.Arrays.sort(Arrays.java:1516)
    at java.base/java.util.ArrayList.sort(ArrayList.java:1717)
    at HomeWork6_4.Company.main(Company.java:131)

So it seems like, it's not possible to rely on collection during sorting, because its in dirty state. Is that behavior documented somewhere?

Body:
Let us debug by logging what the Comparator is doing internally. For that, I am adding a special logging method to track the results of the comparator. Please check the code below

public static void main(String[] args) {
    Random random = new Random(0);

    var list = new ArrayList<Integer>();

    for (int i = 0; i < 60; i++) {
        list.add(random.nextInt());
    }
    list.sort(logging((x, y) -> {
        int sum = list.stream().reduce(0, Integer::sum);
        return Integer.compare(x + sum, y + sum);
    }));
}

public static Comparator<Integer> logging(Comparator<Integer> c) {
    return (Integer a, Integer b)-> {
        int r = c.compare(a, b);
        System.err.printf("%7d  %7d => %2d%n", a, b, r);
        return r;
    };
}

The behaviour of Comparator for two inputs (T a, T b) is following

(i) returns  less than 0 ,  means a<b
(ii)returns 0 , means a==b
(iii)return greater than 0 , means a>b

If any comparator doesn't satisfy these rules, we say the comparator is broken.
Now let's pay close attention to what the comparator is logging

-723955400  -1155484576 => -1  // broken (a>b but comparator Integer.compare(a+sum,b+sum) returned less than 0)
1033096058  -723955400 =>  1   // broken
1033096058  -1155484576 => -1
1033096058  -723955400 =>  1
-1690734402  1033096058 =>  1. // broken

This shows that the specific comparator you used Integer.compare(a+sum, b+sum) has overflown and resulted in the inconsistent result when you apply against the list elements. When such a broken comparator is used sort(c) throws such Exception.


问:
Combining Vectors using a Loop
If I have vectors m1, m2, ... m"n" and I want to create a vector that includes all of the values, how would I go about this?

For example:

```<code>m1 = c(0, 2, 4)
m2 = c(1, 4)
m3 = (3)
</code>```

I want a vector "totalmods" which outputs {0, 2, 4, 1, 4, 3}

My attempt where nummod is "n", the vector with the largest number was:

```<code>for(i in 1:nummod){
  totalmods <- c(paste("m",i, sep = ""))
}
</code>```

Thanks for your help!

答:
One option could be:</p>

```<code>Reduce(c, mget(ls(pattern = "^m\\d+")))

[1] 0 2 4 1 4 3
</code>```

Title: Combining Vectors using a Loop

Body:
If I have vectors m1, m2, ... m"n" and I want to create a vector that includes all of the values, how would I go about this?

For example:

m1 = c(0, 2, 4)
m2 = c(1, 4)
m3 = (3)

I want a vector "totalmods" which outputs {0, 2, 4, 1, 4, 3}

My attempt where nummod is "n", the vector with the largest number was:

for(i in 1:nummod){
  totalmods <- c(paste("m",i, sep = ""))
}

Thanks for your help!

Body:
One option could be:

Reduce(c, mget(ls(pattern = "^m\\d+")))

[1] 0 2 4 1 4 3


问:
Tips for studying Android
I joined a company recently and they have requested me to develop a few applications for Android. I've never seen it before - though I'm familiar with Java, so the programmatic syntax is familiar to me - and I'd like to know if there is a good site/textbook/whatever where I could learn how to program for Android OS - the simpler the better!

In particular, I'm searching for some way to allow me to use Android to do 2 things - to get a GPS location on a regular basis and to get an application connecting with a remote database. These are my priorities at the moment, but this doesn't mean you can't indicate me a knowledge source that doesn't have these on it. I do need to learn to program on this system, and I'll be thankful for whatever you indicate me. But if you happen to know where I could find these 2 items, please don't be shy and let me know.

Thanks in advance for your replies.

答:
I think the first and the best start point to the Android developing, the Android Developers site (Official).
Here is some link for you:
developer.android.com/sdk/installing.html

developer.android.com/resources/tutorials/hello-world.html

developer.android.com/resources/tutorials/views/index.html

developer.android.com/reference/packages.html

developer.android.com/guide/practices/ui_guidelines/index.html

developer.android.com/reference/android/location/GpsSatellite.html

developer.android.com/guide/topics/location/index.html

ContentLicense: CC BY-SA 3.0

Title: Tips for studying Android


问:
Writing out a binary structure to file, unexpected results?
I'm trying to write out a packed data structure to a binary file, however as you can see from od -x below the results are not expected in their ordering.  I'm using gcc on a 64-bit Intel system.  Does anyone know why the ordering is wrong?  It doesn't look like an endianness issue.

```<code>#include <stdio.h>
#include <stdlib.h>

struct B {
     char a;
     int b;
     char c;
     short d;
} __attribute__ ((packed));

int main(int argc, char *argv[])
{
     FILE *fp;
     fp = fopen("temp.bin", "w");

     struct B b = {'a', 0xA5A5, 'b', 0xFF};

     if (fwrite(&b, sizeof(b), 1, fp) != 1)
          printf("Error fwrite\n");

     exit(0);
}
</code>```

ASCII 61 is 'a', so the b.a member.  ASCII 62 is 'b', so the b.c member.  It's odd how 0xA5A5 is spread out over the sequence.

```<code>$ od -x temp.bin
0000000 a561 00a5 6200 00ff
0000010
</code>```

答:
od -x writes out two little-endian bytes. Per the od man page:

```<code>-x     same as -t x2, select hexadecimal 2-byte units
</code>```

So

```<code>0000000 a561 00a5 6200 00ff
</code>```

is, on disk:

```<code>0000000 61a5 a500 0062 ff00
</code>```

Body:
I'm trying to write out a packed data structure to a binary file, however as you can see from od -x below the results are not expected in their ordering.  I'm using gcc on a 64-bit Intel system.  Does anyone know why the ordering is wrong?  It doesn't look like an endianness issue.

#include <stdio.h>
#include <stdlib.h>

struct B {
     char a;
     int b;
     char c;
     short d;
} __attribute__ ((packed));

int main(int argc, char *argv[])
{
     FILE *fp;
     fp = fopen("temp.bin", "w");

     struct B b = {'a', 0xA5A5, 'b', 0xFF};

     if (fwrite(&b, sizeof(b), 1, fp) != 1)
          printf("Error fwrite\n");

     exit(0);
}

ASCII 61 is 'a', so the b.a member.  ASCII 62 is 'b', so the b.c member.  It's odd how 0xA5A5 is spread out over the sequence.

$ od -x temp.bin
0000000 a561 00a5 6200 00ff
0000010

Body:
od -x writes out two little-endian bytes. Per the od man page:

-x     same as -t x2, select hexadecimal 2-byte units

So

0000000 a561 00a5 6200 00ff

is, on disk:

0000000 61a5 a500 0062 ff00


问:
AWS CDK retrieving resources ID [Python]
Newbie question but I am trying to get the Id for my VPC or/and the subnetsID that were created using CDK Python.

For more details , I am trying to create a vpc and then using RAM share private subnets to my org.

I have tried vpcName.vpc_id and I get back a {$Token} and I have tried many other things with no luck.

Please note that by using boto3 and hardcoding the vpc-id I was able to complete the above but it is not really portable!

Thanks all,

Mazza

答:
Below code can help you. But it will only work while deployment using "cdk deploy".</p>

```<code>vpc = ec2.Vpc(self, "TheVPC",
    cidr="10.0.0.0/16"
)

# Iterate the private subnets
selection = vpc.select_subnets(
    subnet_type=ec2.SubnetType.PRIVATE # Can change to PUBLIC or ISOLATED
)

# Read the Subnet
for subnet in selection.subnets:
    pass
</code>```

Body:
Below code can help you. But it will only work while deployment using "cdk deploy".

vpc = ec2.Vpc(self, "TheVPC",
    cidr="10.0.0.0/16"
)

# Iterate the private subnets
selection = vpc.select_subnets(
    subnet_type=ec2.SubnetType.PRIVATE # Can change to PUBLIC or ISOLATED
)

# Read the Subnet
for subnet in selection.subnets:
    pass


问:
Extract data from stdout_lines in Ansible and match same element
I'm trying to match all of same element of my 2 stdout_lines variables in Ansible and write them to file. What should i do?

variableA:

```<code> "stdout_lines": [
            "process1",
            "process2",
            "process3",
            "process4",
            "process5",
            "process6",
            "process7",
            "process8"
        ]
</code>```

variableB:

```<code>"stdout_lines": [
                "processID1",
                "processID2",
                "processID3",
                "processID4",
                "processID5",
                "processID6",
                "processID7",
                "processID8"
            ]
</code>```

I tried this but it's not work.

```<code>- name: save to log
  lineinfile:
      dest: '{{pathlog}}'
      line: 'Process: {{ item.name }}    PID({{item.id}})'
  with_items:
      - { name: "{{variableA.stdout_lines}}", id: "{{variableB.stdout_lines}}" }
</code>```

Expected results :

```<code>Process: process1  PID (processID1)
Process: process2  PID (processID2)
Process: process3  PID (processID3)
Process: process4  PID (processID4)
Process: process5  PID (processID5)
Process: process6  PID (processID6)
Process: process7  PID (processID7)
Process: process8  PID (processID8)
</code>```

Failed results I received:

```<code>Process: [u'process1', u'process2', u'process3', u'process4', u'process5', u'process6', u'process7', u'process8']    PID([u'processID1', u'processID2', u'processID3', u'processID4', u'processID5', u'processID6', u'processID7', u'processID8'])
</code>```

答:
with_indexed_items will do the trick:

```<code>  - debug:
      msg: "Process: {{ VariableA.stdout_lines[item.0] }} PID ({{ item.1 }})"
    with_indexed_items: "{{ VariableB.stdout_lines }}"
</code>```

Body:
I'm trying to match all of same element of my 2 stdout_lines variables in Ansible and write them to file. What should i do?

variableA:

 "stdout_lines": [
            "process1",
            "process2",
            "process3",
            "process4",
            "process5",
            "process6",
            "process7",
            "process8"
        ]

variableB:

"stdout_lines": [
                "processID1",
                "processID2",
                "processID3",
                "processID4",
                "processID5",
                "processID6",
                "processID7",
                "processID8"
            ]

I tried this but it's not work.

- name: save to log
  lineinfile:
      dest: '{{pathlog}}'
      line: 'Process: {{ item.name }}    PID({{item.id}})'
  with_items:
      - { name: "{{variableA.stdout_lines}}", id: "{{variableB.stdout_lines}}" }

Expected results :

Process: process1  PID (processID1)
Process: process2  PID (processID2)
Process: process3  PID (processID3)
Process: process4  PID (processID4)
Process: process5  PID (processID5)
Process: process6  PID (processID6)
Process: process7  PID (processID7)
Process: process8  PID (processID8)

Failed results I received:

Process: [u'process1', u'process2', u'process3', u'process4', u'process5', u'process6', u'process7', u'process8']    PID([u'processID1', u'processID2', u'processID3', u'processID4', u'processID5', u'processID6', u'processID7', u'processID8'])

Body:
with_indexed_items will do the trick:

  - debug:
      msg: "Process: {{ VariableA.stdout_lines[item.0] }} PID ({{ item.1 }})"
    with_indexed_items: "{{ VariableB.stdout_lines }}"


问:
Create DataFrame from multiple lists?
I have two lists

```<code>list1=['a','b','c']

list2=[1,2]
</code>```

I want my dataframe output to look like:

col1     col2
a        1
a        2
b        1
b        2
c        1
c        2
```

How can this be done?

答:
If you don't want to explicitly import itertools, pd.MultiIndex has a from_product method that you might piggyback on:

```<code>list1 = ['a','b','c']
list2 = [1, 2]
pd.DataFrame(pd.MultiIndex.from_product((list1, list2)).to_list(), columns=['col1', 'col2'])
  col1  col2
0    a     1
1    a     2
2    b     1
3    b     2
4    c     1
5    c     2
</code>```

Title: Create DataFrame from multiple lists?

Body:
I have two lists

list1=['a','b','c']

list2=[1,2]

I want my dataframe output to look like:

col1     col2
a        1
a        2
b        1
b        2
c        1
c        2

How can this be done?

Body:
If you don't want to explicitly import itertools, pd.MultiIndex has a from_product method that you might piggyback on:

list1 = ['a','b','c']
list2 = [1, 2]
pd.DataFrame(pd.MultiIndex.from_product((list1, list2)).to_list(), columns=['col1', 'col2'])
  col1  col2
0    a     1
1    a     2
2    b     1
3    b     2
4    c     1
5    c     2


答:
Try this

- name: save to log
  lineinfile:
    create: true
    dest: '{{ pathlog }}'
    line: 'Process: {{ item.0 }}    PID({{ item.1 }})'
  loop: "{{ variableA.stdout_lines|zip(variableB.stdout_lines)|list }}"
```

<p>should give</p>

<pre class="lang-sh prettyprint-override"><code>shell> cat /tmp/test.txt
Process: process1    PID(processID1)
Process: process2    PID(processID2)
Process: process3    PID(processID3)
Process: process4    PID(processID4)
Process: process5    PID(processID5)
Process: process6    PID(processID6)
Process: process7    PID(processID7)
Process: process8    PID(processID8)
</code>```

Title: Extract data from stdout_lines in Ansible and match same element

Body:
Try this

- name: save to log
  lineinfile:
    create: true
    dest: '{{ pathlog }}'
    line: 'Process: {{ item.0 }}    PID({{ item.1 }})'
  loop: "{{ variableA.stdout_lines|zip(variableB.stdout_lines)|list }}"

should give

shell> cat /tmp/test.txt
Process: process1    PID(processID1)
Process: process2    PID(processID2)
Process: process3    PID(processID3)
Process: process4    PID(processID4)
Process: process5    PID(processID5)
Process: process6    PID(processID6)
Process: process7    PID(processID7)
Process: process8    PID(processID8)


问:
Reactor Flux flatMap operator throughput/concurrency control and achieve backpressure
I am using Flux to build my reactive pipeline. In the pipeline, I need to call 3 different external system REST APIs, which are very strict with their Rate of access.
I will be throttled exponentially if i breach the rate-per-sec threshold. Each system will have their own thresholds.

I am using Spring WebClient to make the REST API calls; among 3 APIs, 2 of them are GET and 1 is POST.

In my reactor pipeline, the WebClient are wrapped within the flatMap to perform the API calls, like the below code:

```<code>WebClient getApiCall1 = WebClient.builder().build().get("api-system-1").retrieve().bodyToMono(String.class) //actual return DTO is different from string
WebClient getApiCall2 = WebClient.builder().build().get("api-system-2").retrieve().bodyToMono(String.class) //actual return DTO is different from string
WebClient getApiCall3 = WebClient.builder().build().get("api-system-3").retrieve().bodyToMono(String.class) //actual return DTO is different from string

    Flux.generator(generator) // Generator pushes the elements from source 1 at a time

    // make call to 1st API Service
    .flatMap(data -> getApiCall1)
    .map(api1Response -> api1ResponseModified)

    // make call to 2nd API Service
    .flatMap(api1ResponseModified -> getApiCall2)
    .map(api2Response -> api2ResponseModified)

// make call to 3rd API Service
.flatMap(api2ResponseModified -> getApiCall3)
.map(api3Response -> api3ResponseModified)

// rest of the pipeline operators

//end
.subscriber();
</code>```

The problem is, if I dont set the concurrency value to the flatMap, then I the pipeline execution breaching the threshold within few seconds of service startup.
If I set the value of concurrency to 1, 2, 5, 10, then the throughput is becoming very low.

The Question is, Without setting any value to the concurrency How could I achieve the Backpressure which should honour the rate limits of the external system?

答:
Given you have a "rate per second" requirement, I would explicitly window the flux and limit each window to the chosen time period. This will give you the maximum throughput without being throttled.

I would use a helper function similar to:

```<code>public static <T> Flux<T> limitIntervalRate(Flux<T> flux, int ratePerInterval, Duration interval) {
    return flux
            .window(ratePerInterval)
            .zipWith(Flux.interval(Duration.ZERO, interval))
            .flatMap(Tuple2::getT1);
}
</code>```

which allows you to do:

```<code>sourceFlux
        .transform(f -> limitIntervalRate(f, 2, Duration.ofSeconds(1))) //Limit to a rate of 2 per second
</code>```

You can then map this as necessary onto your WebClient calls while respecting the limit in place for each API:

```<code>sourceFlux
        //...assume API 1 has a limit of 10 calls per second
        .transform(f -> limitIntervalRate(f, 10, Duration.ofSeconds(1)))
        .flatMap(data -> getApiCall1)
        .map(api1Response -> api1ResponseModified)

        //...assume API 2 has a limit of 20 calls per second
        .transform(f -> limitIntervalRate(f, 20, Duration.ofSeconds(1)))
        .flatMap(api1ResponseModified -> getApiCall2)
        .map(api2Response -> api2ResponseModified)
</code>```

...and so on.

Body:
I am using Flux to build my reactive pipeline. In the pipeline, I need to call 3 different external system REST APIs, which are very strict with their Rate of access.
I will be throttled exponentially if i breach the rate-per-sec threshold. Each system will have their own thresholds.

I am using Spring WebClient to make the REST API calls; among 3 APIs, 2 of them are GET and 1 is POST.

In my reactor pipeline, the WebClient are wrapped within the flatMap to perform the API calls, like the below code:

WebClient getApiCall1 = WebClient.builder().build().get("api-system-1").retrieve().bodyToMono(String.class) //actual return DTO is different from string
WebClient getApiCall2 = WebClient.builder().build().get("api-system-2").retrieve().bodyToMono(String.class) //actual return DTO is different from string
WebClient getApiCall3 = WebClient.builder().build().get("api-system-3").retrieve().bodyToMono(String.class) //actual return DTO is different from string

    Flux.generator(generator) // Generator pushes the elements from source 1 at a time

    // make call to 1st API Service
    .flatMap(data -> getApiCall1)
    .map(api1Response -> api1ResponseModified)

    // make call to 2nd API Service
    .flatMap(api1ResponseModified -> getApiCall2)
    .map(api2Response -> api2ResponseModified)

// make call to 3rd API Service
.flatMap(api2ResponseModified -> getApiCall3)
.map(api3Response -> api3ResponseModified)

// rest of the pipeline operators

//end
.subscriber();

The problem is, if I dont set the concurrency value to the flatMap, then I the pipeline execution breaching the threshold within few seconds of service startup.
If I set the value of concurrency to 1, 2, 5, 10, then the throughput is becoming very low.

The Question is, Without setting any value to the concurrency How could I achieve the Backpressure which should honour the rate limits of the external system?

Body:
Given you have a "rate per second" requirement, I would explicitly window the flux and limit each window to the chosen time period. This will give you the maximum throughput without being throttled.

I would use a helper function similar to:

public static <T> Flux<T> limitIntervalRate(Flux<T> flux, int ratePerInterval, Duration interval) {
    return flux
            .window(ratePerInterval)
            .zipWith(Flux.interval(Duration.ZERO, interval))
            .flatMap(Tuple2::getT1);
}

which allows you to do:

sourceFlux
        .transform(f -> limitIntervalRate(f, 2, Duration.ofSeconds(1))) //Limit to a rate of 2 per second

You can then map this as necessary onto your WebClient calls while respecting the limit in place for each API:

sourceFlux
        //...assume API 1 has a limit of 10 calls per second
        .transform(f -> limitIntervalRate(f, 10, Duration.ofSeconds(1)))
        .flatMap(data -> getApiCall1)
        .map(api1Response -> api1ResponseModified)

        //...assume API 2 has a limit of 20 calls per second
        .transform(f -> limitIntervalRate(f, 20, Duration.ofSeconds(1)))
        .flatMap(api1ResponseModified -> getApiCall2)
        .map(api2Response -> api2ResponseModified)

...and so on.


问:
script is unable to find the CDN
I'm confused about how to use typejs CDN:

I put the CDN in the head of the HTML document and the scripts at the very end of the body but I get this error: (I think the script is unable to find the CDN!) Why?! Am I used the incorrect order to use the CDN or the script?

Uncaught TypeError: Typed.new is not a function at
  HTMLDocument.

Here is the code :

I have the CDN at the very beginning of the head tag:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/typed.js/1.1.7/typed.min.js"></script>
</code>```

And the script at the very end of the body:

```<code><script src="typing.js"></script>
</code>```

<!DOCTYPE html>

    <link href="./TheSaaS — Responsive Bootstrap SaaS, Startup & WebApp Template_files/page.min.css" rel="stylesheet">
    <link href="./TheSaaS — Responsive Bootstrap SaaS, Startup & WebApp Template_files/style.css" rel="stylesheet">

    <link rel="apple-touch-icon" href="http://thetheme.io/thesaas/assets/img/apple-touch-icon.png">
    <link rel="icon" href="http://thetheme.io/thesaas/assets/img/favicon.png">

    <meta property="og:title" content="TheSaaS">
    <meta property="og:description" content="A responsive, professional, and multipurpose SaaS, Software, Startup and WebApp landing template powered by Bootstrap 4.">
    <meta property="og:image" content="http://thetheme.io/thesaas/assets/img/og-img.jpg">
    <meta property="og:url" content="http://thetheme.io/thesaas/">
    <meta name="twitter:card" content="summary_large_image">

        Buy Now

      <canvas class="constellation" data-radius="0" width="1536" height="763"></canvas>

              Built For |

              TheSaaS is an elegant, modern and fully customizable SaaS and WebApp template powered by Bootstrap 4

            Buy Now — $39
            Explore Demos

Fun Fact

This is the most popular technology template on Themeforest. See Proof.

<button class="pswp__button pswp__button--close" title="Close (Esc)"></button> <button class="pswp__button pswp__button--share" title="Share"></button> <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button> <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

<button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"></button> <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"></button>

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

<p>And here is the script:</p>

```document.addEventListener('DOMContentLoaded', function(){
    Typed.new('.type', {
    strings: ["neighbor", "family", "team", "community"],
    stringsElement: null,
    // typing speed
    typeSpeed: 60,
    // time before typing starts
    startDelay: 600,
    // backspacing speed
    backSpeed: 20,
    // time before backspacing
    backDelay: 500,
    // loop
    loop: true,
    // false = infinite
    loopCount: 5,
    // show cursor
    showCursor: false,
    // character for cursor
    cursorChar: "|",
    // attribute to type (null == text)
    attr: null,
    // either html or text
    contentType: 'html',
    });
});
```

答:
While I've never heard of this library, let alone used it, it is immediately apparent from the docs that you're using it wrong: it should be new Typed(...) (using Typed as a constructor), not Typed.new(...) as you are. The Typed function object clearly has no new property , which explains the error you're getting.

If the problem had been that the library hadn't loaded, as you seem to think, then the error would have been different. Then Typed would be undefined, and the reported error would have been about trying to access a property of undefined. The actual error means that Typed exists but the new property isn't a function (such errors often mean the "not a function" value is undefined). The distinction may seem subtle but such reasoning can often help narrow down the source of an error.

Title: script is unable to find the CDN

Body:
I'm confused about how to use typejs CDN:

I put the CDN in the head of the HTML document and the scripts at the very end of the body but I get this error: (I think the script is unable to find the CDN!) Why?! Am I used the incorrect order to use the CDN or the script?

Uncaught TypeError: Typed.new is not a function at
  HTMLDocument.

Here is the code :

I have the CDN at the very beginning of the head tag:

And the script at the very end of the body:

<!DOCTYPE html>

    <link href="./TheSaaS — Responsive Bootstrap SaaS, Startup & WebApp Template_files/page.min.css" rel="stylesheet">
    <link href="./TheSaaS — Responsive Bootstrap SaaS, Startup & WebApp Template_files/style.css" rel="stylesheet">

    <link rel="apple-touch-icon" href="http://thetheme.io/thesaas/assets/img/apple-touch-icon.png">
    <link rel="icon" href="http://thetheme.io/thesaas/assets/img/favicon.png">

    <meta property="og:title" content="TheSaaS">
    <meta property="og:description" content="A responsive, professional, and multipurpose SaaS, Software, Startup and WebApp landing template powered by Bootstrap 4.">
    <meta property="og:image" content="http://thetheme.io/thesaas/assets/img/og-img.jpg">
    <meta property="og:url" content="http://thetheme.io/thesaas/">
    <meta name="twitter:card" content="summary_large_image">

        Buy Now

      <canvas class="constellation" data-radius="0" width="1536" height="763"></canvas>

              Built For |

              TheSaaS is an elegant, modern and fully customizable SaaS and WebApp template powered by Bootstrap 4

            Buy Now — $39
            Explore Demos

Fun Fact

This is the most popular technology template on Themeforest. See Proof.

<button class="pswp__button pswp__button--close" title="Close (Esc)"></button> <button class="pswp__button pswp__button--share" title="Share"></button> <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button> <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

<button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"></button> <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"></button>

And here is the script:

document.addEventListener('DOMContentLoaded', function(){
    Typed.new('.type', {
    strings: ["neighbor", "family", "team", "community"],
    stringsElement: null,
    // typing speed
    typeSpeed: 60,
    // time before typing starts
    startDelay: 600,
    // backspacing speed
    backSpeed: 20,
    // time before backspacing
    backDelay: 500,
    // loop
    loop: true,
    // false = infinite
    loopCount: 5,
    // show cursor
    showCursor: false,
    // character for cursor
    cursorChar: "|",
    // attribute to type (null == text)
    attr: null,
    // either html or text
    contentType: 'html',
    });
});


问:
How can I get the last row without order by and assign a value to a variable?
I have a query that is within a View so I can not use order by . I have a column called Course that column is an Int Column and it can have many repeating values . There is also a column called status that status column is also an Int and it will have unique values . I am trying to create a query where we can get the last row of a particular Course and see if the Status is 2 if yes then add 1 to @MyValue if not then add 0 to the variable .I have an ID column which is the primary key, without order by I am having a tough time figuring this one out .

MyValue is a smallint and we simply assign the value

CourseNumber is a Int and a table can have many (Course) @CourseNumber with the same number

There will only be 1 combination of CourseNumber and Status . We can have many CourseNumbers with the same number etc 120 however each one will have a different Status

What I want to do with the query below is get the last record of @CourseNumber we have an ID column and check if the status of the last record of @CourseNumber is equal to 2 . If it's equal to 2 then assign the value 1 to @MyValue and if it is not equal to 2 then assign the value 0 .

```<code>    SELECT @MyValue =(SELECT count(*) FROM MyTasks as MT WHERE MT.Course = @CourseNumber And MT.status=2)
</code>```

Sample: ID Course Status

1   23  4

2   23  5

3   23  2

4   23  1

Assuming that was the database table the Course is [@CourseNumber] is 23 . We would want to get the last row of the Course number which is [4] and we would want the status which is [1] since the status is not 2 for that last row we would just return a 0 and we would only return a 1 if the last row of the course number has a status of 1 .  This is a sql function inside of a view . I try to leave out some of things that might not be necessary since it is a large View and function .

答:
You want to self join to the table to determine the maximum ID value to find the record you want.  You say add 1 to @MyValue and later you say to set @MyValue = 1.  This will add 1 to @MyValue.  If you want @MyValue = 1, change the case statement removing the @MyValue parameter.</p>

```<code>DECLARE @MyValue INT = 0
    , @CourseNumber INT = 23

SELECT @MyValue = CASE WHEN t0.Status = 2 THEN @MyValue + 1 ELSE @MyValue END
FROM MyTasks t0
JOIN
(
    SELECT Couse
        , MAX(ID) MAXID
    FROM MyTasks
    WHERE Course = @CourseNumber
) t1 ON t0.Course = t1.Course AND t0.ID = t1.MAXID
</code>```

Body:
I have a query that is within a View so I can not use order by . I have a column called Course that column is an Int Column and it can have many repeating values . There is also a column called status that status column is also an Int and it will have unique values . I am trying to create a query where we can get the last row of a particular Course and see if the Status is 2 if yes then add 1 to @MyValue if not then add 0 to the variable .I have an ID column which is the primary key, without order by I am having a tough time figuring this one out .

MyValue is a smallint and we simply assign the value

CourseNumber is a Int and a table can have many (Course) @CourseNumber with the same number

There will only be 1 combination of CourseNumber and Status . We can have many CourseNumbers with the same number etc 120 however each one will have a different Status

What I want to do with the query below is get the last record of @CourseNumber we have an ID column and check if the status of the last record of @CourseNumber is equal to 2 . If it's equal to 2 then assign the value 1 to @MyValue and if it is not equal to 2 then assign the value 0 .

    SELECT @MyValue =(SELECT count(*) FROM MyTasks as MT WHERE MT.Course = @CourseNumber And MT.status=2)

Sample: ID Course Status

1   23  4

2   23  5

3   23  2

4   23  1

Assuming that was the database table the Course is [@CourseNumber] is 23 . We would want to get the last row of the Course number which is [4] and we would want the status which is [1] since the status is not 2 for that last row we would just return a 0 and we would only return a 1 if the last row of the course number has a status of 1 .  This is a sql function inside of a view . I try to leave out some of things that might not be necessary since it is a large View and function .

Body:
You want to self join to the table to determine the maximum ID value to find the record you want.  You say add 1 to @MyValue and later you say to set @MyValue = 1.  This will add 1 to @MyValue.  If you want @MyValue = 1, change the case statement removing the @MyValue parameter.

DECLARE @MyValue INT = 0
    , @CourseNumber INT = 23

SELECT @MyValue = CASE WHEN t0.Status = 2 THEN @MyValue + 1 ELSE @MyValue END
FROM MyTasks t0
JOIN
(
    SELECT Couse
        , MAX(ID) MAXID
    FROM MyTasks
    WHERE Course = @CourseNumber
) t1 ON t0.Course = t1.Course AND t0.ID = t1.MAXID


问:
Creating gender dropdown in Phoenix / Elixir results in "assign @all_genders not available in eex template."
I am wanting to Add Gender to a client that comes from a database (and other look up tables)

I have defined the Client as so:

```<code>defmodule Dropdown.Clients.Client do
  use Ecto.Schema
  import Ecto.Changeset
  alias Dropdown.Clients.Admin

  schema "clients" do
    field :email, :string
    field :name, :string

    belongs_to :genders, Admin
</code>```

And Gender

```<code>defmodule Dropdown.Clients.Admin do
  use Ecto.Schema
  import Ecto.Changeset

  schema "gender" do
    field :gender, :string
    has_many :clients, Client
  end
</code>```

Controller add and create functions are like so:

```<code>  def new(conn, _params) do
    changeset = Clients.change_client(%Client{})
    gender_query = from g in Admin, select: {g.gender, g.id}
    all_genders = Dropdown.Repo.all(gender_query)

    render(conn, "new.html", all_genders: all_genders, changeset: changeset)
  end

  def create(conn, %{"client" => client_params}) do

    case Clients.create_client(client_params) do
      {:ok, client} ->
        conn
        |> put_flash(:info, "Client created successfully.")
        |> redirect(to: Routes.client_path(conn, :show, client))

      {:error, %Ecto.Changeset{} = changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
  end
</code>```

The corresponding Context is:

```<code>    Client
    |> Repo.get!(id)
    |> Repo.preload(:genders)
  end

  def create_client(attrs \\ %{}) do
    %Client{}
    |> IO.inspect()
    |> Client.changeset(attrs)
    |> Repo.insert()
  end
</code>```

In the Add form:

```<code>  <%= select(f, :gender_id, @all_genders) %>
  <%= error_tag f, :gender_id %>
</code>```

I have the form show the Gender dropdown, however, when I submit I get an error:

assign @all_genders not available in eex template.

The IO.inspect shows:

```<code>  [debug] Processing with DropdownWeb.ClientController.create/2
  Parameters: %{"_csrf_token" => "ECAXCnJJEw1ZGRtyFmoZDDF_GjQ3CHFzqvxrAypk0JW5N3kkE1UytpBJ", "client" => %{"email" => "george@example.com", "gender_id" => "1", "name" => "George Company"}}
  Pipelines: [:browser]
</code>```

Any suggestions on fixing this would be much appreciated.

答:
The error was a typo in the changeset. Here is the full Client context

```<code>defmodule Dropdown.Clients.Client do
  use Ecto.Schema
  import Ecto.Changeset
  alias Dropdown.Clients.Admin

  schema "clients" do
    field :email, :string
    field :name, :string

    belongs_to :genders, Admin

    timestamps()
  end

  @doc false
  def changeset(client, attrs) do
    client
    |> cast(attrs, [:name, :email, :genders_id])
    |> validate_required([:name, :email, :genders_id])
  end
end
</code>```

And for completeness the Admin as well

```<code>defmodule Dropdown.Clients.Admin do
  use Ecto.Schema
  import Ecto.Changeset

  schema "gender" do
    field :gender, :string

    timestamps()
  end

  @doc false
  def changeset(admin, attrs) do
    admin
    |> cast(attrs, [:gender])
    |> validate_required([:gender])
  end
end
</code>```

Body:
I am wanting to Add Gender to a client that comes from a database (and other look up tables)

I have defined the Client as so:

defmodule Dropdown.Clients.Client do
  use Ecto.Schema
  import Ecto.Changeset
  alias Dropdown.Clients.Admin

  schema "clients" do
    field :email, :string
    field :name, :string

    belongs_to :genders, Admin

And Gender

defmodule Dropdown.Clients.Admin do
  use Ecto.Schema
  import Ecto.Changeset

  schema "gender" do
    field :gender, :string
    has_many :clients, Client
  end

Controller add and create functions are like so:

  def new(conn, _params) do
    changeset = Clients.change_client(%Client{})
    gender_query = from g in Admin, select: {g.gender, g.id}
    all_genders = Dropdown.Repo.all(gender_query)

    render(conn, "new.html", all_genders: all_genders, changeset: changeset)
  end

  def create(conn, %{"client" => client_params}) do

    case Clients.create_client(client_params) do
      {:ok, client} ->
        conn
        |> put_flash(:info, "Client created successfully.")
        |> redirect(to: Routes.client_path(conn, :show, client))

      {:error, %Ecto.Changeset{} = changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
  end

The corresponding Context is:

    Client
    |> Repo.get!(id)
    |> Repo.preload(:genders)
  end

  def create_client(attrs \\ %{}) do
    %Client{}
    |> IO.inspect()
    |> Client.changeset(attrs)
    |> Repo.insert()
  end

In the Add form:

  <%= select(f, :gender_id, @all_genders) %>
  <%= error_tag f, :gender_id %>

I have the form show the Gender dropdown, however, when I submit I get an error:

assign @all_genders not available in eex template.

The IO.inspect shows:

  [debug] Processing with DropdownWeb.ClientController.create/2
  Parameters: %{"_csrf_token" => "ECAXCnJJEw1ZGRtyFmoZDDF_GjQ3CHFzqvxrAypk0JW5N3kkE1UytpBJ", "client" => %{"email" => "george@example.com", "gender_id" => "1", "name" => "George Company"}}
  Pipelines: [:browser]

Any suggestions on fixing this would be much appreciated.

Body:
The error was a typo in the changeset. Here is the full Client context

defmodule Dropdown.Clients.Client do
  use Ecto.Schema
  import Ecto.Changeset
  alias Dropdown.Clients.Admin

  schema "clients" do
    field :email, :string
    field :name, :string

    belongs_to :genders, Admin

    timestamps()
  end

  @doc false
  def changeset(client, attrs) do
    client
    |> cast(attrs, [:name, :email, :genders_id])
    |> validate_required([:name, :email, :genders_id])
  end
end

And for completeness the Admin as well

defmodule Dropdown.Clients.Admin do
  use Ecto.Schema
  import Ecto.Changeset

  schema "gender" do
    field :gender, :string

    timestamps()
  end

  @doc false
  def changeset(admin, attrs) do
    admin
    |> cast(attrs, [:gender])
    |> validate_required([:gender])
  end
end


问:
Can't understand what UIScenes are
I can't find a clear definition of what UIScenes are

Are they just for handling the background calls? Are they like a ViewController? Do we use them often or nah?

答:
The biggest thing is that scenes set up multiple window support. It is also useful for SwiftUI.

The SceneDelegate controls what is displayed on the screen "to manage life-cycle events in one instance of your app's user interface.", while the AppDelegate controls your entire app life-cycle.

Read the App and Environment Article and scenes from Apple instead of UIScene documentation.

Scene:

Scene, Manage multiple instances of your app’s UI simultaneously, and
  direct resources to the appropriate instance of your UI.

We had only one scene back then before iOS 13, So the only thing we need to run ViewControllers simultaneously was multiple Windows on top of each other. But now, each application can have multiple instances running at the same time! Each scene has its own state and it might be in the foreground while others are in the background or are suspended, while Window was completely dependent on the application itself.

Imagine we have 2 view controllers (consider there are no scenes) running on the left and right side of the device and then we need to show a banner. Using the old window method will show the banner on both of them! And if you need to pick one, you may end up finding the correct controller and presenting the banner on it.

So apple introduced Scene, a container for each separate instance of the app. So you can manage each one separately and each of them acts as a separate app. It has its own windows and controllers. But all of them are managed by a single object, UIApplication.shared and it has a delegate to handle general events (usually from outside of the app) and entire application life cycle.

Title: Can't understand what UIScenes are


问:
Why can my fields not be bound in a T-SQL join?
So I have the following SQL statement:

```<code>SELECT
    CASE
    WHEN table1.Recommendation = 1 THEN 'Condition1'
    WHEN table1.Recommendation = 2 THEN 'Condition2'
    WHEN table1.Recommendation = 3 THEN 'Condition3'
    ELSE ' '
    END
    AS Recommendation,
    table2.Notes,
    table3.ItemDescription AS Item,
    table4.Description AS Concern
FROM Job
RIGHT JOIN table2 ON Job.JobId = table2.JobId
LEFT JOIN table1 ON table2.table2Id = table1.table2Id
INNER JOIN table3 ON table2.table3Id = table3.table3Id
LEFT JOIN table1 customName ON table4.table4Id = customName.table4Id
WHERE Job.JobId = @JobId AND table1.Condition = 3
</code>```

This is for a telerik report, and the JobId variable will be input with an actual job id. table2 holds the JobId, as well as the table1 id. I am trying to get the table4.Description, but everytime I get the errors:

```<code>The multi-part identifier table4.table4Id could not be bound.
The multi-part identifier table4.Description could not be bound.
</code>```

At this point I don't know what to try from here. Any help would be appreciated! I will gladly add any more information as possible to try to figure out this issue

答: You haven't used any alias table4; because of that, the compiler gives the error.

Body:
So I have the following SQL statement:

SELECT
    CASE
    WHEN table1.Recommendation = 1 THEN 'Condition1'
    WHEN table1.Recommendation = 2 THEN 'Condition2'
    WHEN table1.Recommendation = 3 THEN 'Condition3'
    ELSE ' '
    END
    AS Recommendation,
    table2.Notes,
    table3.ItemDescription AS Item,
    table4.Description AS Concern
FROM Job
RIGHT JOIN table2 ON Job.JobId = table2.JobId
LEFT JOIN table1 ON table2.table2Id = table1.table2Id
INNER JOIN table3 ON table2.table3Id = table3.table3Id
LEFT JOIN table1 customName ON table4.table4Id = customName.table4Id
WHERE Job.JobId = @JobId AND table1.Condition = 3

This is for a telerik report, and the JobId variable will be input with an actual job id. table2 holds the JobId, as well as the table1 id. I am trying to get the table4.Description, but everytime I get the errors:

The multi-part identifier table4.table4Id could not be bound.
The multi-part identifier table4.Description could not be bound.

At this point I don't know what to try from here. Any help would be appreciated! I will gladly add any more information as possible to try to figure out this issue


问:
Not able to deploy war in JBoss AS 7 through Eclipse luna.
I am using Eclipse luna with Jboss tools 4.2.0.Beta2 and JbossAS 7.1.1.

I am deployed my application from eclipse and started Jboss.
Then i'm getting a problem that deployment starts completes the deployment and again re deploy the application.
Its happening for more than 2 times and undeploys.

I am not able to deploy my application.

Please share the resolution for the above problem.

答:
On your standalone.xml edit deployment-scanner with enabled="true" and auto-deploy-exploded="true"

```<code><deployment-scanner path="deployments" relative-to="jboss.server.base.dir" scan-enabled="true" scan-interval="5000" auto-deploy-exploded="true" deployment-timeout="1200" runtime-failure-causes-rollback="${jboss.deployment.scanner.rollback.on.failure:false}"/>
</code>```

Body:
On your standalone.xml edit deployment-scanner with enabled="true" and auto-deploy-exploded="true"

<deployment-scanner path="deployments" relative-to="jboss.server.base.dir" scan-enabled="true" scan-interval="5000" auto-deploy-exploded="true" deployment-timeout="1200" runtime-failure-causes-rollback="${jboss.deployment.scanner.rollback.on.failure:false}"/>


问:
Impossible to display ads in a ListViews.separated Flutter
I'm using firebase_admob in flutter and I want to display ads in a ListView.separated.

```<code>     void initState(){
    FirebaseAdMob.instance.initialize(appId: 'ca-app-pub-XXXXXXXXXXXXXXXXXXXXXXX');
  }

  static const MobileAdTargetingInfo targetingInfo = MobileAdTargetingInfo(
    keywords: <String>['flutterio', 'beautiful apps'],
    contentUrl: 'https://flutter.io',
    childDirected: false,
    testDevices: <String>[], // Android emulators are considered test devices
  );

  BannerAd myBanner = BannerAd(
    // Replace the testAdUnitId with an ad unit id from the AdMob dash.
    // https://developers.google.com/admob/android/test-ads
    // https://developers.google.com/admob/ios/test-ads
    adUnitId: BannerAd.testAdUnitId,
    size: AdSize.smartBanner,
    targetingInfo: targetingInfo,
    listener: (MobileAdEvent event) {
      print("BannerAd event is $event");
    },
  );
</code>```

And where I want to display the ads :

```<code>return ListView.separated(
        padding: EdgeInsets.zero,
        itemCount: data.articles.length,
        separatorBuilder: (context, index) {
          if (index % 5 == 0) { // Display `AdmobBanner` every 5 'separators'.
           return myBanner;
          }
          return Divider();
        },
</code>```

But I get this issue : error: The return type 'BannerAd' isn't a 'Widget', as defined by anonymous closure. (return_of_invalid_type_from_closure at  lib\src\ui\home\home_screen.dart:445).

What is the best solution ?

Thanks

答: Try using this unofficial admob plugin for flutter. </p>

Body:
I'm using firebase_admob in flutter and I want to display ads in a ListView.separated.

     void initState(){
    FirebaseAdMob.instance.initialize(appId: 'ca-app-pub-XXXXXXXXXXXXXXXXXXXXXXX');
  }

  static const MobileAdTargetingInfo targetingInfo = MobileAdTargetingInfo(
    keywords: <String>['flutterio', 'beautiful apps'],
    contentUrl: 'https://flutter.io',
    childDirected: false,
    testDevices: <String>[], // Android emulators are considered test devices
  );

  BannerAd myBanner = BannerAd(
    // Replace the testAdUnitId with an ad unit id from the AdMob dash.
    // https://developers.google.com/admob/android/test-ads
    // https://developers.google.com/admob/ios/test-ads
    adUnitId: BannerAd.testAdUnitId,
    size: AdSize.smartBanner,
    targetingInfo: targetingInfo,
    listener: (MobileAdEvent event) {
      print("BannerAd event is $event");
    },
  );

And where I want to display the ads :

return ListView.separated(
        padding: EdgeInsets.zero,
        itemCount: data.articles.length,
        separatorBuilder: (context, index) {
          if (index % 5 == 0) { // Display `AdmobBanner` every 5 'separators'.
           return myBanner;
          }
          return Divider();
        },

But I get this issue : error: The return type 'BannerAd' isn't a 'Widget', as defined by anonymous closure. (return_of_invalid_type_from_closure at  lib\src\ui\home\home_screen.dart:445).

What is the best solution ?

Thanks


问:
Is it possible to "copy" a function into another process and execute it in a thread without using LoadLibrary?
I'm trying to write and execute a single function function:

```<code>int thread(void) {
    WCHAR boxTitle = L"testing...";
    WCHAR message = L"hello?";
    int (*MessageBoxW)(HWND, LPCWSTR, LPCWSTR, UINT);
    MessageBoxW = (LPVOID)0x7FFCA28E2750; // address of MessageBoxW function in user32.dll on my machine
    MessageBoxW(NULL, message, boxTitle, MB_OK);
    return 0;
}
</code>```

In another process using VirtualAllocEx, WriteProcessMemory, and CreateRemoteThread:

```<code>int main(void) {

    HANDLE hProc;
    LPVOID baseAddr;
    int funcSize;

    funcSize = (int)main - (int)thread;
    hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, 10724); // notepad.exe PID on my machine
    baseAddr = VirtualAllocEx(hProc, NULL, funcSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

    WriteProcessMemory(hProc, baseAddr, &thread, funcSize, NULL);
    CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE)baseAddr, NULL, 0, NULL);
    CloseHandle(hProc);

    return 0;
}
</code>```

The problem is that the message box doesn't properly display the LPCWSTR arguments that I provide to the MessageBoxW function through my function pointer. The message box appears, but the box title and message body are blank.

Here is a link to an image displaying this issue:

I have a feeling that this issue involves something with character encoding and the way that I have copied my function into the virtual address space of the remote process, but I really can't figure out what's wrong.

答:
With this approach, no assembly is necessary, but you have to be careful to add all necessary functions, strings, etc. to the data structure.

(I didn't add any error checks and cleanup.)

```<code>#include <windows.h>

#ifndef __MINGW32__
#define CODE_SEG(seg) __declspec(code_seg(seg))
#else
#define CODE_SEG(seg) __attribute__((section(seg)))
#endif

typedef int WINAPI func_MessageBoxW(HWND, LPCWSTR, LPCWSTR, UINT);

struct data
{
  func_MessageBoxW *fMessageBoxW;
  wchar_t boxTitle[11];
  wchar_t message[7];
};

static CODE_SEG(".text$1") DWORD WINAPI inj(LPVOID para)
{
  struct data *data = para;
  data->fMessageBoxW(NULL, data->message, data->boxTitle, MB_OK);
  return 0;
}

CODE_SEG(".text$2") int main(int argc, char **argv)
{
  HANDLE hProc;
  LPVOID baseAddr;
  size_t funcSize, fullSize;
  int pid;
  struct data data;
  HMODULE user32;

  if (argc < 2)
    return 1;

  user32 = LoadLibrary("user32.dll");
  data.fMessageBoxW = (func_MessageBoxW*)GetProcAddress(user32, "MessageBoxW");
  wcscpy(data.boxTitle, L"testing...");
  wcscpy(data.message, L"hello?");

  pid = atoi(argv[1]);
  funcSize = (size_t)&main - (size_t)&inj;
  fullSize = funcSize + sizeof(data);
  hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
  baseAddr = VirtualAllocEx(hProc, NULL, fullSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

  WriteProcessMemory(hProc, baseAddr, &data, sizeof(data), NULL);
  WriteProcessMemory(hProc, (void*)((size_t)baseAddr + sizeof(data)), &inj, funcSize, NULL);
  CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE)((size_t)baseAddr + sizeof(data)), baseAddr, 0, NULL);
  CloseHandle(hProc);

  return 0;
}
</code>```

Body:
I'm trying to write and execute a single function function:

int thread(void) {
    WCHAR boxTitle = L"testing...";
    WCHAR message = L"hello?";
    int (*MessageBoxW)(HWND, LPCWSTR, LPCWSTR, UINT);
    MessageBoxW = (LPVOID)0x7FFCA28E2750; // address of MessageBoxW function in user32.dll on my machine
    MessageBoxW(NULL, message, boxTitle, MB_OK);
    return 0;
}

In another process using VirtualAllocEx, WriteProcessMemory, and CreateRemoteThread:

int main(void) {

    HANDLE hProc;
    LPVOID baseAddr;
    int funcSize;

    funcSize = (int)main - (int)thread;
    hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, 10724); // notepad.exe PID on my machine
    baseAddr = VirtualAllocEx(hProc, NULL, funcSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

    WriteProcessMemory(hProc, baseAddr, &thread, funcSize, NULL);
    CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE)baseAddr, NULL, 0, NULL);
    CloseHandle(hProc);

    return 0;
}

The problem is that the message box doesn't properly display the LPCWSTR arguments that I provide to the MessageBoxW function through my function pointer. The message box appears, but the box title and message body are blank.

Here is a link to an image displaying this issue:

I have a feeling that this issue involves something with character encoding and the way that I have copied my function into the virtual address space of the remote process, but I really can't figure out what's wrong.

Body:
With this approach, no assembly is necessary, but you have to be careful to add all necessary functions, strings, etc. to the data structure.

(I didn't add any error checks and cleanup.)

#include <windows.h>

#ifndef __MINGW32__
#define CODE_SEG(seg) __declspec(code_seg(seg))
#else
#define CODE_SEG(seg) __attribute__((section(seg)))
#endif

typedef int WINAPI func_MessageBoxW(HWND, LPCWSTR, LPCWSTR, UINT);

struct data
{
  func_MessageBoxW *fMessageBoxW;
  wchar_t boxTitle[11];
  wchar_t message[7];
};

static CODE_SEG(".text$1") DWORD WINAPI inj(LPVOID para)
{
  struct data *data = para;
  data->fMessageBoxW(NULL, data->message, data->boxTitle, MB_OK);
  return 0;
}

CODE_SEG(".text$2") int main(int argc, char **argv)
{
  HANDLE hProc;
  LPVOID baseAddr;
  size_t funcSize, fullSize;
  int pid;
  struct data data;
  HMODULE user32;

  if (argc < 2)
    return 1;

  user32 = LoadLibrary("user32.dll");
  data.fMessageBoxW = (func_MessageBoxW*)GetProcAddress(user32, "MessageBoxW");
  wcscpy(data.boxTitle, L"testing...");
  wcscpy(data.message, L"hello?");

  pid = atoi(argv[1]);
  funcSize = (size_t)&main - (size_t)&inj;
  fullSize = funcSize + sizeof(data);
  hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
  baseAddr = VirtualAllocEx(hProc, NULL, fullSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

  WriteProcessMemory(hProc, baseAddr, &data, sizeof(data), NULL);
  WriteProcessMemory(hProc, (void*)((size_t)baseAddr + sizeof(data)), &inj, funcSize, NULL);
  CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE)((size_t)baseAddr + sizeof(data)), baseAddr, 0, NULL);
  CloseHandle(hProc);

  return 0;
}


问:
fixed snackBar in bottom of screen
i am new to dart
So i am frustrated by the snackBar is appears just in the footer of the body.
and above of persistentFooterButtons and bottomNavigationBar
plz someone help me to fixed the snackbar on the end of screen .

this my code:

```<code>    Widget build(BuildContext context) {
       return Scaffold(

  key: scaffoldKey,

  backgroundColor: Colors.white,

  appBar: AppBar(),

  body:  SafeArea(

          Material(

             color: Color(0xFF43bdd2),

             borderRadius: BorderRadius.circular(25.0),

             child: MaterialButton(

                       onPressed:(){ _showSnack; },

                        child: Text('إرسال'),

                                  ),

                         ),  ),

  persistentFooterButtons: <Widget>[

               Text('hello everyone'),

           ],

  bottomNavigationBar: BottomAppBar(

    child: Container(

      padding: EdgeInsets.only(bottom: 3),

          child: Text("©Copyright flutter 2020",style:   TextStyle(color:Colors.black,fontWeight:     FontWeight.bold),textAlign: TextAlign.center,),

    ),

  ),);}

         _showSnack(){scaffoldKey.currentState.showSnackBar(SnackBar(content:   Text('hi, here i am a snackBar'),)) ;}
</code>```

答:
You can use a Flushbar to show a similar widget at the bottom.

```<code>FlatButton(
  child: Text('Show Snackbar'),
  onPressed: () {
    Flushbar(
      flushbarPosition: FlushbarPosition.BOTTOM, //Make sure at the bottom
    )
      ..title = 'hi, here i am a snackBar'
      ..show(context);
  },
),
</code>```

Installing the package (https://pub.dartlang.org/packages/flushbar)

Add this in pubspec.ymal

```<code>dependencies:
  flushbar: ^1.10.4
</code>```

Then import the flushber in the file you are on

```<code>import 'package:flushbar/flushbar.dart';
</code>```

Title: fixed snackBar in bottom of screen

Body:
i am new to dart
So i am frustrated by the snackBar is appears just in the footer of the body.
and above of persistentFooterButtons and bottomNavigationBar
plz someone help me to fixed the snackbar on the end of screen .

this my code:

    Widget build(BuildContext context) {
       return Scaffold(

  key: scaffoldKey,

  backgroundColor: Colors.white,

  appBar: AppBar(),

  body:  SafeArea(

          Material(

             color: Color(0xFF43bdd2),

             borderRadius: BorderRadius.circular(25.0),

             child: MaterialButton(

                       onPressed:(){ _showSnack; },

                        child: Text('إرسال'),

                                  ),

                         ),  ),

  persistentFooterButtons: <Widget>[

               Text('hello everyone'),

           ],

  bottomNavigationBar: BottomAppBar(

    child: Container(

      padding: EdgeInsets.only(bottom: 3),

          child: Text("©Copyright flutter 2020",style:   TextStyle(color:Colors.black,fontWeight:     FontWeight.bold),textAlign: TextAlign.center,),

    ),

  ),);}

         _showSnack(){scaffoldKey.currentState.showSnackBar(SnackBar(content:   Text('hi, here i am a snackBar'),)) ;}

Body:
You can use a Flushbar to show a similar widget at the bottom.

FlatButton(
  child: Text('Show Snackbar'),
  onPressed: () {
    Flushbar(
      flushbarPosition: FlushbarPosition.BOTTOM, //Make sure at the bottom
    )
      ..title = 'hi, here i am a snackBar'
      ..show(context);
  },
),

Installing the package (https://pub.dartlang.org/packages/flushbar)

Add this in pubspec.ymal

dependencies:
  flushbar: ^1.10.4

Then import the flushber in the file you are on

import 'package:flushbar/flushbar.dart';


问:
Find element by TEXT in SeleniumBase
I'm using SeleniumBase and I need to click on an element identified like this below:

```<code><span class="text">
                Contato PF e PJ
            </span>
</code>```

I need to catch by the text inside (Contato PF e PJ). How can I do this with SeleniumBase?

```<code>from seleniumbase import BaseCase
</code>```

self.click(...

答: find_element_by_xpath('//span[contains(text(), "Contato PF e PJ")]')

Title: Find element by TEXT in SeleniumBase

Body:
I'm using SeleniumBase and I need to click on an element identified like this below:

                Contato PF e PJ

I need to catch by the text inside (Contato PF e PJ). How can I do this with SeleniumBase?

from seleniumbase import BaseCase

self.click(...


问:
Return Original List using Substring in LINQ
I have the following data

```<code>ItemId | ItemName | ItemBy | ItemCreatedOn
  1    | A100     |  User1 |  2016-10-04
  2    | A200     |  User1 |  2016-10-04
  3    | A300     |  User1 |  2016-10-04
  4    | A400     |  User1 |  2016-10-04
  5    | A600     |  User1 |  2016-10-04
  6    | D100     |  User1 |  2016-10-04
  7    | D900     |  User1 |  2016-10-04
  8    | D200     |  User1 |  2016-10-04
  9    | D300     |  User1 |  2016-10-04
</code>```

This is what I want to return:

```<code> ItemId | ItemName | ItemBy | ItemCreatedOn
  5     | A600   |  User1 |  2016-10-04
</code>```

My approach

Get all the list of items starting with A

```<code>var allItems = db.Items.Where(x.ItemName[0] == itemName[0]).ToList();
</code>```

use substring

```<code>var items = allItems.Select(x => x.Substring(1));
</code>```

The above returns a list of string, but I want to return a list of all the items without A so that I can use Max() on ItemName to get the record I need

How can I return the list of objects and then use Max correctly?

答:
To find the max valued item in the ItemName column whose ItemName start with the letter A I would try this</p>

```<code>// Filter with ItemName that starts with A then build an anonymous type
// containing only the ItemId and the value parsed from the substring
// Finally order in descending value on the anonymous column "value"
var search = allItems.Where(x => x.ItemName.StartsWith("A"))
    .Select(x => new {id=x.ItemId, value = Int32.Parse(x.ItemName.Substring(1))})
    .OrderByDescending(k => k.value).ToList();

// The first element in search (if any) contains the id to search for
// in the original list.
if(search.Count > 0)
    var yourItem = allItems.FirstOrDefault(i => i.ItemId == search[0].id);
</code>```

Body:
I have the following data

ItemId | ItemName | ItemBy | ItemCreatedOn
  1    | A100     |  User1 |  2016-10-04
  2    | A200     |  User1 |  2016-10-04
  3    | A300     |  User1 |  2016-10-04
  4    | A400     |  User1 |  2016-10-04
  5    | A600     |  User1 |  2016-10-04
  6    | D100     |  User1 |  2016-10-04
  7    | D900     |  User1 |  2016-10-04
  8    | D200     |  User1 |  2016-10-04
  9    | D300     |  User1 |  2016-10-04

This is what I want to return:

 ItemId | ItemName | ItemBy | ItemCreatedOn
  5     | A600   |  User1 |  2016-10-04

My approach

Get all the list of items starting with A

var allItems = db.Items.Where(x.ItemName[0] == itemName[0]).ToList();

use substring

var items = allItems.Select(x => x.Substring(1));

The above returns a list of string, but I want to return a list of all the items without A so that I can use Max() on ItemName to get the record I need

How can I return the list of objects and then use Max correctly?

Body:
To find the max valued item in the ItemName column whose ItemName start with the letter A I would try this

// Filter with ItemName that starts with A then build an anonymous type
// containing only the ItemId and the value parsed from the substring
// Finally order in descending value on the anonymous column "value"
var search = allItems.Where(x => x.ItemName.StartsWith("A"))
    .Select(x => new {id=x.ItemId, value = Int32.Parse(x.ItemName.Substring(1))})
    .OrderByDescending(k => k.value).ToList();

// The first element in search (if any) contains the id to search for
// in the original list.
if(search.Count > 0)
    var yourItem = allItems.FirstOrDefault(i => i.ItemId == search[0].id);


问:
Flutter DropdownButtonFormField.onChanged doesn't update UI
I have a screen with a DropdownButtonFormField:

```<code>var _list = ['foo', 'bar'];
String _value;

build() {
  ...
  DropdownButtonFormField(
    items: _items(ctx),
    onChanged: (item) => _onChanged(ctx, item),
    value: _value,
  )
  ...
}

List<DropdownMenuItem<String>> _items(ctx) {
  final specialNone = DropdownMenuItem(
    child: Text('NONE'),
    value: '#none',
  );
  final specialNew = DropdownMenuItem(
    child: Text('CREATE NEW'),
    value: '#new',
  );

  return [
    specialNone,
    specialNew,
    ..._list.map((o) => DropdownMenuItem(child: Text(o), value: o)).toList()
  ];
}

void _onChanged(ctx, String value) async {
  if (value == '#new') {
    final result = await Navigator.pushNamed(ctx, '/vendor');

    if (result != null)
      setState(() {
        _list.add(result);
        _value = result;
      });
  } else if (value == '#none')
    setState(() {
      _value = null;
    });
  else
    setState(() {
      _value = value;
    });
}
</code>```

There's a special item "CREATE NEW" in the items list. When clicked, a new item will be added to the list, and I want it to be selected instead of selecting "CREATE NEW".

NOTE: If you change DropdownButtonFormField to DropdownButton, it will work.

答:
What's going on?

Using a DropdownButtonFormField vs a DropdownButton wraps the DropdownButton with a FormField that maintains the current state of the form field.

What does this mean?

When you call setState on your class, your widget rebuilds like it's supposed to, but the FormFields state is not updated so it doesn't look like anything happened. However, the list of items that's nested in the DropdownButton (inside the DropdownButtonFormField) is being updated appropriately.

Possible Solution

I would suggest trying to use the selectedItemBuilder method of the DropdownButtonFormField and see if that allows the FormState to recognize the updated items. Alternatively, use a DropdownButton and manually wrap it in a FormField so you can update the items like you want (if you even need the FormField).

Body:
I have a screen with a DropdownButtonFormField:

var _list = ['foo', 'bar'];
String _value;

build() {
  ...
  DropdownButtonFormField(
    items: _items(ctx),
    onChanged: (item) => _onChanged(ctx, item),
    value: _value,
  )
  ...
}

List<DropdownMenuItem<String>> _items(ctx) {
  final specialNone = DropdownMenuItem(
    child: Text('NONE'),
    value: '#none',
  );
  final specialNew = DropdownMenuItem(
    child: Text('CREATE NEW'),
    value: '#new',
  );

  return [
    specialNone,
    specialNew,
    ..._list.map((o) => DropdownMenuItem(child: Text(o), value: o)).toList()
  ];
}

void _onChanged(ctx, String value) async {
  if (value == '#new') {
    final result = await Navigator.pushNamed(ctx, '/vendor');

    if (result != null)
      setState(() {
        _list.add(result);
        _value = result;
      });
  } else if (value == '#none')
    setState(() {
      _value = null;
    });
  else
    setState(() {
      _value = value;
    });
}

There's a special item "CREATE NEW" in the items list. When clicked, a new item will be added to the list, and I want it to be selected instead of selecting "CREATE NEW".

NOTE: If you change DropdownButtonFormField to DropdownButton, it will work.


问:
What does the HTTP header Pragma: Public mean?
What does the HTTP header Pragma: Public mean?</p>

答: Useful when you come across this error: http://trac.edgewall.org/ticket/1020. IE 8 & less seems to like to cache things when they are on a SSL server. Putting 'Pragma:public' helps with: "Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found. Please try again later"</p>

ContentLicense: CC BY-SA 2.5


问:
Rosalind: REVP failing the given case
I wrote a solution to this challenge . It successfully handles the example case given, but not the actual case.

Challenge:
A DNA string is a reverse palindrome if it is equal to its reverse complement. For instance, GCATGC is a reverse palindrome because its reverse complement is GCATGC. For example:

5'...GCATGC...3'

3'...CGTACG...5'

Given:

A DNA string of length at most 1 kbp in FASTA format.

Return:

The position and length of every reverse palindrome in the string
  having length between 4 and 12. You may return these pairs in any
  order.

Sample Dataset

>Rosalind_24 TCAATGCATGCGGGTCTATATGCAT

Sample Output

4 6

5 4

6 6

7 4

17 4

18 4

20 6

21 4

For the sample, it works. However it failed on the actual sample.

Actual Dataset:

>Rosalind_7901 ATATAGTCGGCTGTCCAGGCAATCGCGAGATGGGGAACGACATCTTGGTACTTTACGGAT GCCAAGACTTAATATCTGGCCCGGATATGACCGCGAGCACCCCCTACTCGTCTGTCGGTT TCGGCCGGCATGACCTGTCCTCTTGATAATAGATATAAGTTGCCAACCGCACTATTTCAA GATCAGATGCCCCAAGGCACAAGGCACAGAAGAATCAGGTACTGAGCAAACAGCGCCCAT TTGTCAGCGCAACTCCGAGCGACAGGCACAAGTGGTAGTAACATCTGTAGTCTACGAGCG CGGGACCGATGTAAAAAGCAACGAGAGACGGGGCCGTCGATAGAAAAGCAATGGAGTCCA TATGGGCACGCTGAGCGTGCCTGTACTAATTTCTATGGGCTACTGGCACTAGGGGCTTAA GCCCTCGGTTACCGCGCTTTATGAATATAGTTTTCGTGCCAGGAGTGTCTTGTTTCGAGG AAGCGTGAGCTACACTTAGCACGTCCGGGCTTATTGGAAATTTGTTCAGTCTGTATGCTC CGCAATATCATGTCGGCGCTCATTCAATGTTGCGTGTAATTTAGACCTCTACTACAGCTG GGGTTGGAGCGGTCGGTAGTAAGACGTATGATTACGGTTTACATCCCGCCGGCGGACACG GAACGTGATTTTCAGCATTGTCCCATCGTAGGGATTGGGGCCCTAGTAGGTGTGGGTAGC ACGTTACATGAAGCTATCCAATGGCGTATATACTCCATCCCATCGGACTAGAAGATTTGA GGGACCCAGTCATAACTGGTGCAAAATTACGTTACAAAAGCCGAGGATACAGTATA

Actual Output:

1 4
2 4
23 6
24 4
48 4
70 4
73 4
79 4
82 4
86 4
93 4
124 6
125 4
126 6
127 4
131 4
155 4
156 4
184 4
222 4
236 4
251 4
337 4
342 4
389 4
394 4
415 4
423 4
440 4
441 4
452 4
453 4
482 4
496 4
509 4
513 4
526 6
527 4
554 4
558 4
565 4
587 4
604 6
605 4
634 4
656 10
657 8
658 6
659 4
674 4
709 6
710 4
714 4
733 4
739 4
744 4
758 8
759 4
759 6
760 4
761 4
780 4
813 4
818 4
822 4
846 4

Code:

```<code>from string import maketrans
table=maketrans('ATCG','TAGC')

protein=open('rosalind_revp.txt','r').read()[14::].strip()

for i in range(len(protein)):
    for ii in range(2,7):
        if protein[i:i+ii]==protein[i+2*ii-1:i+ii-1:-1].translate(table):
            print str(i+1),str(2*ii)
</code>```

(When testing sample, the 4th line is

protein=open('rosalind_revp.txt','r').read()[12::].strip()

I even manually matched a bunch of the position-length pairs, and sad to find that they all worked perfectly. I still don't know why the result wasn't accepted.
Could anyone let me know where I was wrong?

答:
This is my github link and it has the solution hope this works
    def reverse(l):
            t=""
            for i in range(len(l)):
                if(l[i]=='A'):
                    t=t+'T'
                elif(l[i]=='T'):
                    t=t+'A'
                elif(l[i]=='C'):
                    t=t+'G'
                elif(l[i]=='G'):
                    t=t+'C'
            return t
        def rev(d):
            return d[len(d)::-1]
        k=input()
        p=input()
        for i in range(len(p)):
            for j in range(4,14):
                if (p[i:i+j]==rev(reverse(p[i:i+j]))and i+j<=len(p)):
                    print(i+1, end=" ")
                    print(j)

https://github.com/jssssv007/stackexcahnge

Title: Rosalind: REVP failing the given case

Body:
I wrote a solution to this challenge . It successfully handles the example case given, but not the actual case.

Challenge:
A DNA string is a reverse palindrome if it is equal to its reverse complement. For instance, GCATGC is a reverse palindrome because its reverse complement is GCATGC. For example:

5'...GCATGC...3'

3'...CGTACG...5'

Given:

A DNA string of length at most 1 kbp in FASTA format.

Return:

The position and length of every reverse palindrome in the string
  having length between 4 and 12. You may return these pairs in any
  order.

Sample Dataset

>Rosalind_24 TCAATGCATGCGGGTCTATATGCAT

Sample Output

4 6

5 4

6 6

7 4

17 4

18 4

20 6

21 4

For the sample, it works. However it failed on the actual sample.

Actual Dataset:

>Rosalind_7901 ATATAGTCGGCTGTCCAGGCAATCGCGAGATGGGGAACGACATCTTGGTACTTTACGGAT GCCAAGACTTAATATCTGGCCCGGATATGACCGCGAGCACCCCCTACTCGTCTGTCGGTT TCGGCCGGCATGACCTGTCCTCTTGATAATAGATATAAGTTGCCAACCGCACTATTTCAA GATCAGATGCCCCAAGGCACAAGGCACAGAAGAATCAGGTACTGAGCAAACAGCGCCCAT TTGTCAGCGCAACTCCGAGCGACAGGCACAAGTGGTAGTAACATCTGTAGTCTACGAGCG CGGGACCGATGTAAAAAGCAACGAGAGACGGGGCCGTCGATAGAAAAGCAATGGAGTCCA TATGGGCACGCTGAGCGTGCCTGTACTAATTTCTATGGGCTACTGGCACTAGGGGCTTAA GCCCTCGGTTACCGCGCTTTATGAATATAGTTTTCGTGCCAGGAGTGTCTTGTTTCGAGG AAGCGTGAGCTACACTTAGCACGTCCGGGCTTATTGGAAATTTGTTCAGTCTGTATGCTC CGCAATATCATGTCGGCGCTCATTCAATGTTGCGTGTAATTTAGACCTCTACTACAGCTG GGGTTGGAGCGGTCGGTAGTAAGACGTATGATTACGGTTTACATCCCGCCGGCGGACACG GAACGTGATTTTCAGCATTGTCCCATCGTAGGGATTGGGGCCCTAGTAGGTGTGGGTAGC ACGTTACATGAAGCTATCCAATGGCGTATATACTCCATCCCATCGGACTAGAAGATTTGA GGGACCCAGTCATAACTGGTGCAAAATTACGTTACAAAAGCCGAGGATACAGTATA

Actual Output:

1 4
2 4
23 6
24 4
48 4
70 4
73 4
79 4
82 4
86 4
93 4
124 6
125 4
126 6
127 4
131 4
155 4
156 4
184 4
222 4
236 4
251 4
337 4
342 4
389 4
394 4
415 4
423 4
440 4
441 4
452 4
453 4
482 4
496 4
509 4
513 4
526 6
527 4
554 4
558 4
565 4
587 4
604 6
605 4
634 4
656 10
657 8
658 6
659 4
674 4
709 6
710 4
714 4
733 4
739 4
744 4
758 8
759 4
759 6
760 4
761 4
780 4
813 4
818 4
822 4
846 4

Code:

from string import maketrans
table=maketrans('ATCG','TAGC')

protein=open('rosalind_revp.txt','r').read()[14::].strip()

for i in range(len(protein)):
    for ii in range(2,7):
        if protein[i:i+ii]==protein[i+2*ii-1:i+ii-1:-1].translate(table):
            print str(i+1),str(2*ii)

(When testing sample, the 4th line is

protein=open('rosalind_revp.txt','r').read()[12::].strip()

I even manually matched a bunch of the position-length pairs, and sad to find that they all worked perfectly. I still don't know why the result wasn't accepted.
Could anyone let me know where I was wrong?


问:
Nginx reverse proxy to backend gives an error ERR_CONNECTION_REFUSED
I have an application running on a server at port 6001(frontend, built by react.js) and port 6002(backend, built by node.js) in EC2 instance.

When I send a request through ubuntu terminal in the instance by curl -X GET http://127.0.0.1:6002/api/works, It works fine, I get a proper data.

Now I go to a browser with the domain (http://example.com). However, I only get the front end getting called. When I send a request on a browser to the backend server, It gives me an error GET http://127.0.0.1:6002/api/works net::ERR_CONNECTION_REFUSED (the domain goes through ELB)

Here's my nginx config.

```<code>server {
        listen 80;
        listen [::]:80;

        server_name example.com;

        root /home/www/my-project/;
        index index.html;

        location / {
                proxy_pass http://127.0.0.1:6001/;
        }

        location /api/ {
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $host;
                proxy_redirect off;
                proxy_pass http://127.0.0.1:6002/;
                proxy_set_header X-Real-IP $remote_addr;
        }
}
</code>```

my case is similar to this, he/she says

```<code>My entry point via the aws dns takes me to the React app 127.0.0.1:4100 that is the port 80 nginx is listening to. The react app is the one that makes the backend calls and it is coded to make the backend api calls on 127.0.0.1:1323/api. The client error you saw was because it is displaying what the react app is trying to call in the server, but nginx is not redirecting that call to the app that is running at that port. Does that make sense?
</code>```

the selected answer didn't work on me.

Also, According to the comment, the problem is solved by sending a request by http://AWS_IP/ on the react app. but I'm not sure If it's a good solution for me since there's no point to use ELB then? If I understand the concept of ELB right? I think the requests need to be done via ELB?

Please help, this is driving me crazy.

答:
From your question, I understood the following things,

Your Domain is pointing to Amazon ELB

And there is a VM behind this ELB, and it has Nginx and 2 applications in it.

Nginx is listening on port 80 and Backend application is listening on port
6002 and frontend is listening on port 6001

YOUR FRONTEND APPLICATION IS CALLING THE BACKEND FROM YOUR LOCAL BROWSER USING
http://127.0.0.1:6002/api/works

Here is the problem,

You can curl 127.0.0.1 from the same instance where the application is running(listening to port 6001) because you are hitting the localhost of that instance, And it is different when your web application running on your local browser because your react application(all javascript application) executes in your local machine and for backend call, it is hitting the localhost(in your case) and returning CONNECTION REFUSED.

So the solution is you've to change the backend URL so that it should look something like http://yourdomain/api/works

In Addition to this, I've a couple of suggestions on your configuration.

You don't need a separate web server for your frontend since you can use the same Nginx.

Make sure that your ELB target port is 80 or the same port that NGINX is listening to.

And close the ports 6001 and 6002 (if it is publically accessible)

Body:
I have an application running on a server at port 6001(frontend, built by react.js) and port 6002(backend, built by node.js) in EC2 instance.

When I send a request through ubuntu terminal in the instance by curl -X GET http://127.0.0.1:6002/api/works, It works fine, I get a proper data.

Now I go to a browser with the domain (http://example.com). However, I only get the front end getting called. When I send a request on a browser to the backend server, It gives me an error GET http://127.0.0.1:6002/api/works net::ERR_CONNECTION_REFUSED (the domain goes through ELB)

Here's my nginx config.

server {
        listen 80;
        listen [::]:80;

        server_name example.com;

        root /home/www/my-project/;
        index index.html;

        location / {
                proxy_pass http://127.0.0.1:6001/;
        }

        location /api/ {
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $host;
                proxy_redirect off;
                proxy_pass http://127.0.0.1:6002/;
                proxy_set_header X-Real-IP $remote_addr;
        }
}

my case is similar to this, he/she says

My entry point via the aws dns takes me to the React app 127.0.0.1:4100 that is the port 80 nginx is listening to. The react app is the one that makes the backend calls and it is coded to make the backend api calls on 127.0.0.1:1323/api. The client error you saw was because it is displaying what the react app is trying to call in the server, but nginx is not redirecting that call to the app that is running at that port. Does that make sense?

the selected answer didn't work on me.

Also, According to the comment, the problem is solved by sending a request by http://AWS_IP/ on the react app. but I'm not sure If it's a good solution for me since there's no point to use ELB then? If I understand the concept of ELB right? I think the requests need to be done via ELB?

Please help, this is driving me crazy.