问:
plotting with specific values for heatmap in pheatmap
I have a data frame like this:

```<code>gene    s1  s2  s3
1   -3.83   -8.17   -8.59
2   0.33    -4.51   -7.27
3   0.15    -5.26   -6.2
4   -0.08   -6.13   -5.95
5   -1.15   -4.82   -5.75
6   -0.99   -4.11   -4.85
7   0.42    -4.18   -4.54
8   -0.32   -3.43   -4.4
9   -0.72   -3.37   -4.39
</code>```

I want to make a heatmap using pheatmap where if anything is below -4 it should be green and anything over +4 should be red and everything in between should red/green shades. I also don't want to scale my data and no clustering. I have this code so far in R:

```<code>d <- read.table("test.txt", header = TRUE, sep = "\t", row.names = 1, quote = "")

pheatmap(as.matrix(d),  # matrix
         scale = "none",         # z score scaling applied to rows
         cluster_cols=FALSE,    # do not cluster columns
         cluster_rows = FALSE,
         treeheight_row=0,      # do not show row dendrogram
         show_rownames=FALSE,   # do not show row names i.e gene names
         main = "test.txt",
         color = colorRampPalette(c("#0016DB","#FFFFFF","#FFFF00"))(50),
         )
</code>```

How can I plot this with the color scheme I mentioned above.

Thanks

答:
d <-read.table(text="gene      s1      s2      s3
                        1   -3.83   -8.17   -8.59
                        2    0.33   -4.51   -7.27
                        3    0.15   -5.26   -6.20
                        4   -0.08   -6.13   -5.95
                        5   -1.15   -4.82   -5.75
                        6   -0.99   -4.11   -4.85
                        7   0.42    -4.18   -4.54
                        8   -0.32   -3.43   -4.40
                        9   -0.72   -3.37   -4.39", header=T)

library(pheatmap)

my_colors <- c(min(d),seq(-4,4,by=0.01),max(d))

my_palette <- c("green",colorRampPalette(colors = c("green", "red"))
                (n = length(my_colors)-2), "red")

pheatmap(as.matrix(d),
         scale = "none",
         cluster_cols=FALSE,
         cluster_rows = FALSE,
         treeheight_row=0,
         show_rownames=FALSE,
         main = "test.txt",
         color = my_palette,
         breaks = my_colors)
```

Created on 2019-05-29 by the reprex package (v0.3.0)

Body:
I have a data frame like this:

gene    s1  s2  s3
1   -3.83   -8.17   -8.59
2   0.33    -4.51   -7.27
3   0.15    -5.26   -6.2
4   -0.08   -6.13   -5.95
5   -1.15   -4.82   -5.75
6   -0.99   -4.11   -4.85
7   0.42    -4.18   -4.54
8   -0.32   -3.43   -4.4
9   -0.72   -3.37   -4.39

I want to make a heatmap using pheatmap where if anything is below -4 it should be green and anything over +4 should be red and everything in between should red/green shades. I also don't want to scale my data and no clustering. I have this code so far in R:

d <- read.table("test.txt", header = TRUE, sep = "\t", row.names = 1, quote = "")

pheatmap(as.matrix(d),  # matrix
         scale = "none",         # z score scaling applied to rows
         cluster_cols=FALSE,    # do not cluster columns
         cluster_rows = FALSE,
         treeheight_row=0,      # do not show row dendrogram
         show_rownames=FALSE,   # do not show row names i.e gene names
         main = "test.txt",
         color = colorRampPalette(c("#0016DB","#FFFFFF","#FFFF00"))(50),
         )

How can I plot this with the color scheme I mentioned above.

Thanks

Body:
d <-read.table(text="gene      s1      s2      s3
                        1   -3.83   -8.17   -8.59
                        2    0.33   -4.51   -7.27
                        3    0.15   -5.26   -6.20
                        4   -0.08   -6.13   -5.95
                        5   -1.15   -4.82   -5.75
                        6   -0.99   -4.11   -4.85
                        7   0.42    -4.18   -4.54
                        8   -0.32   -3.43   -4.40
                        9   -0.72   -3.37   -4.39", header=T)

library(pheatmap)

my_colors <- c(min(d),seq(-4,4,by=0.01),max(d))

my_palette <- c("green",colorRampPalette(colors = c("green", "red"))
                (n = length(my_colors)-2), "red")

pheatmap(as.matrix(d),
         scale = "none",
         cluster_cols=FALSE,
         cluster_rows = FALSE,
         treeheight_row=0,
         show_rownames=FALSE,
         main = "test.txt",
         color = my_palette,
         breaks = my_colors)

Created on 2019-05-29 by the reprex package (v0.3.0)


来源: stackexchange

问:
Loop for all possible combinations from 3 variables
I have a bit of code that runs some stats for a moving 3D window at varying size. I have created a loop to to do this in increments of 5 from 5 to 50 as below.

For example first X = 5, Y = 5, Z = 5, then X = 10, Y = 10, z = 10 etc.

This works fine, but what I'd like to do is run the loop with every possible combination of X, Y and Z in increments of 5.

For example

```<code>X  Y  Z
5  5  5
10 5  5
15 5  5
.. .. ..
50 5  5
5  10 5
5  15 5
5  20 5
.. .. ..
10 10 5
10 15 5
</code>```

etc,

so all in all it would be 1000 possible combinations I think

Can i do this with something like itertools.permutations?

I'm pretty new to python and coding so help would be much appreciated

```<code>#python code
sizeX = (0)
sizeY = (0)
sizeZ = (0)
count = (0)

for i in range(0,10):
 count = (count + 1)
 sizeX = (sizeX + 5)
 sizeY = (sizeY + 5)
 sizeZ = (sizeZ + 5)

#run the code
</code>```

答:
If you know you will have 3 variables for certain, you can use nested for loops with range:

```<code>for i in range(5, 55, 5):
    for j in range(5, 55, 5):
        for k in range(5, 55, 5):
            print(i, j, k)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a bit of code that runs some stats for a moving 3D window at varying size. I have created a loop to to do this in increments of 5 from 5 to 50 as below.

For example first X = 5, Y = 5, Z = 5, then X = 10, Y = 10, z = 10 etc.

This works fine, but what I'd like to do is run the loop with every possible combination of X, Y and Z in increments of 5.

For example

X  Y  Z
5  5  5
10 5  5
15 5  5
.. .. ..
50 5  5
5  10 5
5  15 5
5  20 5
.. .. ..
10 10 5
10 15 5

etc,

so all in all it would be 1000 possible combinations I think

Can i do this with something like itertools.permutations?

I'm pretty new to python and coding so help would be much appreciated

#python code
sizeX = (0)
sizeY = (0)
sizeZ = (0)
count = (0)

for i in range(0,10):
 count = (count + 1)
 sizeX = (sizeX + 5)
 sizeY = (sizeY + 5)
 sizeZ = (sizeZ + 5)

#run the code

Body:
If you know you will have 3 variables for certain, you can use nested for loops with range:

for i in range(5, 55, 5):
    for j in range(5, 55, 5):
        for k in range(5, 55, 5):
            print(i, j, k)


问:
Find nearby postcode with a base postcode
This is with reference to this question: Find UK PostCodes closest to other UK Post Codes by matching the Post Code String

```<code>--User wants to get all postcodes nearby B193SH
-- Postcode  = 'B193SH'
-- Latitude  = 52.488460
-- Longitude = -1.895690

SELECT [HouseNumber],
             [Street],
             [Area],
             [PostCode],
             [Latitude],
             [Longitude],
FROM   [dbo].[Address]
WHERE  ([Latitude]  BETWEEN ( 52.488460 - 0.100000 ) AND ( 52.488460 + 0.100000 )) AND
             ([Longitude] BETWEEN ( -1.895690 - 0.100000 ) AND ( -1.895690 + 0.100000 ))
ORDER  BY [PostCode]
GO
</code>```

Executing this query, i get a couple of results. But the question stands that what difference (meters/miles) does a +/- 0.100000 to Lat/Lon makes?

Should I try to find close postcodes by using the first three letter of the base postcode, i.e., 'B19'?

Please see the reference question for a full detail of my scenerio.

Thanks!

答:
Given the approximate radius of the Earth being 6378.1 km.

Latitude (and longitude, when along equator)

```<code>2 * pi * 6378.1 * 0.1 / 360 = 11.1319 km (4 d.p.)
</code>```

Longitude when along x degrees north or south

For example, when at 50 degrees north:

```<code>2 * pi * 6378.1 * cos(50) * 0.1 / 360 = 7.1554 km (4 d.p.)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is with reference to this question: Find UK PostCodes closest to other UK Post Codes by matching the Post Code String

--User wants to get all postcodes nearby B193SH
-- Postcode  = 'B193SH'
-- Latitude  = 52.488460
-- Longitude = -1.895690

SELECT [HouseNumber],
             [Street],
             [Area],
             [PostCode],
             [Latitude],
             [Longitude],
FROM   [dbo].[Address]
WHERE  ([Latitude]  BETWEEN ( 52.488460 - 0.100000 ) AND ( 52.488460 + 0.100000 )) AND
             ([Longitude] BETWEEN ( -1.895690 - 0.100000 ) AND ( -1.895690 + 0.100000 ))
ORDER  BY [PostCode]
GO

Executing this query, i get a couple of results. But the question stands that what difference (meters/miles) does a +/- 0.100000 to Lat/Lon makes?

Should I try to find close postcodes by using the first three letter of the base postcode, i.e., 'B19'?

Please see the reference question for a full detail of my scenerio.

Thanks!

Body:
Given the approximate radius of the Earth being 6378.1 km.

Latitude (and longitude, when along equator)

2 * pi * 6378.1 * 0.1 / 360 = 11.1319 km (4 d.p.)

Longitude when along x degrees north or south

For example, when at 50 degrees north:

2 * pi * 6378.1 * cos(50) * 0.1 / 360 = 7.1554 km (4 d.p.)


问:
Dependency injection in .NET Azure Functions - Azure Cosmos DB Client
I read an article on Microsoft Docs about using dependency injection in .NET Azure Functions.

Everything works fine, as you can see in the article, it registers CosmosClient

```<code>builder.Services.AddSingleton((s) => {
     return new CosmosClient(Environment.GetEnvironmentVariable("COSMOSDB_CONNECTIONSTRING"));
    });
</code>```

The question is, how can I use Cosmos Client in my function?
I do not want to create every time instance of Cosmos Client.

```<code>public  class CosmosDbFunction
{
    public CosmosDbFunction()
    {

    }

    [FunctionName("CosmosDbFunction")]
    public  async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        // TODO: do something later
        return null;
    }
}
</code>```

答:
You don't have to use an interface.  You can just inject the CosmosClient directly.

There's an example of this in the Cosmos client samples directory which includes the following code:

private CosmosClient cosmosClient;
public AzureFunctionsCosmosClient(CosmosClient cosmosClient)
{
    this.cosmosClient = cosmosClient;
}
```

For testing, it seems the team creating this client has decided on the approach of making everything abstract/virtual to allow mocking frameworks to override methods as needed.  This is touched on in issue #303.  See also on Stack Overflow: How do I mock a class without an interface?

Body:
I read an article on Microsoft Docs about using dependency injection in .NET Azure Functions.

Everything works fine, as you can see in the article, it registers CosmosClient

builder.Services.AddSingleton((s) => {
     return new CosmosClient(Environment.GetEnvironmentVariable("COSMOSDB_CONNECTIONSTRING"));
    });

The question is, how can I use Cosmos Client in my function?
I do not want to create every time instance of Cosmos Client.

public  class CosmosDbFunction
{
    public CosmosDbFunction()
    {

    }

    [FunctionName("CosmosDbFunction")]
    public  async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        // TODO: do something later
        return null;
    }
}

Body:
You don't have to use an interface.  You can just inject the CosmosClient directly.

There's an example of this in the Cosmos client samples directory which includes the following code:

private CosmosClient cosmosClient;
public AzureFunctionsCosmosClient(CosmosClient cosmosClient)
{
    this.cosmosClient = cosmosClient;
}

For testing, it seems the team creating this client has decided on the approach of making everything abstract/virtual to allow mocking frameworks to override methods as needed.  This is touched on in issue #303.  See also on Stack Overflow: How do I mock a class without an interface?


问:
WebChat programmatic post activity not working - no message sent on button click
I am following these 2 samples:

Webchat with react

Programmatic post activity

My bot is working ok. I can send and process activities via directline. My test helpButton logs ok, but there is no actual 'help' message sent when I click the button like in the sample.

var mainBotConnection;

const { createStore, ReactWebChat } = window.WebChat;
const { createProvider } = window.ReactRedux;
const Provider = createProvider('webchat');
const Store = createStore();

// get a token
const RequestToken = async (user) => {
    ...
};

(async function () {
   RequestToken(agent)
        .then(token => {

            //init main chat bot
            mainBotConnection = window.WebChat.createDirectLine({token: token});

            ...

            //grab mainbot placeholder and put it on screen
            window.ReactDOM.render(
                <Provider store={Store}>
                    <ReactWebChat
                        directLine={mainBotConnection}
                        storeKey='webchat'
                        userID={user.id}
                        username={user.name}
                        styleOptions={mainBotStyleOptions}
                    />
                </Provider>,
                document.getElementById('webchat'));

            // this message does not appear
            Store.dispatch({
                type: 'WEB_CHAT/SEND_MESSAGE',
                payload: { text: 'StartUp hello!' }
            });
        });

    // test button
    document.querySelector('#helpButton').addEventListener('click', () => {
        // this is successfully logged
        console.log(`help button clicked`);

        // 'help' text does not appear in bot
        Store.dispatch({
            type: 'WEB_CHAT/SEND_MESSAGE',
            payload: { text: 'help' }
        });

        // this is also successfully logged
        console.log(Store);
    });

    document.querySelector('#webchat').focus();
})().catch(err => console.error(err));```

答:
You need to add store={Store} to your ReactWebChat component:

[...]
<Provider store={Store}>
    <ReactWebChat
        directLine={mainBotConnection}
        storeKey='webchat'
        userID={user.id}
        username={user.name}
        styleOptions={mainBotStyleOptions}
        store={Store} // ADD THIS PART
    />
</Provider>,
[...]
```

That being said, without the rest of your code, I wasn't able to test this exactly. Instead, I started up the React with Redux Sample. If I removed store={Store}, it didn't work, but if I left it in there, it worked just fine and sent both the welcome and help messages. You may also need: <Provider store={ store } key='webchat'>, but like I said, I wasn't able to test your exact code.

Body:
You need to add store={Store} to your ReactWebChat component:

[...]
<Provider store={Store}>
    <ReactWebChat
        directLine={mainBotConnection}
        storeKey='webchat'
        userID={user.id}
        username={user.name}
        styleOptions={mainBotStyleOptions}
        store={Store} // ADD THIS PART
    />
</Provider>,
[...]

That being said, without the rest of your code, I wasn't able to test this exactly. Instead, I started up the React with Redux Sample. If I removed store={Store}, it didn't work, but if I left it in there, it worked just fine and sent both the welcome and help messages. You may also need: <Provider store={ store } key='webchat'>, but like I said, I wasn't able to test your exact code.


问:
jQuery loop over JSON result from AJAX Success?
On the jQuery AJAX success callback I want to loop over the results of the object.     This is an example of how the response looks in Firebug.

```<code>[
 {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
 {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
 {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]
</code>```

How can I loop over the results so that I would have access to each of the elements?
I have tried something like below but this does not seem to be working.

```<code>jQuery.each(data, function(index, itemData) {
  // itemData.TEST1
  // itemData.TEST2
  // itemData.TEST3
});
</code>```

答:
If you are using the short method of JQuery ajax call function as shown below, the returned data needs to be interpreted as a json object for you to be able to loop through. </p>

```<code>$.get('url', function(data, statusText, xheader){
 // your code within the success callback
  var data = $.parseJSON(data);
  $.each(data, function(i){
         console.log(data[i]);
      })
})
</code>```

ContentLicense: CC BY-SA 2.5

Body:
On the jQuery AJAX success callback I want to loop over the results of the object.     This is an example of how the response looks in Firebug.

[
 {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
 {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
 {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]

How can I loop over the results so that I would have access to each of the elements?
I have tried something like below but this does not seem to be working.

jQuery.each(data, function(index, itemData) {
  // itemData.TEST1
  // itemData.TEST2
  // itemData.TEST3
});

Body:
If you are using the short method of JQuery ajax call function as shown below, the returned data needs to be interpreted as a json object for you to be able to loop through.

$.get('url', function(data, statusText, xheader){
 // your code within the success callback
  var data = $.parseJSON(data);
  $.each(data, function(i){
         console.log(data[i]);
      })
})


问:
Selecting adjacent and previous siblings in CSS
Say for instance I have the following HTML

```<code><ul>
  <li><a href="a">A</a></li>
  <li><a href="b">B</a></li>
  <li class="myclass"><a href="c">C</a></li>
  <li><a href="d">D</a></li>
  <li><a href="e">E</a></li>
</ul>
</code>```

Now I can detemine the next sibling to the li with the class="myclass" by using the following css .someclass + li {}. However if I wanted to apply a CSS rule to previous li, is it possible to do this using css rather than jQuery's $("#some-id").prevAll() or writing some JavaScript to find this?

I'm not that confident as I've never heard of this and my searching hasn't provided a solution.

Thanks

答: There is no selector that does that even in the CSS3 specification; you will either have to be creative in assigning classes to the elements and using other selectors, or go with jQuery.</p>

Body:
Say for instance I have the following HTML

A

B

C

D

E

Now I can detemine the next sibling to the li with the class="myclass" by using the following css .someclass + li {}. However if I wanted to apply a CSS rule to previous li, is it possible to do this using css rather than jQuery's $("#some-id").prevAll() or writing some JavaScript to find this?

I'm not that confident as I've never heard of this and my searching hasn't provided a solution.

Thanks


问:
Scaling an SVG that is not inline
First, let me apologise for not knowing the proper terms for things. I'm new to SVG and am working to a tight deadline.

I wanted some scalable icons for a website I am redesigning and I persuaded a graphic artist friend of mine to create these icons for me in Inkscape. These icons are meant to be very small, roughly 25 pixels x 25 pixels and to indicate email links, internal links and external links. I plan to use the appropriate one on each anchor tag in my site.

The icons she created are quite nice but render very large in the browser. Opening the icons in the Eclipse text editor, I can see the following values:

```<code>viewBox="0 0 540 540"
height="540"
width="540"

 y="0"

 preserveAspectRatio="none"
 height="540"
 width="540" />
</code>```

In the course of trying to figure out how to make the icons smaller, I've seen multiple references to this article as a good one for scaling SVGs: https://css-tricks.com/scale-svg/

Unfortunately, I'm getting quite confused on what I need to do in my case since I don't have an inline SVG. (I'm not sure what mine is properly called: an external SVG?) Also, I'm not using IMG or SVG tags in my HTML markup. I've created special classes of anchors called internal-link, external-link, and email-link and I'm pointing to my SVGs via ::before pseudo-selectors as in this example:

```<code>/* External link */
.external-link {
    background-color: green;
}
.external-link::before {
    content: url("../images/link-external-ana.svg") "  ";
}
</code>```

This approach allows me to keep my HTML markup nice and simple, as in this example:

```<code><p>Skype is a widely used
communications program that works on many computers, tablets, and WiFi-   connected smartphones.
Skype can be downloaded at <a class="external-link"   href="https://www.skype.com/en/" target="_blank">the Skype website</a>.</p>
</code>```

Unfortunately, the article doesn't address my approach where I am NOT using IMG or SRC tags or the content property of a ::before selector so I'm really not sure what to do to make my icon suitably small.

For what it's worth, I have tinkered with the icons themselves and changed the aforementioned values so that the 540 was changed to 35 in each instance and y was changed to 10 to push it down a bit to be roughly lined up with the baseline of the text shown in the anchor but I have to believe there is a better approach. Editing the icon itself would seem to limit it to being only one size forever and forcing me to make multiple versions of the icon for each size I want, which would appear to defeat the purpose of making them scalable in the first place. I'm hoping I can leave the icon unaltered and ONLY adjust the CSS to control the scaling.

Is that possible? If so, how?

答:
With many thanks to enxaneta, I now have my code working exactly as I wanted. The original SVG files are completely untouched and I've been able to keep my original HTML unchanged as well; I didn't add the div that enxaneta proposed and just did this:

```<code><p>Skype can be downloaded at <a class="external-link" href="https://www.skype.com/en/" target="_blank">the Skype website</a>.
</code>```

Ultimately, I just needed to tweak enxaneta's CSS a little bit so that now it says:

```<code>/* External link */
.external-link {
    background-color: green;
}
.external-link::before {
    content: "";
    display: inline-block; /* was block */
    width: 30px;
    height: 25px;
    background-position: -3px 2px;
    background-image: url("../images/icons/link-external-ana.svg");
    background-size: cover;
    }
</code>```

The height got reduced slightly so that I could push my icon down a few pixels. I added the background-position property to enable me to move the icon around a bit within its bounding box. I found that the width, height, and margin properties in the .external-link selector that enxaneta provided made no difference at all so I just deleted them. Now my icons appear right where I want them to be.

Enxaneta's reply was extremely valuable to me because I really didn't know that I could use anything beyond the content property in a ::before pseudo-selector! The only examples I had seen showed only the content property. Knowing that I can use all the standard properties there did a lot to enable me to tweak enxaneta's suggestion to fit my precise needs.

I hope this helps someone in the future....

Title: Scaling an SVG that is not inline

Body:
First, let me apologise for not knowing the proper terms for things. I'm new to SVG and am working to a tight deadline.

I wanted some scalable icons for a website I am redesigning and I persuaded a graphic artist friend of mine to create these icons for me in Inkscape. These icons are meant to be very small, roughly 25 pixels x 25 pixels and to indicate email links, internal links and external links. I plan to use the appropriate one on each anchor tag in my site.

The icons she created are quite nice but render very large in the browser. Opening the icons in the Eclipse text editor, I can see the following values:

viewBox="0 0 540 540"
height="540"
width="540"

 y="0"

 preserveAspectRatio="none"
 height="540"
 width="540" />

In the course of trying to figure out how to make the icons smaller, I've seen multiple references to this article as a good one for scaling SVGs: https://css-tricks.com/scale-svg/

Unfortunately, I'm getting quite confused on what I need to do in my case since I don't have an inline SVG. (I'm not sure what mine is properly called: an external SVG?) Also, I'm not using IMG or SVG tags in my HTML markup. I've created special classes of anchors called internal-link, external-link, and email-link and I'm pointing to my SVGs via ::before pseudo-selectors as in this example:

/* External link */
.external-link {
    background-color: green;
}
.external-link::before {
    content: url("../images/link-external-ana.svg") "  ";
}

This approach allows me to keep my HTML markup nice and simple, as in this example:

Skype is a widely used
communications program that works on many computers, tablets, and WiFi-   connected smartphones.
Skype can be downloaded at the Skype website.

Unfortunately, the article doesn't address my approach where I am NOT using IMG or SRC tags or the content property of a ::before selector so I'm really not sure what to do to make my icon suitably small.

For what it's worth, I have tinkered with the icons themselves and changed the aforementioned values so that the 540 was changed to 35 in each instance and y was changed to 10 to push it down a bit to be roughly lined up with the baseline of the text shown in the anchor but I have to believe there is a better approach. Editing the icon itself would seem to limit it to being only one size forever and forcing me to make multiple versions of the icon for each size I want, which would appear to defeat the purpose of making them scalable in the first place. I'm hoping I can leave the icon unaltered and ONLY adjust the CSS to control the scaling.

Is that possible? If so, how?

Body:
With many thanks to enxaneta, I now have my code working exactly as I wanted. The original SVG files are completely untouched and I've been able to keep my original HTML unchanged as well; I didn't add the div that enxaneta proposed and just did this:

<p>Skype can be downloaded at <a class="external-link" href="https://www.skype.com/en/" target="_blank">the Skype website</a>.

Ultimately, I just needed to tweak enxaneta's CSS a little bit so that now it says:

/* External link */
.external-link {
    background-color: green;
}
.external-link::before {
    content: "";
    display: inline-block; /* was block */
    width: 30px;
    height: 25px;
    background-position: -3px 2px;
    background-image: url("../images/icons/link-external-ana.svg");
    background-size: cover;
    }

The height got reduced slightly so that I could push my icon down a few pixels. I added the background-position property to enable me to move the icon around a bit within its bounding box. I found that the width, height, and margin properties in the .external-link selector that enxaneta provided made no difference at all so I just deleted them. Now my icons appear right where I want them to be.

Enxaneta's reply was extremely valuable to me because I really didn't know that I could use anything beyond the content property in a ::before pseudo-selector! The only examples I had seen showed only the content property. Knowing that I can use all the standard properties there did a lot to enable me to tweak enxaneta's suggestion to fit my precise needs.

I hope this helps someone in the future....


问:
Testing if a java program calls System.exist - without exiting Junit
I am trying to test a file processing program with Junit. In some cases, the program should print an error and finish its run. However, using "System.exit(-1)" causes the program to exit the entire Junit tests.
Is there some way of avoiding it?

I can instead print the error and then return null, however I find it quite inelegant.

    private List<String> parseData(String[] args){
        if (args.length != 2){
            System.err.println(ERROR + INPUT_ERROR + "\n");
            System.exit(EXIT_CODE);
```

Is there a way to check if the program called "System.exit" without closing it?
Thank you.

答:
While I think AdrianM's solution is the ideal one, you could also solve this with mocking.

Option one: Use a mocking framework such as PowerMock that lets you mock static methods so that you can make System.exit do nothing.

Option two: Use dependency injection and any mocking framework. Create this interface and implementing class:

```<code>public interface SystemExit {
    void exit(int code);
}

public class SystemExitImpl implements SystemExit {
    public void exit(int code) {
        System.exit(code);
    }
}
</code>```

Then, make the class that contains parseData take a SystemExit as a constructor parameter and store it in a member variable (or have a setter for the member variable that lets you set it after construction). In your production code, pass a SystemExitImpl. In your test, create a mock for SystemExit and pass that instead.

Body:
I am trying to test a file processing program with Junit. In some cases, the program should print an error and finish its run. However, using "System.exit(-1)" causes the program to exit the entire Junit tests.
Is there some way of avoiding it?

I can instead print the error and then return null, however I find it quite inelegant.

    private List<String> parseData(String[] args){
        if (args.length != 2){
            System.err.println(ERROR + INPUT_ERROR + "\n");
            System.exit(EXIT_CODE);

Is there a way to check if the program called "System.exit" without closing it?
Thank you.

Body:
While I think AdrianM's solution is the ideal one, you could also solve this with mocking.

Option one: Use a mocking framework such as PowerMock that lets you mock static methods so that you can make System.exit do nothing.

Option two: Use dependency injection and any mocking framework. Create this interface and implementing class:

public interface SystemExit {
    void exit(int code);
}

public class SystemExitImpl implements SystemExit {
    public void exit(int code) {
        System.exit(code);
    }
}

Then, make the class that contains parseData take a SystemExit as a constructor parameter and store it in a member variable (or have a setter for the member variable that lets you set it after construction). In your production code, pass a SystemExitImpl. In your test, create a mock for SystemExit and pass that instead.


问:
How to animate Android Navigation Architecture fragment as sliding over old fragment?
In example navigation action defined in navigation graph:

```<code><action
    android:id="@+id/action_fragment1_to_fragment2"
    app:destination="@id/fragment2"
    app:enterAnim="@anim/right_slide_in"
    app:popExitAnim="@anim/left_slide_out"/>
</code>```

When Fragment2 opens and starts sliding into view from the right, Fragment1 disappears instantly (sadly). When Fragment2 is closed and starts sliding to the right, Fragment1 is nicely visible under it, giving a nice stack pop effect (comparable to iOS).

How can I keep Fragment1 visible while Fragment2 slides into view?

答:
I think using the R.anim.hold animation will create the effect you want:

```<code>int holdingAnimation = R.anim.hold;
int inAnimation = R.anim.right_slide_in;
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(inAnimation, holdingAnimation, inAnimation, holdingAnimation);
/*
... Add in your fragments and other navigation calls
*/
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
</code>```

Or just label it as you have within the action.

Here is the R.anim.hold animation mentioned above:

```<code><?xml version="1.0" encoding="utf-8"?>
<set
    xmlns:android="http://schemas.android.com/apk/res/android">
  <translate
      android:duration="@android:integer/config_longAnimTime"
      android:fromYDelta="0.0%p"
      android:toYDelta="0.0%p"/>
</set>
</code>```

Body:
In example navigation action defined in navigation graph:

<action
    android:id="@+id/action_fragment1_to_fragment2"
    app:destination="@id/fragment2"
    app:enterAnim="@anim/right_slide_in"
    app:popExitAnim="@anim/left_slide_out"/>

When Fragment2 opens and starts sliding into view from the right, Fragment1 disappears instantly (sadly). When Fragment2 is closed and starts sliding to the right, Fragment1 is nicely visible under it, giving a nice stack pop effect (comparable to iOS).

How can I keep Fragment1 visible while Fragment2 slides into view?

Body:
I think using the R.anim.hold animation will create the effect you want:

int holdingAnimation = R.anim.hold;
int inAnimation = R.anim.right_slide_in;
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(inAnimation, holdingAnimation, inAnimation, holdingAnimation);
/*
... Add in your fragments and other navigation calls
*/
transaction.commit();
getSupportFragmentManager().executePendingTransactions();

Or just label it as you have within the action.

Here is the R.anim.hold animation mentioned above:

<?xml version="1.0" encoding="utf-8"?>
<set
    xmlns:android="http://schemas.android.com/apk/res/android">
  <translate
      android:duration="@android:integer/config_longAnimTime"
      android:fromYDelta="0.0%p"
      android:toYDelta="0.0%p"/>
</set>


问:
How to create a collapsing tree table in html/css/js?
I have some data to display that is both tabular and hierarchical. I'd like to let the user be able to expand and collapse the nodes.

Sort of like this, except functional:

http://www.maxdesign.com.au/articles/tree-table/

What would be the best way to approach this? I'm not adverse to using an off-the-shelf plugin.

答:
I'll throw jsTree into the ring, too.  I've found it fairly adaptable to your particular situation.  It's packed as a jQuery plugin.

It can run from a variety of data sources, but my favorite is a simple nested list, as described by @joe_coolish or here:

```<code><ul>
  <li>
    Item 1
    <ul>
      <li>Item 1.1</li>
      ...
    </ul>
  </li>
  ...
</ul>
</code>```

This structure fails gracefully into a static tree when JS is not available in the client, and is easy enough to read and understand from a coding perspective.

Body:
I'll throw jsTree into the ring, too.  I've found it fairly adaptable to your particular situation.  It's packed as a jQuery plugin.

It can run from a variety of data sources, but my favorite is a simple nested list, as described by @joe_coolish or here:

<ul>
  <li>
    Item 1
    <ul>
      <li>Item 1.1</li>
      ...
    </ul>
  </li>
  ...
</ul>

This structure fails gracefully into a static tree when JS is not available in the client, and is easy enough to read and understand from a coding perspective.


问:
switchMap after catchError does not emit values
I'm using Angular and RxJS.

I intend to add an item to a collection (1st Observable), and then get the collection (2nd Observable), everything on the same stream of data.

Then I offer the Observable to the component and a child component receives it with an async pipeline.

The problem appears when first addItem AJAX call fails. I tried to keep returning the whole updated list of collection items, so child component has fresh data, but last step is never done and child item never receives the collection after an addItem fail.

This is my code:

public addItem(item) {

  this.itemCollection$ = this.itemService.addItem(item).pipe(
        catchError((err) => {
          this.logger.error('Couldnt add Item to Collection');
          return of();
        }),
        switchMap(() =>
  this.itemsService.getItemsByItemId(this.itemId)));

}
```

<p>Console result:</p>

```POST http://localhost:3000/api/XXXX/XXX/XXXXX/items 400 (Bad Request)
ngx-logger.js:245 2019-05-29T17:25:39.557Z ERROR [items-page-module.9c3988b4c0f0dbc7bc65.hot-update.js:319] Couldnt add Item to Collection
```

So error is logged on console, but child component never gets the new list of items.

What should I do so itemCollection$ observable emits an item's collection, despite of the error?

Thank you!

答:
When you call of() it creates an observable that emits nothing but immediately completes, because it was given no arguments. The problem is that the switchMap() operator will only trigger in response to an emitted value.

Therefore, the following effectively silences all errors in an observable.

    throwError('ouch').pipe(
        catchError(() => of())
    ).subscribe(()=> {
         console.log('I am never printed');
    }, ()=> {
         console.log('I am never printed');
    }, ()=> {
         console.log('COMPLETED!'); // this will be printed.
    });
```
<p>In the above example, the <code>catchError()</code> transitions to an <em>empty</em> observable. Neither the subscriber callback or error callback are executed. Only the complete callback is executed.</p>
<p>Any operators that exist after the <code>catchError()</code> are never used because nothing is emitted.</p>
<p>You can <em>fix</em> this by emitting <em>undefined</em> or any other value.</p>
<pre class="lang-ts prettyprint-override"><code>public addItem(item) {
    this.itemCollection$ = this.itemService.addItem(item).pipe(
        catchError((err) => {
          this.logger.error('Couldnt add Item to Collection');
          return of(undefined);
        }),
        switchMap(() => this.itemsService.getItemsByItemId(this.itemId)));
}
</code>```

Body:
I'm using Angular and RxJS.

I intend to add an item to a collection (1st Observable), and then get the collection (2nd Observable), everything on the same stream of data.

Then I offer the Observable to the component and a child component receives it with an async pipeline.

The problem appears when first addItem AJAX call fails. I tried to keep returning the whole updated list of collection items, so child component has fresh data, but last step is never done and child item never receives the collection after an addItem fail.

This is my code:

public addItem(item) {

  this.itemCollection$ = this.itemService.addItem(item).pipe(
        catchError((err) => {
          this.logger.error('Couldnt add Item to Collection');
          return of();
        }),
        switchMap(() =>
  this.itemsService.getItemsByItemId(this.itemId)));

}

Console result:

POST http://localhost:3000/api/XXXX/XXX/XXXXX/items 400 (Bad Request)
ngx-logger.js:245 2019-05-29T17:25:39.557Z ERROR [items-page-module.9c3988b4c0f0dbc7bc65.hot-update.js:319] Couldnt add Item to Collection

So error is logged on console, but child component never gets the new list of items.

What should I do so itemCollection$ observable emits an item's collection, despite of the error?

Thank you!

Body:
When you call of() it creates an observable that emits nothing but immediately completes, because it was given no arguments. The problem is that the switchMap() operator will only trigger in response to an emitted value.

Therefore, the following effectively silences all errors in an observable.

    throwError('ouch').pipe(
        catchError(() => of())
    ).subscribe(()=> {
         console.log('I am never printed');
    }, ()=> {
         console.log('I am never printed');
    }, ()=> {
         console.log('COMPLETED!'); // this will be printed.
    });

In the above example, the catchError() transitions to an empty observable. Neither the subscriber callback or error callback are executed. Only the complete callback is executed.

Any operators that exist after the catchError() are never used because nothing is emitted.

You can fix this by emitting undefined or any other value.

public addItem(item) {
    this.itemCollection$ = this.itemService.addItem(item).pipe(
        catchError((err) => {
          this.logger.error('Couldnt add Item to Collection');
          return of(undefined);
        }),
        switchMap(() => this.itemsService.getItemsByItemId(this.itemId)));
}


问:
Multiline text to fit parent container in React JS
I am using a flexbox layout and am trying to get the text in a specific div to be resized to fit that div.

So for example, if I have code as follows:

```<code><div style={{display: "flex"}}>
   <div style={{flex: 1}}>
      A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.
   </div>
   <div style={{flex: 1}}>
      Some other text
   </div>
</div>
</code>```

In reality, the text will be pulled from a database, so will be dynamic in length.

How can I get the text in the first div to automatically adjust to fit the entire div?

Clarification: the div should stay a fixed size and only the text should be downsized to fit the div rather than overflowing the div.

Update

I have also posted a more specific question about a specific module called react-textfit not working the way I would expect it to work.

答:
Here is some code that should do what you are asking.

```<code>let size_div = document.querySelector("#font_size");
let div = document.querySelector("#fixed");

while (div.scrollHeight > div.clientHeight) {
  let style = window.getComputedStyle(div, null).getPropertyValue('font-size');
  let fontSize = parseFloat(style);

  if (fontSize <= 1) {
    break;
  }

  div.style.fontSize = "" + (fontSize - 1) + "px";
  size_div.innerHTML = " " + div.style.fontSize;
}
</code>```

You can try it out here:
https://codepen.io/lowtex/pen/xNawEO

Body:
I am using a flexbox layout and am trying to get the text in a specific div to be resized to fit that div.

So for example, if I have code as follows:

      A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.

      Some other text

In reality, the text will be pulled from a database, so will be dynamic in length.

How can I get the text in the first div to automatically adjust to fit the entire div?

Clarification: the div should stay a fixed size and only the text should be downsized to fit the div rather than overflowing the div.

Update

I have also posted a more specific question about a specific module called react-textfit not working the way I would expect it to work.

Body:
Here is some code that should do what you are asking.

let size_div = document.querySelector("#font_size");
let div = document.querySelector("#fixed");

while (div.scrollHeight > div.clientHeight) {
  let style = window.getComputedStyle(div, null).getPropertyValue('font-size');
  let fontSize = parseFloat(style);

  if (fontSize <= 1) {
    break;
  }

  div.style.fontSize = "" + (fontSize - 1) + "px";
  size_div.innerHTML = "&nbsp;" + div.style.fontSize;
}

You can try it out here:
https://codepen.io/lowtex/pen/xNawEO


问:
Upload File Directly to Google Cloud Storage from user's webpage
I have a web application.
It is similar to WeTransfer.
Upload file from browser and share link with receiver.
I want to upload user's file directly to Google Cloud storage, and then share the link of file with someone who can download the file. I have seen some codes of uploading with C# which requires passing of file through our server towards Google Cloud Storage, But I want to directly upload from user's browser (JavaScript) to google cloud storage and then share the link. </p>

<p>Is that possible in any way without exposing credentials to JavaScript?
If yes then HOW? </p>

答:
There are lots of examples on the Internet in most languages including JavaScript. Google search and study how this is done. You are possibly choosing the worst environment for accomplishing your goal (JavaScript in a Browser). Some companies spend months trying to get the browser interface and to upload objects correctly when they need absolutely clean code (no copyright issues) AND need to handle all the problems that the public Internet causes worldwide.

From a design / security view I will give you some tips:

You will need to use signed-urls. This prevents leaking credentials. This is a pain to get correct for browser-based uploads. The alternatives are to open the bucket to the public which is VERY DANGEROUS or to use an intermediary such as Google Compute Engine.

Providing this service will cost you money. At this time network egress starts at $0.12 per GB and goes up depending on the region. This price will drop in the third/fourth quarter of 2019 to $0.105 per GB.

You mentioned sending a link. You will need a form for the user to enter the email address. Then you need to store that email address in a database such as Cloud Datastore.

Once the upload completes, you need logic to connect the file upload with the email address stored in step #3. Cloud Storage supports triggers so that a backed service can be notified that the file transfer is complete. You then map the email address to the Cloud Storage object and send an email. Use Cloud Pub/Sub to receive notifications from Cloud Storage and then call either Cloud Functions or Cloud Run to process and fire off the email.

Good luck with this project. Getting a prototype working is not that difficult. Handling all the real world issues, browser incompatibilities, mobile (iOS and Android), etc. will drive you nuts.

Body:
I have a web application.
It is similar to WeTransfer.
Upload file from browser and share link with receiver.
I want to upload user's file directly to Google Cloud storage, and then share the link of file with someone who can download the file. I have seen some codes of uploading with C# which requires passing of file through our server towards Google Cloud Storage, But I want to directly upload from user's browser (JavaScript) to google cloud storage and then share the link.

Is that possible in any way without exposing credentials to JavaScript?
If yes then HOW?


问:
Why Volley response is received as "[" and not JSON
I am learning about Volley and I don't know why the response from  GET method is coming as a single char -> [.

I am using this method to get the JSON response:

```<code>    public void getJsonMethod() {
    // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(context);
    // String url = "https://www.w3schools.com/js/myTutorials.txt";
    String url = "http://www.google.com"; // with this url I am getting response

    // Request a string response from the provided URL.
    final StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    System.out.println("Response is: " + response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println("Response is not good" + error.getMessage());
        }
    });
    // Add the request to the RequestQueue.
    queue.add(stringRequest);
}
</code>```

When I am using this link I do get a response but when I try to use some link that contains nothing but JSON like this one my response it "[".

I am calling this method from Activity like this:

```<code> GetJsonClass getJson = new GetJsonClass(this);
 getJson.getJsonMethod();
</code>```

Any ideas on what am I doing wrong here?

Answer + code

If anyone will start using Volley maybe this can help him :

as David Lacroix said in his answer, I called stringRequest and notJsonArrayRequest.

Here is how it should have been:

```<code>   public void getJsonMethod() {
    // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(context);
    String url = "your url";
    JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            System.out.println("this is response good" + response);
        }
    }, new ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println("this is response bad" + error);
        }
    });
    queue.add(jsonObjectRequest);
}
</code>```

答:
myTutorials.txt  is being served with status code 304 (no proper suffix and MIME type either):

304 Not Modified. If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code. The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.

In other terms, what the browser may display is not neccessarily the same what the server has sent. eg. GSON would accept that JSON only with option lenient enabled, because the array has no name.

see RFC 2616.

Body:
I am learning about Volley and I don't know why the response from  GET method is coming as a single char -> [.

I am using this method to get the JSON response:

    public void getJsonMethod() {
    // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(context);
    // String url = "https://www.w3schools.com/js/myTutorials.txt";
    String url = "http://www.google.com"; // with this url I am getting response

    // Request a string response from the provided URL.
    final StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    System.out.println("Response is: " + response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println("Response is not good" + error.getMessage());
        }
    });
    // Add the request to the RequestQueue.
    queue.add(stringRequest);
}

When I am using this link I do get a response but when I try to use some link that contains nothing but JSON like this one my response it "[".

I am calling this method from Activity like this:

 GetJsonClass getJson = new GetJsonClass(this);
 getJson.getJsonMethod();

Any ideas on what am I doing wrong here?

Answer + code

If anyone will start using Volley maybe this can help him :

as David Lacroix said in his answer, I called stringRequest and notJsonArrayRequest.

Here is how it should have been:

   public void getJsonMethod() {
    // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(context);
    String url = "your url";
    JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            System.out.println("this is response good" + response);
        }
    }, new ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println("this is response bad" + error);
        }
    });
    queue.add(jsonObjectRequest);
}


问:
How can I keep doxygen from documenting #defines in a C file?
I have #define values in headers that I certainly want Doxygen to document but I have others in C files that I treat as static constants and I don't want Doxygen to document them.  Something as simple and stupid as

```<code>#define NUMBER_OF(a) (sizeof((a))/sizeof((a)[0]))
#define MSTR(e) #e
</code>```

How can I keep Doxygen from putting those #defines in the documentation it creates? I've tried marking it with @internal but that didn't seem to help.

A somewhat-related question on Doxygen and #define, how can I get:

```<code>#define SOME_CONSTANT 1234 /**< An explanation */
</code>```

to put "SOME_CONSTANT" and "An explanation" but not "1234" in the output?

答:
There is no need to use the \cond and \endcond commands. You can hide the initializer by simply using the \hideinitializer command:

```<code>#define SOME_CONSTANT 1234 /**< An explanation @hideinitializer */
</code>```

Regarding the first question, you may set HIDE_UNDOC_MEMBERS = YES and only the macros having a Doxygen documentation block will be shown in the output.

Body:
I have #define values in headers that I certainly want Doxygen to document but I have others in C files that I treat as static constants and I don't want Doxygen to document them.  Something as simple and stupid as

#define NUMBER_OF(a) (sizeof((a))/sizeof((a)[0]))
#define MSTR(e) #e

How can I keep Doxygen from putting those #defines in the documentation it creates? I've tried marking it with @internal but that didn't seem to help.

A somewhat-related question on Doxygen and #define, how can I get:

#define SOME_CONSTANT 1234 /**< An explanation */

to put "SOME_CONSTANT" and "An explanation" but not "1234" in the output?

Body:
There is no need to use the \cond and \endcond commands. You can hide the initializer by simply using the \hideinitializer command:

#define SOME_CONSTANT 1234 /**< An explanation @hideinitializer */

Regarding the first question, you may set HIDE_UNDOC_MEMBERS = YES and only the macros having a Doxygen documentation block will be shown in the output.


问:
Remove objects from array in CodeIgniter
I have this function:

```<code>public function get_free_courtrooms() {
        $post = file_get_contents('php://input');
        $_POST = json_decode($post, true);

        $date = $this->input->post('date', true);
        $time_start = $this->input->post('time_start', true);
        $time_end = $this->input->post('time_end', true);

        $where = array('date' => $date);
        $reservations = $this->MY_Model->get('reservations', $where);

        $courtrooms = $this->MY_Model->get('courtrooms');

        $output = array(
            'free_courtrooms' => $free_courtrooms
        );

        echo json_encode($output);
        exit();
    }
</code>```

I need to remove all courtrooms from $courtrooms that are booked in sending hours ($time_start, $time_end).

In reservations table I have:

id

courtroom_id

date

time_start

time_end

答:
I would start with simple function to check overlapping 2 time:

```<code>function isOverlap($s1, $e1, $s2, $e2) {
    return (($s1 > $s2 && $s1 < $e2) || ($e1 > $s2 && $e1 < $e2)
            || ($s1 < $s2 && $e1 > $2) || ($s1 > $s2 && $e1 < $e2));
}
</code>```

This will be visualization of the 4 cases:

```<code>---     |    ---  |   -------   |     ---
  ---   |   ---   |     ---     |   -------
</code>```

Now just fill array of all busy rooms:

```<code>foreach($reservations as $res) {
    if (isOverlap($time_start, $time_end, $res["start"], $res["end"]))
        $busy_courtrooms[] = $res["id"];
}
</code>```

Now calculate the diff between all the $courtrooms and the $busy_courtrooms using array-diff:

```<code>$free_courtrooms = array_diff($courtrooms, $busy_courtrooms);
</code>```

And you done

I don't now how your $reservations array is build but I guess it has "start" and "end" attribute...

Body:
I have this function:

public function get_free_courtrooms() {
        $post = file_get_contents('php://input');
        $_POST = json_decode($post, true);

        $date = $this->input->post('date', true);
        $time_start = $this->input->post('time_start', true);
        $time_end = $this->input->post('time_end', true);

        $where = array('date' => $date);
        $reservations = $this->MY_Model->get('reservations', $where);

        $courtrooms = $this->MY_Model->get('courtrooms');

        $output = array(
            'free_courtrooms' => $free_courtrooms
        );

        echo json_encode($output);
        exit();
    }

I need to remove all courtrooms from $courtrooms that are booked in sending hours ($time_start, $time_end).

In reservations table I have:

id

courtroom_id

date

time_start

time_end

Body:
I would start with simple function to check overlapping 2 time:

function isOverlap($s1, $e1, $s2, $e2) {
    return (($s1 > $s2 && $s1 < $e2) || ($e1 > $s2 && $e1 < $e2)
            || ($s1 < $s2 && $e1 > $2) || ($s1 > $s2 && $e1 < $e2));
}

This will be visualization of the 4 cases:

---     |    ---  |   -------   |     ---
  ---   |   ---   |     ---     |   -------

Now just fill array of all busy rooms:

foreach($reservations as $res) {
    if (isOverlap($time_start, $time_end, $res["start"], $res["end"]))
        $busy_courtrooms[] = $res["id"];
}

Now calculate the diff between all the $courtrooms and the $busy_courtrooms using array-diff:

$free_courtrooms = array_diff($courtrooms, $busy_courtrooms);

And you done

I don't now how your $reservations array is build but I guess it has "start" and "end" attribute...


问:
how to " sort csv file" python
I'm trying to create a new file that contains only the data for movies with a rank above 9.

The dataset that I'm analyzing contains rating on many movies obtained from IMDB.
The data fields are:

Votes: the number of people rating the movie

Rank: the averate rating of the movie

Title: the name of the movie

Year: the year in which the movie was released

The code I tried:

```<code>import csv

filename = "IMDB.txt"
with open(filename, 'rt', encoding='utf-8-sig') as imdb_file:
    imdb_reader = csv.DictReader(imdb_file, delimiter = '\t')
    with open('new file.csv', 'w', newline='') as high_rank:
        fieldnames = ['Votes', 'Rank', 'Title', 'Year']
        writer = csv.DictWriter(high_rank, fieldnames=fieldnames)
        writer.writeheader()
        for line_number, current_row in enumerate (imdb_reader):
            if(float(current_row['Rank']) > 9.0):
                csv_writer.writerow(dict(current_row))
</code>```

but unfortunately its not working, what should i do ?

答:
Based on your comment, your locale default encoding appears to be something that doesn't support the whole Unicode range. You need to specify an encoding for the output file that will handle arbitrary Unicode characters. Typically, on non-Windows systems you'd use 'utf-8'; on Windows, you might use 'utf-16' or 'utf-8-sig' (Windows programs often assume UTF-8 without an explicit signature is in the locale encoding, and misinterpret it). The fix is as simple as changing:

```<code>with open('new file.csv', 'w', newline='') as high_rank:
</code>```

to:

```<code>with open('new file.csv', 'w', encoding='utf-8', newline='') as high_rank:
</code>```

changing the specified encoding to whatever makes sense for your OS and use case.

Title: how to " sort csv file" python

Body:
I'm trying to create a new file that contains only the data for movies with a rank above 9.

The dataset that I'm analyzing contains rating on many movies obtained from IMDB.
The data fields are:

Votes: the number of people rating the movie

Rank: the averate rating of the movie

Title: the name of the movie

Year: the year in which the movie was released

The code I tried:

import csv

filename = "IMDB.txt"
with open(filename, 'rt', encoding='utf-8-sig') as imdb_file:
    imdb_reader = csv.DictReader(imdb_file, delimiter = '\t')
    with open('new file.csv', 'w', newline='') as high_rank:
        fieldnames = ['Votes', 'Rank', 'Title', 'Year']
        writer = csv.DictWriter(high_rank, fieldnames=fieldnames)
        writer.writeheader()
        for line_number, current_row in enumerate (imdb_reader):
            if(float(current_row['Rank']) > 9.0):
                csv_writer.writerow(dict(current_row))

but unfortunately its not working, what should i do ?

Body:
Based on your comment, your locale default encoding appears to be something that doesn't support the whole Unicode range. You need to specify an encoding for the output file that will handle arbitrary Unicode characters. Typically, on non-Windows systems you'd use 'utf-8'; on Windows, you might use 'utf-16' or 'utf-8-sig' (Windows programs often assume UTF-8 without an explicit signature is in the locale encoding, and misinterpret it). The fix is as simple as changing:

with open('new file.csv', 'w', newline='') as high_rank:

to:

with open('new file.csv', 'w', encoding='utf-8', newline='') as high_rank:

changing the specified encoding to whatever makes sense for your OS and use case.


问:
All items in list query with nHibernate
I know there is the Restriction "In" which allows to detect if one or more elements in property is in target list but I need something which would tell me if all the items from property are in target list. Here's an example:

I want a person with all these Competencies

```<code>CompetenciesCriterion : IList<Competency>
  { Walking, Running, Rolling }
</code>```

Between PersonA and PersonB:

```<code>PersonA : Person
  Competencies : IList<Competency>
    { Walking }

PersonB : Person
  Competencies : IList<Competency>
    { Walking, Rolling, Running }
</code>```

Is there a Restriction or Expression which would allow me to execute this search or do you know a clean way to do this instead of stacking the "In" within a "Conjunction"?

Thanks in advance,

Étienne Brouillard

答:
I found a way to get the result I wanted. Stacking "In" is not working so I figured out that using a subquery and counting the "In" will produce a criteria on which I can verify the condition that the counts are equal.

Here's a sample:

```<code>var competencySubQuery = DetachedCriteria.For<Employee>("employee2");
competencySubQuery.CreateAlias("employee2.Competencies", "employee2Competencies");
competencySubQuery.SetProjection(Projections.Count(Projections.Property("employee2Competencies.Competency")));
competencySubQuery.Add(Restrictions.In("employee2Competencies.Competency",     searchCriteria.Competencies));
competencySubQuery.Add(Restrictions.EqProperty("employee2.Id", "Employee.Id"));
criteriaJunction.Add(Subqueries.Eq(searchCriteria.Competencies.Count(), competencySubQuery));
</code>```

criteriaJunction being the criteria used in the end for the FindAll and searchCriteria
 being the POCO containing the criteria sent to a service.

Title: All items in list query with nHibernate

Body:
I know there is the Restriction "In" which allows to detect if one or more elements in property is in target list but I need something which would tell me if all the items from property are in target list. Here's an example:

I want a person with all these Competencies

CompetenciesCriterion : IList<Competency>
  { Walking, Running, Rolling }

Between PersonA and PersonB:

PersonA : Person
  Competencies : IList<Competency>
    { Walking }

PersonB : Person
  Competencies : IList<Competency>
    { Walking, Rolling, Running }

Is there a Restriction or Expression which would allow me to execute this search or do you know a clean way to do this instead of stacking the "In" within a "Conjunction"?

Thanks in advance,

Étienne Brouillard

Body:
I found a way to get the result I wanted. Stacking "In" is not working so I figured out that using a subquery and counting the "In" will produce a criteria on which I can verify the condition that the counts are equal.

Here's a sample:

var competencySubQuery = DetachedCriteria.For<Employee>("employee2");
competencySubQuery.CreateAlias("employee2.Competencies", "employee2Competencies");
competencySubQuery.SetProjection(Projections.Count(Projections.Property("employee2Competencies.Competency")));
competencySubQuery.Add(Restrictions.In("employee2Competencies.Competency",     searchCriteria.Competencies));
competencySubQuery.Add(Restrictions.EqProperty("employee2.Id", "Employee.Id"));
criteriaJunction.Add(Subqueries.Eq(searchCriteria.Competencies.Count(), competencySubQuery));

criteriaJunction being the criteria used in the end for the FindAll and searchCriteria
 being the POCO containing the criteria sent to a service.


问:
How do I turn off the HAL browser on my product?
```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-rest-hal-browser</artifactId>
</dependency>
</code>```

Testing was easy with the HAL browser in Spring Data Rest, but I would like to turn off the HAL browser in the product version.

I think there are two ways.

Separate the controller that applies only to the product version profile to prevent routing.

At build time, block dependecy references by profile. (In my case maven, exclude setting)

I do not know if this is a good way. Is there any alternative, or why should not I turn off the HAL browser?

答:
One way to do this is by using a maven profile to enable the HAL-browser

```<code>    <profiles>
        <profile>
            <id>HAL_BROWSER</id>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.data</groupId>
                    <artifactId>spring-data-rest-hal-browser</artifactId>
                </dependency>
            </dependencies>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 ....
</code>```

if you want the HAL-browser switched on, just launch your app like:

```<code>mvn spring-boot:run -PHAL_BROWSER
</code>```

Body:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-rest-hal-browser</artifactId>
</dependency>

Testing was easy with the HAL browser in Spring Data Rest, but I would like to turn off the HAL browser in the product version.

I think there are two ways.

Separate the controller that applies only to the product version profile to prevent routing.

At build time, block dependecy references by profile. (In my case maven, exclude setting)

I do not know if this is a good way. Is there any alternative, or why should not I turn off the HAL browser?

Body:
One way to do this is by using a maven profile to enable the HAL-browser

    <profiles>
        <profile>
            <id>HAL_BROWSER</id>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.data</groupId>
                    <artifactId>spring-data-rest-hal-browser</artifactId>
                </dependency>
            </dependencies>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 ....

if you want the HAL-browser switched on, just launch your app like:

mvn spring-boot:run -PHAL_BROWSER


问:
Why is it not a good practice to synchronize on Boolean?
My architect always says that

Never synchronize on Boolean

I am not able to understand the reason why and would really appreciate if someone could explain with an example as to why it is not a good practice.
Reference Sample Code

```<code>private Boolean isOn = false;
private String statusMessage = "I'm off";
public void doSomeStuffAndToggleTheThing(){

   // Do some stuff
   synchronized(isOn){
      if(isOn){
         isOn = false;
         statusMessage = "I'm off";
         // Do everything else to turn the thing off
      } else {
         isOn = true;
         statusMessage = "I'm on";
         // Do everything else to turn the thing on
      }
   }
}
</code>```

答:
All wrapper classes are immutable. One of the major reason why one should not synchronize on them.

As if 2 threads synchronize on wrapper class object and one of them modifies its value,it will be synchronized on a new/modified object and both threads will be synchronized on 2 different objects. So,The whole purpose of synchronization is lost.

Body:
My architect always says that

Never synchronize on Boolean

I am not able to understand the reason why and would really appreciate if someone could explain with an example as to why it is not a good practice.
Reference Sample Code

private Boolean isOn = false;
private String statusMessage = "I'm off";
public void doSomeStuffAndToggleTheThing(){

   // Do some stuff
   synchronized(isOn){
      if(isOn){
         isOn = false;
         statusMessage = "I'm off";
         // Do everything else to turn the thing off
      } else {
         isOn = true;
         statusMessage = "I'm on";
         // Do everything else to turn the thing on
      }
   }
}


问:
R - Tallying up number of new individuals encountered as days go by based on ID
I am monitoring an animal population. I have their individual IDs as numbers, the date they were encountered on, and the number of individuals encountered on that day. I want to sum up the total number of different individuals encountered as the days go by, so I need it to recognize same IDs and only add new individuals to the total encountered.

This is my dataset, the last column being my desired outcome:

```<code>Month Day   ID    N. individuals that day     Total encountered
5     13    44    3                           3
5     13    58    3                           3
5     13    57    3                           3
5     14    58    1                           3
5     15    44    2                           4
5     15    06    2                           4
</code>```

答:
Edit - updated to working, but inelegant, solution. The process here was to use padr to create a row for every ID in every date, with a 1 once it appears. Then we can count how many IDs have appeared as of each date, and add that to the original with a join.

```<code>library(tidyverse); library(lubridate)

# First, make a date column for easier sorting etc.
df1 <- df %>%
  mutate(date = ymd(paste(2019, Month, Day))) %>%
  select(date, ID) %>%
  mutate(appearance = 1)   # For counting later; if missing = NA in padded version

df2 <- df1 %>%
  padr::pad(group = "ID", start_val = min(df1$date), end_val = max(df1$dat)) %>%
  fill(appearance) %>%
  count(date, Month = month(date), Day = day(date),
        wt = appearance, name = "Total_encountered_calc")

df %>%
  left_join(df2)
</code>```

Output

```<code>  Month Day ID N_individuals_that_day Total_encountered       date Total_encountered_calc
1     5  13 44                      3                 3 2019-05-13                    3
2     5  13 58                      3                 3 2019-05-13                    3
3     5  13 57                      3                 3 2019-05-13                    3
4     5  14 58                      1                 3 2019-05-14                    3
5     5  15 44                      2                 4 2019-05-15                    4
6     5  15  6                      2                 4 2019-05-15                    4
</code>```

Body:
I am monitoring an animal population. I have their individual IDs as numbers, the date they were encountered on, and the number of individuals encountered on that day. I want to sum up the total number of different individuals encountered as the days go by, so I need it to recognize same IDs and only add new individuals to the total encountered.

This is my dataset, the last column being my desired outcome:

Month Day   ID    N. individuals that day     Total encountered
5     13    44    3                           3
5     13    58    3                           3
5     13    57    3                           3
5     14    58    1                           3
5     15    44    2                           4
5     15    06    2                           4

Body:
Edit - updated to working, but inelegant, solution. The process here was to use padr to create a row for every ID in every date, with a 1 once it appears. Then we can count how many IDs have appeared as of each date, and add that to the original with a join.

library(tidyverse); library(lubridate)

# First, make a date column for easier sorting etc.
df1 <- df %>%
  mutate(date = ymd(paste(2019, Month, Day))) %>%
  select(date, ID) %>%
  mutate(appearance = 1)   # For counting later; if missing = NA in padded version

df2 <- df1 %>%
  padr::pad(group = "ID", start_val = min(df1$date), end_val = max(df1$dat)) %>%
  fill(appearance) %>%
  count(date, Month = month(date), Day = day(date),
        wt = appearance, name = "Total_encountered_calc")

df %>%
  left_join(df2)

Output

  Month Day ID N_individuals_that_day Total_encountered       date Total_encountered_calc
1     5  13 44                      3                 3 2019-05-13                    3
2     5  13 58                      3                 3 2019-05-13                    3
3     5  13 57                      3                 3 2019-05-13                    3
4     5  14 58                      1                 3 2019-05-14                    3
5     5  15 44                      2                 4 2019-05-15                    4
6     5  15  6                      2                 4 2019-05-15                    4


问:
Reading a float or double from json with swift
I am trying to read a json file with swift and it contains a field with 0.97.

If I tried to cast the field to a float, it would return nil, but if I were to cast it to a double, it would return the correct value. However, the only difference I could find on double and float was that double is 64-bit while float is 32-bit. I am wondering what is causing the difference.

答:
Seems to work for me:</p>

```<code>var jsonString = "{\n" +
    "\"float\":0.97,\n" +
    "\"double\":0.97\n" +
    "}\n"

struct Outcome: Decodable {
    let float: Float?
    let double: Double?
}
let data = jsonString.data(using: .utf8)!
let outcome = try JSONDecoder().decode(Outcome.self, from: data)
print(outcome) // Outcome(float: Optional(0.97), double: Optional(0.97))
</code>```

Body:
Seems to work for me:

var jsonString = "{\n" +
    "\"float\":0.97,\n" +
    "\"double\":0.97\n" +
    "}\n"

struct Outcome: Decodable {
    let float: Float?
    let double: Double?
}
let data = jsonString.data(using: .utf8)!
let outcome = try JSONDecoder().decode(Outcome.self, from: data)
print(outcome) // Outcome(float: Optional(0.97), double: Optional(0.97))


答:
See https://developer.android.com/training/volley/request

StringRequest. Specify a URL and receive a raw string in response. See Setting Up a Request Queue for an example.
  JsonObjectRequest and JsonArrayRequest (both subclasses of JsonRequest). Specify a URL and get a JSON object or array (respectively) in response.

You should be using a JsonArrayRequest

Title: Why Volley response is received as "[" and not JSON


问:
Lighttpd - Possible to use .htaccess / directory
I know most tutorials and topics say that you have to edit lighttpd.conf and add the rewrite rules there, but is it possible to use the .htaccess files per directory utilizing the lighttpd format?

Thanks

答:
No, lighttpd does currently not support .htaccess or a similar per directory feature. Lighttpd2 (which is pre-alpha at this moment) however will probably provide such a feature.

If you only want to set per per directory PHP settings you might want to take a look here (or .user.ini which is supported from PHP 5.3.x)


问:
Neo4j Cypher queries EXPLAINed identically but warnings are generated just for one
I have csv file containing a one-to-many relation where each element of type A is composed by one or more elements of type B but each element of B refers to only one element of type A.

An example:

```<code>   A   |  B
-------------
   a1  |  b1
   a1  |  b2
   a1  |  b3
   a2  |  b4
</code>```

I have already created the node in a neo4j graph and now I want to create an edge for these relationships.

I thought this query

```<code>LOAD CSV WITH HEADERS FROM "file:///file.csv" AS row
WITH row
MATCH (n:A {A_ID: row.a_id}), (t:B {BID : row.b_id})
MERGE (n)-[:HAS_CONNECTION]->(t);
</code>```

but Neo4j prompts the following warning:

This query builds a cartesian product between disconnected patterns.
  If a part of a query contains multiple disconnected patterns, this
  will build a cartesian product between all those parts. This may
  produce a large amount of data and slow down query processing. While
  occasionally intended, it may often be possible to reformulate the
  query that avoids the use of this cross product, perhaps by adding a
  relationship between the different parts or by using OPTIONAL MATCH
  (identifier is: (t))

So I changed it to:

```<code>LOAD CSV WITH HEADERS FROM "file:///file.csv" AS row
WITH row
MATCH (t:B {BID : row.b_id})
WITH row, t
MATCH (n:A {AID: row.a_id})
MERGE (n)-[:HAS_CONNECTION]->(t);
</code>```

and Neo4j does not complain.

However if I EXPLAIN both the queries the result is the same.

Is neo4j useless complaining about the first query or there are effective benefits with the second?

答:
While the warning is true, the queries do build a cartesian product, that is fine in this case, as this is exactly what you want, n and t even if they aren't connected, and cardinality would be low in any case (likely 1, if these are unique nodes).

Disregard the warning and keep your first query, when you're doing something like this where the expected number of nodes of each of those variables is 1, or at least small.

As for why the warning doesn't appear in the second plan, that's likely just a limitation on what is looked at to generate the warning. These are still equivalent, and the same thing applies.

And just to note the real reason for the warning, it's to prevent you from doing something like:

```<code>MATCH (a:A), (b:B)
</code>```

or similar, where you would end up with a cartesian product between all of one kind of node against all of another. When you narrow these down with specific properties (especially unique properties) that's just a 1x1 cartesian product, no issues.

Body:
I have csv file containing a one-to-many relation where each element of type A is composed by one or more elements of type B but each element of B refers to only one element of type A.

An example:

   A   |  B
-------------
   a1  |  b1
   a1  |  b2
   a1  |  b3
   a2  |  b4

I have already created the node in a neo4j graph and now I want to create an edge for these relationships.

I thought this query

LOAD CSV WITH HEADERS FROM "file:///file.csv" AS row
WITH row
MATCH (n:A {A_ID: row.a_id}), (t:B {BID : row.b_id})
MERGE (n)-[:HAS_CONNECTION]->(t);

but Neo4j prompts the following warning:

This query builds a cartesian product between disconnected patterns.
  If a part of a query contains multiple disconnected patterns, this
  will build a cartesian product between all those parts. This may
  produce a large amount of data and slow down query processing. While
  occasionally intended, it may often be possible to reformulate the
  query that avoids the use of this cross product, perhaps by adding a
  relationship between the different parts or by using OPTIONAL MATCH
  (identifier is: (t))

So I changed it to:

LOAD CSV WITH HEADERS FROM "file:///file.csv" AS row
WITH row
MATCH (t:B {BID : row.b_id})
WITH row, t
MATCH (n:A {AID: row.a_id})
MERGE (n)-[:HAS_CONNECTION]->(t);

and Neo4j does not complain.

However if I EXPLAIN both the queries the result is the same.

Is neo4j useless complaining about the first query or there are effective benefits with the second?

Body:
While the warning is true, the queries do build a cartesian product, that is fine in this case, as this is exactly what you want, n and t even if they aren't connected, and cardinality would be low in any case (likely 1, if these are unique nodes).

Disregard the warning and keep your first query, when you're doing something like this where the expected number of nodes of each of those variables is 1, or at least small.

As for why the warning doesn't appear in the second plan, that's likely just a limitation on what is looked at to generate the warning. These are still equivalent, and the same thing applies.

And just to note the real reason for the warning, it's to prevent you from doing something like:

MATCH (a:A), (b:B)

or similar, where you would end up with a cartesian product between all of one kind of node against all of another. When you narrow these down with specific properties (especially unique properties) that's just a 1x1 cartesian product, no issues.


问:
Does minimize requests fields saves more quota?
Since YouTube Data API comes with quota limitation, so we could trace our quota based on sent requests with given quota in the documentation.

But the documentation only comes down to "part" level instead of "fields" level, so for example...

YouTube_Service_Public.search().list(
    part="snippet",
    channelId=channel_id,
    maxResults=50,
    order="date",
    type="video",
    fields="items(etag,id/videoId,snippet(publishedAt,thumbnails/default,title))"
).execute()
```

<pre class="lang-py prettyprint-override"><code>YouTube_Service_Public.search().list(
    part="snippet",
    channelId=channel_id,
    maxResults=50,
    order="date",
    type="video"
).execute()
</code>```

Does the first request cost less quota than the latter?

or do they cost equally 100 quotas since they all request "snippet" part?

答: Quota cost would be the same. The fields parameter is just to reduce bandwidth usage.</p>

Body:
Since YouTube Data API comes with quota limitation, so we could trace our quota based on sent requests with given quota in the documentation.

But the documentation only comes down to "part" level instead of "fields" level, so for example...

YouTube_Service_Public.search().list(
    part="snippet",
    channelId=channel_id,
    maxResults=50,
    order="date",
    type="video",
    fields="items(etag,id/videoId,snippet(publishedAt,thumbnails/default,title))"
).execute()

YouTube_Service_Public.search().list(
    part="snippet",
    channelId=channel_id,
    maxResults=50,
    order="date",
    type="video"
).execute()

Does the first request cost less quota than the latter?

or do they cost equally 100 quotas since they all request "snippet" part?


问:
Multiple Generic Types
So first of all, I will specify that my question is not referring to having multiple generics being applied to a class. I know you can do that simply with a comma.

My question is if there is a way to have multiple possible extensions for a generics. For example:

```<code>public class Foo<? extends String>{}
public class Bar<? extends StringBuilder>{}
//combined
public class FooBar<? extends String, StringBuilder>{}
//or perhaps
public class FooBar<? extends String || StringBuilder>{}
</code>```

I know the FooBar class will not compile but I hope that is helpful in explaining my question and the specified intent. To lastly reiterate my question: is it possible for two classes to be extended in the generic clause or a way that would simulate such an action indirectly?

Note I am not asking how generics work, nor how extensions work, nor anything involving how and when to use of generics, for I already know this. If the question needs clarification, I will edit to provide further understanding to the best of my abilities.

答:
It's not possible for a class to extend both String and StringBuilder since classes only have one parent class. However, they can implement multiple interfaces, which you can specify with &.

```<code>class FooBar<T extends String & Runnable & Collection<Integer>> {}
</code>```

(Note that String is final so it's not actually possible to satisfy the above constraint.)

Title: Multiple Generic Types

Body:
So first of all, I will specify that my question is not referring to having multiple generics being applied to a class. I know you can do that simply with a comma.

My question is if there is a way to have multiple possible extensions for a generics. For example:

public class Foo<? extends String>{}
public class Bar<? extends StringBuilder>{}
//combined
public class FooBar<? extends String, StringBuilder>{}
//or perhaps
public class FooBar<? extends String || StringBuilder>{}

I know the FooBar class will not compile but I hope that is helpful in explaining my question and the specified intent. To lastly reiterate my question: is it possible for two classes to be extended in the generic clause or a way that would simulate such an action indirectly?

Note I am not asking how generics work, nor how extensions work, nor anything involving how and when to use of generics, for I already know this. If the question needs clarification, I will edit to provide further understanding to the best of my abilities.

Body:
It's not possible for a class to extend both String and StringBuilder since classes only have one parent class. However, they can implement multiple interfaces, which you can specify with &.

class FooBar<T extends String & Runnable & Collection<Integer>> {}

(Note that String is final so it's not actually possible to satisfy the above constraint.)


问:
Return 0 to second instance of duplicate
I have a similar data set to the following:

```<code>A  B   C
1  10  5
1  20  1
2  30  1
2  30  1
</code>```

I'd like to add a column returning 1, until we hit a duplicate of A & B, when I need to return a 0, but only for the second instance, so:

```<code>A  B   C  D
1  10  5  1
1  20  1  1
2  30  1  1
2  30  1  0
</code>```

Any help appreciated.

答:
An option would be</p>
```<code>df$D <- as.integer(!duplicated(df[c("A", "B")]))
df$D
#[1] 1 1 1 0

</code>```

Body:
I have a similar data set to the following:

A  B   C
1  10  5
1  20  1
2  30  1
2  30  1

I'd like to add a column returning 1, until we hit a duplicate of A & B, when I need to return a 0, but only for the second instance, so:

A  B   C  D
1  10  5  1
1  20  1  1
2  30  1  1
2  30  1  0

Any help appreciated.

Body:
An option would be

df$D <- as.integer(!duplicated(df[c("A", "B")]))
df$D
#[1] 1 1 1 0


问:
C# library to native C++ application
I know I can use dll import + wrapping (managed) to use C++ libraries in C# applications (question link>>) but what's opposite? How can I use C# library in my C++ application? I'll handle events/operations/results in C# library but my application created with C++. For example here is my C++ application:

//In this example; Manager will be my C# library's instance, Log is a C# library's function that can print something. (That's only an example, not works. For describing something to understand my question)

```<code>int main()
{
   if(MySystem.Start() == 0) //If there is no error
   {
      Manager.Log("System started successfully!"); //Post it to C# library!
   }
   return 0;
}
</code>```

EDIT: Solution should be native C++. I'll not use C++\CLI!

EDIT: Only c++ application will be native. Namely I can create a shared c++ library to handle C# library. C++ App.(Event) >> C++\CLI Lib. >> C# Library, this way is posibble. Is there any example/topic/start point?

>> MY SOLUTION (After answers, should be helpful for others): I'll create a C++\CLI shared library and I'll use it with my native C++ app. This library will handle my C# library (more about in this question>>). If I don't need C#, I'll re-code my C++\CLI library as native library. I think that is pretty useful.

答:
CoreRT allows to compile native libraries for windows, linux and osx x64 platform this avoid to you use an C++ compatible layer.
CoreRT uses NetCore, and NetCore doesn't support C++/CLI.

https://dev.to/encrypt0r/writing-native-libraries-in-c-3kl

Title: C# library to native C++ application

Body:
I know I can use dll import + wrapping (managed) to use C++ libraries in C# applications (question link>>) but what's opposite? How can I use C# library in my C++ application? I'll handle events/operations/results in C# library but my application created with C++. For example here is my C++ application:

//In this example; Manager will be my C# library's instance, Log is a C# library's function that can print something. (That's only an example, not works. For describing something to understand my question)

int main()
{
   if(MySystem.Start() == 0) //If there is no error
   {
      Manager.Log("System started successfully!"); //Post it to C# library!
   }
   return 0;
}

EDIT: Solution should be native C++. I'll not use C++\CLI!

EDIT: Only c++ application will be native. Namely I can create a shared c++ library to handle C# library. C++ App.(Event) >> C++\CLI Lib. >> C# Library, this way is posibble. Is there any example/topic/start point?

>> MY SOLUTION (After answers, should be helpful for others): I'll create a C++\CLI shared library and I'll use it with my native C++ app. This library will handle my C# library (more about in this question>>). If I don't need C#, I'll re-code my C++\CLI library as native library. I think that is pretty useful.


问:
How do I keep my splash screen over React components
I am trying to put a splash screen on my app. However, React is rendering its components above the splash screen.

My HTML looks like this:

```<code><div id='overlay'>
   <img/>
</div>
<div id='root'></div>

#overlay {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(36,79,53, 1);
  z-index: 99;
}

#root{
  height: 100vh;
  z-index: 1;
}
</code>```

What else can I do?

答:
I'll leave this up for a bit, run the snippet, you can see the problem is not with the code you posted. I made the overlay a bit transparent so you can see it is over the red text below.

class Thingy extends React.Component {
  render() {
    const {title} = this.props;
    console.log("rendered");
    return (

{title}

    );
  }
}

// Render it
ReactDOM.render(
  <Thingy title="I'm the thingy" />,
  document.getElementById("root")
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#overlay {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(36,79,53, .7);
  z-index: 99;
}

#root{
  height: 100vh;
  z-index: 1;
}
.thingy{
  color: red;
}</code>```

```

Body:
I am trying to put a splash screen on my app. However, React is rendering its components above the splash screen.

My HTML looks like this:

#overlay {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(36,79,53, 1);
  z-index: 99;
}

#root{
  height: 100vh;
  z-index: 1;
}

What else can I do?

Body:
I'll leave this up for a bit, run the snippet, you can see the problem is not with the code you posted. I made the overlay a bit transparent so you can see it is over the red text below.

class Thingy extends React.Component {
  render() {
    const {title} = this.props;
    console.log("rendered");
    return (
      <div className="thingy">
        <div>{title}</div>
      </div>
    );
  }
}

// Render it
ReactDOM.render(
  <Thingy title="I'm the thingy" />,
  document.getElementById("root")
);

#overlay {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(36,79,53, .7);
  z-index: 99;
}

#root{
  height: 100vh;
  z-index: 1;
}
.thingy{
  color: red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='overlay'>
   <img/>
</div>
<div id='root'></div>


问:
socketio inter server communication with redis and haproxy
I'm working on a project which uses SocketIO and should be Horizontally scalable. Im using

A Load Balancer using HAProxy

Multiple Node Servers (2-4)

Database server(Redis and MongoDB)

I'm able to redirect my incoming Socket connections to Node servers using roundrobin method. Socket connection is stable and if I use socket.emit() I'm receiving the data. I'm also able to emit to the Other socket connection connected to the same Node server.

I'm facing issue in the following scenario:

User A connected to Node server 1 and User B connected to Node Server 2

My intention is to store the Socket data in redis

If User A wants to send some data to User B, how can I tell the Node server 2 to emit the data to User B from Node server 1

Please let me know how can I achieve this (with ref if possible).

Thanks in advance.

答:
Have a look at socket.io Redis adapter. It should be exactly what you need.

clients() method in particular looks promising. Keep in mind, that socket.io creates a unique room for each client.


问:
How to customise Google chrome to add search options on a right click?
As short cuts, I have added various search engine entries in my browser to get to a page having a patterned URL easily.

But this still does not solve the problem completely. While browsing, if I see some text that corresponds to one of the pages, I need to copy the text, open a new tab and then use my search entry to go to that page.

A couple of steps can be saved if I can directly right click and go to the search engine.

How can I do that? Do I need to create an extension for this or something simpler can help?

Current:

copy text

open new tab

search engine keyword followed by tab

paste text

press return

Desired:

select text

right click and select search

答:
Like this >1: https://i.stack.imgur.com/Cuu4c.png
Simple,

1) Find,download and install a chrome extension that supports this feature.

2) Edit the js files as text files.

3) Replace all the original links in the plug in with the link of the search engine that you want to use.

4) Add the new extension with a different name.

done


问:
Django: Adding user to groups in a signal
I created a signal which is supped to do 3 things:

Create a User

Create the Profile of said user

Add User to a Group

Using a signal, steps 1 and 2 work fine but I can't seem to add the user to a group (step 3).

```<code># Signals
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
  if created:
    Profile.objects.create(user=instance)
    group = Group.objects.get(name='generics')
    instance.groups.add(group)
</code>```

Did some debugging and found out that even if I comment out Profile.objects.create(user=instance) I still can't add any groups to instance.

Am I missing anything here? I'm not getting any errors.

Edit 1: This is a custom User model.

```<code>from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
  first_name = None
  last_name = None

  class Meta:
    verbose_name_plural = 'users'

  def __str__(self):
    return self.username
</code>```

I simply moved first_name and last_name to the Profile table. Didn't do anything else as you can see. Users and Profiles are successfully being created so this custom model works just fine.

Although unnecessary, I added instance.save() after adding the group but it still won't work. The admin shows no groups have been added and the the db table core_user_groups is still empty.

Edit 2: Add console test

Even more weird, I tried adding the group using ./manage.py shell and it works fine.

```<code>>>> from core.models import User
>>> from django.contrib.auth.models import Group
>>> group = Group.objects.get(pk=1)
>>> group
<Group: generics>
>>> user = User.objects.get(pk=23)
>>> user
<User: sonic>
>>> user.groups.add(group)

# At this point I check the admin and the db and it worked. Hmmm....but how to do it within a signal...
</code>```

答:
If you want just to add some fields to default user model, you shouldn't inherit from abstract user. Better to use related models using one-to-one field

My suggestion is to remove custom class. And add relation between your profile and auth.User models.

Body:
I created a signal which is supped to do 3 things:

Create a User

Create the Profile of said user

Add User to a Group

Using a signal, steps 1 and 2 work fine but I can't seem to add the user to a group (step 3).

# Signals
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
  if created:
    Profile.objects.create(user=instance)
    group = Group.objects.get(name='generics')
    instance.groups.add(group)

Did some debugging and found out that even if I comment out Profile.objects.create(user=instance) I still can't add any groups to instance.

Am I missing anything here? I'm not getting any errors.

Edit 1: This is a custom User model.

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
  first_name = None
  last_name = None

  class Meta:
    verbose_name_plural = 'users'

  def __str__(self):
    return self.username

I simply moved first_name and last_name to the Profile table. Didn't do anything else as you can see. Users and Profiles are successfully being created so this custom model works just fine.

Although unnecessary, I added instance.save() after adding the group but it still won't work. The admin shows no groups have been added and the the db table core_user_groups is still empty.

Edit 2: Add console test

Even more weird, I tried adding the group using ./manage.py shell and it works fine.

>>> from core.models import User
>>> from django.contrib.auth.models import Group
>>> group = Group.objects.get(pk=1)
>>> group
<Group: generics>
>>> user = User.objects.get(pk=23)
>>> user
<User: sonic>
>>> user.groups.add(group)

# At this point I check the admin and the db and it worked. Hmmm....but how to do it within a signal...