问:
I need filtered values with index name from data
I am getting values what I have filtered from below script but not getting index name can help me to get with index name

chas = df.CHAS[df.CHAS>=1]

chas

for above script am getting result like below

142    1

152    1

154    1

155    1

I need result like below

```<code>CHAS
</code>```

141 1

152 1

154 1

155 1

答:
IIUC, you want to obtain a DataFrame instead of a Series. Simple, just ask for a list of 1 column:

```<code>df[['CHAS']][df.CHAS >=1]
</code>```

or even better:

```<code>df.loc[df['CHAS']>=1, [CHAS]]
</code>```

Body:
I am getting values what I have filtered from below script but not getting index name can help me to get with index name

chas = df.CHAS[df.CHAS>=1]

chas

for above script am getting result like below

142    1

152    1

154    1

155    1

I need result like below

CHAS

141 1

152 1

154 1

155 1

Body:
IIUC, you want to obtain a DataFrame instead of a Series. Simple, just ask for a list of 1 column:

df[['CHAS']][df.CHAS >=1]

or even better:

df.loc[df['CHAS']>=1, [CHAS]]


来源: stackexchange

问:
How do I control optical zoom in a running "Internet Explorer_Server" instance?
Windows Live Writer hosts an Internet Explorer control for editing, but there's no zoom control. I'd like to be able to send a zoom command to it. Since other apps host the IE browser, I'd think a utility that can send zoom commands to specific IE browser instances would be really handy, but I haven't found one.

I've seen there's a command, OLECMDID_OPTICAL_ZOOM, but I'm not sure how to send that command to it. Ideally I'd like to do this from C# or Powershell.

Note: The question is asking about controlling the zoom in a web browser control in a running application which I did not create, the main example being the editor surface in Windows Live Writer.

答:
It's quite easy....

You need to override the normal web browser control by creating a derived class.

That derived class, is then used to access the underlying activeX implementation of the parent web browser control, at which point you are able to access the 'ExecWB' method which is sadly not exposed publicly in the standard object.

Once you have this underlying object, you can simply then just provide any public methods you wish, for things like zoom, then pass those directly into the activeX interface.

I've written a smaple winforms program to show how it's done, I've uploaded the project to my MSN sky drive here:

Web browser zoom

ContentLicense: CC BY-SA 3.0


问:
Facebook debugger, Open Graph image tag - Facebook can't process certain images hosted on CloudFront
In the Facebook debugger, scraping the URL "https://www.givingway.com/organization/the-light-and-leadership-initiative" yields the error:

Corrupted Image

Provided og:image URL, https://d141thk7ygtt3c.cloudfront.net/043a7261-eb4f-48ce-9db6-8cbeefcf86df.jpg could not be processed as an image. It may be corrupted or may have an invalid format.

At the same time scraping the URL "https://www.givingway.com/organization/youth-in-action-against-poverty-and-hivaids-yaapha" works fine.

I can't figure out what causes this issue, as both pages:

are both produced from the same template, and share the same HTML structure.

have an og:image with the same structure.

<meta property="og:image" content="https://d141thk7ygtt3c.cloudfront.net/043a7261-eb4f-48ce-9db6-8cbeefcf86df.jpg" />

<meta property="og:image" content="https://d141thk7ygtt3c.cloudfront.net/b954d1df-57e6-4beb-acae-2916997a8e4e.jpg" />

Both images are JPEG.

Opening the image URL in a separate tab displays an image - which isn't the behavior I'd expect from a corrupted page.

This inconsistency occurs on various pages - certain pages are scraped successfully, while others aren't.

答:
If you upload a image file to s3 by library(ex. python boto3), please check ContentType arguments.

I uploaded a image file with boto3 without ContentType arguments, the content-type of file in metadata set default value "binary/octet-stream".

After i passed ContentType="image/png" argument, metadata set well and facebook og tag looks good. (description below image, not aside)

ContentLicense: CC BY-SA 4.0


问:
Asserting the values in array, array not having name
i'm trying to mock HttpMessageNotReadableException, below is the Junit 5 code.

```<code>@BeforeEach
    public void setUp()
    {
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    void testHandleHttpMessageNotReadableException() throws Exception {
        String jsonStr = "{\"name\":\"ABC\"}";

        mockMvc.perform(post("/abc/pqr-stu")
                .content(jsonStr)
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isBadRequest())
                //.andExpect(jsonPath("$").isArray())
                //.andExpect(jsonPath("$", hasSize(1)))
                .andExpect(jsonPath("$.field", hasItem("somethingId")))
                .andExpect(jsonPath("$.message", hasItem("Something is Mandatory")));

        verify(mockRepository, times(0)).save(any(ModelConfig.class));

    }
</code>```

after mocking uri : /abc/pqr-stu

below are the logs

```<code>MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /abc/pqr-stu
       Parameters = {}
          Headers = [Content-Type:"application/json", Content-Length:"491"]
             Body = <no character encoding set>
    Session Attrs = {}

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", Content-Type:"application/json"]
     Content type = application/json
             Body = [{"field":"somethingId","value":null,"message":"Something is Mandatory"}]
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 6.735 s <<< FAILURE! - in com.XXXControllerTest
[ERROR] testHandleHttpMessageNotReadableException  Time elapsed: 0.269 s  <<< FAILURE!
java.lang.AssertionError: No value at JSON path "$.field"
    at com.controller.XXXControllerTest.testHandleHttpMessageNotReadableException(XXXControllerTest.java:60)
Caused by: com.jayway.jsonpath.PathNotFoundException: Expected to find an object with property ['field'] in path $ but found 'net.minidev.json.JSONArray'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.
    at com.controller.XXXControllerTest.testHandleHttpMessageNotReadableException(XXXControllerTest.java:60)

Junit result
[INFO]
[INFO] Results:
[INFO]
[ERROR] Failures:
[ERROR]   XXXControllerTest.testHandleHttpMessageNotReadableException:60 No value at JSON path "$.field"
</code>```

so from the errors, i figured out that test case is getting failed while reading the response.

please help me out how to read/assert field,value,message

```<code>[{"field":"somethingId","value":null,"message":"Something is Mandatory"}]
</code>```

答:
below code works fine</p>

```<code>mockMvc.perform(post("/abc/pqr-stu")
                .content(emptyJson).header(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isBadRequest())
                .andExpect(jsonPath("$").isArray())
                .andExpect(jsonPath("$", hasSize(1)))
                .andExpect(jsonPath("$.[0].field", is("somethingId")))
                .andExpect(jsonPath("$.[0].message", is("Something is Mandatory")));
</code>```

Body:
i'm trying to mock HttpMessageNotReadableException, below is the Junit 5 code.

@BeforeEach
    public void setUp()
    {
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    void testHandleHttpMessageNotReadableException() throws Exception {
        String jsonStr = "{\"name\":\"ABC\"}";

        mockMvc.perform(post("/abc/pqr-stu")
                .content(jsonStr)
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isBadRequest())
                //.andExpect(jsonPath("$").isArray())
                //.andExpect(jsonPath("$", hasSize(1)))
                .andExpect(jsonPath("$.field", hasItem("somethingId")))
                .andExpect(jsonPath("$.message", hasItem("Something is Mandatory")));

        verify(mockRepository, times(0)).save(any(ModelConfig.class));

    }

after mocking uri : /abc/pqr-stu

below are the logs

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /abc/pqr-stu
       Parameters = {}
          Headers = [Content-Type:"application/json", Content-Length:"491"]
             Body = <no character encoding set>
    Session Attrs = {}

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", Content-Type:"application/json"]
     Content type = application/json
             Body = [{"field":"somethingId","value":null,"message":"Something is Mandatory"}]
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 6.735 s <<< FAILURE! - in com.XXXControllerTest
[ERROR] testHandleHttpMessageNotReadableException  Time elapsed: 0.269 s  <<< FAILURE!
java.lang.AssertionError: No value at JSON path "$.field"
    at com.controller.XXXControllerTest.testHandleHttpMessageNotReadableException(XXXControllerTest.java:60)
Caused by: com.jayway.jsonpath.PathNotFoundException: Expected to find an object with property ['field'] in path $ but found 'net.minidev.json.JSONArray'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.
    at com.controller.XXXControllerTest.testHandleHttpMessageNotReadableException(XXXControllerTest.java:60)

Junit result
[INFO]
[INFO] Results:
[INFO]
[ERROR] Failures:
[ERROR]   XXXControllerTest.testHandleHttpMessageNotReadableException:60 No value at JSON path "$.field"

so from the errors, i figured out that test case is getting failed while reading the response.

please help me out how to read/assert field,value,message

[{"field":"somethingId","value":null,"message":"Something is Mandatory"}]

Body:
below code works fine

mockMvc.perform(post("/abc/pqr-stu")
                .content(emptyJson).header(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isBadRequest())
                .andExpect(jsonPath("$").isArray())
                .andExpect(jsonPath("$", hasSize(1)))
                .andExpect(jsonPath("$.[0].field", is("somethingId")))
                .andExpect(jsonPath("$.[0].message", is("Something is Mandatory")));


问:
Select all values from last date that is shared between rows grouped by a value
I have a Postgresql table with a list of values for countries over time, and their continents. Values can be NULL. I’d like to get the sum for each continent over time, up to the latest date each continent has data for.

This is my table (view on DB Fiddle):

```<code>| continent | country | date       | value | id  |
| --------- | ------- | ---------- | ----- | --- |
| Europe    | Germany | 2020-05-25 | 10    | 1   |
| Europe    | Germany | 2020-05-26 | 11    | 2   |
| Europe    | Germany | 2020-05-27 | 12    | 3   |
| Europe    | Germany | 2020-05-28 | 13    | 4   |
| Europe    | Italy   | 2020-05-25 | 20    | 5   |
| Europe    | Italy   | 2020-05-26 | 21    | 6   |
| Europe    | Italy   | 2020-05-27 | 22    | 7   |
| Europe    | Italy   | 2020-05-28 | 23    | 8   |
| Europe    | France  | 2020-05-25 | 30    | 9   |
| Europe    | France  | 2020-05-26 | 31    | 10  |
| Europe    | France  | 2020-05-27 | 32    | 11  |
| Europe    | France  | 2020-05-28 | NULL  | 12  |
| Africa    | Congo   | 2020-05-25 | 40    | 13  |
| Africa    | Congo   | 2020-05-26 | 41    | 14  |
| Africa    | Congo   | 2020-05-27 | NULL  | 15  |
</code>```

And this is what I’d like to get back. Note that the Europe includes data up to the 27th, because France has no data for the 28th, and Africa up to the 26th, because that’s the last date its countries have data for.

```<code>| continent | date       | value |
| --------- | ---------- | ----- |
| Europe    | 2020-05-27 | 66    |
| Africa    | 2020-05-26 | 41    |
| Europe    | 2020-05-26 | 63    |
| Africa    | 2020-05-25 | 40    |
| Europe    | 2020-05-25 | 60    |
</code>```

I managed to almost get there by including the number of countries per continent that have data on each date.

SELECT
    countries.continent,
    countries.date,
    SUM(countries.value) AS value,
    COUNT(countries.country) AS countries_count
FROM
    countries
WHERE
    countries.value IS NOT NULL
GROUP BY
    countries.continent,
    countries.date
ORDER BY
    countries.date DESC,
    countries.continent;
```

```| continent | date       | value | countries_count |
| --------- | ---------- | ----- | --------------- |
| Europe    | 2020-05-28 | 36    | 2               |
| Europe    | 2020-05-27 | 66    | 3               |
| Africa    | 2020-05-26 | 41    | 1               |
| Europe    | 2020-05-26 | 63    | 3               |
| Africa    | 2020-05-25 | 40    | 1               |
| Europe    | 2020-05-25 | 60    | 3               |
```

<p>I also managed to get the number of countries per continent.</p>

<pre class="lang-sql prettyprint-override"><code>SELECT
    countries.continent,
    COUNT(DISTINCT countries.country) as number_of_countries
FROM
    countries
GROUP BY
    countries.continent;
</code>```

```<code>| continent | number_of_countries |
| --------- | ------------------- |
| Africa    | 1                   |
| Europe    | 3                   |
</code>```

I’m stuck on how to combine the two queries to filter out rows that haven’t got the full number of countries for the continent (e. g. select rows where countries_count is 3 for Europe and 1 for Africa.

This is the end result I’d like to get back:

```<code>| continent | date       | value |
| --------- | ---------- | ----- |
| Europe    | 2020-05-27 | 66    |
| Africa    | 2020-05-26 | 41    |
| Europe    | 2020-05-26 | 63    |
| Africa    | 2020-05-25 | 40    |
| Europe    | 2020-05-25 | 60    |
</code>```

Or maybe there’s a completely different way to go about this?

View on DB Fiddle

答:
You can filter with a having clause to exclude groups where any country is null

```<code>SELECT
    continent,
    date,
    SUM(value) AS value
FROM countries
GROUP BY continent, date
HAVING BOOL_AND(value is not null)
ORDER BY date DESC, continent
</code>```

Body:
I have a Postgresql table with a list of values for countries over time, and their continents. Values can be NULL. I’d like to get the sum for each continent over time, up to the latest date each continent has data for.

This is my table (view on DB Fiddle):

| continent | country | date       | value | id  |
| --------- | ------- | ---------- | ----- | --- |
| Europe    | Germany | 2020-05-25 | 10    | 1   |
| Europe    | Germany | 2020-05-26 | 11    | 2   |
| Europe    | Germany | 2020-05-27 | 12    | 3   |
| Europe    | Germany | 2020-05-28 | 13    | 4   |
| Europe    | Italy   | 2020-05-25 | 20    | 5   |
| Europe    | Italy   | 2020-05-26 | 21    | 6   |
| Europe    | Italy   | 2020-05-27 | 22    | 7   |
| Europe    | Italy   | 2020-05-28 | 23    | 8   |
| Europe    | France  | 2020-05-25 | 30    | 9   |
| Europe    | France  | 2020-05-26 | 31    | 10  |
| Europe    | France  | 2020-05-27 | 32    | 11  |
| Europe    | France  | 2020-05-28 | NULL  | 12  |
| Africa    | Congo   | 2020-05-25 | 40    | 13  |
| Africa    | Congo   | 2020-05-26 | 41    | 14  |
| Africa    | Congo   | 2020-05-27 | NULL  | 15  |

And this is what I’d like to get back. Note that the Europe includes data up to the 27th, because France has no data for the 28th, and Africa up to the 26th, because that’s the last date its countries have data for.

| continent | date       | value |
| --------- | ---------- | ----- |
| Europe    | 2020-05-27 | 66    |
| Africa    | 2020-05-26 | 41    |
| Europe    | 2020-05-26 | 63    |
| Africa    | 2020-05-25 | 40    |
| Europe    | 2020-05-25 | 60    |

I managed to almost get there by including the number of countries per continent that have data on each date.

SELECT
    countries.continent,
    countries.date,
    SUM(countries.value) AS value,
    COUNT(countries.country) AS countries_count
FROM
    countries
WHERE
    countries.value IS NOT NULL
GROUP BY
    countries.continent,
    countries.date
ORDER BY
    countries.date DESC,
    countries.continent;

| continent | date       | value | countries_count |
| --------- | ---------- | ----- | --------------- |
| Europe    | 2020-05-28 | 36    | 2               |
| Europe    | 2020-05-27 | 66    | 3               |
| Africa    | 2020-05-26 | 41    | 1               |
| Europe    | 2020-05-26 | 63    | 3               |
| Africa    | 2020-05-25 | 40    | 1               |
| Europe    | 2020-05-25 | 60    | 3               |

I also managed to get the number of countries per continent.

SELECT
    countries.continent,
    COUNT(DISTINCT countries.country) as number_of_countries
FROM
    countries
GROUP BY
    countries.continent;

| continent | number_of_countries |
| --------- | ------------------- |
| Africa    | 1                   |
| Europe    | 3                   |

I’m stuck on how to combine the two queries to filter out rows that haven’t got the full number of countries for the continent (e. g. select rows where countries_count is 3 for Europe and 1 for Africa.

This is the end result I’d like to get back:

| continent | date       | value |
| --------- | ---------- | ----- |
| Europe    | 2020-05-27 | 66    |
| Africa    | 2020-05-26 | 41    |
| Europe    | 2020-05-26 | 63    |
| Africa    | 2020-05-25 | 40    |
| Europe    | 2020-05-25 | 60    |

Or maybe there’s a completely different way to go about this?

View on DB Fiddle

Body:
You can filter with a having clause to exclude groups where any country is null

SELECT
    continent,
    date,
    SUM(value) AS value
FROM countries
GROUP BY continent, date
HAVING BOOL_AND(value is not null)
ORDER BY date DESC, continent


问:
Execute closure from another method in an extension Swift
I have a class that is a delegate to a custom modal view, therefore it has a method for when the modal has been dismissed. I am extending that class and in the extension I have a method that accepts a completion closure.

I can't write in the main implementation of the class or the modal's implementation - only the extension.

I want to execute the closure when the modal is dismissed, but I can't seem to figure it out on my own. Is it even possible?

Here is an example of what I want to do:

```<code>extension MyClass {
    func method(completion: (Int) -> ()) {
        // showing the modal
    }
}

extension MyClass: ModalDelegate {
    func modalDismissed() {
        // here I want to execute the completion passed to method()
    }
}
</code>```

答:
Assign the completion as a variable to a MyClass's property in method and call it in modalDismissed:

class MyClass {
    var classCompletion: (() -> ())?
}

extension MyClass {
    func method(completion: @escaping () -> ()) {
        classCompletion = completion
    }
}

extension MyClass: ModalDelegate {
    func modalDismissed() {
        classCompletion?()
    }
}
```

<p>Update: If you can't "write in the main implementation of the class", here's a method using <code>static</code> property. This is a hack and has many limitations but does the work. Otherwise without writing to the main implementation you can't do anything.</p>

<pre class="lang-swift prettyprint-override"><code>extension MyClass {
    static var classCompletion: (() -> ())?

    func method(completion: @escaping () -> ()) {
        MyClass.classCompletion = completion
    }
}

extension MyClass: ModalDelegate {
    func modalDismissed() {
        MyClass.classCompletion?()
    }
}
</code>```

Body:
I have a class that is a delegate to a custom modal view, therefore it has a method for when the modal has been dismissed. I am extending that class and in the extension I have a method that accepts a completion closure.

I can't write in the main implementation of the class or the modal's implementation - only the extension.

I want to execute the closure when the modal is dismissed, but I can't seem to figure it out on my own. Is it even possible?

Here is an example of what I want to do:

extension MyClass {
    func method(completion: (Int) -> ()) {
        // showing the modal
    }
}

extension MyClass: ModalDelegate {
    func modalDismissed() {
        // here I want to execute the completion passed to method()
    }
}

Body:
Assign the completion as a variable to a MyClass's property in method and call it in modalDismissed:

class MyClass {
    var classCompletion: (() -> ())?
}

extension MyClass {
    func method(completion: @escaping () -> ()) {
        classCompletion = completion
    }
}

extension MyClass: ModalDelegate {
    func modalDismissed() {
        classCompletion?()
    }
}

Update: If you can't "write in the main implementation of the class", here's a method using static property. This is a hack and has many limitations but does the work. Otherwise without writing to the main implementation you can't do anything.

extension MyClass {
    static var classCompletion: (() -> ())?

    func method(completion: @escaping () -> ()) {
        MyClass.classCompletion = completion
    }
}

extension MyClass: ModalDelegate {
    func modalDismissed() {
        MyClass.classCompletion?()
    }
}


问:
PHP braces { } replace <?php ?>?
I've seen in someones source code they load template.tpl and inside is ...value="{$phcode}"...
does {$phcode} replace <?php $phcode ?>

I don't find any reference in php manual.

答:
Most likely it is Smarty template.

More info here: http://www.smarty.net/syntax_comparison

Title: PHP braces { } replace <?php ?>?


问:
Deploying Redmine docker container to App Services
I would like to deploy Redmine Docker image to Azure App Services and point it to the MySql instance deployed to Azure Database for MySQL servers. This would give me a fully managed architecture. I have created an instance of MySql and can connect to it from my local PC using MySql Workbench. Unfortunately the Redmine Docker image I am deploying to App Services fails to start. The log says: Docker on instance ******* experienced container start failures. The application log indicates there is an issue with Startup Command. After reviewing the container crash logs I have noticed that my startup command is appended to the docker run command:

docker run -d -p 6390:3000 --name redminetest_0_3d4d8283 -e WEBSITES_ENABLE_APP_SERVICE_STORAGE=false -e WEBSITE_SITE_NAME=redminetest -e WEBSITE_AUTH_ENABLED=False -e PORT=3000 -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=redminetest.azurewebsites.net -e WEBSITE_INSTANCE_ID=c0f955200062b837a8b06271f039c1d9a6aa1309ada101b0e47bf9c23c0ba3a3 redmine:latest --name MyRedmine -e REDMINE_DB_MYSQL=51.140.184.11 -e REDMINE_DB_PORT=3306 -e REDMINE_DB_USERNAME=special@mysqlredmine -e REDMINE_DB_PASSWORD=Sp3c1al! redmine

I can see straight away that --name argument and image name/tag was duplicated by my command. This is something I can correct but how can I append my environment variables before the image name/tag (redmine:latest) ?

UPDATE:

Please see the screenshot below. This demonstrates the issue. My environment variables were appended after the image name.

答:
The correct format of docker run is below:-

```<code>Usage:  docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
</code>```

According to which you should pass Image Name in the end and all other options like -p, -e, -d, etc. should be pass before Image Name.

Below is the correct command:

```<code>docker run -d -p 6390:3000 --name redminetest_0_3d4d8283 -e WEBSITES_ENABLE_APP_SERVICE_STORAGE=false -e WEBSITE_SITE_NAME=redminetest -e WEBSITE_AUTH_ENABLED=False -e PORT=3000 -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=redminetest.azurewebsites.net -e WEBSITE_INSTANCE_ID=c0f955200062b837a8b06271f039c1d9a6aa1309ada101b0e47bf9c23c0ba3a3 -e REDMINE_DB_MYSQL=51.140.184.11 -e REDMINE_DB_PORT=3306 -e REDMINE_DB_USERNAME=special@mysqlredmine -e REDMINE_DB_PASSWORD=Sp3c1al! redmine:latest
</code>```

Body:
The correct format of docker run is below:-

Usage:  docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

According to which you should pass Image Name in the end and all other options like -p, -e, -d, etc. should be pass before Image Name.

Below is the correct command:

docker run -d -p 6390:3000 --name redminetest_0_3d4d8283 -e WEBSITES_ENABLE_APP_SERVICE_STORAGE=false -e WEBSITE_SITE_NAME=redminetest -e WEBSITE_AUTH_ENABLED=False -e PORT=3000 -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=redminetest.azurewebsites.net -e WEBSITE_INSTANCE_ID=c0f955200062b837a8b06271f039c1d9a6aa1309ada101b0e47bf9c23c0ba3a3 -e REDMINE_DB_MYSQL=51.140.184.11 -e REDMINE_DB_PORT=3306 -e REDMINE_DB_USERNAME=special@mysqlredmine -e REDMINE_DB_PASSWORD=Sp3c1al! redmine:latest


问:
How to make a navbar that could change size individually on mouse hover?

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

Responsive Navbar with Links of Same Width

Try to resize the browser window to see the responsive effect.

    Home
    Search
    Contact
    Login

```

enter image description here

In the image, when I hover to the home in navbar, all the height of the nav bar changed same with the one that is hovered. My question is, Is there a way to make the size change individually on hover, so when I hover the home link, it only change the height of the home link?

答:
Just removed background color from navbar and give to .navbar a

* {box-sizing: border-box}
body {font-family: Arial, Helvetica, sans-serif;}

.navbar {
  width: 100%;
  overflow: auto;
}

.navbar a {
  float: left;
  padding: 12px;
  background-color: #555;
  color: white;
  text-decoration: none;
  font-size: 17px;
  width: 25%; /* Four links of equal widths */
  text-align: center;
}

.navbar a:hover {
  background-color: #000;
  height:1500px;
}

.navbar a.active {
  background-color: #4CAF50;
}

@media screen and (max-width: 500px) {
  .navbar a {
    float: none;
    display: block;
    width: 100%;
    text-align: left;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>

</style>
<body>

<h2>Responsive Navbar with Links of Same Width</h2>
<p>Try to resize the browser window to see the responsive effect.</p>

<div class="navbar">
  Home
  Search
  Contact
  Login
</div>

</body>
</html></code>```

Body:
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

Responsive Navbar with Links of Same Width

Try to resize the browser window to see the responsive effect.

    Home
    Search
    Contact
    Login

enter image description here

In the image, when I hover to the home in navbar, all the height of the nav bar changed same with the one that is hovered. My question is, Is there a way to make the size change individually on hover, so when I hover the home link, it only change the height of the home link?

Body:
Just removed background color from navbar and give to .navbar a

* {box-sizing: border-box}
body {font-family: Arial, Helvetica, sans-serif;}

.navbar {
  width: 100%;
  overflow: auto;
}

.navbar a {
  float: left;
  padding: 12px;
  background-color: #555;
  color: white;
  text-decoration: none;
  font-size: 17px;
  width: 25%; /* Four links of equal widths */
  text-align: center;
}

.navbar a:hover {
  background-color: #000;
  height:1500px;
}

.navbar a.active {
  background-color: #4CAF50;
}

@media screen and (max-width: 500px) {
  .navbar a {
    float: none;
    display: block;
    width: 100%;
    text-align: left;
  }
}

<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>

</style>
<body>

<h2>Responsive Navbar with Links of Same Width</h2>
<p>Try to resize the browser window to see the responsive effect.</p>

<div class="navbar">
  <a class="active" href="#">Home</a>
  <a href="#">Search</a>
  <a href="#">Contact</a>
  <a href="#">Login</a>
</div>

</body>
</html>


问:
error when changing the language top menu
I want to change the icon when the phone language changes.
Use this code to draw the top menu.
If the language changes to the phone, the exit icon will be flipped.

The icon would look like this if the language of the phone is Arabic and its natural form.

The icon will look like this if the language of the phone is English and it is not normal and inverted

```<code><?xml version="1.0" encoding="utf-8"?>
<menu
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/back"
        android:icon="@drawable/menue_backe"
        android:title="close"
        app:showAsAction="ifRoom"/>
</menu>

</code>```

```<code> public override bool OnCreateOptionsMenu(IMenu menu)
        {
            MenuInflater.Inflate(Resource.Menu.toolbar_menub, menu);
            return base.OnPrepareOptionsMenu(menu);
        }

        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            switch (item.ItemId)
            {
                case Resource.Id.back:
                    //do something

                    Finish();

                    return true;

            }
            return base.OnOptionsItemSelected(item);
        }
        //
</code>```

答:
You can have a try with follow ways to change Back button icon ：

```<code>ActionBar.SetDisplayHomeAsUpEnabled(true);
ActionBar.SetHomeAsUpIndicator(Resource.Mipmap.Icon); // here modify the image as your need
</code>```

Then modify it by laugnge in needed Activity :

```<code>protected override void OnResume()
{
    base.OnResume();

    string locale = Locale.Default.Language;
    //System.Console.WriteLine("-----"+locale);
    if (locale == "en")
    {
        ActionBar.SetDisplayHomeAsUpEnabled(true);
        ActionBar.SetHomeAsUpIndicator(Resource.Mipmap.Icon);
    }
    else
    {
        // other language
    }
}
</code>```

Body:
I want to change the icon when the phone language changes.
Use this code to draw the top menu.
If the language changes to the phone, the exit icon will be flipped.

The icon would look like this if the language of the phone is Arabic and its natural form.

The icon will look like this if the language of the phone is English and it is not normal and inverted

<?xml version="1.0" encoding="utf-8"?>
<menu
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/back"
        android:icon="@drawable/menue_backe"
        android:title="close"
        app:showAsAction="ifRoom"/>
</menu>

 public override bool OnCreateOptionsMenu(IMenu menu)
        {
            MenuInflater.Inflate(Resource.Menu.toolbar_menub, menu);
            return base.OnPrepareOptionsMenu(menu);
        }

        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            switch (item.ItemId)
            {
                case Resource.Id.back:
                    //do something

                    Finish();

                    return true;

            }
            return base.OnOptionsItemSelected(item);
        }
        //

Body:
You can have a try with follow ways to change Back button icon ：

ActionBar.SetDisplayHomeAsUpEnabled(true);
ActionBar.SetHomeAsUpIndicator(Resource.Mipmap.Icon); // here modify the image as your need

Then modify it by laugnge in needed Activity :

protected override void OnResume()
{
    base.OnResume();

    string locale = Locale.Default.Language;
    //System.Console.WriteLine("-----"+locale);
    if (locale == "en")
    {
        ActionBar.SetDisplayHomeAsUpEnabled(true);
        ActionBar.SetHomeAsUpIndicator(Resource.Mipmap.Icon);
    }
    else
    {
        // other language
    }
}


问:
Recursive tree search stops too early
I'm fairly new both to Python and Recursion, so I might have failed to find some relevant question but I haven't seen this exact one. I have a task to find children count for each name in the following list:

parents = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'V', 'W', 'X', 'Y', 'Z']

I have the following graph structure with parents above and children below (both in dict and in graph diagram form). Each letter counts as its own child, so the minimal child count is one.

data = {'G': ['F'], 'A': [], 'B': ['A'], 'C': ['A'], 'D': ['B', 'C'], 'E': ['D'], 'F': ['D'], 'X': [], 'Y': ['X', 'A'], 'Z': ['X'], 'V': ['Z', 'Y'], 'W': ['V']}

```<code>     A   X
    /|\ / \
   B C Y   Z
    \|  \ /
     D   V
    / \   \
   E   F   W
        \
         G
</code>```

I happen to know the right answers to the question

```<code>Node   Correct   My_answers
A       10          10
B       5           1          Incorrect
C       5           5
D       4           4
E       1           1
F       2           2
G       1           1
V       2           2
W       1           1
X       5           2          Incorrect
Y       3           3
Z       3           1          Incorrect
</code>```

I've tried to split the solution into two different functions then print out the answers using a simple loop. is_parent() checks whether par is a parent if cld and if I'm not mistaken this implies that cld is a child of par. I've done it that way due to the input format. Then I have child_count() that just spits out the counter by iterating over all the names and checking whether given potential child (pot_child) has par as its parent. My suspicion is that I have a problem in is_parent() that spits out False before it extensively checked all the tree branches therefore leading to child count below true ones.

Here is complete code I wrote, data and parents are defined above.

```<code>def is_parent(cld, par, data):
    if cld == par:
        return True
    else:
        for par_2 in data[cld]:
            x = is_parent(par_2,par,data)
        if len(data[cld]) == 0:
            x = False
    return x
def child_count(par, data):
    cnt = 0
    for pot_child in data:  # for each potential child
        cnt += 1 if is_parent(pot_child, par, data) else 0
    return cnt

for parent in parents:
    print(parent,":",child_count(parent, data))
</code>```

Sorry for overly long introduction to the question, but the essence of what I'm trying to ask is two-fold. First, is my general approach to the problem is suitable (two functions and then a loop), is there a faster, more readable alternative? Second, how do I prevent my recursive search algorithm from stopping the search too early (I've tried the visualizer but it stops after 1000 steps which is not enough for my algorithm)? How to make sure (in general) that recursive algorithm does not stop too early.

I would also greatly appreciate some free resources to get solidly acquainted with how to properly write recursion in Python

Thanks is advance!

答:
The error is here:

```<code>def is_parent(cld, par, data):
    if cld == par:
        return True
    else:
        for par_2 in data[cld]:
            x = is_parent(par_2,par,data) # <=== if x is True, return True!
            if x: break # <== quick fix
        if len(data[cld]) == 0:
            x = False
    return x
</code>```

The login behind is simple. If one of the graph "branches" leads to the parent, the result is True regardless of other branches

After some cleanup:

```<code>def is_parent(cld, par, data):
    return cld == par or any(is_parent(par_2,par,data) for par_2 in data[cld])
</code>```

The oriented graph must not contain loops. The title mentions a "tree", even if the example data is not strictly a tree, but it is loop free. If loops were allowed, a set of visited nodes would be needed to stop endless recursion.

(I'm sorry for not answering the question how to write recursive functions in general and what resources are recommended)

Title: Recursive tree search stops too early

Body:
I'm fairly new both to Python and Recursion, so I might have failed to find some relevant question but I haven't seen this exact one. I have a task to find children count for each name in the following list:

parents = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'V', 'W', 'X', 'Y', 'Z']

I have the following graph structure with parents above and children below (both in dict and in graph diagram form). Each letter counts as its own child, so the minimal child count is one.

data = {'G': ['F'], 'A': [], 'B': ['A'], 'C': ['A'], 'D': ['B', 'C'], 'E': ['D'], 'F': ['D'], 'X': [], 'Y': ['X', 'A'], 'Z': ['X'], 'V': ['Z', 'Y'], 'W': ['V']}

     A   X
    /|\ / \
   B C Y   Z
    \|  \ /
     D   V
    / \   \
   E   F   W
        \
         G

I happen to know the right answers to the question

Node   Correct   My_answers
A       10          10
B       5           1          Incorrect
C       5           5
D       4           4
E       1           1
F       2           2
G       1           1
V       2           2
W       1           1
X       5           2          Incorrect
Y       3           3
Z       3           1          Incorrect

I've tried to split the solution into two different functions then print out the answers using a simple loop. is_parent() checks whether par is a parent if cld and if I'm not mistaken this implies that cld is a child of par. I've done it that way due to the input format. Then I have child_count() that just spits out the counter by iterating over all the names and checking whether given potential child (pot_child) has par as its parent. My suspicion is that I have a problem in is_parent() that spits out False before it extensively checked all the tree branches therefore leading to child count below true ones.

Here is complete code I wrote, data and parents are defined above.

def is_parent(cld, par, data):
    if cld == par:
        return True
    else:
        for par_2 in data[cld]:
            x = is_parent(par_2,par,data)
        if len(data[cld]) == 0:
            x = False
    return x
def child_count(par, data):
    cnt = 0
    for pot_child in data:  # for each potential child
        cnt += 1 if is_parent(pot_child, par, data) else 0
    return cnt

for parent in parents:
    print(parent,":",child_count(parent, data))

Sorry for overly long introduction to the question, but the essence of what I'm trying to ask is two-fold. First, is my general approach to the problem is suitable (two functions and then a loop), is there a faster, more readable alternative? Second, how do I prevent my recursive search algorithm from stopping the search too early (I've tried the visualizer but it stops after 1000 steps which is not enough for my algorithm)? How to make sure (in general) that recursive algorithm does not stop too early.

I would also greatly appreciate some free resources to get solidly acquainted with how to properly write recursion in Python

Thanks is advance!

Body:
The error is here:

def is_parent(cld, par, data):
    if cld == par:
        return True
    else:
        for par_2 in data[cld]:
            x = is_parent(par_2,par,data) # <=== if x is True, return True!
            if x: break # <== quick fix
        if len(data[cld]) == 0:
            x = False
    return x

The login behind is simple. If one of the graph "branches" leads to the parent, the result is True regardless of other branches

After some cleanup:

def is_parent(cld, par, data):
    return cld == par or any(is_parent(par_2,par,data) for par_2 in data[cld])

The oriented graph must not contain loops. The title mentions a "tree", even if the example data is not strictly a tree, but it is loop free. If loops were allowed, a set of visited nodes would be needed to stop endless recursion.

(I'm sorry for not answering the question how to write recursive functions in general and what resources are recommended)


问:
.click event doesn't seem to fire
I've got the following code inside of a

答:
Seems to work for me, what browser are you using?

http://jsfiddle.net/YLCff/

Title: .click event doesn't seem to fire

Body: I've got the following code inside of a


问:
new-dfnsroot target : root target share wasnt found. namespace root target share should exist when creating new namespace
Trying to create new namespace folder using PowerShell
DFNS Root folder getting below error

new-dfnsroot target : root target share wasnt found. namespace root target share should exist when creating new namespace

答:
Share the path before you create the new namespace folder.

C:\DNSFolder\Home --> Share this folder for everyone


答: It's not PHP, it's using a templating language like Smarty.</p>

Title: PHP braces { } replace <?php ?>?

Body:
I've seen in someones source code they load template.tpl and inside is ...value="{$phcode}"...
does {$phcode} replace <?php $phcode ?>

I don't find any reference in php manual.


问:
MS-ACCESS / SQL - How to apply where clause in multiple conditions
```<code>SELECT Stock.*
FROM Stock
WHERE (
(
(Stock.ComputerPartNumber) In (SELECT [ComputerPartNumber] FROM [Stock] As Tmp GROUP BY [ComputerPartNumber] HAVING Count(*)=2)
)
AND
(
(Stock.EquipmentName)="EquipmentA" Or (Stock.EquipmentName)="EquipmentB")
)
OR (
(
(Stock.ComputerPartNumber) In (SELECT [ComputerPartNumber] FROM [Stock] As Tmp GROUP BY [ComputerPartNumber] HAVING Count(*)=1)
)
AND (
(Stock.EquipmentName)="EquipmentA" Or (Stock.EquipmentName)="EquipmentB"
)
);
</code>```

I am using the above SQL to achieve below 3 items:-

Find out all of the ComputerPartNumber which used by EquipmentA and/or EquipmentB only

Filter out the query result if the ComputerPartNumber used by equipment other than EquipmentA and EquipmentB.

If the ComputerPartNumber is used by both EquipmentA and EquipmentC, filter out the result also.

However the item 3 cannot be filtered out successfully. What should I do in order to achieve the item3?
Table and Query snapshots are attached. Thanks in advance!

Table

Query

答:
What you need to do is to check if the total number of times a part is used in all pieces of Equipment is equal to the total number of times a part is used by either Equipment A or B:

```<code>SELECT S.StorageID, S.ComputerPartNumber, S.EquipmentName, S.Result
FROM Stock AS S
WHERE
(SELECT COUNT(*) FROM Stock AS S1 WHERE S1.ComputerPartNumber=S.ComputerPartNumber)
=(SELECT COUNT(*) FROM Stock AS S2 WHERE S2.ComputerPartNumber=S.ComputerPartNumber AND S2.EquipmentName IN("EquipmentA","EquipmentB"))
</code>```

Regards,

Body:
SELECT Stock.*
FROM Stock
WHERE (
(
(Stock.ComputerPartNumber) In (SELECT [ComputerPartNumber] FROM [Stock] As Tmp GROUP BY [ComputerPartNumber] HAVING Count(*)=2)
)
AND
(
(Stock.EquipmentName)="EquipmentA" Or (Stock.EquipmentName)="EquipmentB")
)
OR (
(
(Stock.ComputerPartNumber) In (SELECT [ComputerPartNumber] FROM [Stock] As Tmp GROUP BY [ComputerPartNumber] HAVING Count(*)=1)
)
AND (
(Stock.EquipmentName)="EquipmentA" Or (Stock.EquipmentName)="EquipmentB"
)
);

I am using the above SQL to achieve below 3 items:-

Find out all of the ComputerPartNumber which used by EquipmentA and/or EquipmentB only

Filter out the query result if the ComputerPartNumber used by equipment other than EquipmentA and EquipmentB.

If the ComputerPartNumber is used by both EquipmentA and EquipmentC, filter out the result also.

However the item 3 cannot be filtered out successfully. What should I do in order to achieve the item3?
Table and Query snapshots are attached. Thanks in advance!

Table

Query

Body:
What you need to do is to check if the total number of times a part is used in all pieces of Equipment is equal to the total number of times a part is used by either Equipment A or B:

SELECT S.StorageID, S.ComputerPartNumber, S.EquipmentName, S.Result
FROM Stock AS S
WHERE
(SELECT COUNT(*) FROM Stock AS S1 WHERE S1.ComputerPartNumber=S.ComputerPartNumber)
=(SELECT COUNT(*) FROM Stock AS S2 WHERE S2.ComputerPartNumber=S.ComputerPartNumber AND S2.EquipmentName IN("EquipmentA","EquipmentB"))

Regards,


问:
Declare and initialize variable for assigning list of anonymous types
I try to join two tables:

```<code>var data = from request in context.Requests
                        join account in context.AutolineAccts
                            on request.PkRequest.ToString() equals account.AccountCode
                        select new
                        {
                            ID = request.PkRequest.ToString(),
                            Location = request.FkLocation,
                            RequestDate = request.RequestDate.Value,
                            Requestor = request.FkRequestor,
                            DebitorNr = request.FkDebitor.ToString(),
                            NewDebit = request.Debit.ToString(),
                            ApprovalStatus = request.ApprovalStatus.ToString(),
                            RecommendationStatus = request.RecommendationStatus.ToString(),
                            DebitorName = account.CustomerSname,
                            Limit = account.CreditLimit
                        };
</code>```

Now I want to filter the result set depending on the status of the user:

```<code>// Accounting user
if (ActiveDirectoryHelper.CheckIfUserIsInADGroup(userLogin, AdGroups.ACCOUNTING) )

    req = data.Where(x => x.RecommendationStatus == null).ToList();

// After sales manager
else if (ActiveDirectoryHelper.CheckIfUserIsInADGroup(userLogin, AdGroups.SAV_LEADERS))
    req = data.OrderByDescending(x => x.ID).ToList();

// Everybody else
else
    req = data.OrderByDescending(x => x.PkRequest).ToList();
</code>```

And that's where I'm stuck. When I don't have the join and only retrieve a "Request" type, I can just declare a list of Requests

```<code>List<Requests> req;
</code>```

But with that combination of Requests and AutolineAccts I would have to declare and initialize a list of "items" (req) to assign the result set to in the if-else segments. But I don't know how that anonymous variable should look like.

Later on I have to map the result set to a list of my IndexViewModels:

```<code>foreach (var item in req)
                viewModel.CLModels.Add(new IndexViewModel
                {
                    ID = item .PkRequest.ToString(),
                    Location = item .FkLocation,
                    RequestDate = item .RequestDate.Value,
                    Requestor = item .FkRequestor,
                    DebitorNr = item .FkDebitor.ToString(),
                    NewDebit = item .Debit.ToString(),
                    ApprovalStatus = item .ApprovalStatus.ToString(),
                    RecommendationStatus = item .RecommendationStatus.ToString(),
                    DebitorName = item.CustomerSname,
                    Limit = item.CreditLimit
                });
</code>```

Any idea to solve this issue?

答:
One option to avoid dynamic is to give the compiler an example of your anonymous type:

var req = new[]
{
    new
    {
        ID = "",
        Location = "",
        RequestDate = DateTime.Now,
        Requestor = "",
        DebitorNr = "",
        NewDebit = "",
        ApprovalStatus = "",
        RecommendationStatus = "",
        DebitorName = "",
        Limit = 0
    }
}.ToList();
```

<p>Obviously you should adjust the values to match the type that you expect.</p>

<p>It's a bit ugly, but personally I'd prefer that over using dynamic typing.</p>

<p>If you wanted to avoid actually allocating the array and the list, you could use type inference in a fairly horrible way:</p>

<pre class="lang-cs prettyprint-override"><code>// Simple method that returns null, but enables type inference
public static List<T> ProvideNullList(T sample) => null;

// Call it when you want to declare your variable:
var sample = new
{
    ID = "",
    Location = "",
    RequestDate = DateTime.Now,
    Requestor = "",
    DebitorNr = "",
    NewDebit = "",
    ApprovalStatus = "",
    RecommendationStatus = "",
    DebitorName = "",
    Limit = 0
};
var req = GenericHelpers.ProvideNullList(sample);
</code>```

That does still allocate the sample, but it's at least a bit better than the array and list as well.

Body:
I try to join two tables:

var data = from request in context.Requests
                        join account in context.AutolineAccts
                            on request.PkRequest.ToString() equals account.AccountCode
                        select new
                        {
                            ID = request.PkRequest.ToString(),
                            Location = request.FkLocation,
                            RequestDate = request.RequestDate.Value,
                            Requestor = request.FkRequestor,
                            DebitorNr = request.FkDebitor.ToString(),
                            NewDebit = request.Debit.ToString(),
                            ApprovalStatus = request.ApprovalStatus.ToString(),
                            RecommendationStatus = request.RecommendationStatus.ToString(),
                            DebitorName = account.CustomerSname,
                            Limit = account.CreditLimit
                        };

Now I want to filter the result set depending on the status of the user:

// Accounting user
if (ActiveDirectoryHelper.CheckIfUserIsInADGroup(userLogin, AdGroups.ACCOUNTING) )

    req = data.Where(x => x.RecommendationStatus == null).ToList();

// After sales manager
else if (ActiveDirectoryHelper.CheckIfUserIsInADGroup(userLogin, AdGroups.SAV_LEADERS))
    req = data.OrderByDescending(x => x.ID).ToList();

// Everybody else
else
    req = data.OrderByDescending(x => x.PkRequest).ToList();

And that's where I'm stuck. When I don't have the join and only retrieve a "Request" type, I can just declare a list of Requests

List<Requests> req;

But with that combination of Requests and AutolineAccts I would have to declare and initialize a list of "items" (req) to assign the result set to in the if-else segments. But I don't know how that anonymous variable should look like.

Later on I have to map the result set to a list of my IndexViewModels:

foreach (var item in req)
                viewModel.CLModels.Add(new IndexViewModel
                {
                    ID = item .PkRequest.ToString(),
                    Location = item .FkLocation,
                    RequestDate = item .RequestDate.Value,
                    Requestor = item .FkRequestor,
                    DebitorNr = item .FkDebitor.ToString(),
                    NewDebit = item .Debit.ToString(),
                    ApprovalStatus = item .ApprovalStatus.ToString(),
                    RecommendationStatus = item .RecommendationStatus.ToString(),
                    DebitorName = item.CustomerSname,
                    Limit = item.CreditLimit
                });

Any idea to solve this issue?

Body:
One option to avoid dynamic is to give the compiler an example of your anonymous type:

var req = new[]
{
    new
    {
        ID = "",
        Location = "",
        RequestDate = DateTime.Now,
        Requestor = "",
        DebitorNr = "",
        NewDebit = "",
        ApprovalStatus = "",
        RecommendationStatus = "",
        DebitorName = "",
        Limit = 0
    }
}.ToList();

Obviously you should adjust the values to match the type that you expect.

It's a bit ugly, but personally I'd prefer that over using dynamic typing.

If you wanted to avoid actually allocating the array and the list, you could use type inference in a fairly horrible way:

// Simple method that returns null, but enables type inference
public static List<T> ProvideNullList(T sample) => null;

// Call it when you want to declare your variable:
var sample = new
{
    ID = "",
    Location = "",
    RequestDate = DateTime.Now,
    Requestor = "",
    DebitorNr = "",
    NewDebit = "",
    ApprovalStatus = "",
    RecommendationStatus = "",
    DebitorName = "",
    Limit = 0
};
var req = GenericHelpers.ProvideNullList(sample);

That does still allocate the sample, but it's at least a bit better than the array and list as well.


问:
Disabling User dragging on BottomSheet
I am trying to disable user dragging on BottomSheet. The reason I want to disable is two things. 1. It's preventing the ListView from scrolling downward, 2. I don't want users to dismiss using dragging but with a button on the BottomSheetView. This is what I've done

```<code> bottomSheetBehavior = BottomSheetBehavior.from(bottomAnc);
    bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
        @Override
        public void onStateChanged(@NonNull View bottomSheet, int newState) {
            if (newState == BottomSheetBehavior.STATE_EXPANDED) {
                //Log.e("BottomSheet", "Expanded");
            } else if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
                //Log.e("BottomSheet", "Collapsed");
            }
        }

        @Override
        public void onSlide(@NonNull View bottomSheet, float slideOffset) {
            // React to dragging events
            bottomSheet.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    int action = MotionEventCompat.getActionMasked(event);
                    switch (action) {
                        case MotionEvent.ACTION_DOWN:
                            return false;
                        default:
                            return true;
                    }
                }
            });
        }
    });
</code>```

The bottomSheetLayout

```<code>    <?xml version="1.0" encoding="utf-8"?><FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
app:behavior_hideable="true"
app:behavior_peekHeight="0dp"
app:layout_behavior="@string/bottom_sheet_behavior"
android:id="@+id/bottomSheet">

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:elevation="10dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="center_vertical">

            <TextView
                android:id="@+id/text1"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Order Items"
                android:layout_margin="16dp"
                android:textAppearance="@android:style/TextAppearance.Large"/>

            <Button
                android:layout_width="50dp"
                android:layout_height="wrap_content"
                android:layout_marginRight="5dp"
                android:background="@drawable/bg_accept"/>

            <Button
                android:layout_width="50dp"
                android:layout_height="wrap_content"
                android:layout_marginRight="8dp"
                android:background="@drawable/bg_cancel"/>

        </LinearLayout>

        <ListView
            android:id="@+id/item_edit"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/white"
            android:divider="@color/md_divider_black"
            android:dividerHeight="1dp"/>

    </LinearLayout>

</android.support.v7.widget.CardView>
</code>```

答:
With 'com.google.android.material:material:1.2.0-alpha06'

Works great with NestedScrollView and RecyclerView

Example code:

```<code>    LinearLayout contentLayout = findViewById(R.id.contentLayout);
    sheetBehavior = BottomSheetBehavior.from(contentLayout);
    sheetBehavior.setDraggable(false);
</code>```

Title: Disabling User dragging on BottomSheet

Body:
I am trying to disable user dragging on BottomSheet. The reason I want to disable is two things. 1. It's preventing the ListView from scrolling downward, 2. I don't want users to dismiss using dragging but with a button on the BottomSheetView. This is what I've done

 bottomSheetBehavior = BottomSheetBehavior.from(bottomAnc);
    bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
        @Override
        public void onStateChanged(@NonNull View bottomSheet, int newState) {
            if (newState == BottomSheetBehavior.STATE_EXPANDED) {
                //Log.e("BottomSheet", "Expanded");
            } else if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
                //Log.e("BottomSheet", "Collapsed");
            }
        }

        @Override
        public void onSlide(@NonNull View bottomSheet, float slideOffset) {
            // React to dragging events
            bottomSheet.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    int action = MotionEventCompat.getActionMasked(event);
                    switch (action) {
                        case MotionEvent.ACTION_DOWN:
                            return false;
                        default:
                            return true;
                    }
                }
            });
        }
    });

The bottomSheetLayout

    <?xml version="1.0" encoding="utf-8"?><FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
app:behavior_hideable="true"
app:behavior_peekHeight="0dp"
app:layout_behavior="@string/bottom_sheet_behavior"
android:id="@+id/bottomSheet">

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:elevation="10dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="center_vertical">

            <TextView
                android:id="@+id/text1"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Order Items"
                android:layout_margin="16dp"
                android:textAppearance="@android:style/TextAppearance.Large"/>

            <Button
                android:layout_width="50dp"
                android:layout_height="wrap_content"
                android:layout_marginRight="5dp"
                android:background="@drawable/bg_accept"/>

            <Button
                android:layout_width="50dp"
                android:layout_height="wrap_content"
                android:layout_marginRight="8dp"
                android:background="@drawable/bg_cancel"/>

        </LinearLayout>

        <ListView
            android:id="@+id/item_edit"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/white"
            android:divider="@color/md_divider_black"
            android:dividerHeight="1dp"/>

    </LinearLayout>

</android.support.v7.widget.CardView>

Body:
With 'com.google.android.material:material:1.2.0-alpha06'

Works great with NestedScrollView and RecyclerView

Example code:

    LinearLayout contentLayout = findViewById(R.id.contentLayout);
    sheetBehavior = BottomSheetBehavior.from(contentLayout);
    sheetBehavior.setDraggable(false);


问:
How do I load a React component through a JavaScript UMD?
I am trying to use the following external component in my React project. My project is not based directly on the npm ecosystem (I am using react-dom), so I have been trying to import the component using a static compiled JavaScript file with a regular script tag in my html.

The file generated by the build seems to be a JavaScript UMD. I have tried to load this module using RequireJS, but I have been having the problem described here.

I'm not really sure whether I am approaching this correctly. I know that Browserfy performs similar functions to RequireJS, but I'm not even certain whether I should be pursuing this as a possible avenue.

What is the canonical way to load a component like this into the browser?

This question may be a duplicate of this similar question, but it does not have any real answers.

答: For reference, I found that this can be done using existing libraries, such as https://github.com/revolunet/react-umd-loader . Even if the libraries themselves are somewhat deprecated, the techniques used are still relevant.</p>


问:
Python sleep function does not catch interrupt signal
I cannot catch the INT signal in the main thread, please advise me how to fix the problem. I wish that the sleep method could be interrupted by CTRL+C, but it waits till the timer is ended..</p>

```<code>import pygtk
pygtk.require('2.0')

import gtk
import time
import urllib2
import re
import signal
import sys

import __main__

from time import ctime, strftime, localtime
from threading import Thread

myThread = None

class MyThread(Thread):

    def __init__(self, filename):
        Thread.__init__(self)
        self.filename = filename;
        self.terminate = False

    def StopProcess(self):
        self.terminate = True

    def run(self):
        while self.terminate <> True:
            time.sleep(5)
            self.terminate = True

def SignalHandler(signum, frame):
    if (myThread <> None):
        myThread.StopProcess()
    sys.exit()

if __name__ == "__main__":

    signal.signal(signal.SIGINT, SignalHandler)

    myThread = MyThread("aaa")
    myThread.start()
</code>```

答:
Believe it or not, this will work.

```<code>from Queue import Queue, Empty
def signal_safe_sleep(delay):
  q = Queue()
  try: q.get(True, delay)
  except Empty: pass
</code>```

Alternatively, you can create some file descriptors using os.pipe() and then use select.select() on them within your signal_safe_sleep function.  Both approaches will allow Python signal handlers to be called before signal_safe_sleep returns.

Body:
I cannot catch the INT signal in the main thread, please advise me how to fix the problem. I wish that the sleep method could be interrupted by CTRL+C, but it waits till the timer is ended..

import pygtk
pygtk.require('2.0')

import gtk
import time
import urllib2
import re
import signal
import sys

import __main__

from time import ctime, strftime, localtime
from threading import Thread

myThread = None

class MyThread(Thread):

    def __init__(self, filename):
        Thread.__init__(self)
        self.filename = filename;
        self.terminate = False

    def StopProcess(self):
        self.terminate = True

    def run(self):
        while self.terminate <> True:
            time.sleep(5)
            self.terminate = True

def SignalHandler(signum, frame):
    if (myThread <> None):
        myThread.StopProcess()
    sys.exit()

if __name__ == "__main__":

    signal.signal(signal.SIGINT, SignalHandler)

    myThread = MyThread("aaa")
    myThread.start()

Body:
Believe it or not, this will work.

from Queue import Queue, Empty
def signal_safe_sleep(delay):
  q = Queue()
  try: q.get(True, delay)
  except Empty: pass

Alternatively, you can create some file descriptors using os.pipe() and then use select.select() on them within your signal_safe_sleep function.  Both approaches will allow Python signal handlers to be called before signal_safe_sleep returns.


问:
When Ubuntu 18.04 deploys zabbix4.0, the database type is PostgreSQL instead of MySQL. How can I set this to support MySQL?
In Ubuntu 18.04 server, I use binary file to install zabbix4.0 according to the official website document of zabbix4.0, and I use MySQL 5.7.30 database. After installation, when I configure the front end of zabbix4.0,In the database configuration page, I only see one option of PostgreSQL, not mysql, as shown in the following figure:

In my server, I have installed MySQL version 5.7.30, and imported the data of ZABBIX 4.0 into the ZABBIX database, without any PostgreSQL installed

Excuse me, how can I make zabbix4.0 support MySQL 5.7.30 that I have installed? Thank you!

I installed zabbix4.0 according to the official documents:
https://www.zabbix.com/documentation/4.0/zh/manual/installation/install_from_packages/debian_ubuntu

This is my installation method:

```<code># install zabbix
cd ~/download
wget https://repo.zabbix.com/zabbix/4.0/ubuntu/pool/main/z/zabbix-
release/zabbix-release_ 4.0-2+bionic_ all.deb
sudo dpkg -i zabbix-release_ 4.0-2+bionic_ all.deb
sudo apt-get update

#install Server/proxy/
sudo apt-get install -y zabbix-server-mysql
sudo apt-get install -y zabbix-frontend-php
</code>```

答:
With Ubuntu, you got two type of databases when donwloading Zabbix, PostgreSql and MySql. You need to re-download (I mean installation and configuration) Zabbix choosing MySql as database.
The following link could help Zabbix (Ubuntu) with MySql as database</p>

Body:
In Ubuntu 18.04 server, I use binary file to install zabbix4.0 according to the official website document of zabbix4.0, and I use MySQL 5.7.30 database. After installation, when I configure the front end of zabbix4.0,In the database configuration page, I only see one option of PostgreSQL, not mysql, as shown in the following figure:

In my server, I have installed MySQL version 5.7.30, and imported the data of ZABBIX 4.0 into the ZABBIX database, without any PostgreSQL installed

Excuse me, how can I make zabbix4.0 support MySQL 5.7.30 that I have installed? Thank you!

I installed zabbix4.0 according to the official documents:
https://www.zabbix.com/documentation/4.0/zh/manual/installation/install_from_packages/debian_ubuntu

This is my installation method:

# install zabbix
cd ~/download
wget https://repo.zabbix.com/zabbix/4.0/ubuntu/pool/main/z/zabbix-
release/zabbix-release_ 4.0-2+bionic_ all.deb
sudo dpkg -i zabbix-release_ 4.0-2+bionic_ all.deb
sudo apt-get update

#install Server/proxy/
sudo apt-get install -y zabbix-server-mysql
sudo apt-get install -y zabbix-frontend-php


问:
How can I reduce the function template specializations?
I'm trying to write a property validator to be used in UE4, using their reflection system.
I first came up with this:

```<code>class FDataValidator
{
public:
    FDataValidator( UObject & object, TArray< FText > & validation_errors ) :
        Object( object ),
        ValidationResult( validation_errors.Num() == 0 ? EDataValidationResult::Valid : EDataValidationResult::Invalid ),
        ObjectClass( Object.GetClass() ),
        ValidationErrors( validation_errors )
    {}

    template < class _TYPE_ >
    FDataValidator & GreaterThan( const FName property_name, const _TYPE_ value );

    EDataValidationResult Result() const
    {
        return ValidationResult;
    }

private:
    template < class _PROPERTY_TYPE_, class _VALUE_TYPE_, class _COMPARATOR_TYPE_ >
    FDataValidator & CompareProperty( const FName property_name, const _VALUE_TYPE_ value, _COMPARATOR_TYPE_ comparator = _COMPARATOR_TYPE_() )
    {
        if ( auto * property = GetTypedProperty< _PROPERTY_TYPE_ >( property_name ) )
        {
            const auto property_value = property->GetPropertyValue_InContainer( &Object );

            if ( !comparator( property_value, value ) )
            {
                AddError( FText::FromString( FString::Printf( TEXT( "%s must be greater than %f" ), *property_name.ToString(), value ) ) );
            }
        }

        return *this;
    }

    template < class _PROPERTY_TYPE_ >
    _PROPERTY_TYPE_ * GetTypedProperty( const FName property_name )
    {
        if ( auto * property = ObjectClass->FindPropertyByName( property_name ) )
        {
            if ( auto * typed_property = Cast< _PROPERTY_TYPE_ >( property ) )
            {
                return typed_property;
            }
        }

        return nullptr;
    }

    void AddError( FText text )
    {
        ValidationErrors.Emplace( text );
        ValidationResult = EDataValidationResult::Invalid;
    }

    UObject & Object;
    EDataValidationResult ValidationResult;
    UClass * ObjectClass;
    TArray< FText > & ValidationErrors;
};

template <>
FDataValidator & FDataValidator::GreaterThan< float >( const FName property_name, const float value )
{
    return CompareProperty< UFloatProperty, float, std::greater< float > >( property_name, value );
}

template <>
FDataValidator & FDataValidator::GreaterThan< int >( const FName property_name, const int value )
{
    return CompareProperty< UIntProperty, int, std::greater< int > >( property_name, value );
}
</code>```

I only implemented GreaterThan for 2 types, and I'd like to know if I can not refactor the class to avoid so many template specializations.

Would it be possible to have something like that, where I pass for example std::greater< _VALUE_TYPE_ > around and let the system infer what _VALUE_TYPE_ is to call GetTypedProperty with the correct type?

```<code>class FDataValidator
{
public:
    template < class _VALUE_TYPE_ >
    FDataValidator & GreaterThan( const FName property_name, const _VALUE_TYPE_ value )
    {
        return NumericComparator< std::greater< _VALUE_TYPE_ > >( property_name, value );
    }

private:

    // How to write this to infer for example that _VALUE_TYPE_ is float when passed std::greater< float > ?
    template < typename _COMPARATOR_TYPE_ >
    FDataValidator & NumericComparator( FName property_name, _VALUE_TYPE_ value, _COMPARATOR_TYPE_ comparator = _COMPARATOR_TYPE_() );
};

template < class _VALUE_TYPE_, class _COMPARATOR_TYPE_ >
FDataValidator & NumericComparator( FName property_name, _VALUE_TYPE_ value, _COMPARATOR_TYPE_ comparator = _COMPARATOR_TYPE_() )
{
    return CompareProperty< UFloatProperty, float, std::greater< float > >( property_name, value );
}
</code>```

Thanks

答:
UFloatProperty and other numeric types seem to inherit from TProperty_Numeric<T>.
So something like this might be a solution:

```<code>template <typename T>
FDataValidator& FDataValidator::GreaterThan<T>(const FName property_name, const T value)
{
    return CompareProperty<TProperty_Numeric<T>, T, std::greater<T>>(property_name, value);
}
</code>```

Body:
I'm trying to write a property validator to be used in UE4, using their reflection system.
I first came up with this:

class FDataValidator
{
public:
    FDataValidator( UObject & object, TArray< FText > & validation_errors ) :
        Object( object ),
        ValidationResult( validation_errors.Num() == 0 ? EDataValidationResult::Valid : EDataValidationResult::Invalid ),
        ObjectClass( Object.GetClass() ),
        ValidationErrors( validation_errors )
    {}

    template < class _TYPE_ >
    FDataValidator & GreaterThan( const FName property_name, const _TYPE_ value );

    EDataValidationResult Result() const
    {
        return ValidationResult;
    }

private:
    template < class _PROPERTY_TYPE_, class _VALUE_TYPE_, class _COMPARATOR_TYPE_ >
    FDataValidator & CompareProperty( const FName property_name, const _VALUE_TYPE_ value, _COMPARATOR_TYPE_ comparator = _COMPARATOR_TYPE_() )
    {
        if ( auto * property = GetTypedProperty< _PROPERTY_TYPE_ >( property_name ) )
        {
            const auto property_value = property->GetPropertyValue_InContainer( &Object );

            if ( !comparator( property_value, value ) )
            {
                AddError( FText::FromString( FString::Printf( TEXT( "%s must be greater than %f" ), *property_name.ToString(), value ) ) );
            }
        }

        return *this;
    }

    template < class _PROPERTY_TYPE_ >
    _PROPERTY_TYPE_ * GetTypedProperty( const FName property_name )
    {
        if ( auto * property = ObjectClass->FindPropertyByName( property_name ) )
        {
            if ( auto * typed_property = Cast< _PROPERTY_TYPE_ >( property ) )
            {
                return typed_property;
            }
        }

        return nullptr;
    }

    void AddError( FText text )
    {
        ValidationErrors.Emplace( text );
        ValidationResult = EDataValidationResult::Invalid;
    }

    UObject & Object;
    EDataValidationResult ValidationResult;
    UClass * ObjectClass;
    TArray< FText > & ValidationErrors;
};

template <>
FDataValidator & FDataValidator::GreaterThan< float >( const FName property_name, const float value )
{
    return CompareProperty< UFloatProperty, float, std::greater< float > >( property_name, value );
}

template <>
FDataValidator & FDataValidator::GreaterThan< int >( const FName property_name, const int value )
{
    return CompareProperty< UIntProperty, int, std::greater< int > >( property_name, value );
}

I only implemented GreaterThan for 2 types, and I'd like to know if I can not refactor the class to avoid so many template specializations.

Would it be possible to have something like that, where I pass for example std::greater< _VALUE_TYPE_ > around and let the system infer what _VALUE_TYPE_ is to call GetTypedProperty with the correct type?

class FDataValidator
{
public:
    template < class _VALUE_TYPE_ >
    FDataValidator & GreaterThan( const FName property_name, const _VALUE_TYPE_ value )
    {
        return NumericComparator< std::greater< _VALUE_TYPE_ > >( property_name, value );
    }

private:

    // How to write this to infer for example that _VALUE_TYPE_ is float when passed std::greater< float > ?
    template < typename _COMPARATOR_TYPE_ >
    FDataValidator & NumericComparator( FName property_name, _VALUE_TYPE_ value, _COMPARATOR_TYPE_ comparator = _COMPARATOR_TYPE_() );
};

template < class _VALUE_TYPE_, class _COMPARATOR_TYPE_ >
FDataValidator & NumericComparator( FName property_name, _VALUE_TYPE_ value, _COMPARATOR_TYPE_ comparator = _COMPARATOR_TYPE_() )
{
    return CompareProperty< UFloatProperty, float, std::greater< float > >( property_name, value );
}

Thanks

Body:
UFloatProperty and other numeric types seem to inherit from TProperty_Numeric<T>.
So something like this might be a solution:

template <typename T>
FDataValidator& FDataValidator::GreaterThan<T>(const FName property_name, const T value)
{
    return CompareProperty<TProperty_Numeric<T>, T, std::greater<T>>(property_name, value);
}


问:
Array in URL parameter (Angular)
I have a filter with checkboxes where after checking added parameter to the url like this

```<code>https://localhost:8080/api/records?page=0&locationIds=1,2
</code>```

But want to be like this

```<code>https://localhost:8080/api/records?page=0&locationIds=1&locationIds=2
</code>```

As I understood thats 'cause I pass an Array to URL parameter and my main thought is to rewrite this forEach not for 'key', but for 'httpParams[key]' in file candidate.service.ts(not sure) but don't know how to make it right.
Here is my code:

filter.service.ts. (In this service filter returns as array)

```<code>filterByValues(filterType: string, value): FilterParams {
  if (!this.filterParams[filterType]) {
    this.filterParams[filterType] = [value];
  } else if (this.isValueInParams(this.filterParams[filterType], value)) {
    this.filterParams[filterType] = this.removeValueFromParams(this.filterParams[filterType], value);
  } else {
    this.filterParams[filterType].push(value); //return  [1, 2]
  }
  return this.filterParams;
}

isValueInParams(params, value) {
  return params.some(item => value === item);
}
</code>```

I use this service in other file, when I check some of checkboxes, this id added to Array

candidate-filter.ts

```<code>filterByLocation(location: Location) {
  const filtersToEmit = this.filterService.filterByValues(CandidateFilter.LOCATION, location.id);
  this.candidatesHttpParams.emit(filtersToEmit);
}
</code>```

Here where I add the url:

candidate.service.ts

```<code>get(page: number, httpParams: FilterParams): Observable<Candidate[]> {
  let params = new HttpParams().set('page', page.toString());

  //My main thought is to rewrite this forEach not for 'key', but for 'httpParams[key]'. Not sure

  Object.keys(httpParams).forEach(key =>
  params = params.append(key, httpParams[key])); //key = locationIds, httpParams[key] = [1,2]
  return this.http.get<Candidate[]>(this.url, { params });
}
</code>```

And where actually get Candidates

import-page.ts

```<code> private getCandidates(page: number) {
this.candidateViewService.get(page, this.params)

//this.params = {key: Array(2)} // [1, 2]

  .subscribe(
    (candidates: CandidateView[]) => this.candidates = candidates,
    error => this.logger.error(error.message));
    console.log('this Params',this.params)
}
</code>```

Hope my question is clear. Would be really grateful for any help!

答:
Check this rough example in JS, I hope it will lead you to what you need.

var page = 0;
var locationIds = [1, 2];
function getCall(baseUrl, page, locationIds) {

  let str = baseUrl + "?page" + page + "&"; // adding the first page params.
  locationIds.forEach((element, index) => {
    str += "locationsIds="+element;
    if (index < locationIds.length - 1) { //check if it's the last item or not
      str += "&";
    }
  });
  // do your http call (this.http refers to HttpClient)
    // this.http.get(str).subscribe((data) => {
  //   your code.
  // })
  return str; // only for the example purpose to log the str created;
};
console.log(getCall("http://localhost:8080/records", page, locationIds));```

And if you check the dev console in your browser after uncommenting the http get call in your angular app you will have in the network tab your request :

I'm sure it's not the unique way achieving this with angular. But it's the first way poping in my mind. Feel free to ask some question for your integration in your app.

Title: Array in URL parameter (Angular)

Body:
I have a filter with checkboxes where after checking added parameter to the url like this

https://localhost:8080/api/records?page=0&locationIds=1,2

But want to be like this

https://localhost:8080/api/records?page=0&locationIds=1&locationIds=2

As I understood thats 'cause I pass an Array to URL parameter and my main thought is to rewrite this forEach not for 'key', but for 'httpParams[key]' in file candidate.service.ts(not sure) but don't know how to make it right.
Here is my code:

filter.service.ts. (In this service filter returns as array)

filterByValues(filterType: string, value): FilterParams {
  if (!this.filterParams[filterType]) {
    this.filterParams[filterType] = [value];
  } else if (this.isValueInParams(this.filterParams[filterType], value)) {
    this.filterParams[filterType] = this.removeValueFromParams(this.filterParams[filterType], value);
  } else {
    this.filterParams[filterType].push(value); //return  [1, 2]
  }
  return this.filterParams;
}

isValueInParams(params, value) {
  return params.some(item => value === item);
}

I use this service in other file, when I check some of checkboxes, this id added to Array

candidate-filter.ts

filterByLocation(location: Location) {
  const filtersToEmit = this.filterService.filterByValues(CandidateFilter.LOCATION, location.id);
  this.candidatesHttpParams.emit(filtersToEmit);
}

Here where I add the url:

candidate.service.ts

get(page: number, httpParams: FilterParams): Observable<Candidate[]> {
  let params = new HttpParams().set('page', page.toString());

  //My main thought is to rewrite this forEach not for 'key', but for 'httpParams[key]'. Not sure

  Object.keys(httpParams).forEach(key =>
  params = params.append(key, httpParams[key])); //key = locationIds, httpParams[key] = [1,2]
  return this.http.get<Candidate[]>(this.url, { params });
}

And where actually get Candidates

import-page.ts

 private getCandidates(page: number) {
this.candidateViewService.get(page, this.params)

//this.params = {key: Array(2)} // [1, 2]

  .subscribe(
    (candidates: CandidateView[]) => this.candidates = candidates,
    error => this.logger.error(error.message));
    console.log('this Params',this.params)
}

Hope my question is clear. Would be really grateful for any help!

Body:
Check this rough example in JS, I hope it will lead you to what you need.

var page = 0;
var locationIds = [1, 2];
function getCall(baseUrl, page, locationIds) {

  let str = baseUrl + "?page" + page + "&"; // adding the first page params.
  locationIds.forEach((element, index) => {
    str += "locationsIds="+element;
    if (index < locationIds.length - 1) { //check if it's the last item or not
      str += "&";
    }
  });
  // do your http call (this.http refers to HttpClient)
    // this.http.get(str).subscribe((data) => {
  //   your code.
  // })
  return str; // only for the example purpose to log the str created;
};
console.log(getCall("http://localhost:8080/records", page, locationIds));

And if you check the dev console in your browser after uncommenting the http get call in your angular app you will have in the network tab your request :

I'm sure it's not the unique way achieving this with angular. But it's the first way poping in my mind. Feel free to ask some question for your integration in your app.


问:
Pthread create as detached
I have a problem creating a thread as detached. Here's the code I wrote:

```<code>void* testFunction() {

    pthread_attr_t attr;
    int chk,rc;

pthread_attr_init(&attr);
printf("thread_attr_init: %d\n",rc);

pthread_attr_getdetachstate(&attr, &chk);
printf("thread_attr_getdetachedstate: %d\n",rc);

if(chk == PTHREAD_CREATE_DETACHED )
    printf("Detached\n");
else if (chk == PTHREAD_CREATE_JOINABLE)
    printf("Joinable\n");

return NULL;
}

int main (int argc, const char * argv[]) {

pthread_t thread1;
pthread_attr_t attr;

int rc;

rc = pthread_attr_init(&attr);

printf("attr_init: %d\n",rc);
rc = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
printf("attr_setdetachedstate: %d\n",rc);

rc = pthread_create(&thread1, &attr, testFunction, NULL);
printf("attr_create: %d\n",rc);

sleep(4);
pthread_cancel(thread1);

return 0;
}
</code>```

The problem is that testFunction() always print "Joinable". Can anyone tell me where I'm getting wrong?

答: Your testFunction is not examining anything about the current thread, rather just the initially-detached flag of a completely new attribute object you just created. Moreover, it is completely impossible, in the POSIX threads API, to recover the attributes a thread was created with or determine if a thread is detached or not. You simply have to trust that the implementation behaves as required, just like you have to trust that, if malloc(100) returns a non-null pointer, it points to a location at which you can store at least 100 bytes. This is the nature of C.

Title: Pthread create as detached

Body:
I have a problem creating a thread as detached. Here's the code I wrote:

void* testFunction() {

    pthread_attr_t attr;
    int chk,rc;

pthread_attr_init(&attr);
printf("thread_attr_init: %d\n",rc);

pthread_attr_getdetachstate(&attr, &chk);
printf("thread_attr_getdetachedstate: %d\n",rc);

if(chk == PTHREAD_CREATE_DETACHED )
    printf("Detached\n");
else if (chk == PTHREAD_CREATE_JOINABLE)
    printf("Joinable\n");

return NULL;
}

int main (int argc, const char * argv[]) {

pthread_t thread1;
pthread_attr_t attr;

int rc;

rc = pthread_attr_init(&attr);

printf("attr_init: %d\n",rc);
rc = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
printf("attr_setdetachedstate: %d\n",rc);

rc = pthread_create(&thread1, &attr, testFunction, NULL);
printf("attr_create: %d\n",rc);

sleep(4);
pthread_cancel(thread1);

return 0;
}

The problem is that testFunction() always print "Joinable". Can anyone tell me where I'm getting wrong?


问:
How to find font and colour for each text in Python web scraping?
I wrote a Python scraper that can scrape text from websites and now I am in the process of labelling font and size.
For example the CSS is:

```<code>td{ font-family:Arial; font-size:9pt; }
hr { height:1px; }
.currency { color:#000099; }
</code>```

HTML:

```<code><td align="left">
<font class="currency">USD</font>
"3.20"
</td>
</code>```

My desired output:

```<code>{
"text": ["USD", "3.20"],
"font": ["Arial", "Arial"],
"colours": ["#000099", "#000000"],
}
</code>```

Is there any way I can do this with BeautifulSoup or regex?

Body:
I wrote a Python scraper that can scrape text from websites and now I am in the process of labelling font and size.
For example the CSS is:

td{ font-family:Arial; font-size:9pt; }
hr { height:1px; }
.currency { color:#000099; }

HTML:

USD
"3.20"

My desired output:

{
"text": ["USD", "3.20"],
"font": ["Arial", "Arial"],
"colours": ["#000099", "#000000"],
}

Is there any way I can do this with BeautifulSoup or regex?

Body:
Is there any way I can do this with BeautifulSoup or regex?

Yes and no, but it's probably more work than its worth, and not bulletproof, so I would lean towards no. If you are using beautifulsoup alone and want to know what styles are applied to an element as if you were using a browser, then it's hard.

You need to add some other tools in the mix, such as a headless browser.

Keeping your setup

HTML + CSS

First, some background.

HTML is the document itself, the one with the information, computer program-parsable, and transformable. And this is what you have so far with your program.

CSS is just something made for the browsers and for humans. Its purpose is to make the document prettier, clearer and easier to use. To get a broader view of how CSS is used by the browser, check this How CSS works MDN article. This means that the styles are loaded separately and applied "at runtime", in the browser. There's also at least three different way to specify styles on an element (separate documents, inline, etc).

Scraping

I suppose you use something like requests to download the page, then feed it to beautifulsoup, and then pick whatever data you need from there. To use that diagram from the article, what you have are the first three boxes from the top row, i.e. without loading or parsing the CSS, and without displaying the page.

This also goes for any DOM manipulation that happens in the browser after the page is loaded, e.g. content loaded dynamically via API calls, or any JS that modifies the page — you won't be able to catch those in the requests-beautifulsoup pipeline.

So, out of the box, there doesn't seem to be a way of grabbing an element with bs, and querying what styles are applied to it, because that's not its scope. What you can do is to get the styling separately and make sense of it on your own.

DIY

First, you can get the element's style attribute (td['style']), and parse that for the fonts. Note that there's a bunch of ways of specifying that, too, e.g. font: italic 1.2em "Fira Sans", serif;, font: small-caps bold 24px/1 sans-serif;, font-family: 'Fira Sans', serif; font-size: 1.2em;. But then, there's also the cascading part of the CSS, which means that an element's parent can apply styles to its children.

Then there's also <style> tags in the document, as well as <link rel="stylesheet">.

The point is that this is work done by a browser (and a hard task at that!), you would be partly replicating it, and there's other things you could use.

Headless browser

The thing for the job has a name and this is it. What it means is that it's a browser implementation without the actual GUI, and which you can use programatically, through an API. This makes it great for testing websites, for instance, as well as scraping pages that have dynamic content, or for which you need styling info.

I can't recommend any, having not used any myself, but this should be enough to get you started.


问:
Change the font size of UISearchBar
How can I change the font size of UISearchBar ?

答:
iOS 13 or later:

```<code>if #available(iOS 13.0, *) {
    // set your desired font size
    self.searchBar.searchTextField.font = .systemFont(ofSize: 14.0)
}
</code>```

Title: Change the font size of UISearchBar

Body:
iOS 13 or later:

if #available(iOS 13.0, *) {
    // set your desired font size
    self.searchBar.searchTextField.font = .systemFont(ofSize: 14.0)
}


问:
How do I write info into a txt file or csv file using input from a flask app that is hosted on pythonanywhere
I don't understand the problem. Before when I ran this code in terminal it was working fine but when I hosted it on pythonanywhere this code does not write the input from the html form into the txt file. I'm really confused as of what is happening.
My python code is this

```<code>def write_file(data):
    with open('new.txt', 'a') as f:
        f.write(data + '\n')

@app.route('/in/', methods=['GET', 'POST'])
def notin():
    if request.method == 'POST':
        notin = str(request.form['in'])
        write_file(notin)
        return render_template('in.html')
    return render_template('form.html')
</code>```

My html code is(in.html):

```<code><!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
 <form method="POST" action='/in/'>
      <div class="form-group">
        <input type="text" name="in">
      </div>
    </form>

  </body>
</html>
</code>```

答: You're using a relative path to a file without paying attention to the working directory that your code is running with. Use the full path to new.txt so that the working directory does not affect where the file is written.</p>

Body:
I don't understand the problem. Before when I ran this code in terminal it was working fine but when I hosted it on pythonanywhere this code does not write the input from the html form into the txt file. I'm really confused as of what is happening.
My python code is this

def write_file(data):
    with open('new.txt', 'a') as f:
        f.write(data + '\n')

@app.route('/in/', methods=['GET', 'POST'])
def notin():
    if request.method == 'POST':
        notin = str(request.form['in'])
        write_file(notin)
        return render_template('in.html')
    return render_template('form.html')

My html code is(in.html):

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

 <form method="POST" action='/in/'>

        <input type="text" name="in">

    </form>


问:
Is there a way to check internal method variables with rspec?
i'm using Rspec for testing. I'm currently creating a combat system and i would need to test it as extensively as needed.

Till now, using rspec, i mostly check the outcome of a method on whether it should return a certain value, create certain records and so on.

But how can i actually(if possible) check a variable inside a method ? Think of this example :

```<code>def combat
  weapon_damage = 30
  total_damage = weapon_damage + other_damage
  total_damage
end
</code>```

How can i check the weapon_damage was 30, for example ? Or the value of other_damage ? As you see, i'm looking for a way to test the in between steps of my methods.

答: you can not do that. In your case, I would suggest, you separate the call into multiple methods so you can test their outcome one by one. In general, if you tend to ask yourself what your methods are actually doing, it's a good sign that you should separate the code into multiple methods.</p>

Body:
i'm using Rspec for testing. I'm currently creating a combat system and i would need to test it as extensively as needed.

Till now, using rspec, i mostly check the outcome of a method on whether it should return a certain value, create certain records and so on.

But how can i actually(if possible) check a variable inside a method ? Think of this example :

def combat
  weapon_damage = 30
  total_damage = weapon_damage + other_damage
  total_damage
end

How can i check the weapon_damage was 30, for example ? Or the value of other_damage ? As you see, i'm looking for a way to test the in between steps of my methods.


问:
Is there a way to test an instance variable in objective c?
I need to test an instance variable in Objective C.

I have this snippet in myViewController.m

```<code>@implementation myViewController
{
NSView *myView;
}
</code>```

I need to add a test in myViewControllerTest.mm that tests a case when myView.window happens to be nil

```<code>-(void) myTest
{
// 1. assert condition 1 is true
// 2. mock myView.window and set it to nil OR set myView.window directly to nil
// 3. assert condition 1 is false
}
</code>```

I'd like to know the best approach to achieve step 2 in the test. Approaches I tried:

Add an explicit setter - (void)setMyView:(NSView*)myView just for the unit test purpose and use that in myTest.
I have a feeling that this is not a good way.

make myView as a property and put it in myViewController.h so that I'll have a setter without explicitly defining one.

Unsuccessful attempt at mocking using OCMock. (need to explore further)

Please suggest what the best approach is and what are the pros/cons of them.
Thanks !

Edit : Answer I ended up using in my test file.

[myViewController setValue:nil forKeyPath:@"myViewControl.window"];

https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueCoding/BasicPrinciples.html#//apple_ref/doc/uid/20002170-BAJEAIEE

答:
You can add setter only for testing in your test file myViewControllerTest.mm

This has no effect to your production code.

like below using Extension

// Write this in test file.
@interface MyViewController(Test)
- (void)setMyView:(NSView *)myView;
@end
```

<p>or just use <code>valueForKey:</code> to get private field.</p>

<pre class="lang-c prettyprint-override"><code>-(void) myTest
{
  id myViewController = ...;
  NSView *myView = [myViewController valueForKey:@"myView"];
  myView.window = nil;
  // ...
}
</code>```

Body:
I need to test an instance variable in Objective C.

I have this snippet in myViewController.m

@implementation myViewController
{
NSView *myView;
}

I need to add a test in myViewControllerTest.mm that tests a case when myView.window happens to be nil

-(void) myTest
{
// 1. assert condition 1 is true
// 2. mock myView.window and set it to nil OR set myView.window directly to nil
// 3. assert condition 1 is false
}

I'd like to know the best approach to achieve step 2 in the test. Approaches I tried:

Add an explicit setter - (void)setMyView:(NSView*)myView just for the unit test purpose and use that in myTest.
I have a feeling that this is not a good way.

make myView as a property and put it in myViewController.h so that I'll have a setter without explicitly defining one.

Unsuccessful attempt at mocking using OCMock. (need to explore further)

Please suggest what the best approach is and what are the pros/cons of them.
Thanks !

Edit : Answer I ended up using in my test file.

[myViewController setValue:nil forKeyPath:@"myViewControl.window"];

https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueCoding/BasicPrinciples.html#//apple_ref/doc/uid/20002170-BAJEAIEE

Body:
You can add setter only for testing in your test file myViewControllerTest.mm

This has no effect to your production code.

like below using Extension

// Write this in test file.
@interface MyViewController(Test)
- (void)setMyView:(NSView *)myView;
@end

or just use valueForKey: to get private field.

-(void) myTest
{
  id myViewController = ...;
  NSView *myView = [myViewController valueForKey:@"myView"];
  myView.window = nil;
  // ...
}


问:
Turning byte array back into img
```<code>public byte[] ImageToByte(string imgUrl)
{
    try
    {
        byte[] imageBytes = client.DownloadData(imgUrl);
        return imageBytes;
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        return null;
    }
}
</code>```

So i've used this piece of code to download images as bitarrays and I have added them to a database.
I wanna know how I can turn the byte array back into an image.

答:
Try  this :</p>

```<code>using (var ms = new MemoryStream(byteArray))
{
    return Image.FromStream(ms);
}
</code>```

Title: Turning byte array back into img

Body:
public byte[] ImageToByte(string imgUrl)
{
    try
    {
        byte[] imageBytes = client.DownloadData(imgUrl);
        return imageBytes;
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        return null;
    }
}

So i've used this piece of code to download images as bitarrays and I have added them to a database.
I wanna know how I can turn the byte array back into an image.

Body:
Try  this :

using (var ms = new MemoryStream(byteArray))
{
    return Image.FromStream(ms);
}