问:
Nginx internal dns resolve issue
I have nginx container in AWS that does reverse proxy for my website e.g. https://example.com. I have backend services that automatically register in local DNS - aws.local (this is done by AWS ECS Auto-Discovery).
The problem I have is that nginx is only resolving name to IP during start, so when service container is rebooted and gets new IP, nginx still tries old IP and I have "502 Bad Gateway" error.

Here is a code that I am running:

```<code>worker_processes 1;
events { worker_connections 1024; }
http {
    sendfile on;
    include    /etc/nginx/mime.types;
    log_format  graylog2_json  '{ "timestamp": "$time_iso8601", '
                       '"remote_addr": "$remote_addr", '
                       '"body_bytes_sent": $body_bytes_sent, '
                       '"request_time": $request_time, '
                       '"response_status": $status, '
                       '"request": "$request", '
                       '"request_method": "$request_method", '
                       '"host": "$host",'
                       '"upstream_cache_status": "$upstream_cache_status",'
                       '"upstream_addr": "$upstream_addr",'
                       '"http_x_forwarded_for": "$http_x_forwarded_for",'
                       '"http_referrer": "$http_referer", '
                       '"http_user_agent": "$http_user_agent" }';

    upstream service1 {
        server service1.aws.local:8070;
    }

    upstream service2 {
        server service2.aws.local:8080;
    }

    resolver 10.0.0.2 valid=10s;

    server {
        listen 443 http2 ssl;
        server_name example.com;
        location /main {
            proxy_pass         http://service1;
        }

        location /auth {
            proxy_pass         http://service2;
        }
</code>```

I find advices to change nginx config to resolve names per request, but then I see my browser tries to open "service2.aws.local:8070" and fails since its AWS local DNS name. I should see https://example.com/auth" on my browser.

```<code>server {

        set $main service1.aws.local:2000;
        set $auth service2.aws.local:8070;

        location /main {
            proxy_http_version 1.1;
            proxy_pass http://$main;
        }
        location /auth {
            proxy_http_version 1.1;
            proxy_pass http://$auth;
        }
</code>```

Can you help me fixing it?
Thanks !!!

答:
TL;DR

```<code>resolver 169.254.169.253;
set $upstream "service1.aws.local";
proxy_pass http://$upstream:8070;
</code>```

Just like with ECS, I experienced the same issue when using Docker Compose.

According to six8's comment on GitHub

nginx only resolves hostnames on startup. You can use variables with
proxy_pass to get it to use the resolver for runtime lookups.

See:

https://forum.nginx.org/read.php?2,215830,215832#msg-215832

https://www.ruby-forum.com/topic/4407628

It's quite annoying.

One of the links above provides an example

```<code>resolver 127.0.0.1;
set $backend "foo.example.com";
proxy_pass http://$backend;
</code>```

The resolver part is necessary. And we can't refer to the defined upstreams here.

According to Ivan Frolov's answer on StackExchange, the resolver's address should be set to 169.254.169.253

Title: Nginx internal dns resolve issue

Body:
I have nginx container in AWS that does reverse proxy for my website e.g. https://example.com. I have backend services that automatically register in local DNS - aws.local (this is done by AWS ECS Auto-Discovery).
The problem I have is that nginx is only resolving name to IP during start, so when service container is rebooted and gets new IP, nginx still tries old IP and I have "502 Bad Gateway" error.

Here is a code that I am running:

worker_processes 1;
events { worker_connections 1024; }
http {
    sendfile on;
    include    /etc/nginx/mime.types;
    log_format  graylog2_json  '{ "timestamp": "$time_iso8601", '
                       '"remote_addr": "$remote_addr", '
                       '"body_bytes_sent": $body_bytes_sent, '
                       '"request_time": $request_time, '
                       '"response_status": $status, '
                       '"request": "$request", '
                       '"request_method": "$request_method", '
                       '"host": "$host",'
                       '"upstream_cache_status": "$upstream_cache_status",'
                       '"upstream_addr": "$upstream_addr",'
                       '"http_x_forwarded_for": "$http_x_forwarded_for",'
                       '"http_referrer": "$http_referer", '
                       '"http_user_agent": "$http_user_agent" }';

    upstream service1 {
        server service1.aws.local:8070;
    }

    upstream service2 {
        server service2.aws.local:8080;
    }

    resolver 10.0.0.2 valid=10s;

    server {
        listen 443 http2 ssl;
        server_name example.com;
        location /main {
            proxy_pass         http://service1;
        }

        location /auth {
            proxy_pass         http://service2;
        }

I find advices to change nginx config to resolve names per request, but then I see my browser tries to open "service2.aws.local:8070" and fails since its AWS local DNS name. I should see https://example.com/auth" on my browser.

server {

        set $main service1.aws.local:2000;
        set $auth service2.aws.local:8070;

        location /main {
            proxy_http_version 1.1;
            proxy_pass http://$main;
        }
        location /auth {
            proxy_http_version 1.1;
            proxy_pass http://$auth;
        }

Can you help me fixing it?
Thanks !!!

Body:
TL;DR

resolver 169.254.169.253;
set $upstream "service1.aws.local";
proxy_pass http://$upstream:8070;

Just like with ECS, I experienced the same issue when using Docker Compose.

According to six8's comment on GitHub

nginx only resolves hostnames on startup. You can use variables with
proxy_pass to get it to use the resolver for runtime lookups.

See:

https://forum.nginx.org/read.php?2,215830,215832#msg-215832

https://www.ruby-forum.com/topic/4407628

It's quite annoying.

One of the links above provides an example

resolver 127.0.0.1;
set $backend "foo.example.com";
proxy_pass http://$backend;

The resolver part is necessary. And we can't refer to the defined upstreams here.

According to Ivan Frolov's answer on StackExchange, the resolver's address should be set to 169.254.169.253


来源: stackexchange

问:
Why does using void keyword before synchronized throws an error in Java, but the reverse works fine?
```<code>import java.util.*;

public class Deadlock extends Thread{

    private String name;

    public static void main(String[] args) {

    }

    public class MyObject{
        public void synchronized foo(String name) { //throws error saying 'Syntax error on token "void", volatile expected'

        }
    }
}
</code>```

But if, public void synchronized is changed to
public synchronized void, everything is fine.

Why is that?

答: What are you returning? Are you returning synchronized, or are you returning void? Since synchronized isn't something you can return, it has to be void. You see, the return type must always come immediately before the function name.</p>

ContentLicense: CC BY-SA 4.0

Body:
import java.util.*;

public class Deadlock extends Thread{

    private String name;

    public static void main(String[] args) {

    }

    public class MyObject{
        public void synchronized foo(String name) { //throws error saying 'Syntax error on token "void", volatile expected'

        }
    }
}

But if, public void synchronized is changed to
public synchronized void, everything is fine.

Why is that?


问:
Got an error while testing redux-saga with delay functions by using Redux Saga Test Plan library
I'm trying to test my redux-saga functions by using Redux Saga Test Plan library and I'm stuck due to delay functions in my saga.

If I remove the line, yield delay(1000) all tests pass without any error.

saga.js

```<code>export function* addWorkoutSaga({ payload }) {
    try {
        yield put(beginAjaxCall());

        yield delay(1000);
        yield call(WorkoutService.add, payload);

        yield call(toast.success, "Item added successfully.");
        yield put(closeModal(Modal.AddWorkout));
        yield put(addWorkout.success());
        yield call(fetchWorkoutsSaga);
    }
    catch (error) {
        console.log(error)
        yield put(addWorkout.failure({ errorMessage: error.statusText }));
        yield call(toast.error, "Error occured.  Please try again.");
    }
}
</code>```

saga.test.js

```<code>import {
    call,
    put,
    //takeLatest,
    delay
} from 'redux-saga/effects';
import * as matchers from 'redux-saga-test-plan/matchers';
import { expectSaga } from 'redux-saga-test-plan';
import { throwError } from 'redux-saga-test-plan/providers';
import {
    fetchWorkouts,
    addWorkout,
    //editWorkout,
    deleteWorkout
} from '../../actions/workoutApiActionsForSaga';
import { WorkoutService } from "../../services";
import {
    fetchWorkoutsSaga,
    deleteWorkoutSaga,
    addWorkoutSaga
} from '../workouts.saga'

describe('testing Workouts Sagas with redux-saga-test-plan', () => {

    const fakeAddPayload = {
        payload: {
            id: '6e8dbbc8-233f-41b1-ade3-ca568b35918c',
            date: '2019-05-27T18:10:35.282Z',
            workoutType: 'Running',
            calories: 100
        }
    };

    const errorToThrow = {
        statusText: 'custom Error Message'
    };

    it('should call addWorkoutSaga function', () => {
        return expectSaga(addWorkoutSaga, fakeAddPayload)
            .provide([
                [matchers.call.fn(delay), null],
                [matchers.call.fn(WorkoutService.add), null],
                [matchers.call.fn(fetchWorkoutsSaga), null]
            ])
            .call(WorkoutService.add, fakeAddPayload.payload)
            .put(addWorkout.success())
            .call(fetchWorkoutsSaga)
            .run();
    });
});
</code>```

When I ran the test, I got the following error because expected value is not equal to the actual value.

```<code>Expected
    --------
    { '@@redux-saga/IO': true,
      combinator: false,
      type: 'CALL',
      payload:
       { context: null,
         fn: [Function: add],
         args:
          [ { id: '6e8dbbc8-233f-41b1-ade3-ca568b35918c',
              date: '2019-05-27T18:10:35.282Z',
              workoutType: 'Running',
              calories: 100 } ] } }

    Actual:
    ------
    1. { '@@redux-saga/IO': true,
      combinator: false,
      type: 'CALL',
      payload: { context: null, fn: [Function: delayP], args: [ 1000 ] } }

      at new SagaTestError (node_modules/redux-saga-test-plan/lib/shared/SagaTestError.js:17:57)
      at node_modules/redux-saga-test-plan/lib/expectSaga/expectations.js:67:13
      at node_modules/redux-saga-test-plan/lib/expectSaga/index.js:563:7
          at Array.forEach (<anonymous>)
      at checkExpectations (node_modules/redux-saga-test-plan/lib/expectSaga/index.js:562:18)
</code>```

It seems to me that, the error is related to delay function.  When I tried to change the delay function to yield call(delay, 1000), it throws this error

```<code>Error: instead of writing `yield call(delay, 1000)` where delay is an effect from `redux-saga/effects` you should write `yield delay(1000)`
</code>```

If I changed the line to yield call(delay(1000));, it showed the following different error

```<code>Error: call: argument of type {context, fn} has undefined or null `fn`
</code>```

Could you please help me how I could test my saga with delays?  I don't want to remove the delay statements in the code to make the tests pass.

答:
You can simply mock call which delay uses under the hood.

As described in further detail here: https://github.com/jfairbank/redux-saga-test-plan/issues/257

Body:
I'm trying to test my redux-saga functions by using Redux Saga Test Plan library and I'm stuck due to delay functions in my saga.

If I remove the line, yield delay(1000) all tests pass without any error.

saga.js

export function* addWorkoutSaga({ payload }) {
    try {
        yield put(beginAjaxCall());

        yield delay(1000);
        yield call(WorkoutService.add, payload);

        yield call(toast.success, "Item added successfully.");
        yield put(closeModal(Modal.AddWorkout));
        yield put(addWorkout.success());
        yield call(fetchWorkoutsSaga);
    }
    catch (error) {
        console.log(error)
        yield put(addWorkout.failure({ errorMessage: error.statusText }));
        yield call(toast.error, "Error occured.  Please try again.");
    }
}

saga.test.js

import {
    call,
    put,
    //takeLatest,
    delay
} from 'redux-saga/effects';
import * as matchers from 'redux-saga-test-plan/matchers';
import { expectSaga } from 'redux-saga-test-plan';
import { throwError } from 'redux-saga-test-plan/providers';
import {
    fetchWorkouts,
    addWorkout,
    //editWorkout,
    deleteWorkout
} from '../../actions/workoutApiActionsForSaga';
import { WorkoutService } from "../../services";
import {
    fetchWorkoutsSaga,
    deleteWorkoutSaga,
    addWorkoutSaga
} from '../workouts.saga'

describe('testing Workouts Sagas with redux-saga-test-plan', () => {

    const fakeAddPayload = {
        payload: {
            id: '6e8dbbc8-233f-41b1-ade3-ca568b35918c',
            date: '2019-05-27T18:10:35.282Z',
            workoutType: 'Running',
            calories: 100
        }
    };

    const errorToThrow = {
        statusText: 'custom Error Message'
    };

    it('should call addWorkoutSaga function', () => {
        return expectSaga(addWorkoutSaga, fakeAddPayload)
            .provide([
                [matchers.call.fn(delay), null],
                [matchers.call.fn(WorkoutService.add), null],
                [matchers.call.fn(fetchWorkoutsSaga), null]
            ])
            .call(WorkoutService.add, fakeAddPayload.payload)
            .put(addWorkout.success())
            .call(fetchWorkoutsSaga)
            .run();
    });
});

When I ran the test, I got the following error because expected value is not equal to the actual value.

Expected
    --------
    { '@@redux-saga/IO': true,
      combinator: false,
      type: 'CALL',
      payload:
       { context: null,
         fn: [Function: add],
         args:
          [ { id: '6e8dbbc8-233f-41b1-ade3-ca568b35918c',
              date: '2019-05-27T18:10:35.282Z',
              workoutType: 'Running',
              calories: 100 } ] } }

    Actual:
    ------
    1. { '@@redux-saga/IO': true,
      combinator: false,
      type: 'CALL',
      payload: { context: null, fn: [Function: delayP], args: [ 1000 ] } }

      at new SagaTestError (node_modules/redux-saga-test-plan/lib/shared/SagaTestError.js:17:57)
      at node_modules/redux-saga-test-plan/lib/expectSaga/expectations.js:67:13
      at node_modules/redux-saga-test-plan/lib/expectSaga/index.js:563:7
          at Array.forEach (<anonymous>)
      at checkExpectations (node_modules/redux-saga-test-plan/lib/expectSaga/index.js:562:18)

It seems to me that, the error is related to delay function.  When I tried to change the delay function to yield call(delay, 1000), it throws this error

Error: instead of writing `yield call(delay, 1000)` where delay is an effect from `redux-saga/effects` you should write `yield delay(1000)`

If I changed the line to yield call(delay(1000));, it showed the following different error

Error: call: argument of type {context, fn} has undefined or null `fn`

Could you please help me how I could test my saga with delays?  I don't want to remove the delay statements in the code to make the tests pass.


问:
array of radio - jquery
i have the code below and it shows a list of radio buttons
My question is how i can make a list of buttons, the equivalent for this in an array mode (jquery)

```<code>  <input type="radio" name="name1" value="450" /> 450€<br />
  <input type="radio" name="name2" value="500" /> 500€<br />
  <input type="radio" name="name3" value="550" /> 550€<br />
  <input type="radio" name="name4" value="600" /> 600€<br />
  <input type="radio" name="name5" value="650" /> 650€<br />
  <input type="radio" name="name6" value="700" /> 700€<br />
</code>```

this simple make an array without change anything. And another question, how i will can access the values when i will have this in an array mode?

thanks

答:
Hopefully this will guide you in the right direction! I built a simple function create as many radios as you specify and increment the value by 50. Try modifying this a little to get to your desired solution!</p>

```<code>function populateRadios(){
  var i = 0,
      numberOfRadios = 3,
      baseNumber = 0;
    for(i; i<numberOfRadios; i++){
        var aRadio = document.createElement('input');
        aRadio.type = 'radio'
        aRadio.name = 'radio1';
        aRadio.id = 'radio' + i;
        baseNumber += 50;
        aRadio.value = baseNumber

       $('#theForm').append(aRadio)
    }
}
populateRadios()
</code>```

ContentLicense: CC BY-SA 3.0

Title: array of radio - jquery

Body:
i have the code below and it shows a list of radio buttons
My question is how i can make a list of buttons, the equivalent for this in an array mode (jquery)

  <input type="radio" name="name1" value="450" /> 450€

  <input type="radio" name="name2" value="500" /> 500€

  <input type="radio" name="name3" value="550" /> 550€

  <input type="radio" name="name4" value="600" /> 600€

  <input type="radio" name="name5" value="650" /> 650€

  <input type="radio" name="name6" value="700" /> 700€

this simple make an array without change anything. And another question, how i will can access the values when i will have this in an array mode?

thanks

Body:
Hopefully this will guide you in the right direction! I built a simple function create as many radios as you specify and increment the value by 50. Try modifying this a little to get to your desired solution!

function populateRadios(){
  var i = 0,
      numberOfRadios = 3,
      baseNumber = 0;
    for(i; i<numberOfRadios; i++){
        var aRadio = document.createElement('input');
        aRadio.type = 'radio'
        aRadio.name = 'radio1';
        aRadio.id = 'radio' + i;
        baseNumber += 50;
        aRadio.value = baseNumber

       $('#theForm').append(aRadio)
    }
}
populateRadios()


问:
npm script start production build with hash
When building a webpack production version of my server, I use a hash in the filename to separate different builds from one another.

The name of the file would be something like:

```<code>server.5eff6913d2d4ac0c39e1.js
</code>```

From the command prompt it's easy to start my server app.

Is there a way to do this dynamically from an npm script (i.e. automatically take the latest version)?

答:
Solved this by cleaning the output folder before rebuilding (webpack plugin) and using </p>

```<code>"build:server:prod": "webpack --config webpack.server.prod.config.js",
"build:client:prod": "webpack --config webpack.client.prod.config.js",
"start:server:prod": "export NODE_ENV=production && node ./dist/server.*.js",
"start:iso:prod": "npm run build:client:prod && npm run build:server:prod && npm run start:server:prod"
</code>```

Body:
When building a webpack production version of my server, I use a hash in the filename to separate different builds from one another.

The name of the file would be something like:

server.5eff6913d2d4ac0c39e1.js

From the command prompt it's easy to start my server app.

Is there a way to do this dynamically from an npm script (i.e. automatically take the latest version)?

Body:
Solved this by cleaning the output folder before rebuilding (webpack plugin) and using

"build:server:prod": "webpack --config webpack.server.prod.config.js",
"build:client:prod": "webpack --config webpack.client.prod.config.js",
"start:server:prod": "export NODE_ENV=production && node ./dist/server.*.js",
"start:iso:prod": "npm run build:client:prod && npm run build:server:prod && npm run start:server:prod"


问:
Counting and adding distinct values that occur in certain dates using PostgreSQL
Using some SQL in the tables of some database, I get a result like this:

```<code>id  name    date            status
1   John    2018-05-03      PRESENT
2   Mary    2018-05-03      NOT PRESENT
3   Jane    2018-05-03      NOT PRESENT
2   Mary    2018-05-04      PRESENT
1   John    2018-05-04      PRESENT
1   John    2018-05-05      PRESENT
2   Mary    2018-05-05      NOT PRESENT
3   Jane    2018-05-04      PRESENT
3   Jane    2018-05-05      NOT PRESENT
1   John    2018-05-06      PRESENT
</code>```

I wanna use further SQL to get in a result like this one:

```<code>id  name    date      present   not present
1   John    2018-05       4           0
2   Mary    2018-05       1           2
3   Jane    2018-05       2           1
</code>```

In other words, I wanna extract how many classes a student attended in a given month, based on the status he/she received everyday. How can I achieve that?

答:
```<code>select id, name, to_char(date,'YYYY-MM') as date,
       sum((case when status = 'PRESENT' then 1 end )) present,
       sum((case when status = 'NOT PRESENT' then 1 end )) not_present
  from your_result_table
 group by id, name, to_char(date,'YYYY-MM')
</code>```

Body:
Using some SQL in the tables of some database, I get a result like this:

id  name    date            status
1   John    2018-05-03      PRESENT
2   Mary    2018-05-03      NOT PRESENT
3   Jane    2018-05-03      NOT PRESENT
2   Mary    2018-05-04      PRESENT
1   John    2018-05-04      PRESENT
1   John    2018-05-05      PRESENT
2   Mary    2018-05-05      NOT PRESENT
3   Jane    2018-05-04      PRESENT
3   Jane    2018-05-05      NOT PRESENT
1   John    2018-05-06      PRESENT

I wanna use further SQL to get in a result like this one:

id  name    date      present   not present
1   John    2018-05       4           0
2   Mary    2018-05       1           2
3   Jane    2018-05       2           1

In other words, I wanna extract how many classes a student attended in a given month, based on the status he/she received everyday. How can I achieve that?


问:
Add Class to outside div with specific class
Hey I try to add a class to the div with "teaser-background item-1" class when I hover the div with "teaser-item item-1" class or when I hover "item-2" then add a class to the div with "teaser-item item-2".

#HTML

```<code><div class="teaser-home-container">
   <div class="teaser-home owl-carousel owl-theme">
      <div class="owl-item">
         <div class="teaser-item item-1"></div>
      </div>
      <div class="owl-item">
         <div class="teaser-item item-2"></div>
      </div>
   </div>
   <div class="teaser-home--background">
      <div class="teaser-background item-1"></div>
      <div class="teaser-background item-2"></div>
   </div>
</div>
</code>```

#Jquery

```<code>$thisClass = $(this).find("div[class^=item-]").attr('class');
$('.owl-item').hover(function(){
   $(this).parents('.teaser-home-container').find($thisClass).addClass('hover');
};
</code>```

答:
Its Not a good idea to work with classes in your case .. It can be done by using data attribute

You can Start from here

$('.owl-item .teaser-item').hover(function(){
  var GetData = $(this).data("item");
   $(this).closest('.teaser-home-container').find('[data-bg="'+GetData+'"]').addClass('hover');
},
function(){
  $(this).closest('.teaser-home-container').find('[data-bg]').removeClass("hover");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hover{
  background : red;
}</code>```

Item 1

Item 2

Bg 1

Bg 2

```

Body:
Hey I try to add a class to the div with "teaser-background item-1" class when I hover the div with "teaser-item item-1" class or when I hover "item-2" then add a class to the div with "teaser-item item-2".

#HTML

#Jquery

$thisClass = $(this).find("div[class^=item-]").attr('class');
$('.owl-item').hover(function(){
   $(this).parents('.teaser-home-container').find($thisClass).addClass('hover');
};

Body:
Its Not a good idea to work with classes in your case .. It can be done by using data attribute

You can Start from here

$('.owl-item .teaser-item').hover(function(){
  var GetData = $(this).data("item");
   $(this).closest('.teaser-home-container').find('[data-bg="'+GetData+'"]').addClass('hover');
},
function(){
  $(this).closest('.teaser-home-container').find('[data-bg]').removeClass("hover");
});

.hover{
  background : red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="teaser-home-container">
   <div class="teaser-home owl-carousel owl-theme">
      <div class="owl-item">
         <div class="teaser-item" data-item="1">Item 1</div>
      </div>
      <div class="owl-item">
         <div class="teaser-item" data-item="2">Item 2</div>
      </div>
   </div>
   <div class="teaser-home--background">
      <div class="teaser-background" data-bg="1">Bg 1</div>
      <div class="teaser-background" data-bg="2">Bg 2</div>
   </div>
</div>


问:
Difference in capitalization (javascript)
I noticed in my code that I used .Length and .length (for an array).  I now in some languages, this doesn't work.  What happened here?  Are these things just not case sensitive?</p>

答: JavaScript is case sensitive.  One thing that's possible is that someone added a property called Length to Array's prototype in your codebase.</p>


问:
Email validation C# asp.net
I used the following pattern to validate my email field.

```<code>    return Regex.IsMatch(email,
                 @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                 @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                 RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
</code>```

It uses the following reference:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/how-to-verify-that-strings-are-in-valid-email-format

My requirement is to have maximum number of 64 characters for user part, and max length for whole email string is 254 characters.  The pattern in the reference only allow max 134 characters. Can someone give clear explanation of the meaning for the pattern? What is the right pattern to achieve my goal?

答: If you wanted to avoid using regex (which is, in my opinion, difficult to decipher), you could use the .Split() method on the email string using the "@" symbol as your delimiter. Then, you can check the string lengths of the two components from there.

Title: Email validation C# asp.net

Body:
I used the following pattern to validate my email field.

    return Regex.IsMatch(email,
                 @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                 @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                 RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));

It uses the following reference:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/how-to-verify-that-strings-are-in-valid-email-format

My requirement is to have maximum number of 64 characters for user part, and max length for whole email string is 254 characters.  The pattern in the reference only allow max 134 characters. Can someone give clear explanation of the meaning for the pattern? What is the right pattern to achieve my goal?


问:
SQL0104 Token Col_Name was not valid
I am trying to update TableA with the below query and  it gives me an error
"IBM.Data.DB2.iSeries.iDB2SQLErrorException: 'SQL0104 Token CNUM was not valid. Valid tokens: USE SKIP WAIT WITH FETCH LIMIT ORDER WHERE OFFSET". Though i am able to update the database with the same query in DB2.

```<code>using (IDbCommand command = this.connection.CreateCommand())
{
    command.CommandText = string.Format(
        @"UPDATE {0}.TableA
        SET
        STS = @Status,
        USR = @User
        WHERE
        CNUM = @CNum", CoreServer.CoreCollection);

    IDbDataParameter statusParam = CoreServer.CreateParameter(command, "@Status", string.Empty, 3);
    IDbDataParameter UserParam = CoreServer.CreateParameter(command, "@User", string.Empty, 50);
    IDbDataParameter cNumberParam = CoreServer.CreateParameter(command, "@CNum", string.Empty, 30);

    statusParam.Value = CoreServer.ConvertToDatabase(input.Status);
    UserParam.Value = input.User == null ? null : input.User.Trim();
    cNumberParam.Value = input.CNumber.Trim();

    iDB2Command db2Command = (iDB2Command)command;
    db2Command.Transaction = (iDB2Transaction)transaction;
    db2Command.ExecuteNonQuery();
}
</code>```

Other Insert and Select queries works fine for the same table

答:
I got this error when I did a copy/paste of the sql where some sort of non-printable character was present.

To narrow down the problem I:

replaced the sql with something simple... like "select * from
myTable"

removed as much of the query text as possible

put pieces back in gradually and tested after each step

put the sql into a hex-text editor (or regular editor and    replaced
spaces with * and then looked for something that looked like    a
space)

Title: SQL0104 Token Col_Name was not valid

Body:
I am trying to update TableA with the below query and  it gives me an error
"IBM.Data.DB2.iSeries.iDB2SQLErrorException: 'SQL0104 Token CNUM was not valid. Valid tokens: USE SKIP WAIT WITH FETCH LIMIT ORDER WHERE OFFSET". Though i am able to update the database with the same query in DB2.

using (IDbCommand command = this.connection.CreateCommand())
{
    command.CommandText = string.Format(
        @"UPDATE {0}.TableA
        SET
        STS = @Status,
        USR = @User
        WHERE
        CNUM = @CNum", CoreServer.CoreCollection);

    IDbDataParameter statusParam = CoreServer.CreateParameter(command, "@Status", string.Empty, 3);
    IDbDataParameter UserParam = CoreServer.CreateParameter(command, "@User", string.Empty, 50);
    IDbDataParameter cNumberParam = CoreServer.CreateParameter(command, "@CNum", string.Empty, 30);

    statusParam.Value = CoreServer.ConvertToDatabase(input.Status);
    UserParam.Value = input.User == null ? null : input.User.Trim();
    cNumberParam.Value = input.CNumber.Trim();

    iDB2Command db2Command = (iDB2Command)command;
    db2Command.Transaction = (iDB2Transaction)transaction;
    db2Command.ExecuteNonQuery();
}

Other Insert and Select queries works fine for the same table


问:
Extraction of Data using tbodyclass and Beautifulsoup
Extraction with tbody class using BeautifulSoup and Python 3.

Im trying to extract the table (summary) on top of it. Im using BeautifulSoup for extraction. However I get the following error while using tclass to extract the table containing name,age,info etc

I am aware I can use the previous table{class :datatable} to extract the table .However I want to try extracting using tbody class

How do i extract the table with tbodyclass and what error am i making?
Im bit new to web scraping and any  detailed help would be appreciated

Here is the code

```<code>import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import requests

urls=['https://www.reuters.com/finance/stocks/company- officers/GOOG.O',
      'https://www.reuters.com/finance/stocks/company- officers/AMZN',
      'https://www.reuters.com/finance/stocks/company- officers/AAPL']

for item in urls:
   response=requests.get(item)
   data=response.content
   soup=BeautifulSoup(data,'html.parser')
   required_data=soup.find_all(class_='moduleBody')
   real_data=required_data.find_all(tbodyclass_='dataSmall')
   print(real_data)
</code>```

Here is the Error

```<code>Traceback (most recent call last):
 File "C:\Users\XXXX\Desktop\scrape.py", line 15, in <module>
real_data=required_data.find_all(tbodyclass_='dataSmall')
 File "C:\Users\XXXX\AppData\Local\Programs\Python\Python37\lib\site-
 packages\bs4\element.py", line 1620, in __getattr__
"ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key
AttributeError: ResultSet object has no attribute 'find_all'. You're
probably treating a list of items like a single item. Did you call
find_all() when you meant to call find()?
</code>```

答:
To get the table under summary, you can try the following script:

```<code>import requests
from bs4 import BeautifulSoup

URLS = [
    'https://www.reuters.com/finance/stocks/company- officers/GOOG.O',
    'https://www.reuters.com/finance/stocks/company- officers/AMZN',
    'https://www.reuters.com/finance/stocks/company- officers/AAPL'
]

for url in URLS:
    r = requests.get(url,headers={"User-Agent":"Mozilla/5.0"})
    soup = BeautifulSoup(r.text,"lxml")
    for items in soup.select_one("h3:contains(Summary)").find_parent().find_next_sibling().select("table tr"):
        data = [' '.join(item.text.split()) for item in items.select("th,td")]
        print(data)
</code>```

Body:
Extraction with tbody class using BeautifulSoup and Python 3.

Im trying to extract the table (summary) on top of it. Im using BeautifulSoup for extraction. However I get the following error while using tclass to extract the table containing name,age,info etc

I am aware I can use the previous table{class :datatable} to extract the table .However I want to try extracting using tbody class

How do i extract the table with tbodyclass and what error am i making?
Im bit new to web scraping and any  detailed help would be appreciated

Here is the code

import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import requests

urls=['https://www.reuters.com/finance/stocks/company- officers/GOOG.O',
      'https://www.reuters.com/finance/stocks/company- officers/AMZN',
      'https://www.reuters.com/finance/stocks/company- officers/AAPL']

for item in urls:
   response=requests.get(item)
   data=response.content
   soup=BeautifulSoup(data,'html.parser')
   required_data=soup.find_all(class_='moduleBody')
   real_data=required_data.find_all(tbodyclass_='dataSmall')
   print(real_data)

Here is the Error

Traceback (most recent call last):
 File "C:\Users\XXXX\Desktop\scrape.py", line 15, in <module>
real_data=required_data.find_all(tbodyclass_='dataSmall')
 File "C:\Users\XXXX\AppData\Local\Programs\Python\Python37\lib\site-
 packages\bs4\element.py", line 1620, in __getattr__
"ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key
AttributeError: ResultSet object has no attribute 'find_all'. You're
probably treating a list of items like a single item. Did you call
find_all() when you meant to call find()?

Body:
To get the table under summary, you can try the following script:

import requests
from bs4 import BeautifulSoup

URLS = [
    'https://www.reuters.com/finance/stocks/company- officers/GOOG.O',
    'https://www.reuters.com/finance/stocks/company- officers/AMZN',
    'https://www.reuters.com/finance/stocks/company- officers/AAPL'
]

for url in URLS:
    r = requests.get(url,headers={"User-Agent":"Mozilla/5.0"})
    soup = BeautifulSoup(r.text,"lxml")
    for items in soup.select_one("h3:contains(Summary)").find_parent().find_next_sibling().select("table tr"):
        data = [' '.join(item.text.split()) for item in items.select("th,td")]
        print(data)


问:
Error: Network error: Error writing result to store for query (Apollo Client)
I am using Apollo Client to make an application to query my server using Graphql. I have a python server on which I execute my graphql queries which fetches data from the database and then returns it back to the client.

I have created a custom NetworkInterface for the client that helps me to make make customized server request (by default ApolloClient makes a POST call to the URL we specify). The network interface only has to have a query() method wherein we return the promise for the result of form Promise<ExecutionResult>.

I am able to make the server call and fetch the requested data but still getting the following error.

```<code>Error: Network error: Error writing result to store for query
{
   query something{
      row{
         data
      }
   }
}
Cannot read property 'row' of undefined
    at new ApolloError (ApolloError.js:32)
    at ObservableQuery.currentResult (ObservableQuery.js:76)
    at GraphQL.dataForChild (react-apollo.browser.umd.js:410)
    at GraphQL.render (react-apollo.browser.umd.js:448)
    at ReactCompositeComponent.js:796
    at measureLifeCyclePerf (ReactCompositeComponent.js:75)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:795)
    at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822)
    at ReactCompositeComponentWrapper._updateRenderedComponent (ReactCompositeComponent.js:746)
    at ReactCompositeComponentWrapper._performComponentUpdate (ReactCompositeComponent.js:724)
    at ReactCompositeComponentWrapper.updateComponent (ReactCompositeComponent.js:645)
    at ReactCompositeComponentWrapper.performUpdateIfNecessary (ReactCompositeComponent.js:561)
    at Object.performUpdateIfNecessary (ReactReconciler.js:157)
    at runBatchedUpdates (ReactUpdates.js:150)
    at ReactReconcileTransaction.perform (Transaction.js:140)
    at ReactUpdatesFlushTransaction.perform (Transaction.js:140)
    at ReactUpdatesFlushTransaction.perform (ReactUpdates.js:89)
    at Object.flushBatchedUpdates (ReactUpdates.js:172)
    at ReactDefaultBatchingStrategyTransaction.closeAll (Transaction.js:206)
    at ReactDefaultBatchingStrategyTransaction.perform (Transaction.js:153)
    at Object.batchedUpdates (ReactDefaultBatchingStrategy.js:62)
    at Object.enqueueUpdate (ReactUpdates.js:200)
</code>```

I want to know the possible cause of the error and solution if possible.

答:
I've finally found out what is causing this issue after battling with it in various parts of our app for months. What helped to shed some light on it was switching from apollo-cache-inmemory to apollo-cache-hermes.

I experimented with Hermes hoping to mitigate this ussue, but unfortunately it fails to update the cache the same as apollo-cache-inmemory. What is curious though is that hermes shows a very nice user friendly message, unlike  apollo-cache-inmemory. This lead me to a revelation that cache really hits this problem when it's trying to store an object type that is already in the cache with an ID, but the new object type is lacking it. So apollo-cache-inmemory should work fine if you are meticulously consistent when querying your fields. If you omit id field everywhere for a certain object type it will happily work. If you use id field everywhere it will work correctly. Once you mix queries with and without id that's when cache blows up with this horrible error message.

This is not a bug-it's working as intended, it's even documented here: https://www.apollographql.com/docs/react/caching/cache-configuration/#default-identifiers

2020 update: Apollo has since removed this "feature" from the cache, so this error should not be thrown anymore in apollo-client 3 and newer.

Body:
I am using Apollo Client to make an application to query my server using Graphql. I have a python server on which I execute my graphql queries which fetches data from the database and then returns it back to the client.

I have created a custom NetworkInterface for the client that helps me to make make customized server request (by default ApolloClient makes a POST call to the URL we specify). The network interface only has to have a query() method wherein we return the promise for the result of form Promise<ExecutionResult>.

I am able to make the server call and fetch the requested data but still getting the following error.

Error: Network error: Error writing result to store for query
{
   query something{
      row{
         data
      }
   }
}
Cannot read property 'row' of undefined
    at new ApolloError (ApolloError.js:32)
    at ObservableQuery.currentResult (ObservableQuery.js:76)
    at GraphQL.dataForChild (react-apollo.browser.umd.js:410)
    at GraphQL.render (react-apollo.browser.umd.js:448)
    at ReactCompositeComponent.js:796
    at measureLifeCyclePerf (ReactCompositeComponent.js:75)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:795)
    at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822)
    at ReactCompositeComponentWrapper._updateRenderedComponent (ReactCompositeComponent.js:746)
    at ReactCompositeComponentWrapper._performComponentUpdate (ReactCompositeComponent.js:724)
    at ReactCompositeComponentWrapper.updateComponent (ReactCompositeComponent.js:645)
    at ReactCompositeComponentWrapper.performUpdateIfNecessary (ReactCompositeComponent.js:561)
    at Object.performUpdateIfNecessary (ReactReconciler.js:157)
    at runBatchedUpdates (ReactUpdates.js:150)
    at ReactReconcileTransaction.perform (Transaction.js:140)
    at ReactUpdatesFlushTransaction.perform (Transaction.js:140)
    at ReactUpdatesFlushTransaction.perform (ReactUpdates.js:89)
    at Object.flushBatchedUpdates (ReactUpdates.js:172)
    at ReactDefaultBatchingStrategyTransaction.closeAll (Transaction.js:206)
    at ReactDefaultBatchingStrategyTransaction.perform (Transaction.js:153)
    at Object.batchedUpdates (ReactDefaultBatchingStrategy.js:62)
    at Object.enqueueUpdate (ReactUpdates.js:200)

I want to know the possible cause of the error and solution if possible.


问:
how to use Moya RxSwift to get an array of REST merged
I am trying to learn RxSwift. I had been using Moya and now want to try my hand at RxSwift. Totally confused.

```<code> let popServiceProvider = MoyaProvider<PopRESTService>()
    let o1 = popServiceProvider.rx.request(.getPopByCity(city: "London")).asObservable()
    let o2 = popServiceProvider.rx.request(.getPopByCity(city: "Tokyo")).asObservable()

    let pObservables:[Observable<Response>] = [o1, o2]
    let stats: Observable<Response> = Observable.combineLatest(pObservables)
    let m = stats.map({ a in
        print(a)
    })
</code>```

First I get an error on let stats:

Cannot convert value of type 'Observable<[Response]>' to specified type 'Observable'

am I even going in the right direction?

EDIT:

Even this doesn't work. Never first the subscribe:

```<code>   wServiceProvider.rx.request(.getWeatherByCity(city: "Chicago"))
    .debug()
    .map(Weather.self)
    .subscribe({ (event) in
        switch event {
        case let .success(response):
            print(response)

        case let .error(response):
            print(response)
        }
    })
    .disposed(by: self.disposeBag)
</code>```

答:
I recommend using Observable.combineLatest(o1, o2) variant of combineLatest (this form is limited by 8 arguments)

Assuming that type returned from case getPopByCity(city: String) might look like:

struct PopByCity: Decodable {
  let count: Float
}
```

<p>you probably want to implement the request like that:</p>

<pre class="lang-swift prettyprint-override"><code>Observable.combineLatest(o1, o2)
  .map { (resp1: Response, resp2: Response) -> [PopByCity] in
    let pop1 = try? JSONDecoder().decode(PopByCity.self, from: resp1.data)
    let pop2 = try? JSONDecoder().decode(PopByCity.self, from: resp2.data)
    return [pop1, pop2].compactMap { $0 }
  }
  .subscribe(onNext: { (result: [PopByCity]) in
    print(result)
  })
  .disposed(by: disposeBag)
</code>```

But if you still need an array of requests:

Observable.combineLatest([o1, o2])
  .map { (responses: [Response]) -> [PopByCity] in
    responses.map { try? JSONDecoder().decode(PopByCity.self, from: $0.data) }
      .compactMap { $0 }
  }
  .subscribe(onNext: { (result: [PopByCity]) in
    print(result)
  })
  .disposed(by: disposeBag)
```

For the second option, keep in mind, that it is not a good practice to send tons of async request at the same time. For many request need to be performed I recommend using Concat operator or combination of Concat + Reduce if you have to handle all responses in one place after the last response.

Body:
I am trying to learn RxSwift. I had been using Moya and now want to try my hand at RxSwift. Totally confused.

 let popServiceProvider = MoyaProvider<PopRESTService>()
    let o1 = popServiceProvider.rx.request(.getPopByCity(city: "London")).asObservable()
    let o2 = popServiceProvider.rx.request(.getPopByCity(city: "Tokyo")).asObservable()

    let pObservables:[Observable<Response>] = [o1, o2]
    let stats: Observable<Response> = Observable.combineLatest(pObservables)
    let m = stats.map({ a in
        print(a)
    })

First I get an error on let stats:

Cannot convert value of type 'Observable<[Response]>' to specified type 'Observable'

am I even going in the right direction?

EDIT:

Even this doesn't work. Never first the subscribe:

   wServiceProvider.rx.request(.getWeatherByCity(city: "Chicago"))
    .debug()
    .map(Weather.self)
    .subscribe({ (event) in
        switch event {
        case let .success(response):
            print(response)

        case let .error(response):
            print(response)
        }
    })
    .disposed(by: self.disposeBag)

Body:
I recommend using Observable.combineLatest(o1, o2) variant of combineLatest (this form is limited by 8 arguments)

Assuming that type returned from case getPopByCity(city: String) might look like:

struct PopByCity: Decodable {
  let count: Float
}

you probably want to implement the request like that:

Observable.combineLatest(o1, o2)
  .map { (resp1: Response, resp2: Response) -> [PopByCity] in
    let pop1 = try? JSONDecoder().decode(PopByCity.self, from: resp1.data)
    let pop2 = try? JSONDecoder().decode(PopByCity.self, from: resp2.data)
    return [pop1, pop2].compactMap { $0 }
  }
  .subscribe(onNext: { (result: [PopByCity]) in
    print(result)
  })
  .disposed(by: disposeBag)

But if you still need an array of requests:

Observable.combineLatest([o1, o2])
  .map { (responses: [Response]) -> [PopByCity] in
    responses.map { try? JSONDecoder().decode(PopByCity.self, from: $0.data) }
      .compactMap { $0 }
  }
  .subscribe(onNext: { (result: [PopByCity]) in
    print(result)
  })
  .disposed(by: disposeBag)

For the second option, keep in mind, that it is not a good practice to send tons of async request at the same time. For many request need to be performed I recommend using Concat operator or combination of Concat + Reduce if you have to handle all responses in one place after the last response.


问:
How to check if a variable has been declared even if it hasn't been defined?
This question:

JavaScript check if variable exists (is defined/initialized)

does not regard the case of variables which have been declared but not defined (as opposed to undeclared and undefined). Specifically, if I want to check whether x has been declared, this:

typeof x == 'undefined'

will not do, because...

```<code>var x; //<- declared but undefined
// idontexist  not declared

typeof idontexist === typeof x; // evaluates to true
</code>```

This has implications: if variable has been declared it wont become a global variable, whereas if a variable has not declared, it would become a global variable, possibly leading to memory leak.

So how do I check in javascript if undefined variable has been declared?

Regarding the implications of this, consider this code:

```<code>function test() {

  var x
  console.log(typeof x == typeof y); // true
  if (typeof x == 'undefined') {
     x = 3;
  }
  if (typeof y == 'undefined') {
     y = 5;
  }
}
test();
y; // 5
x; // Reference Error
</code>```

答:
Trying to use an undeclared variable will throw a ReferenceError, so you can use a try catch block to determine if a variable has been declared.

var myVar;

try {
  myVar;
  console.log('myVar was declared.');
} catch(error) {
  if (error instanceof ReferenceError) {
     console.log('myVar was NOT declared');
  } else {
    console.log('Caught some other error.');
  }
}

try {
  notDeclared;
  console.log('notDeclared was declared');
} catch(error) {
  if (error instanceof ReferenceError) {
    console.log('notDeclared was NOT declared.');
   } else {
    console.log('Caught some other error.');
  }
}```

Body:
This question:

JavaScript check if variable exists (is defined/initialized)

does not regard the case of variables which have been declared but not defined (as opposed to undeclared and undefined). Specifically, if I want to check whether x has been declared, this:

typeof x == 'undefined'

will not do, because...

var x; //<- declared but undefined
// idontexist  not declared

typeof idontexist === typeof x; // evaluates to true

This has implications: if variable has been declared it wont become a global variable, whereas if a variable has not declared, it would become a global variable, possibly leading to memory leak.

So how do I check in javascript if undefined variable has been declared?

Regarding the implications of this, consider this code:

function test() {

  var x
  console.log(typeof x == typeof y); // true
  if (typeof x == 'undefined') {
     x = 3;
  }
  if (typeof y == 'undefined') {
     y = 5;
  }
}
test();
y; // 5
x; // Reference Error


问:
Proper way to iterate tf.data.Dataset in session for 2.0
I have downloaded some *.tfrecord data from the youtube-8m project. You can download a 'small' portion of the data with this command:

curl data.yt8m.org/download.py | shard=1,100 partition=2/video/train mirror=us python

I am trying to get an idea of how to use the new tf.data API. I would like to become familiar with the typical ways people iterate through datasets. I have been using the guide on TF website and this slide: Derek Murray's Slides

Here is how I define the dataset:

```<code># Use interleave() and prefetch() to read many files concurrently.
files = tf.data.Dataset.list_files("./youtube_vids/*.tfrecord")
dataset = files.interleave(lambda x: tf.data.TFRecordDataset(x).prefetch(100),
                           cycle_length=8)

# Use num_parallel_calls to parallelize map().
dataset = dataset.map(lambda record: tf.parse_single_example(record, feature_map),
                     num_parallel_calls=2) #

# put in x,y output form
dataset = dataset.map(lambda x: (x['mean_rgb'], x['id']))

# shuffle
dataset = dataset.shuffle(10000)

#one epoch
dataset = dataset.repeat(1)
dataset = dataset.batch(200)

#Use prefetch() to overlap the producer and consumer.
dataset = dataset.prefetch(10)
</code>```

Now, I know in eager execution mode I can just

```<code>for x,y in dataset:
    x,y
</code>```

However, when I attempt to create an iterator as follows:

```<code># A one-shot iterator automatically initializes itself on first use.
iterator = dset.make_one_shot_iterator()

# The return value of get_next() matches the dataset element type.
images, labels = iterator.get_next()
</code>```

And run with session

```<code>with tf.Session() as sess:

    # Loop until all elements have been consumed.
    try:
        while True:
            r = sess.run(images)
    except tf.errors.OutOfRangeError:
        pass
</code>```

I get the warning

```<code>Use `for ... in dataset:` to iterate over a dataset. If using `tf.estimator`, return the `Dataset` object directly from your input function. As a last resort, you can use `tf.compat.v1.data.make_one_shot_iterator(dataset)`.
</code>```

So, here is my question:

What is the proper way to iterate through a dataset within a session? Is it just a matter of v1 and v2 differences?

Also, the advice to pass the dataset directly to an estimator implies that the input function also has an iterator defined as in Derek Murray's slides above, correct?

答:
As for Estimator API, no you don't have to specify iterator, just pass dataset object as input function.

def input_fn(filename):
    dataset = tf.data.TFRecordDataset(filename)
    dataset = dataset.shuffle().repeat()
    dataset = dataset.map(parse_func)
    dataset = dataset.batch()
    return dataset

estimator.train(input_fn=lambda: input_fn())
```

<p>In TF 2.0 dataset became iterable, so, just as warning message says, you can use </p>

```for x,y in dataset:
    x,y
```

Body:
I have downloaded some *.tfrecord data from the youtube-8m project. You can download a 'small' portion of the data with this command:

curl data.yt8m.org/download.py | shard=1,100 partition=2/video/train mirror=us python

I am trying to get an idea of how to use the new tf.data API. I would like to become familiar with the typical ways people iterate through datasets. I have been using the guide on TF website and this slide: Derek Murray's Slides

Here is how I define the dataset:

# Use interleave() and prefetch() to read many files concurrently.
files = tf.data.Dataset.list_files("./youtube_vids/*.tfrecord")
dataset = files.interleave(lambda x: tf.data.TFRecordDataset(x).prefetch(100),
                           cycle_length=8)

# Use num_parallel_calls to parallelize map().
dataset = dataset.map(lambda record: tf.parse_single_example(record, feature_map),
                     num_parallel_calls=2) #

# put in x,y output form
dataset = dataset.map(lambda x: (x['mean_rgb'], x['id']))

# shuffle
dataset = dataset.shuffle(10000)

#one epoch
dataset = dataset.repeat(1)
dataset = dataset.batch(200)

#Use prefetch() to overlap the producer and consumer.
dataset = dataset.prefetch(10)

Now, I know in eager execution mode I can just

for x,y in dataset:
    x,y

However, when I attempt to create an iterator as follows:

# A one-shot iterator automatically initializes itself on first use.
iterator = dset.make_one_shot_iterator()

# The return value of get_next() matches the dataset element type.
images, labels = iterator.get_next()

And run with session

with tf.Session() as sess:

    # Loop until all elements have been consumed.
    try:
        while True:
            r = sess.run(images)
    except tf.errors.OutOfRangeError:
        pass

I get the warning

Use `for ... in dataset:` to iterate over a dataset. If using `tf.estimator`, return the `Dataset` object directly from your input function. As a last resort, you can use `tf.compat.v1.data.make_one_shot_iterator(dataset)`.

So, here is my question:

What is the proper way to iterate through a dataset within a session? Is it just a matter of v1 and v2 differences?

Also, the advice to pass the dataset directly to an estimator implies that the input function also has an iterator defined as in Derek Murray's slides above, correct?

Body:
As for Estimator API, no you don't have to specify iterator, just pass dataset object as input function.

def input_fn(filename):
    dataset = tf.data.TFRecordDataset(filename)
    dataset = dataset.shuffle().repeat()
    dataset = dataset.map(parse_func)
    dataset = dataset.batch()
    return dataset

estimator.train(input_fn=lambda: input_fn())

In TF 2.0 dataset became iterable, so, just as warning message says, you can use

for x,y in dataset:
    x,y


问:
Modal dialog and __doPostback Infinite loop
I've got a modal dialog created using ModalPopupExtender. There is an UI created in it using Webservices and a JQuery Templates. There is also a hidden ASP.NET button which is called from the javascript using the __doPostback() technique. The javascript hides the modal popup and __doPostback is called on the button (which is inside of the ModalPopupExtender)

I use this technique to pass some parameters are from the javascript. The server-side event handler does some processing and transfers to a page (in some cases, back to itself)

This works fine when the page it transfers to is a different one but if it transfers to the same page, the postback happens over and over again until the stack blows.

How do i stop the postback from re-occurring when I postback to the same page. I guess it doesn't happen the first time around because it posts to a different page and the postback is invalidated.

Code samples are difficult to provide as it's a fairly complicated system and it's difficult to break it apart.

It sounds horrible I know, all I want to do, however, it to call a server side function from javascript with some variables. Is there a better way to do this?

答:
Well, you're posting back, so you have server-side control over your markup.  Just stick your javascript that does the repost in a container and in the case that the page posts to itself, hide that container so it's not loaded into the page....

That or you could do client cookies or a querystring param.  Both might be wonky.


问:
what is wrong between two "multiple key pressed" code sample?
I was trying to get multiple key pressed at the same time functionality. I found some answer for that. I was following this one.

JavaScript multiple keydown

The problem is I got some of that code which work. But My version of that does not work. I am totally clueless whats going on.

Code from the answer

```<code>var keys;

document.getElementById('demo').addEventListener("keydown", function (e) {
    keys = (keys || []);
    keys[e.keyCode]=true;

    if (keys[65] && keys[66]){
        document.body.style.backgroundColor = "red";
    }
} , false);

document.getElementById('demo').addEventListener("keyup", function (e) {
    keys[e.keyCode]=false;
    document.body.style.backgroundColor = "green";
    stop();
}, false);
</code>```

My version of code is.

```<code>var keys;

document.getElementById('demo').addEventListener("keydown", function (e) {
keys = (keys || []);
    keys[e.keycode]=true;
    if (keys[65] && keys[66]){
    document.body.style.backgroundColor = "red";
}
} , false);
document.getElementById("demo").addEventListener("keyup", function (e) {
    keys[e.keycode]=false;
    document.body.style.backgroundColor = "green";
//stop();
} , false);
</code>```

In my version of code first part is not working. I can't figure out why?

答:
keycode needs to be written as keyCode in both places.

Make sure the demo element is an input, it won't work with div, etc.

Body:
I was trying to get multiple key pressed at the same time functionality. I found some answer for that. I was following this one.

JavaScript multiple keydown

The problem is I got some of that code which work. But My version of that does not work. I am totally clueless whats going on.

Code from the answer

var keys;

document.getElementById('demo').addEventListener("keydown", function (e) {
    keys = (keys || []);
    keys[e.keyCode]=true;

    if (keys[65] && keys[66]){
        document.body.style.backgroundColor = "red";
    }
} , false);

document.getElementById('demo').addEventListener("keyup", function (e) {
    keys[e.keyCode]=false;
    document.body.style.backgroundColor = "green";
    stop();
}, false);

My version of code is.

var keys;

document.getElementById('demo').addEventListener("keydown", function (e) {
keys = (keys || []);
    keys[e.keycode]=true;
    if (keys[65] && keys[66]){
    document.body.style.backgroundColor = "red";
}
} , false);
document.getElementById("demo").addEventListener("keyup", function (e) {
    keys[e.keycode]=false;
    document.body.style.backgroundColor = "green";
//stop();
} , false);

In my version of code first part is not working. I can't figure out why?


问:
How to measure the amount of memory webview consumes?
Would there be a way to programmatically measure and monitor the memory consumed by

```<code>WebView.loadUrl
</code>```

when we open a webview activity in our Android app?

I have noticed that for some reason the webpage that I open using WebView.loadUrl has some memory leak and the amount of memory it uses keeps on increasing under random conditions. I wanted to programatically catch that and run some method if the memory usage of my WebView page goes beyond a certain range.

答:
You can use the memory profile tool from Android Studio. It shows all the memory usage.

Memory Profile

https://developer.android.com/studio/profile/memory-profiler

Body:
Would there be a way to programmatically measure and monitor the memory consumed by

WebView.loadUrl

when we open a webview activity in our Android app?

I have noticed that for some reason the webpage that I open using WebView.loadUrl has some memory leak and the amount of memory it uses keeps on increasing under random conditions. I wanted to programatically catch that and run some method if the memory usage of my WebView page goes beyond a certain range.


问:
Animating Views from top-bottom to side-by-side in React Native
I am trying to create a custom header for my app and I want to animate it in a certain way. I will describe the way it is supposed to be animated.

If you have a look at the image you will see one red View that contains one green View and a blue View. I would like the Views be arranged side-by-side from their current positions while animating.

I have tried to create the code for a collapsing header and the red View that contains everything, is shrinking based on a ScrollView but I cant get the green and blue Views to come side-by-side.

Home.js

```<code>const HEADER_EXPANDED_VIEW = 200
const HEADER_COLLAPSED_VIEW = 80

export default class HomeActivity extends Component {
    constructor(props) {
        super(props)
        this.state = {
            scrollY: new Animated.Value(0)
        }
    }

    static navigationOptions = {
        title: "HomeActivity",
        header: null
    }

    render() {
        const headerHeight = this.state.scrollY.interpolate({
            inputRange: [0, HEADER_EXPANDED_VIEW - HEADER_COLLAPSED_VIEW],
            outputRange: [HEADER_EXPANDED_VIEW, HEADER_COLLAPSED_VIEW],
            extrapolate: "clamp"
        })

        // console.log(headerHeight)

        return (
            <View style={styles.container}>
                <ScrollView
                    contentContainerStyle={{
                        padding: 16,
                        paddingTop: HEADER_EXPANDED_VIEW,
                        color: "#FFFFFF"
                    }}
                    onScroll={Animated.event([
                        {
                            nativeEvent: {
                                contentOffset: {
                                    y: this.state.scrollY
                                }
                            }
                        }
                    ])}
                >
                    <Text style={styles.title}>This is Title</Text>
                    <Text style={styles.content}>
                    .....
                    </Text>
                </ScrollView>
                <CollapsingHeader headerHeight={headerHeight} />
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    scrollContainer: {
        padding: 16
    },
    title: {
        fontSize: 24,
        marginVertical: 16
    }
})
</code>```

CollapsingHeader.js

```<code>export default class CollapsingHeader extends Component {
    render() {
        return (
            <Animated.View
                style={{
                    height: this.props.headerHeight,
                    width: Dimensions.get("screen").width,
                    position: "absolute",
                    top: 0,
                    left: 0,
                    borderWidth: 2,
                    borderColor: "#FF0000",
                    backgroundColor: "#212121"
                }}
            >
                <View
                    style={{
                        borderWidth: 2,
                        borderColor: "#00FF00"
                    }}
                >
                    <MenuButton />
                </View>

                <View
                    style={{
                        flexDirection: "row",
                        borderWidth: 2,
                        borderColor: "#0000FF"
                    }}
                >
                    <View
                        style={{
                            flexGrow: 1
                        }}
                    >
                        <Text
                            style={{
                                fontFamily: "NunitoSans-Bold",
                                fontSize: 40,
                                color: "#FFFFFF"
                            }}
                        >
                            Home
                        </Text>
                    </View>

                    <SortButton />

                    <SearchButton />
                </View>
            </Animated.View>
        )
    }
}
</code>```

I am relatively new to React Native, please assume I know very little about it.

答:
If you know the headerHeight at which it's going to collapse, then you could add a dynamic flexDirection to the Animated.View style.

style={{
  /* ...your Animated.View styles */
  flexDirection: this.props.headerHeight < /* collapse height */ ? 'row' : 'column'
}}
```

Body:
I am trying to create a custom header for my app and I want to animate it in a certain way. I will describe the way it is supposed to be animated.

If you have a look at the image you will see one red View that contains one green View and a blue View. I would like the Views be arranged side-by-side from their current positions while animating.

I have tried to create the code for a collapsing header and the red View that contains everything, is shrinking based on a ScrollView but I cant get the green and blue Views to come side-by-side.

Home.js

const HEADER_EXPANDED_VIEW = 200
const HEADER_COLLAPSED_VIEW = 80

export default class HomeActivity extends Component {
    constructor(props) {
        super(props)
        this.state = {
            scrollY: new Animated.Value(0)
        }
    }

    static navigationOptions = {
        title: "HomeActivity",
        header: null
    }

    render() {
        const headerHeight = this.state.scrollY.interpolate({
            inputRange: [0, HEADER_EXPANDED_VIEW - HEADER_COLLAPSED_VIEW],
            outputRange: [HEADER_EXPANDED_VIEW, HEADER_COLLAPSED_VIEW],
            extrapolate: "clamp"
        })

        // console.log(headerHeight)

        return (
            <View style={styles.container}>
                <ScrollView
                    contentContainerStyle={{
                        padding: 16,
                        paddingTop: HEADER_EXPANDED_VIEW,
                        color: "#FFFFFF"
                    }}
                    onScroll={Animated.event([
                        {
                            nativeEvent: {
                                contentOffset: {
                                    y: this.state.scrollY
                                }
                            }
                        }
                    ])}
                >
                    <Text style={styles.title}>This is Title</Text>
                    <Text style={styles.content}>
                    .....
                    </Text>
                </ScrollView>
                <CollapsingHeader headerHeight={headerHeight} />
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    scrollContainer: {
        padding: 16
    },
    title: {
        fontSize: 24,
        marginVertical: 16
    }
})

CollapsingHeader.js

export default class CollapsingHeader extends Component {
    render() {
        return (
            <Animated.View
                style={{
                    height: this.props.headerHeight,
                    width: Dimensions.get("screen").width,
                    position: "absolute",
                    top: 0,
                    left: 0,
                    borderWidth: 2,
                    borderColor: "#FF0000",
                    backgroundColor: "#212121"
                }}
            >
                <View
                    style={{
                        borderWidth: 2,
                        borderColor: "#00FF00"
                    }}
                >
                    <MenuButton />
                </View>

                <View
                    style={{
                        flexDirection: "row",
                        borderWidth: 2,
                        borderColor: "#0000FF"
                    }}
                >
                    <View
                        style={{
                            flexGrow: 1
                        }}
                    >
                        <Text
                            style={{
                                fontFamily: "NunitoSans-Bold",
                                fontSize: 40,
                                color: "#FFFFFF"
                            }}
                        >
                            Home
                        </Text>
                    </View>

                    <SortButton />

                    <SearchButton />
                </View>
            </Animated.View>
        )
    }
}

I am relatively new to React Native, please assume I know very little about it.


答:
Use conditional aggregation (using filter) and date_trunc():

```<code>select id, name, date_trunc('month', date),
       count(*) filter (where status = 'PRESENT') as num_present,
       count(*) filter (where status = 'NOT PRESENT') as num_notpresent
from t
group by id, name, date_trunc('month', date)
order by id, name, date_trunc('month', date)
</code>```

Title: Counting and adding distinct values that occur in certain dates using PostgreSQL

Body:
Use conditional aggregation (using filter) and date_trunc():

select id, name, date_trunc('month', date),
       count(*) filter (where status = 'PRESENT') as num_present,
       count(*) filter (where status = 'NOT PRESENT') as num_notpresent
from t
group by id, name, date_trunc('month', date)
order by id, name, date_trunc('month', date)


问:
Repeat a semi-transparent NSImage
In a project I'm working on, I have 3 images: top, middle, and bottom. Top and bottom are fixed height, and middle should be repeated in between the two. (The window size will be changing.) They all are tinted with a color from the user preferences, then need to have their alpha set using a value from the preferences.

I can do pretty much everything. The part I get stuck at is drawing the middle. I decided using [NSColor +colorWithPaternImage:] would be the easiest thing to use. There's a lot of code that makes the actually images and colors, so just assume they exist and are not nil.

```<code>int problem; // just to help explain things

float alpha;
NSImage *middleTinted;

NSRect drawRect = [self bounds];
drawRect.size.height = self.bounds.size.height - topTinted.size.height - bottomTinted.size.height;
drawRect.origin.y = topTinted.size.height;

NSColor* colorOne = [NSColor colorWithPatternImage:middleTinted];
NSColor* colorTwo = [colorOne colorWithAlphaComponent:alpha];

if(problem == 1)
{
    [colorOne set];
}
else if(problem == 2)
{
    [colorTwo set];
}

[NSBezierPath fillRect:drawRect];
</code>```

Assuming problem == 1, it draws the correct image, in the correct location and with the correct size, but no alpha. (Obviously, since I didn't specify one.)

When problem == 2, I'd expect it to do the same thing, but have the correct alpha value. Instead of this, I get a black box.

Is there a solution that will repeat the image with the correct alpha? I figure I could just draw the image manually in a loop, but I'd prefer a more reasonable solution if one exists.

答:
I expect the problem is that pattern colors don't support -colorWithAlphaComponent:.

NSCell.h contains a method called NSDrawThreePartImage that does the work of drawing end caps and a tiled image in between. It also has an alphaFraction parameter that should meet your needs.

If that doesn't work for you, then you might get the pattern color approach to work by re-rendering your middleTinted image into a new NSImage, using the desired alpha value. (See NSImage's draw... methods.)

Title: Repeat a semi-transparent NSImage

Body:
In a project I'm working on, I have 3 images: top, middle, and bottom. Top and bottom are fixed height, and middle should be repeated in between the two. (The window size will be changing.) They all are tinted with a color from the user preferences, then need to have their alpha set using a value from the preferences.

I can do pretty much everything. The part I get stuck at is drawing the middle. I decided using [NSColor +colorWithPaternImage:] would be the easiest thing to use. There's a lot of code that makes the actually images and colors, so just assume they exist and are not nil.

int problem; // just to help explain things

float alpha;
NSImage *middleTinted;

NSRect drawRect = [self bounds];
drawRect.size.height = self.bounds.size.height - topTinted.size.height - bottomTinted.size.height;
drawRect.origin.y = topTinted.size.height;

NSColor* colorOne = [NSColor colorWithPatternImage:middleTinted];
NSColor* colorTwo = [colorOne colorWithAlphaComponent:alpha];

if(problem == 1)
{
    [colorOne set];
}
else if(problem == 2)
{
    [colorTwo set];
}

[NSBezierPath fillRect:drawRect];

Assuming problem == 1, it draws the correct image, in the correct location and with the correct size, but no alpha. (Obviously, since I didn't specify one.)

When problem == 2, I'd expect it to do the same thing, but have the correct alpha value. Instead of this, I get a black box.

Is there a solution that will repeat the image with the correct alpha? I figure I could just draw the image manually in a loop, but I'd prefer a more reasonable solution if one exists.


问:
Is this running truly parallel?
I'm using requests and threading in python to do some stuff. My question is: Is this code running truly multithreaded and is it safe to use? I'm experiencing some slow down over time. Note: I'm not using this exact code but mine is doing similar things.

import time
import requests

current_threads = 0
max_threads = 32

def doStuff():
    global current_threads
    r = requests.get('https://google.de')
    current_threads-=1

while True:
    while current_threads >= max_threads:
        time.sleep(0.05)

    thread = threading.Thread(target = doStuff)
    thread.start()

    current_threads+=1
```

答:
Sure, you're running multiple threads and provided they're not accessing/mutating the same resources you're probably "safe".

Whenever I'm accessing external resources (ie, using requests), I always recommend asyncio over vanilla threading, as it allows custom context switching (everywhere you have an "await" you switch contexts, whereas in vanilla threading switching between threads is determined by the OS and might not be optimal) and reduced overhead (you're only using ONE thread).

Title: Is this running truly parallel?


问:
How do I animate a banner only using CSS, the timeline is messed up
I am trying to create a banner using only CSS and no JS. If I were to use a JS library such as GreenSock or Create if would be easier to set the timing but I have no idea how to do it using only keyframes.

I have tried to set the opacity of the items in order to show the ones beneath but it's not working out.

```<code>    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

.banner{
    position: relative;
    width: 100vw;
}

.first {
    background-color: black;
    position: absolute;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100vw;
    height: 100vh;
}

@keyframes first {
    0% {opacity: 0;}
    50% {opacity: 1;}
    100% {opacity: 0;}
  }

.first img {
    width: 90%;
    position: absolute;
    object-fit: contain;
    top: 30%;
    animation-name: first-screen;
    animation-duration: 2s;
    animation-timing-function: ease;
}

.bg {
width: 100vw;
height: 100vh;
margin-top: -10%;
 overflow: hidden;
 object-fit: cover;
 object-position: center;
 animation-name: bg;
 animation-duration: 3s;
 animation-delay: 2s;
}

@keyframes bg {
    0% {opacity: 0;}
    100% {opacity: 1;}
  }

.offer{
    display: flex;
    width: 100vw;
    object-fit: contain;
    position: fixed;
    bottom:0
}

.copy {
    position: absolute;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100vw;
    height: 100vh;
    animation-name: copy;
    animation-duration: 3s;
    animation-delay: 2s;

}

@keyframes copy {
    0% {opacity: 0;}
    50% {opacity: 1;}
    100% {opacity: 0;}
  }

.headline {
    width: 70%;
    position: absolute;
    object-fit: contain;
    top: 10%;
}

.subheadline {
    width: 70%;
    position: absolute;
    object-fit: contain;
    top: 22%;
}
</code>```

I need the first-screen to fade in and that screen needs to show for two sec and fade away, immediately then the background will fade in in and last for three seconds while the copy also fade in at a different pace. In this case all my elements except the background end up showing at the end of the animation.

This is the html:

```<code>                <div class="first-screen"><img src="img/1st_frame.jpg"/></div>
                <div class="copy">
                    <img src="img/headline.png" class="headline"/>
                    <img src="img/subheadline.png" class="subheadline" />
                </div>
                <img src="img/offer.png" class="offer" />
                <img src="img/bg.jpg" class="bg"/>
</code>```

答:
I kind of fix it by setting the same duration for all the animations and then using percents to show and hide the items but still there are elements that should show up and fade at the same time and have different timing even though the CSS keyframes and properties are the same. The bg and the headlines should both fade at the same time instead only the headlines fade. Does anyone know why?</p>

```<code>html {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

.interstitial {
    position: relative;
    width: 100vw;
}

.first {
    background-color: black;
    position: absolute;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100vw;
    height: 100vh;
}

.first img {
    width: 90%;
    position: absolute;
    object-fit: contain;
    top: 30%;
    animation-name: first-screen;
    animation-duration: 5s;
    animation-timing-function: ease-in;
    animation-fill-mode: forwards;
    animation-iteration-count: infinite;
}

@keyframes first {
    0% {
        opacity: 0.5;
    }

    20% {
        opacity: 1;
    }

    40% {
        opacity: 0
    }

    100% {
        opacity: 0;
    }
}

.bg {
    width: 100vw;
    height: 100vh;
    margin-top: -20%;
    overflow: hidden;
    object-fit: cover;
    object-position: center;
    animation-name: bg;
    animation-duration: 5s;
    animation-timing-function: ease;
    animation-iteration-count: infinite;
    animation-fill-mode: forwards;
    z-index: 0
}

@keyframes bg {
    0% {
        opacity: 0;
    }

    40% {
        opacity: 0;
    }

    100% {
        opacity: 1;
    }
}

.offer {
    display: flex;
    width: 100vw;
    object-fit: contain;
    position: fixed;
    bottom: 0;
    z-index: 999;
}

.copy {
    position: absolute;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100vw;
    height: 100vh;
    animation-name: headlines;
    animation-duration: 5s;
    animation-timing-function: ease;
    animation-iteration-count: infinite;
    animation-fill-mode: forwards;

}

@keyframes headlines {
    0% {
        opacity: 0;
    }

    40% {
        opacity: 0;
    }

    100% {
        opacity: 1;
    }
}

.headline {
    width: 70%;
    position: absolute;
    object-fit: contain;
    top: 10%;
}

.subheadline {
    width: 70%;
    position: absolute;
    object-fit: contain;
    top: 22%;
}
</code>```

Body:
I am trying to create a banner using only CSS and no JS. If I were to use a JS library such as GreenSock or Create if would be easier to set the timing but I have no idea how to do it using only keyframes.

I have tried to set the opacity of the items in order to show the ones beneath but it's not working out.

    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

.banner{
    position: relative;
    width: 100vw;
}

.first {
    background-color: black;
    position: absolute;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100vw;
    height: 100vh;
}

@keyframes first {
    0% {opacity: 0;}
    50% {opacity: 1;}
    100% {opacity: 0;}
  }

.first img {
    width: 90%;
    position: absolute;
    object-fit: contain;
    top: 30%;
    animation-name: first-screen;
    animation-duration: 2s;
    animation-timing-function: ease;
}

.bg {
width: 100vw;
height: 100vh;
margin-top: -10%;
 overflow: hidden;
 object-fit: cover;
 object-position: center;
 animation-name: bg;
 animation-duration: 3s;
 animation-delay: 2s;
}

@keyframes bg {
    0% {opacity: 0;}
    100% {opacity: 1;}
  }

.offer{
    display: flex;
    width: 100vw;
    object-fit: contain;
    position: fixed;
    bottom:0
}

.copy {
    position: absolute;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100vw;
    height: 100vh;
    animation-name: copy;
    animation-duration: 3s;
    animation-delay: 2s;

}

@keyframes copy {
    0% {opacity: 0;}
    50% {opacity: 1;}
    100% {opacity: 0;}
  }

.headline {
    width: 70%;
    position: absolute;
    object-fit: contain;
    top: 10%;
}

.subheadline {
    width: 70%;
    position: absolute;
    object-fit: contain;
    top: 22%;
}

I need the first-screen to fade in and that screen needs to show for two sec and fade away, immediately then the background will fade in in and last for three seconds while the copy also fade in at a different pace. In this case all my elements except the background end up showing at the end of the animation.

This is the html:

Body:
I kind of fix it by setting the same duration for all the animations and then using percents to show and hide the items but still there are elements that should show up and fade at the same time and have different timing even though the CSS keyframes and properties are the same. The bg and the headlines should both fade at the same time instead only the headlines fade. Does anyone know why?

html {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

.interstitial {
    position: relative;
    width: 100vw;
}

.first {
    background-color: black;
    position: absolute;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100vw;
    height: 100vh;
}

.first img {
    width: 90%;
    position: absolute;
    object-fit: contain;
    top: 30%;
    animation-name: first-screen;
    animation-duration: 5s;
    animation-timing-function: ease-in;
    animation-fill-mode: forwards;
    animation-iteration-count: infinite;
}

@keyframes first {
    0% {
        opacity: 0.5;
    }

    20% {
        opacity: 1;
    }

    40% {
        opacity: 0
    }

    100% {
        opacity: 0;
    }
}

.bg {
    width: 100vw;
    height: 100vh;
    margin-top: -20%;
    overflow: hidden;
    object-fit: cover;
    object-position: center;
    animation-name: bg;
    animation-duration: 5s;
    animation-timing-function: ease;
    animation-iteration-count: infinite;
    animation-fill-mode: forwards;
    z-index: 0
}

@keyframes bg {
    0% {
        opacity: 0;
    }

    40% {
        opacity: 0;
    }

    100% {
        opacity: 1;
    }
}

.offer {
    display: flex;
    width: 100vw;
    object-fit: contain;
    position: fixed;
    bottom: 0;
    z-index: 999;
}

.copy {
    position: absolute;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100vw;
    height: 100vh;
    animation-name: headlines;
    animation-duration: 5s;
    animation-timing-function: ease;
    animation-iteration-count: infinite;
    animation-fill-mode: forwards;

}

@keyframes headlines {
    0% {
        opacity: 0;
    }

    40% {
        opacity: 0;
    }

    100% {
        opacity: 1;
    }
}

.headline {
    width: 70%;
    position: absolute;
    object-fit: contain;
    top: 10%;
}

.subheadline {
    width: 70%;
    position: absolute;
    object-fit: contain;
    top: 22%;
}


问:
Running a child process as the parent process
Is it possible to run a child process as a parent process?

My directory structure looks like this:

app/program.exe

app/bin/internal.exe

app/bin/something.dll

The program.exe just executes the internal.exe with some arguments.

#include <stdio.h>
#include <process.h>

int main(void) {
    _execl(".\\bin\\internal.exe",
        "internal.exe", "some args", NULL);

    return 0;
}
```

The arguments are important; without them internal.exe won't do anything.

This mostly works alright, but doesn't integrate well with the taskbar. The program shows up in the taskbar as internal.exe, and pinning it to the taskbar isn't useful, because clicking on the pinned shortcut will execute internal.exe without the arguments, and it will close immediately.

I'd like it to show up as program.exe on the taskbar, so that pinning it to the taskbar pins the working "launcher" instead of the internal part.

Is this possible?

答:
You can't change the child to become the parent in terms of actual processes. The taskbar works at a higher level and gives you more control.

MSDN says:

The following items describe common scenarios that require an explicit AppUserModelID. They also point out cases where multiple explicit AppUserModelIDs should be used.

...

Cooperative or chained processes that to the user are part of the same application should have the same AppUserModelID applied to each process. Examples include games with a launcher process (chained) and Microsoft Windows Media Player, which has a first-run/setup experience running in one process and the main application running in another process (cooperative).

If you are not the author of the child application things become complicated.

If it is Java or some other type of framework it should have the IsHostApp value set. If not, you can try playing with UseExecutableForTaskbarGroupIcon and TaskbarGroupIcon but these will not change the AppUserModelID. Setting NoStartPage will prevent the user from pinning the child application.

If you know how to find the window of the child application you can call SHGetPropertyStoreForWindow in the parent and set the id to the same id as your parent process and/or set the System.AppUserModel.Relaunch* properties.

Body:
Is it possible to run a child process as a parent process?

My directory structure looks like this:

app/program.exe

app/bin/internal.exe

app/bin/something.dll

The program.exe just executes the internal.exe with some arguments.

#include <stdio.h>
#include <process.h>

int main(void) {
    _execl(".\\bin\\internal.exe",
        "internal.exe", "some args", NULL);

    return 0;
}

The arguments are important; without them internal.exe won't do anything.

This mostly works alright, but doesn't integrate well with the taskbar. The program shows up in the taskbar as internal.exe, and pinning it to the taskbar isn't useful, because clicking on the pinned shortcut will execute internal.exe without the arguments, and it will close immediately.

I'd like it to show up as program.exe on the taskbar, so that pinning it to the taskbar pins the working "launcher" instead of the internal part.

Is this possible?


问:
After a few seconds, one turtle stops and the other goes faster
After weeks of trying, I have not come up with a solution to this issue, in which one turtle comes to a complete stop and the other goes 2x - 3x faster. How can I fix this? You must move them both around for a little bit to encounter the issue. Also this is on the site: repl.it

I have tried moving the wn.listen() command but that only switched which turtle stopped and which one didn't. I have unsuccessfully tried to switch the forward() command to goto() and I have tried to use direction specific movement (also unsuccessfully):

```<code>import turtle
import sys
player1 = turtle.Turtle()
player1.up()
player1.goto(0,350)
player1.right(90)
player1.down()
player2 = turtle.Turtle()
wn = turtle.Screen()

#preGame setup
player2.up()
player2.goto(0,-350)
player2.left(90)
player2.down()
player2.color("blue")
player1.color("red")
#main game loop
player1.speed(0)
player2.speed(0)
k = 0

def kr():
  player1.left(90)
def kl():
  player1.right(90)
wn.onkey(kr, "d")
wn.onkey(kl, "a")
def k1():
  player2.right(90)
def k2():
  player2.left(90)
wn.onkey(k1, "k")
wn.onkey(k2, "l")

wn.listen()

while True:
  player1.forward(1)
  player2.forward(1)
  while player1.xcor() < (-350) or player1.xcor() > (350) or player1.ycor() > (350) or  player1.ycor() < (-350):
   player1.back(30)
  while player2.xcor() < (-350) or player2.xcor() > (350) or player2.ycor() > (350) or player2.ycor() < (-350):
   player2.back(30)
   if player1.pos() == player2.pos():
     print ("DONT CRASH INTO THE OTHER PLAYER")
     sys.exit()
</code>```

I expected them both to continue moving indefinitely, but one always stops, and the other is going 2x the speed.

答:
Move the keylisteners outside your loop - having them inside the while loop will reattach them and redefine the functions all the time and confuse turtle.

You need to set them up once not every few milliseconds:

```<code>import turtle
player1 = turtle.Turtle()
player2 = turtle.Turtle()
player1.goto(350, 0)
player2.goto(-350, 0)
player1.right(180)
wn = turtle.Screen()
def kl():
    player1.left(90)
def kr():
    player1.right(90)
def k1():
    player2.right(90)
def k2():
    player2.left(90)
wn.onkey(kl, "d")  # changed to lowercase
wn.onkey(kr, "a")
wn.onkey(k1, "j")  # changed to other letters
wn.onkey(k2, "l")

wn.listen()

while True: # not changing k so just use while True
    player1.forward(1)  # changed speed
    player2.forward(1)
</code>```

Body:
After weeks of trying, I have not come up with a solution to this issue, in which one turtle comes to a complete stop and the other goes 2x - 3x faster. How can I fix this? You must move them both around for a little bit to encounter the issue. Also this is on the site: repl.it

I have tried moving the wn.listen() command but that only switched which turtle stopped and which one didn't. I have unsuccessfully tried to switch the forward() command to goto() and I have tried to use direction specific movement (also unsuccessfully):

import turtle
import sys
player1 = turtle.Turtle()
player1.up()
player1.goto(0,350)
player1.right(90)
player1.down()
player2 = turtle.Turtle()
wn = turtle.Screen()

#preGame setup
player2.up()
player2.goto(0,-350)
player2.left(90)
player2.down()
player2.color("blue")
player1.color("red")
#main game loop
player1.speed(0)
player2.speed(0)
k = 0

def kr():
  player1.left(90)
def kl():
  player1.right(90)
wn.onkey(kr, "d")
wn.onkey(kl, "a")
def k1():
  player2.right(90)
def k2():
  player2.left(90)
wn.onkey(k1, "k")
wn.onkey(k2, "l")

wn.listen()

while True:
  player1.forward(1)
  player2.forward(1)
  while player1.xcor() < (-350) or player1.xcor() > (350) or player1.ycor() > (350) or  player1.ycor() < (-350):
   player1.back(30)
  while player2.xcor() < (-350) or player2.xcor() > (350) or player2.ycor() > (350) or player2.ycor() < (-350):
   player2.back(30)
   if player1.pos() == player2.pos():
     print ("DONT CRASH INTO THE OTHER PLAYER")
     sys.exit()

I expected them both to continue moving indefinitely, but one always stops, and the other is going 2x the speed.

Body:
Move the keylisteners outside your loop - having them inside the while loop will reattach them and redefine the functions all the time and confuse turtle.

You need to set them up once not every few milliseconds:

import turtle
player1 = turtle.Turtle()
player2 = turtle.Turtle()
player1.goto(350, 0)
player2.goto(-350, 0)
player1.right(180)
wn = turtle.Screen()
def kl():
    player1.left(90)
def kr():
    player1.right(90)
def k1():
    player2.right(90)
def k2():
    player2.left(90)
wn.onkey(kl, "d")  # changed to lowercase
wn.onkey(kr, "a")
wn.onkey(k1, "j")  # changed to other letters
wn.onkey(k2, "l")

wn.listen()

while True: # not changing k so just use while True
    player1.forward(1)  # changed speed
    player2.forward(1)


问:
Qt Scale Application Resolution
I created a Qt Application that is guaranteed to always run on a 4:3 monitor. I hardcoded 320x240 as the resolution and designed everything to look great.

Now the requirements changed and the app will run on 640x480 resolution (still 4:3).

Is there an easy way to scale up the entire application, such that everything doubles in size. In particular I would like to avoid having to manually change all button sizes, fonts, absolute positioning for overlays, etc.

I found a lot of answers about high DPI settings, but this has little to do with high DPI.

答:
You could use a QGraphicsView and embed your main widget in it. But your whole application has to apply the same factor to all the widgets.

A QGraphicsView allows you to zoom in.

For example:

```<code>class Widget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFixedSize(320, 420)

        layout = QFormLayout(self)
        btn = QPushButton("Button")
        btn.setFixedSize(100, 40)
        lineEdit = QLineEdit("Button")
        btn.setFixedSize(150, 20)
        layout.addRow("A button", btn)
        layout.addRow("A Line Edit", lineEdit)

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)

    w = Widget()
    view = QGraphicsView()
    scene = QGraphicsScene(0, 0, 1000, 1000)
    view.setFixedSize(320 * 2, 420 * 2)
    view.setScene(scene)
    view.scale(2, 2)
    proxy = scene.addWidget(w)
    view.centerOn(proxy)
    #w = Widget()
    #w.show()
    view.show()
    sys.exit(app.exec_())
</code>```

That's the quickiest way to proceed. The best way would be to refactor your whole code to be independent of the resolution (by using a configuration class, for example).

Title: Qt Scale Application Resolution

Body:
You could use a QGraphicsView and embed your main widget in it. But your whole application has to apply the same factor to all the widgets.

A QGraphicsView allows you to zoom in.

For example:

class Widget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFixedSize(320, 420)

        layout = QFormLayout(self)
        btn = QPushButton("Button")
        btn.setFixedSize(100, 40)
        lineEdit = QLineEdit("Button")
        btn.setFixedSize(150, 20)
        layout.addRow("A button", btn)
        layout.addRow("A Line Edit", lineEdit)

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)

    w = Widget()
    view = QGraphicsView()
    scene = QGraphicsScene(0, 0, 1000, 1000)
    view.setFixedSize(320 * 2, 420 * 2)
    view.setScene(scene)
    view.scale(2, 2)
    proxy = scene.addWidget(w)
    view.centerOn(proxy)
    #w = Widget()
    #w.show()
    view.show()
    sys.exit(app.exec_())

That's the quickiest way to proceed. The best way would be to refactor your whole code to be independent of the resolution (by using a configuration class, for example).


问:
How are pending exceptions managed by the RISC-V specification?
I'm working with the RISC-V specification and have a problem with pending interrupts/exceptions. I'm reading version 1.10 of volume II, published in May 7, 2017.

In section 3.1.14, describing the registers mip and mie it is said that:

Multiple simultaneous interrupts and traps at the same privilege level are handled in the following decreasing priority order: extern interrupts, software interrupts, timer interrupts, then finally any synchronous traps.

Up until that point I thought that exceptions, e.g. a misaligned instruction fetch exception on a JAL/JALR instruction, would be handled immediately by a trap because
 a) there is no way to continue executing your stream of instructions and
 b) there is no description of how an exception could be pending, i.e. there are no concepts described by the specification that could manage state for exceptions (for example registers like mip but for exceptions).

However, the paragraph cited above indicates something different.
My questions are:

Are there pending exceptions in RISC-V?

If yes, how is it possible that the exception still can be handled after an interrupt was handled and isn't forgotten?

答: In my option there are pending exceptions in RISCV-V, exactly by the reason you stated. It is a matter of semantics, if two events occur simultaneously, and one is deferred, it must be pending. One must cater for the possibility of an asynchronous event (interrupt) occurring simultaneously with a trap, and (by section 3.1.14) the asynchronous event has priority. Depending on the implementation one does not neccesarely need to save any state in this case, after the interrupt is handled, the instruction that triggers a trap is re-fetched, and duly leads to an exception. In my view section 3.1.14 describes the serialization of asynchronous events.</p>