问:
Tailor byte array size to NetworkStream response with protocol length included
I have a custom binary protocol response I'm receiving from a TCP server in the following format:

Response Structure

Name    Length    Description

Header  2 bytes   Header is a fixed value Hex 0x0978.

Status  1 byte    A value of 0 is Success.  A value other than 0 indicates an error.  A full description of each possible error is described below.

Length  4 bytes   Unsigned integer of total request length including all bytes in the request (server returns little endian UInt32)

Data    Variable, 0 to 1,048,576 bytes    Data sent from client to server to be encoded or decoded depending on the operation being requested.

Checksum    1 byte    The checksum of bytes in the request from Header to Data (i.e. excluding checksum byte).

The problem I have is that the data is of variable size, so I don't know what size to make the byte array that the response is read into from the stream. How can I achieve this?

EDIT: I want the first 7 bytes to be also included with the data in the final byte array.

答:
One possible solution:</p>

```<code>class Program
{
    private static byte[] data = new byte[8]
    {
        // header
        0,
        0,

        // status
        1,

        // message size
        8,
        0,
        0,
        0,

        // data
        1
    };

    static byte[] Read(Stream stream)
    {
        const int headerLength = 7;
        const int sizePosition = 3;

        var buffer =  new byte[headerLength];
        stream.Read(buffer, 0, headerLength);

        // for BitConverter to work
        // the order of bytes in the array must
        // reflect the endianness of the computer system's architecture
        var size = BitConverter.ToUInt32(buffer, sizePosition);

        var result = new byte[size];
        Array.Copy(buffer, result, headerLength);
        stream.Read(result, headerLength, (int)size - headerLength);

        return result;
    }

    static void Main(string[] args)
    {
        var stream = new MemoryStream(data);
        byte[] bytes = Read(stream);

        foreach (var b in bytes)
        {
            Console.WriteLine(b);
        }
    }
}
</code>```

Body:
One possible solution:

class Program
{
    private static byte[] data = new byte[8]
    {
        // header
        0,
        0,

        // status
        1,

        // message size
        8,
        0,
        0,
        0,

        // data
        1
    };

    static byte[] Read(Stream stream)
    {
        const int headerLength = 7;
        const int sizePosition = 3;

        var buffer =  new byte[headerLength];
        stream.Read(buffer, 0, headerLength);

        // for BitConverter to work
        // the order of bytes in the array must
        // reflect the endianness of the computer system's architecture
        var size = BitConverter.ToUInt32(buffer, sizePosition);

        var result = new byte[size];
        Array.Copy(buffer, result, headerLength);
        stream.Read(result, headerLength, (int)size - headerLength);

        return result;
    }

    static void Main(string[] args)
    {
        var stream = new MemoryStream(data);
        byte[] bytes = Read(stream);

        foreach (var b in bytes)
        {
            Console.WriteLine(b);
        }
    }
}


来源: stackexchange

问:
JavaScript variable changing between two values on a regular basis
I want a variable's value regularly changing between 0 and 1.  If I have a variable whose value is 0 (counter = 0), how can I increase it by 1 (counter = 1) after a few seconds, then decrease it back to 0 ( counter = 0) after another few seconds? An endless loop basically is what I want.

I'm assuming this will require setTimeout or setInterval, but I've absolutely no idea how I'd go about this. I'm very unfamiliar with the syntax; I'm very much a newbie. Does anyone have any pointers?

Thanks!

答:
You can create an endless, timed loop by having a function that calls itself at the end via setTimeout.  See below.

var count = 0;
function flip() {
  count = Number(!count);
  console.log(count);
  setTimeout(flip, 1000);
}

flip();```

ContentLicense: CC BY-SA 3.0


问:
J2ME - code signing using verisign Intermediate CA
I want to sign the J2ME midlet using verisign intermediate CA. Does any one know how to do that or any one succeed with verisign code signing. Please help me with the steps.</p>

答:
You need a Verisign class 3 code signing certificate, which you can then use to sign with as normal using KeyTool

However you need to check which devices you wish to deploy to, as common as a Verisign certificate is, the root certificate is not present on all phones! unfortunately this means if you sign the application you will be unable to install on those devices where the root certificate is not present.

The most ubiquitous root certificate on the phones is the one provided by the UTI for which you will need to look into the Java verified process.

ContentLicense: CC BY-SA 2.5


问:
How do I remove duplicated rows in an H2O.Frame?
I need to remove duplicated rows in an H2O.Frame object.

With a data.frame df in R I would use

```<code>df <- df[!duplicated(df), ]
</code>```

What is the equivalent in H2O? Thank you.

答:
There currently isn't a method to drop duplicate rows but jira tickets have been created for Python and R

If however you have some sort of identifier like an id column with duplicated rows you might be able to use h2o's h2o.group_by method to help with the removal process.

Body:
I need to remove duplicated rows in an H2O.Frame object.

With a data.frame df in R I would use

df <- df[!duplicated(df), ]

What is the equivalent in H2O? Thank you.


答:
This sounds like homework but try this:

```<code>var value = 0;

setInterval(
  function() {
    value = value===0 ? 1 : 0;
    console.log('value =', value);
  },
  1000
);
</code>```

setInterval will call the function over and over again without needing to call setTimeout over and over again.

Title: JavaScript variable changing between two values on a regular basis

Body:
I want a variable's value regularly changing between 0 and 1.  If I have a variable whose value is 0 (counter = 0), how can I increase it by 1 (counter = 1) after a few seconds, then decrease it back to 0 ( counter = 0) after another few seconds? An endless loop basically is what I want.

I'm assuming this will require setTimeout or setInterval, but I've absolutely no idea how I'd go about this. I'm very unfamiliar with the syntax; I'm very much a newbie. Does anyone have any pointers?

Thanks!

Body:
This sounds like homework but try this:

var value = 0;

setInterval(
  function() {
    value = value===0 ? 1 : 0;
    console.log('value =', value);
  },
  1000
);

setInterval will call the function over and over again without needing to call setTimeout over and over again.


问:
Azure Key Vault Secrets unmanaged and managed whats the difference?
Within the Azure portal > KeyVaults > Secrets there appears to be two sets of Secrets: "unmanaged" and "managed".

When adding a new Secret it appears to go straight to the "unmanaged" section (there is no option to choose).

What is the difference between "unmanaged" and "managed" secrets?

Why everytime I create a secret it is "unmanaged"?

How do you create "managed" secrets?

答:
What is the difference between "unmanaged" and "managed" secrets?

A "managed" secret is a secret that backs either a certificate or a storage account key. It can't directly be mutated - for example, if you want to delete it, then you should instead delete the corresponding certificate or storage account key. An "unmanaged" secret is a secret that isn't managed - from AKV's point of view, it's just a blob of data.

Why everytime I create a secret it is "unmanaged"?

Within the Azure Portal, AKV only supports the creation of keys, secrets, and certificates (no storage account key support yet). If you create a certificate, then a managed secret will also be created. Otherwise, if you create a secret (even if you select "Certificate" as an upload option), then it will be an unmanaged secret.

How do you create "managed" secrets?

Not directly. Only by creating a certificate or a storage account key.

More Context:

The Azure Key Vault (AKV) service originally supported only two types of objects that could be stored in a vault: keys and secrets.

Later, AKV introduced a 3rd type of object: certificates. Originally, customers were storing their certs in their vaults as raw secrets (from AKV's point of view, just blobs of data). With this new certificate feature, customers could store certs as first-class AKV objects. Now, AKV can manage the lifetime of the certificate (by auto-renewing or automatically sending an e-mail to remind the customer to manually renew it when it's close to expiry). Under the hood, when a first-class certificate is created in Key Vault, the certificate is backed by a managed key and managed secret.

Likewise, AKV has also introduced a 4th type of object: storage account keys. AKV similarly manages the lifetime of a storage account key, and it's backed by a managed secret.


问:
Group rows into a new row and sum in r
So I have data that seems like this:

```<code> Week        Total Amount        Person
   1            $5                 A
   1            $5                 B
   1            $4                 C
   1            $2                 D
   1            $1                 E
   2            $5                 A
   2            $1                 B
   2            $1                 H
   2            $3                 G
   2            $5                 C
   2            $5                 F
</code>```

How do I make it so that I will show the top 3 for each week and sum all other amounts into "Others"? I want it to show:

```<code> Week        Total Amount        Person
   1            $5                 A
   1            $5                 B
   1            $4                 C
   1            $3                 Others
   2            $5                 A
   2            $5                 C
   2            $5                 F
   2            $5                 Others
</code>```

Notice that the other amounts that are not top 3 are summed into a new total amount, and it accounts for the random number of rows for each week (say week 1 has 5 total amounts for each person, but week 2 has 6, and week 3 may be 8 or 10, and week 4 may be 1 total, but I want the equation to apply for each row)

答:
Base R

```<code>df$Person[ave(df$`Total Amount`, df$Week, FUN = function(x)
    order(x, decreasing = TRUE)) > 3] = "Others"
df2 = aggregate(df["Total Amount"], df[c("Week", "Person")], sum)
df2[order(df2$Week, df2$Person),]
#  Week Person Total Amount
#1    1      A            5
#3    1      B            5
#4    1      C            4
#7    1 Others            3
#2    2      A            5
#5    2      C            5
#6    2      F            5
#8    2 Others            5
</code>```

DATA

```<code>df = structure(list(Week = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
2L), `Total Amount` = c(5L, 5L, 4L, 2L, 1L, 5L, 1L, 1L, 3L, 5L,
5L), Person = c("A", "B", "C", "D", "E", "A", "B", "H", "G",
"C", "F")), .Names = c("Week", "Total Amount", "Person"), class = "data.frame",
row.names = c(NA, -11L))
</code>```

Title: Group rows into a new row and sum in r

Body:
So I have data that seems like this:

 Week        Total Amount        Person
   1            $5                 A
   1            $5                 B
   1            $4                 C
   1            $2                 D
   1            $1                 E
   2            $5                 A
   2            $1                 B
   2            $1                 H
   2            $3                 G
   2            $5                 C
   2            $5                 F

How do I make it so that I will show the top 3 for each week and sum all other amounts into "Others"? I want it to show:

 Week        Total Amount        Person
   1            $5                 A
   1            $5                 B
   1            $4                 C
   1            $3                 Others
   2            $5                 A
   2            $5                 C
   2            $5                 F
   2            $5                 Others

Notice that the other amounts that are not top 3 are summed into a new total amount, and it accounts for the random number of rows for each week (say week 1 has 5 total amounts for each person, but week 2 has 6, and week 3 may be 8 or 10, and week 4 may be 1 total, but I want the equation to apply for each row)

Body:
Base R

df$Person[ave(df$`Total Amount`, df$Week, FUN = function(x)
    order(x, decreasing = TRUE)) > 3] = "Others"
df2 = aggregate(df["Total Amount"], df[c("Week", "Person")], sum)
df2[order(df2$Week, df2$Person),]
#  Week Person Total Amount
#1    1      A            5
#3    1      B            5
#4    1      C            4
#7    1 Others            3
#2    2      A            5
#5    2      C            5
#6    2      F            5
#8    2 Others            5

DATA

df = structure(list(Week = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
2L), `Total Amount` = c(5L, 5L, 4L, 2L, 1L, 5L, 1L, 1L, 3L, 5L,
5L), Person = c("A", "B", "C", "D", "E", "A", "B", "H", "G",
"C", "F")), .Names = c("Week", "Total Amount", "Person"), class = "data.frame",
row.names = c(NA, -11L))


问:
How to create Loopback model with random string as primary key?

TL; DR

How to make Accounts.create({ provider: "facebook" }) create the id primary key automatically?

Description

Given a persistent Loopback model definition

```<code>{
  "name": "Account",
  "plural": "accounts",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "id": {
      "id": true,
      "type": "string",
      "required": true
    },
    "provider": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "acls": [],
  "methods": {}
}
</code>```

how it would be possible add a remote method at Account.js to automatically create a random string as primary key?

答:
You can set it on a new instance creation in a before save operation hook:

```<code>Model.observe('before save', (ctx, next) => {

    // If not acting on an instance or property already set, continue.
    if (!ctx.instance || ctx.instance.id) {
        return next();
    }

    ctx.instance.id = uuid();

    next();

});
</code>```

Body:
TL; DR

How to make Accounts.create({ provider: "facebook" }) create the id primary key automatically?

Description

Given a persistent Loopback model definition

{
  "name": "Account",
  "plural": "accounts",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "id": {
      "id": true,
      "type": "string",
      "required": true
    },
    "provider": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "acls": [],
  "methods": {}
}

how it would be possible add a remote method at Account.js to automatically create a random string as primary key?

Body:
You can set it on a new instance creation in a before save operation hook:

Model.observe('before save', (ctx, next) => {

    // If not acting on an instance or property already set, continue.
    if (!ctx.instance || ctx.instance.id) {
        return next();
    }

    ctx.instance.id = uuid();

    next();

});


问:
Xamarin.Forms Custom Font
I am trying to implement a custom font into my Xamarin forms app. The font is Quicksand-Regular from Google.

Checklist:
Font has been added at different points to Fonts/, the root directory , and the Resources folder.
The build action is set to BundleResource, and the output director has been tested with both Always Copy, and Do Not Copy.
The Plist has been amended with
UIAppFonts Quicksand-Regular.tff

The useable name of the font is just Quicksand but I tried referencing it in the app with both Quicksand and Quicksand-Regular.
I have tried to add,
Style TargetType="Label"
                Setter Property="FontFamily" Value="Quicksand"
           Style

To the app wide resource dictionary, as well as refer directly to the font on a label, both just specifying the FontFamily and referring to it as platform specific.
The odd thing I'm seeing is that in the preview window it's working fine, both label and button text is being replaced correctly but this doesn't work runtime.

I believe then the resource isn't actually getting found or copied to the iOS project correctly but any suggestions would be appreciated.

答:
I can only list what I did to get a font working on iOS:

The font was MaterialIcons-regular.ttf

Added to resources folder

Build Action = BundleResources

Copy To Output Directory = Do not copy

Label FontFamily = "Material Icons" (note the space)

Add font to info.plist

```<code><key>UIAppFonts</key>
<array>
    <string>MaterialIcons-Regular.ttf</string>
</array>
</code>```

Here is a blog post listing the steps required on iOS. It says Copy to output directory should be Always copy. Not what I found but another possible stumbling block.

Title: Xamarin.Forms Custom Font

Body:
I can only list what I did to get a font working on iOS:

The font was MaterialIcons-regular.ttf

Added to resources folder

Build Action = BundleResources

Copy To Output Directory = Do not copy

Label FontFamily = "Material Icons" (note the space)

Add font to info.plist

<key>UIAppFonts</key>
<array>
    <string>MaterialIcons-Regular.ttf</string>
</array>

Here is a blog post listing the steps required on iOS. It says Copy to output directory should be Always copy. Not what I found but another possible stumbling block.


问:
CSS :FirstChild in same section with 2 class not working
Color is not applied as per CSS on the 3rd row, using first child(div.multiple-alerts .normal:first-child span).

https://jsfiddle.net/Lh6cpzeb/

div.multiple-alerts .high:first-child span{ color: yellow; }

div.multiple-alerts .normal:first-child span{ color: yellow; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="multiple-alerts">
  <div class="cls high"><span>high</span></div>
  <div class="cls high"><span>high</span></div>
  <div class="cls normal"><span>normal</span></div>
  <div class="cls normal"><span>normal</span></div>
</div></code>```

答:
The CSS is being applied the correct way, but I think your understanding of how the rules work may be slightly off. You're selecting the first child of all divs with class multiple-alerts which also has the class of normal. Well, the first child of multiple-alerts does not have the class normal (at least in the snippet you included), so your selector matches exactly zero elements.

Now, you may be tempted to go for something like first-of-type, but that only applies to tags, not classes. So, here's a workaround that you might find useful:

Let's say the standard colour for these spans is black, we will set all the spans inside .normal with yellow colour, then override it for all but the first one, like so:

```<code>div.multiple-alerts .normal span {
  color: yellow;
}
div.multiple-alerts .normal ~ .normal span {
  color: black;
}
</code>```

If you're not sure how this is working here, the ~ works similarly to the +, but is broader. The + can only match with the very next sibling, whereas the ~ can match with any succeeding sibling - i.e. after, but not before.

Body:
Color is not applied as per CSS on the 3rd row, using first child(div.multiple-alerts .normal:first-child span).

https://jsfiddle.net/Lh6cpzeb/

div.multiple-alerts .high:first-child span{ color: yellow; }

div.multiple-alerts .normal:first-child span{ color: yellow; }

high

high

normal

normal

Body:
The CSS is being applied the correct way, but I think your understanding of how the rules work may be slightly off. You're selecting the first child of all divs with class multiple-alerts which also has the class of normal. Well, the first child of multiple-alerts does not have the class normal (at least in the snippet you included), so your selector matches exactly zero elements.

Now, you may be tempted to go for something like first-of-type, but that only applies to tags, not classes. So, here's a workaround that you might find useful:

Let's say the standard colour for these spans is black, we will set all the spans inside .normal with yellow colour, then override it for all but the first one, like so:

div.multiple-alerts .normal span {
  color: yellow;
}
div.multiple-alerts .normal ~ .normal span {
  color: black;
}

If you're not sure how this is working here, the ~ works similarly to the +, but is broader. The + can only match with the very next sibling, whereas the ~ can match with any succeeding sibling - i.e. after, but not before.


问:
Creating a line graph using ggplot2 without a set "y"?
I guess I am trying to create a geom_line version of a geom_bar.  The reason I want to do lines is because when I enter

```<code>geom_bar(aes(fill = Decile), position = position_dodge())
</code>```

I am stuck with ten segments and my bar chart looks extremely cluttered.
  I have 11 separate x variables going across the bottom.
The problem is I dont know how to use the count as a "y" variable and have tried things like ..count.. and other approached but am completely lost. Any ideas?

Thanks for the help!

My data looks like this:

Name Decile Division

Joe 1 San Diego

Jan 1 New York

Jay 2 San Diego

Lue 3 Dallas

Suz 2 Seattle

tye 3 Dallas

```<code>MCD <- read.csv("Decile15.csv", header = TRUE)

MCD$MonthNo <- factor(MCD$MonthNo, levels = c(1:11), labels = c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November"))

Decile_names <- c('1' = "Decile #1",
                '2' = "Decile #2",
                '3' = "Decile #3",
                '4' = "Decile #4",
                '5' = "Decile #5"
                 )

MCDGraph <- ggplot(na.omit(MCD), aes(MonthNo))

MCDGraph + geom_bar(aes(fill = Division), color = "black", position = "fill") +     facet_wrap(~Decile, nrow = 1, labeller = labeller(Decile = as_labeller(Decile_names))) + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5)) +     scale_fill_manual(values = c("#DA4424", "#24A0DA", "#F0BC0B", "#43F749", "#4348F7", "#F74369", "#D7B9F5")) + theme(panel.background = element_rect(colour = "black", fill = "white"), panel.grid.minor = element_line(color = "black", size = .5)) + labs(x = "2017", y = "% of Leads Per Month By Division") + scale_y_continuous(labels = percent_format()) + theme(strip.background = element_blank(), strip.text = element_text(size = 25))
</code>```

This is what my % of grouped facet_wrap bar chart looked like.

I split those into 5 so that I could see five plots instead of 10 on one pdf sheet.  Also this is only divided into the 7 total divisions.  I want to do one that is divided into 10.  Here is an example I used to make my grouped regular without faceting anything.

```<code>MC <- read.csv("2017_Full_year.csv", header = TRUE)

MC$MonthNo <- factor(MC$MonthNo, levels = c(1:11), labels = c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November"))

MCH <- ggplot(na.omit(MC), aes(MonthNo))

MCH + geom_bar(aes(fill = Division), position = position_dodge() ) + labs(x = "2017", y = "# of Leads") + theme(axis.line = element_line(color = "black", size = 3, linetype = "solid"), axis.text.x = element_text(face = "bold", color = "black", size = 14),
  axis.text.y = element_text(face = "bold", color = "black", size = 14)) + scale_y_continuous(name = "# Of Leads", breaks = seq(0,1000, 50)) + theme(panel.background = element_rect(colour = "black",
  fill = "white"), panel.grid.minor = element_line(color = "black", size = .5), panel.grid.major = element_line(color = "black", size = .5)) +
  scale_fill_manual(values = c("#DA4424", "#24A0DA", "#F0BC0B", "#43F749", "#4348F7", "#F74369","#D7B9F5"))
</code>```

EDIT: Or should I just create a new csv with the the final counts for each Decile during each month already in it. This would be a quick fix and I can pull the numbers very easily from SQL server.  I was just hoping to do this without having to create a new file.

答:
Not sure how this would look with your real data, but something you could explore that looks nice in situations like these are ridgeplots using the ggrigdes package.  Example is below:

```<code>  library(ggridges)
  library(dplyr)
  library(ggplot2)

  set.seed(99)

  MCD <- tibble(
                Name = sample(c("Joe", "Jay", "Susan", "Nancy", "Mark"), 1000, T),
                Decile = sample(1:10,1000, T) ,
                Division = sample(c('San Diego', 'New York', 'Dallas', 'Seattle', 'LA'), 1000, T),
                MonthNo = sample(1:11, 1000 , T))

  MCD$MonthNo <- factor(MCD$MonthNo, levels = c(1:11), labels = c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November"))

  MCD %>% group_by(Decile, MonthNo) %>% summarize(Count = n()) %>%
       ungroup() %>%  mutate(Decile = factor(Decile)) %>%
       ggplot(aes(x = MonthNo, y = Decile, height = Count, group = Decile, fill = Decile)) +
       geom_density_ridges(alpha = 0.7, show.legend = F, stat = "identity", scale = 1)
</code>```

Body:
I guess I am trying to create a geom_line version of a geom_bar.  The reason I want to do lines is because when I enter

geom_bar(aes(fill = Decile), position = position_dodge())

I am stuck with ten segments and my bar chart looks extremely cluttered.
  I have 11 separate x variables going across the bottom.
The problem is I dont know how to use the count as a "y" variable and have tried things like ..count.. and other approached but am completely lost. Any ideas?

Thanks for the help!

My data looks like this:

Name Decile Division

Joe 1 San Diego

Jan 1 New York

Jay 2 San Diego

Lue 3 Dallas

Suz 2 Seattle

tye 3 Dallas

MCD <- read.csv("Decile15.csv", header = TRUE)

MCD$MonthNo <- factor(MCD$MonthNo, levels = c(1:11), labels = c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November"))

Decile_names <- c('1' = "Decile #1",
                '2' = "Decile #2",
                '3' = "Decile #3",
                '4' = "Decile #4",
                '5' = "Decile #5"
                 )

MCDGraph <- ggplot(na.omit(MCD), aes(MonthNo))

MCDGraph + geom_bar(aes(fill = Division), color = "black", position = "fill") +     facet_wrap(~Decile, nrow = 1, labeller = labeller(Decile = as_labeller(Decile_names))) + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5)) +     scale_fill_manual(values = c("#DA4424", "#24A0DA", "#F0BC0B", "#43F749", "#4348F7", "#F74369", "#D7B9F5")) + theme(panel.background = element_rect(colour = "black", fill = "white"), panel.grid.minor = element_line(color = "black", size = .5)) + labs(x = "2017", y = "% of Leads Per Month By Division") + scale_y_continuous(labels = percent_format()) + theme(strip.background = element_blank(), strip.text = element_text(size = 25))

This is what my % of grouped facet_wrap bar chart looked like.

I split those into 5 so that I could see five plots instead of 10 on one pdf sheet.  Also this is only divided into the 7 total divisions.  I want to do one that is divided into 10.  Here is an example I used to make my grouped regular without faceting anything.

MC <- read.csv("2017_Full_year.csv", header = TRUE)

MC$MonthNo <- factor(MC$MonthNo, levels = c(1:11), labels = c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November"))

MCH <- ggplot(na.omit(MC), aes(MonthNo))

MCH + geom_bar(aes(fill = Division), position = position_dodge() ) + labs(x = "2017", y = "# of Leads") + theme(axis.line = element_line(color = "black", size = 3, linetype = "solid"), axis.text.x = element_text(face = "bold", color = "black", size = 14),
  axis.text.y = element_text(face = "bold", color = "black", size = 14)) + scale_y_continuous(name = "# Of Leads", breaks = seq(0,1000, 50)) + theme(panel.background = element_rect(colour = "black",
  fill = "white"), panel.grid.minor = element_line(color = "black", size = .5), panel.grid.major = element_line(color = "black", size = .5)) +
  scale_fill_manual(values = c("#DA4424", "#24A0DA", "#F0BC0B", "#43F749", "#4348F7", "#F74369","#D7B9F5"))

EDIT: Or should I just create a new csv with the the final counts for each Decile during each month already in it. This would be a quick fix and I can pull the numbers very easily from SQL server.  I was just hoping to do this without having to create a new file.

Body:
Not sure how this would look with your real data, but something you could explore that looks nice in situations like these are ridgeplots using the ggrigdes package.  Example is below:

  library(ggridges)
  library(dplyr)
  library(ggplot2)

  set.seed(99)

  MCD <- tibble(
                Name = sample(c("Joe", "Jay", "Susan", "Nancy", "Mark"), 1000, T),
                Decile = sample(1:10,1000, T) ,
                Division = sample(c('San Diego', 'New York', 'Dallas', 'Seattle', 'LA'), 1000, T),
                MonthNo = sample(1:11, 1000 , T))

  MCD$MonthNo <- factor(MCD$MonthNo, levels = c(1:11), labels = c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November"))

  MCD %>% group_by(Decile, MonthNo) %>% summarize(Count = n()) %>%
       ungroup() %>%  mutate(Decile = factor(Decile)) %>%
       ggplot(aes(x = MonthNo, y = Decile, height = Count, group = Decile, fill = Decile)) +
       geom_density_ridges(alpha = 0.7, show.legend = F, stat = "identity", scale = 1)


问:
MySQL indexing with a two columns, one of which is a foreign key
I have table T1 where col A is primary key and col B is a foreign key which is a primary key in table T2. I want to create an index in T1, a composite one as (B,A). But MySQL is allowing me to create the index as (A,B) only. Is it because col B is a foreign key ?? Please explain</p>

答: InnoDB clusters the data using the primary key. If you don't define the primary key, InnoDB will try to use a unique non-nullable index instead.This will ensure that rows are inserted in sequential order and will offer better performance for joins using primary keys. But in my question, I said that in table T1 the PK is col A and col B is a foreign key which is not unique in T1. So, if I set pk as (A,B) , automatically mysql will index it as primary index. If you try to change the index as (B,A) , since B is not unique, InnoDB cannot index it as it uses cluster indexing. So, it will throw error.</p>


问:
Two-column presentation in HTML/CSS
I'm trying to make a simple two-column layout in HTML/CSS; after consulting some resources, I'm still getting the two divs that should be side-by-side rendering as one below the other.

```<code> <div id="columns" style="width: 100%;">
    <div id="left" style="float: left; width: 60%;">
      <button id="testBtn">show</button>
      <div id="output" style="white-space: pre-line">
        Content goes here
      </div>
    <div>
    <div id="right" style="float: left; width: 40%;">
      <div id="input">
        input displayed here
      </div>
    </div>
  </div>
</code>```

These are some of the links I've consulted:

Simple two column html layout without using tables

https://www.w3schools.com/howto/howto_css_two_columns.asp

I've tried several variations, but so far I'm not getting a two-column layout. When I set the "input" div to "float:right", it appeared indented to the right but was still below the "output" div instead of beside it. Am I missing something?

答:
Your HTML is invalid. Instead of a closing
 tag for #left, you have an opening
 tag.

Try this:

```<code><div id="left" style="float: left; width: 60%;">
    /* content goes here... */
</div>
</code>```

Here is a fiddle demonstrating the modified markup: https://jsfiddle.net/djc87tLc/

Title: Two-column presentation in HTML/CSS

Body:
I'm trying to make a simple two-column layout in HTML/CSS; after consulting some resources, I'm still getting the two divs that should be side-by-side rendering as one below the other.

      <button id="testBtn">show</button>

        Content goes here

        input displayed here

These are some of the links I've consulted:

Simple two column html layout without using tables

https://www.w3schools.com/howto/howto_css_two_columns.asp

I've tried several variations, but so far I'm not getting a two-column layout. When I set the "input" div to "float:right", it appeared indented to the right but was still below the "output" div instead of beside it. Am I missing something?

Body:
Your HTML is invalid. Instead of a closing </div> tag for #left, you have an opening <div> tag.

Try this:

<div id="left" style="float: left; width: 60%;">
    /* content goes here... */
</div>

Here is a fiddle demonstrating the modified markup: https://jsfiddle.net/djc87tLc/


问:
css div not being recognized
I have the following css code:

```<code>#Layer3

{
position:absolute;
width: 89%;
height: 40%;
left: 10%;
top: 56%;
background-color: #f1ffff;
}

#Layer3 h1
{
font-size: medium;
color: #000033;
text-decoration: none;
text-align: center;
}

.tableheader {
    border-width:10px; border-style:solid;
}
.tablecontent {
    height: 95%;
    overflow:auto;
}
</code>```

However, when I use this PHP to generate the html

```<code>echo '<div id="tableheader" class="tableheader">';

echo "<h1>{$query} Auctions</h1>" . "\n";
echo "</div>";
echo '<div id="tablecontent" class="tablecontent">';

echo "<table border='0' width='100%'><tr>" . "\n";

echo "<td width='15%'>Seller ID</td>" . "\n";

echo "<td width='10%'>Start Date</td>" . "\n";

echo "<td width='75%'>Description</td>" . "\n";

echo "</tr>\n";

// printing table rows

    foreach ($rows as $row)

    {

        $pk = $row['ARTICLE_NO'];

        echo '<tr>' . "\n";

table contens generated in here

        echo '</tr>' . "\n";

    }
echo "</table>";
}

echo "</div>";
</code>```

which generates this html:

```<code><div id="tableheader" class="tableheader">
<h1>hardy Auctions</h1>
</div>
<div id="tablecontent" class="tablecontent">
<table border='0' width='100%'>
<tr>
<td width='15%'>Seller ID</td>
<td width='10%'>Start Date</td>
<td width='75%'>Description</td>
the rest of table stuff
</div>
</code>```

The stylesheet is correctly referenced so I am unsure what is causing the error. But there is no border around tableheader at all. Both of these layers are in Layer3 which no longer displays properly on the page.

答:
I've just had a quick look at this and it seams fine, I've also created a local copy of these and the styles work out okay as well, I get a nice thick black border around the h1 text.

So from what your explaining something is either overwriting the styles, or the styles aren't being applied to the page.

Title: css div not being recognized

Body:
I have the following css code:

#Layer3

{
position:absolute;
width: 89%;
height: 40%;
left: 10%;
top: 56%;
background-color: #f1ffff;
}

#Layer3 h1
{
font-size: medium;
color: #000033;
text-decoration: none;
text-align: center;
}

.tableheader {
    border-width:10px; border-style:solid;
}
.tablecontent {
    height: 95%;
    overflow:auto;
}

However, when I use this PHP to generate the html

echo '
';

echo "
{$query} Auctions
" . "\n";
echo "
";
echo '
';

echo "

" . "\n";

echo "Seller ID	" . "\n";

echo "Start Date	" . "\n";

echo "Description	" . "\n";

echo "
\n";

// printing table rows

    foreach ($rows as $row)

    {

        $pk = $row['ARTICLE_NO'];

        echo '
' . "\n";

table contens generated in here

        echo '
' . "\n";

    }
echo "
";
}

echo "
";

which generates this html:

hardy Auctions

Seller ID
Start Date
Description
the rest of table stuff

The stylesheet is correctly referenced so I am unsure what is causing the error. But there is no border around tableheader at all. Both of these layers are in Layer3 which no longer displays properly on the page.

OwnerDisplayName: Anthony


问:
When is a value type / reference type constraint useful in C#?
I'm looking for simple examples that demonstrate when the value type / reference type constraints are useful.

```<code>... where T : struct  // when is this useful?
... where T : class   // and what about this?
</code>```

I remember seeing some very nice examples in the past but I just can't find them.

答:
"T : class" will force the generic type specified to be a class, not a value.  For example, we can make up an ObjectList class that requires the generic type specified to be a class, not a value:

```<code>class ObjectList<T> where T : class {
  ...
}

class SomeObject { ... }

ObjectList<int> invalidList = new ObjectList<int>();  //compiler error

ObjectList<SomeObject> someObjectList = new ObjectList<SomeObject>(); //this works
</code>```

This forces an invariant on your generic type T that otherwise might not be enforceable.  "T : struct" would work the same way.  Note that you can also use this construct to enforce not only that the type T is a class, but also that it matches an interface.  The code sample I took this from also has

```<code>class MyList<T> where T : class, IEntity { ... }
</code>```

which forces T to be a class AND also be an IEntity.

Body:
I'm looking for simple examples that demonstrate when the value type / reference type constraints are useful.

... where T : struct  // when is this useful?
... where T : class   // and what about this?

I remember seeing some very nice examples in the past but I just can't find them.

Body:
"T : class" will force the generic type specified to be a class, not a value.  For example, we can make up an ObjectList class that requires the generic type specified to be a class, not a value:

class ObjectList<T> where T : class {
  ...
}

class SomeObject { ... }

ObjectList<int> invalidList = new ObjectList<int>();  //compiler error

ObjectList<SomeObject> someObjectList = new ObjectList<SomeObject>(); //this works

This forces an invariant on your generic type T that otherwise might not be enforceable.  "T : struct" would work the same way.  Note that you can also use this construct to enforce not only that the type T is a class, but also that it matches an interface.  The code sample I took this from also has

class MyList<T> where T : class, IEntity { ... }

which forces T to be a class AND also be an IEntity.


问:
How to CancelSynchronousIo() on WaitForSingleObject() waiting on stdin?
On Windows 10, I'm waiting for input from the console using

WaitForSingleObject( GetStdHandle(STD_INPUT_HANDLE), ... )

and to cancel this waiting using CancelSynchronousIo().

But the cancellation does nothing (returns 0 and GetLastError() is ERROR_NOT_FOUND).

Any idea what I could be doing wrong?

Should I be able to cancel this waiting for new input on stdin?

(I actually want to do this with any HANDLE whose GetFileType() is FILE_TYPE_CHAR, not only stdin, but stdin is certainly the most important use case and the simplest to test with).

Related discussions I've found:

Synchronous ReadFile() on stdin cannot be unblocked by CancelSynchronousIo()

win32: how stop ReadFile (stdin|pipe)

But unfortunately they only discuss ReadFile(), not WaitForSingleObject(). I've also tried WaitForMultipleObjects() (with just a single object in the array), same problem.

(Background: I'm trying to improve input handling in the GHC Haskell compiler runtime.)

答:
CancelSynchronousIo cancel I/O operations that are issued by the specified thread. more concrete it cancel IRP packets which associated with specified thread via call IoCancelIrp. if use undocumented NtCancelSynchronousIoFile (CancelSynchronousIo internally call it with IoRequestToCancel = 0) we can be more selective - cancel only i/o request which used specified IoRequestToCancel (system check that Irp->UserIosb == IoRequestToCancel and cancel only this requests)

but WaitForSingleObject this is not I/O request. this call not create any IRP which can be canceled. so - no way do this.

however if you use WaitForSingleObjectEx with bAlertable set to TRUE - you can break wait by queue apc to thread by using QueueUserAPC . also if use NtWaitForSingleObject  instead WaitForSingleObjectEx we can also alert thread by using undocumented call NtAlertThread. in this case NtWaitForSingleObject will break with STATUS_ALERTED (note that WaitForSingleObjectEx which internally call NtWaitForSingleObject do special check for STATUS_ALERTED and in case this status - again run NtWaitForSingleObject - as result we can not break WaitForSingleObjectEx by call NtAlertThread, but NtWaitForSingleObject will be breaked.

so if you need break waiting for std input - create additional thread, which must call not CancelSynchronousIo (this senseless) but QueueUserAPC or NtAlertThread (only if you use NtWaitForSingleObject for wait). and input thread must wait in alertable state. so demo code can look like:

```<code>extern "C" NTSYSCALLAPI NTSTATUS NTAPI NtAlertThread(HANDLE ThreadHandle);

VOID NTAPI OnApc(ULONG_PTR Parameter)
{
    DbgPrint("OnApc(%p)\n", Parameter);
}

DWORD CALLBACK BreakWaitThread(HANDLE hThread)
{
    switch (LONG status = MessageBoxW(0, L"Use Apc(yes) or Alert(No) ?", L"BreakWaitThread",
        MB_ICONQUESTION|MB_YESNOCANCEL|MB_DEFBUTTON3))
    {
    case IDYES:
        if (!QueueUserAPC(OnApc, hThread, 0))
        {
            DbgPrint("QueueUserAPC=%u\n", GetLastError());
        }
        break;
    case IDNO:
        if (0 > (status = NtAlertThread(hThread)))
        {
            DbgPrint("AlertThread=%x\n", status);
        }
        break;
    case IDCANCEL:
        DbgPrint("canceled\n");
        break;
    default:
        DbgPrint("MessageBox=%x\n", status);
    }

    CloseHandle(hThread);

    return 0;
}

void ConsoleLoop(HANDLE hStdIn)
{
    ULONG NumberOfEvents, NumberOfEventsRead, n;

    INPUT_RECORD buf[8], *p;

    for (;;)
    {
        switch (ZwWaitForSingleObject(hStdIn, TRUE, 0))
        //switch (WaitForSingleObjectEx(hStdIn, INFINITE, TRUE))
        {
        case WAIT_OBJECT_0:

            while (GetNumberOfConsoleInputEvents(hStdIn, &NumberOfEvents) && NumberOfEvents)
            {
                do
                {
                    NumberOfEventsRead = min(RTL_NUMBER_OF(buf), NumberOfEvents);

                    if (ReadConsoleInput(hStdIn, buf, NumberOfEventsRead, &NumberOfEventsRead) && NumberOfEventsRead)
                    {
                        n = NumberOfEventsRead;
                        p = buf;
                        do
                        {
                            if (p->EventType == KEY_EVENT)
                            {
                                DbgPrint("%u(%u) %C %x %x %x\n",
                                    p->Event.KeyEvent.bKeyDown,
                                    p->Event.KeyEvent.wRepeatCount,
                                    p->Event.KeyEvent.uChar.UnicodeChar,
                                    p->Event.KeyEvent.wVirtualKeyCode,
                                    p->Event.KeyEvent.wVirtualScanCode,
                                    p->Event.KeyEvent.dwControlKeyState);

                                if (VK_OEM_PERIOD == p->Event.KeyEvent.wVirtualKeyCode)
                                {
                                    return ;//if user type '.' return for demo
                                }
                            }
                        } while (p++, --n);
                    }
                    else
                    {
                        FlushConsoleInputBuffer(hStdIn);
                        break;
                    }

                } while (NumberOfEvents -= NumberOfEventsRead);
            }
            continue;

        case STATUS_USER_APC:
            DbgPrint("\nUSER_APC\n");
            return;
        case STATUS_ALERTED:
            DbgPrint("\nALERTED\n");
            return;
        case WAIT_FAILED :
            DbgPrint("\nWAIT_FAILED=%u\n", GetLastError());
            return;
        default:
            __debugbreak();
            return;
        }
    }
}

void SimpleDemo()
{
    if (HANDLE hCurrentThread = OpenThread(THREAD_ALERT|THREAD_SET_CONTEXT , FALSE, GetCurrentThreadId()))
    {
        ULONG dwThreadId;
        HANDLE hThread = CreateThread(0, 0, BreakWaitThread, hCurrentThread, 0, &dwThreadId);

        if (hThread)
        {
            ConsoleLoop(GetStdHandle(STD_INPUT_HANDLE));
            PostThreadMessage(dwThreadId, WM_QUIT, 0, 0);
            WaitForSingleObject(hThread, INFINITE);
            CloseHandle(hThread);
        }
        else
        {
            CloseHandle(hCurrentThread);
        }
    }
}
</code>```

Body:
CancelSynchronousIo cancel I/O operations that are issued by the specified thread. more concrete it cancel IRP packets which associated with specified thread via call IoCancelIrp. if use undocumented NtCancelSynchronousIoFile (CancelSynchronousIo internally call it with IoRequestToCancel = 0) we can be more selective - cancel only i/o request which used specified IoRequestToCancel (system check that Irp->UserIosb == IoRequestToCancel and cancel only this requests)

but WaitForSingleObject this is not I/O request. this call not create any IRP which can be canceled. so - no way do this.

however if you use WaitForSingleObjectEx with bAlertable set to TRUE - you can break wait by queue apc to thread by using QueueUserAPC . also if use NtWaitForSingleObject  instead WaitForSingleObjectEx we can also alert thread by using undocumented call NtAlertThread. in this case NtWaitForSingleObject will break with STATUS_ALERTED (note that WaitForSingleObjectEx which internally call NtWaitForSingleObject do special check for STATUS_ALERTED and in case this status - again run NtWaitForSingleObject - as result we can not break WaitForSingleObjectEx by call NtAlertThread, but NtWaitForSingleObject will be breaked.

so if you need break waiting for std input - create additional thread, which must call not CancelSynchronousIo (this senseless) but QueueUserAPC or NtAlertThread (only if you use NtWaitForSingleObject for wait). and input thread must wait in alertable state. so demo code can look like:

extern "C" NTSYSCALLAPI NTSTATUS NTAPI NtAlertThread(HANDLE ThreadHandle);

VOID NTAPI OnApc(ULONG_PTR Parameter)
{
    DbgPrint("OnApc(%p)\n", Parameter);
}

DWORD CALLBACK BreakWaitThread(HANDLE hThread)
{
    switch (LONG status = MessageBoxW(0, L"Use Apc(yes) or Alert(No) ?", L"BreakWaitThread",
        MB_ICONQUESTION|MB_YESNOCANCEL|MB_DEFBUTTON3))
    {
    case IDYES:
        if (!QueueUserAPC(OnApc, hThread, 0))
        {
            DbgPrint("QueueUserAPC=%u\n", GetLastError());
        }
        break;
    case IDNO:
        if (0 > (status = NtAlertThread(hThread)))
        {
            DbgPrint("AlertThread=%x\n", status);
        }
        break;
    case IDCANCEL:
        DbgPrint("canceled\n");
        break;
    default:
        DbgPrint("MessageBox=%x\n", status);
    }

    CloseHandle(hThread);

    return 0;
}

void ConsoleLoop(HANDLE hStdIn)
{
    ULONG NumberOfEvents, NumberOfEventsRead, n;

    INPUT_RECORD buf[8], *p;

    for (;;)
    {
        switch (ZwWaitForSingleObject(hStdIn, TRUE, 0))
        //switch (WaitForSingleObjectEx(hStdIn, INFINITE, TRUE))
        {
        case WAIT_OBJECT_0:

            while (GetNumberOfConsoleInputEvents(hStdIn, &NumberOfEvents) && NumberOfEvents)
            {
                do
                {
                    NumberOfEventsRead = min(RTL_NUMBER_OF(buf), NumberOfEvents);

                    if (ReadConsoleInput(hStdIn, buf, NumberOfEventsRead, &NumberOfEventsRead) && NumberOfEventsRead)
                    {
                        n = NumberOfEventsRead;
                        p = buf;
                        do
                        {
                            if (p->EventType == KEY_EVENT)
                            {
                                DbgPrint("%u(%u) %C %x %x %x\n",
                                    p->Event.KeyEvent.bKeyDown,
                                    p->Event.KeyEvent.wRepeatCount,
                                    p->Event.KeyEvent.uChar.UnicodeChar,
                                    p->Event.KeyEvent.wVirtualKeyCode,
                                    p->Event.KeyEvent.wVirtualScanCode,
                                    p->Event.KeyEvent.dwControlKeyState);

                                if (VK_OEM_PERIOD == p->Event.KeyEvent.wVirtualKeyCode)
                                {
                                    return ;//if user type '.' return for demo
                                }
                            }
                        } while (p++, --n);
                    }
                    else
                    {
                        FlushConsoleInputBuffer(hStdIn);
                        break;
                    }

                } while (NumberOfEvents -= NumberOfEventsRead);
            }
            continue;

        case STATUS_USER_APC:
            DbgPrint("\nUSER_APC\n");
            return;
        case STATUS_ALERTED:
            DbgPrint("\nALERTED\n");
            return;
        case WAIT_FAILED :
            DbgPrint("\nWAIT_FAILED=%u\n", GetLastError());
            return;
        default:
            __debugbreak();
            return;
        }
    }
}

void SimpleDemo()
{
    if (HANDLE hCurrentThread = OpenThread(THREAD_ALERT|THREAD_SET_CONTEXT , FALSE, GetCurrentThreadId()))
    {
        ULONG dwThreadId;
        HANDLE hThread = CreateThread(0, 0, BreakWaitThread, hCurrentThread, 0, &dwThreadId);

        if (hThread)
        {
            ConsoleLoop(GetStdHandle(STD_INPUT_HANDLE));
            PostThreadMessage(dwThreadId, WM_QUIT, 0, 0);
            WaitForSingleObject(hThread, INFINITE);
            CloseHandle(hThread);
        }
        else
        {
            CloseHandle(hCurrentThread);
        }
    }
}


问:
JPA-override annotation on SuperClass property
I have SuperClass where I have defined my properties and I want to apply one more annotation on  one of the SuperClass Property.

```<code>@MappedSuperclass
public class CartBaseEntity {
private String cartName;

@Column(name = "cart_name")
public String getCartName() {
    return cartName;
 }

public void setCartName(String cartName) {
    this.cartName = cartName;
 }
}
</code>```

And my Sub Class is in below:

```<code>@Entity
@Table(name = "CART2")
public class CartEntity extends CartBaseEntity implements Serializable {

private Set<Items> items;

@Basic(fetch = FetchType.LAZY)
@Override
public String getCartName() {
    return super.getCartName();
  }
}
</code>```

I was trying to override the 'cartName' column and want to add @Basic annotation on it. Is it possible or is there any workarround? TIA

答:
Yes, it's possible with @AttributeOverride annotation applied to a subclass:

```<code>@Entity
@Table(name = "CART2")
@AttributeOverride(name = "cartName", column = @Column(name="CART_NAME"))
public class CartEntity extends CartBaseEntity implements Serializable {
    ...
}
</code>```

UPDATE: here's what JPA 2.1 Specification tells about overriding a column in a mapped superclass:

11.1.4 AttributeOverride Annotation

The AttributeOverride annotation is used to override the mapping of
  a Basic (whether explicit or default) property or field or Id
  property or field.

The AttributeOverride annotation may be applied to an entity that
  extends a mapped superclass or to an embedded field or property to
  override a Basic mapping or Id mapping defined by the mapped
  superclass or embeddable class (or embeddable class of one of its
  attributes).

Body:
I have SuperClass where I have defined my properties and I want to apply one more annotation on  one of the SuperClass Property.

@MappedSuperclass
public class CartBaseEntity {
private String cartName;

@Column(name = "cart_name")
public String getCartName() {
    return cartName;
 }

public void setCartName(String cartName) {
    this.cartName = cartName;
 }
}

And my Sub Class is in below:

@Entity
@Table(name = "CART2")
public class CartEntity extends CartBaseEntity implements Serializable {

private Set<Items> items;

@Basic(fetch = FetchType.LAZY)
@Override
public String getCartName() {
    return super.getCartName();
  }
}

I was trying to override the 'cartName' column and want to add @Basic annotation on it. Is it possible or is there any workarround? TIA

Body:
Yes, it's possible with @AttributeOverride annotation applied to a subclass:

@Entity
@Table(name = "CART2")
@AttributeOverride(name = "cartName", column = @Column(name="CART_NAME"))
public class CartEntity extends CartBaseEntity implements Serializable {
    ...
}

UPDATE: here's what JPA 2.1 Specification tells about overriding a column in a mapped superclass:

11.1.4 AttributeOverride Annotation

The AttributeOverride annotation is used to override the mapping of
  a Basic (whether explicit or default) property or field or Id
  property or field.

The AttributeOverride annotation may be applied to an entity that
  extends a mapped superclass or to an embedded field or property to
  override a Basic mapping or Id mapping defined by the mapped
  superclass or embeddable class (or embeddable class of one of its
  attributes).


问:
GreenHillsCompiler callgraph
in our project we have to use the GreenHillsCompiler Suite MULTI. So everything is configured and running. Reading the compiler manual I found an option for the linker which will generate a callgraph.

I added the option to the linker (elxr) in the makefile with

```<code>LINK_OPT += -callgraph
</code>```

which generates a file with the extension ".graph" in the output folder. This files just contains plain text.

```<code>Function    Function Call   Call Count  Percent of Total    Max Displacement    (bits)
#% BEGIN STATIC GRAPH
myFunc  out 0   in  3
  out   0   100%
  in    3   100%
  myFunc2   1   33% 0   2514    0
  .static00012204   1   33% 0   514 0
  .static0001220b   1   33% 0   1300    0
#% END STATIC GRAPH
</code>```

So the question is:  What tool has to be used further?

What we want is an image or a html-document.

答:
That is the graph. It is in text format.

Note that if you want a graphical representation of a function's call graph, from within the MULTI debugger you can right-click a function and select Browse Other -> Browse Static Calls.

Title: GreenHillsCompiler callgraph

Body:
in our project we have to use the GreenHillsCompiler Suite MULTI. So everything is configured and running. Reading the compiler manual I found an option for the linker which will generate a callgraph.

I added the option to the linker (elxr) in the makefile with

LINK_OPT += -callgraph

which generates a file with the extension ".graph" in the output folder. This files just contains plain text.

Function    Function Call   Call Count  Percent of Total    Max Displacement    (bits)
#% BEGIN STATIC GRAPH
myFunc  out 0   in  3
  out   0   100%
  in    3   100%
  myFunc2   1   33% 0   2514    0
  .static00012204   1   33% 0   514 0
  .static0001220b   1   33% 0   1300    0
#% END STATIC GRAPH

So the question is:  What tool has to be used further?

What we want is an image or a html-document.


问:
iterating through STRINGS in Python (3)
: Write a   function,   named foldStrings(string1,  string2)    that    takes,  as  arguments,  two strings.        If

the two strings are equal   in  length, the function    returns a   string  that    is  formed  by  alternating characters  in  each    of the  two strings.        If  the two strings are not equal   in  length, the function    returns the string  “The    two strings are not
equal   in  length.”

For example, >>>foldStrings(“abc”,  “def”)

should  return  the string  “adbecf” and >>>foldStrings(“a”,    “bc”)

should  return  the string  “The    two strings are not equal in length.”

This is what I have so far:

```<code>def foldStrings(str1, str2):
newStr = ""
counter = 0
if len(str2) == len(str1):
    while counter < len(str2):
        for element in str1:
            for index in str2:
                newStr = newStr + element
                newStr = newStr + index
                counter += 1
    return newStr
else:
    return "The two Strings are not equal in length"
</code>```

and it prints this: 's1s2s3s4s5s6a1a2a3a4a5a6n1n2n3n4n5n6t1t2t3t4t5t6o1o2o3o4o5o6s1s2s3s4s5s6'
instead of this:
's1a2n3t4o5s6'

答:
```<code>#Simple way to do it
def foldStrings(str1, str2):
    newStr = ""
    counter = 0
    if len(str2) == len(str1):
        while counter < len(str2):
            newStr = newStr + str1[counter] + str2[counter]
            counter += 1
        return newStr
    else:
        return "The two Strings are not equal in length"
</code>```

Title: iterating through STRINGS in Python (3)

Body:
: Write a   function,   named foldStrings(string1,  string2)    that    takes,  as  arguments,  two strings.        If

the two strings are equal   in  length, the function    returns a   string  that    is  formed  by  alternating characters  in  each    of the  two strings.        If  the two strings are not equal   in  length, the function    returns the string  “The    two strings are not
equal   in  length.”

For example, >>>foldStrings(“abc”,  “def”)

should  return  the string  “adbecf” and >>>foldStrings(“a”,    “bc”)

should  return  the string  “The    two strings are not equal in length.”

This is what I have so far:

def foldStrings(str1, str2):
newStr = ""
counter = 0
if len(str2) == len(str1):
    while counter < len(str2):
        for element in str1:
            for index in str2:
                newStr = newStr + element
                newStr = newStr + index
                counter += 1
    return newStr
else:
    return "The two Strings are not equal in length"

and it prints this: 's1s2s3s4s5s6a1a2a3a4a5a6n1n2n3n4n5n6t1t2t3t4t5t6o1o2o3o4o5o6s1s2s3s4s5s6'
instead of this:
's1a2n3t4o5s6'


问:
treemap vs hashmap and sort in terms of memory usage
I have a huge file in the format:

```<code>x a
y c
x d
z a
z s
y k
</code>```

I want that the output will be sorted and in the form

```<code>x a,d
y c,k
z a,s,k
</code>```

For this type of task a hash is the best:

The straightforward TreeMap solution would be this:

```<code>Map<String, StringBuilder> agg = Maps.newTreeMap();

while ((line = r.readLine()) != null) {

    String[] arr = line.split("\t");
            String key = arr[0];
            String value = arr[1];

    if(agg.containsKey(key)) {
            agg.get(key).append(",").append(value);
        }
        else {
            agg.put(key, new StringBuilder(value));
        }
    }

}
r.close();

System.out.println("Printing results");
FileWriter f = new FileWriter("out.txt");

for (String key : agg.keySet()) {
    f.write(key+"\t"+agg.get(key)+"\n");
}
</code>```

Another option would be to use a hashmap, take the keyset, sort it and iterate over it.

The different part would be

```<code>    System.out.println("Sorting array");
    List<String> keys = Lists.newArrayList(agg.keySet());
            Collections.sort(keys);
        System.out.println("Printing results");
        FileWriter f = new FileWriter("out.txt");

        for (String key : keys) {
            f.write(key+"\t"+agg.get(key)+"\n");
        }
</code>```

For me the big O is less important because it is a batch job.

For me the memory usage is much more important.

Which strategy is more efficient in terms of memory?

HashMap and the peek in the sort phase or the TreeMap approach

答:
HashMap is not optimal in memory utilization, rather for specific operations. It is backed by an array, which is allocated on initialization and resized when its size reaches certain limits. Consequently, memory is allocated eagerly. Its size is always a power of 2, which is actually a computational optimization for faster bucket index calculation. As a result, the (unused) allocated memory may significantly surpass the actual memory used by your program.

TreeMap provides the optimal memory utilization, while having worse performance in get, add, remove operations comparing to the HashMap. This becomes more obvious by its constructor, which doesn't have any parameter that can affect its computational complexity. All its entries are lazily allocated and associated with the existing entries to form a tree.

Body:
I have a huge file in the format:

x a
y c
x d
z a
z s
y k

I want that the output will be sorted and in the form

x a,d
y c,k
z a,s,k

For this type of task a hash is the best:

The straightforward TreeMap solution would be this:

Map<String, StringBuilder> agg = Maps.newTreeMap();

while ((line = r.readLine()) != null) {

    String[] arr = line.split("\t");
            String key = arr[0];
            String value = arr[1];

    if(agg.containsKey(key)) {
            agg.get(key).append(",").append(value);
        }
        else {
            agg.put(key, new StringBuilder(value));
        }
    }

}
r.close();

System.out.println("Printing results");
FileWriter f = new FileWriter("out.txt");

for (String key : agg.keySet()) {
    f.write(key+"\t"+agg.get(key)+"\n");
}

Another option would be to use a hashmap, take the keyset, sort it and iterate over it.

The different part would be

    System.out.println("Sorting array");
    List<String> keys = Lists.newArrayList(agg.keySet());
            Collections.sort(keys);
        System.out.println("Printing results");
        FileWriter f = new FileWriter("out.txt");

        for (String key : keys) {
            f.write(key+"\t"+agg.get(key)+"\n");
        }

For me the big O is less important because it is a batch job.

For me the memory usage is much more important.

Which strategy is more efficient in terms of memory?

HashMap and the peek in the sort phase or the TreeMap approach


问:
Library depend on a header file
Let's assume I have a project with a series of libraries. I also need to generate a header file that will be used by all of these projects. So I created a CMake file, like this:

```<code>project(main)

add_subdirectory(sub_1)
add_subdirectory(sub_2)
# ...
add_subdirectory(sub_n)

add_custom_command(
    OUTPUT CustomHeader.h
    COMMENT "Generating custom header for all the libraries"
    COMMAND ...)

add_library(${PROJECT_NAME} STATIC ${OBJECT_LIST})
</code>```

The problem is, that I don't know how to tell CMake to run my custom command (that generates this CustomHeader.h) before it would try to build the libraries in the subfolders.

I tried add_custom_target(TARGET MyPrebuild PRE_BUILD ...) but I'm running on Linux, and this option only works on Windows platform according to the documentation.

add_dependencies only work between targets, and not a target and a single file.

I could, in theory, add the header to be among the source files of the individual libraries (in the sub_1, .., sub_n folders) but it feels wrong, as the header is not required to be part of those libraries.

So I just have no idea how I can make a library depend on an include file, that is not part of it.

Any tips how I can overcome this problem?

答:
For make header file (re)built before a library in subdirectory is compiled, you may create target, which builds the file, and make the library dependent from the target:

```<code># *CMakeLists.txt*
# ...
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/CustomHeader.h ...)

add_custom_target(generate_custom_header DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/CustomHeader.h)

# *sub/CMakeLists.txt*
# ...
add_library(libA ...)

add_dependencies(libA generate_custom_header)
</code>```

Instead of using add_dependencies, you may create header-only library which "implements" you header and link with it:

```<code># *CMakeLists.txt*
# ...
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/CustomHeader.h ...)

add_custom_target(generate_custom_header DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/CustomHeader.h)

add_library(libCustom INTERFACE) # Header only library
add_dependencies(libCustom generate_custom_header) # which depends on generated header

# You may even assign include directories for the header-only library
target_include_directories(libCustom INTERFACE ${CMAKE_CURRENT_BINARY_DIR})

# *sub/CMakeLists.txt*
# ...
add_library(libA ...)

target_link_libraries(libA libCustom) # Common linking with a header-only library.
</code>```

Note, that INTERFACE library is a "fake" - it is never created by itself. Instead, all "features" of INTERFACE library are just propagated to its users.

Title: Library depend on a header file

Body:
Let's assume I have a project with a series of libraries. I also need to generate a header file that will be used by all of these projects. So I created a CMake file, like this:

project(main)

add_subdirectory(sub_1)
add_subdirectory(sub_2)
# ...
add_subdirectory(sub_n)

add_custom_command(
    OUTPUT CustomHeader.h
    COMMENT "Generating custom header for all the libraries"
    COMMAND ...)

add_library(${PROJECT_NAME} STATIC ${OBJECT_LIST})

The problem is, that I don't know how to tell CMake to run my custom command (that generates this CustomHeader.h) before it would try to build the libraries in the subfolders.

I tried add_custom_target(TARGET MyPrebuild PRE_BUILD ...) but I'm running on Linux, and this option only works on Windows platform according to the documentation.

add_dependencies only work between targets, and not a target and a single file.

I could, in theory, add the header to be among the source files of the individual libraries (in the sub_1, .., sub_n folders) but it feels wrong, as the header is not required to be part of those libraries.

So I just have no idea how I can make a library depend on an include file, that is not part of it.

Any tips how I can overcome this problem?

Body:
For make header file (re)built before a library in subdirectory is compiled, you may create target, which builds the file, and make the library dependent from the target:

# *CMakeLists.txt*
# ...
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/CustomHeader.h ...)

add_custom_target(generate_custom_header DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/CustomHeader.h)

# *sub/CMakeLists.txt*
# ...
add_library(libA ...)

add_dependencies(libA generate_custom_header)

Instead of using add_dependencies, you may create header-only library which "implements" you header and link with it:

# *CMakeLists.txt*
# ...
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/CustomHeader.h ...)

add_custom_target(generate_custom_header DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/CustomHeader.h)

add_library(libCustom INTERFACE) # Header only library
add_dependencies(libCustom generate_custom_header) # which depends on generated header

# You may even assign include directories for the header-only library
target_include_directories(libCustom INTERFACE ${CMAKE_CURRENT_BINARY_DIR})

# *sub/CMakeLists.txt*
# ...
add_library(libA ...)

target_link_libraries(libA libCustom) # Common linking with a header-only library.

Note, that INTERFACE library is a "fake" - it is never created by itself. Instead, all "features" of INTERFACE library are just propagated to its users.


问:
Automatically leave field after value is entered
I am creating a form in Visual FoxPro where the user will be entering a large number of values that are only one character values.  So that the user does not have to press tab after every key press, I would like to setup the form so that once the value is entered the cursor automatically goes to the next field.

What is a good way to do this?

答:
Make sure you have SET CONFIRM OFF

From the help file:

SET CONFIRM ON | OFF

  ...

  OFF  Specifies that the user can exit a text box by typing past the
  last character in the text box. The insertion point, when it reaches
  the last character in a text box, moves to the next control, and the
  bell is sounded (if SET BELL is set to ON).

OFF is the default value of SET CONFIRM.

SET CONFIRM OFF also affects menu items and menu titles. If SET
  CONFIRM is set to OFF, the user can choose an item from a menu or a
  menu title in a menu bar by pressing the key corresponding to the
  first letter of the menu item or title. (When SET CONFIRM is set to
  ON, this action only selects the menu item or title.)

I made a simple form with two text boxes and verified that after typing one character, it jumps to the next text box.


问:
Is it I/O manipulators that provide the functionality of << and >>?
I have read about I/O manipulators and have thereof been a little confused.It is stated that it is because of these manipulators that we are able to control streams using << and >>. I am not quite sure why, but I have always thought that is was objects, such as std::cout, that controlled the functionality of operators, such as <<.

How is it even possible that functions, since I/O manipulators allegedly are functions, can overload/define operators? :/

Being specific, they state the following for manipulators taking arguments:

These manipulators define their own operator<< or operator>> which
  perform the requested manipulation.

If this is true - that it is not the objects (the classes that they belong to), but these helper functions that control the operators << and >> - how it is known what to do in the following statement?

```<code>std::cout << "static constructor\n";
</code>```

答:
The text you quote is poor wording.

The standard headers define both the manipulator, and a free-function overloaded operator whose operands are the stream and the manipulator. The manipulator does not overload an operator per se.

The manipulator is indeed a function template. It is possible to overload operators so that one of the operands can be a function or a function template.  In the latter case, the overloaded operator is itself a function template.

In your last statement, the syntax x << y is transformed to the function call operator<<(x, y); and then the ordinary name lookup and overload resolution process resolves that call in the same way as any other function call.

Body:
I have read about I/O manipulators and have thereof been a little confused.It is stated that it is because of these manipulators that we are able to control streams using << and >>. I am not quite sure why, but I have always thought that is was objects, such as std::cout, that controlled the functionality of operators, such as <<.

How is it even possible that functions, since I/O manipulators allegedly are functions, can overload/define operators? :/

Being specific, they state the following for manipulators taking arguments:

These manipulators define their own operator<< or operator>> which
  perform the requested manipulation.

If this is true - that it is not the objects (the classes that they belong to), but these helper functions that control the operators << and >> - how it is known what to do in the following statement?

std::cout << "static constructor\n";


答:
Add display:inline-block; box-sizing:border-box; in both the divs and it will work.

```<code>display:inline-block;
</code>```

This will keep the elements inline and box-sizing:border-box; will keep the element's width to your defined width by including any padding or border inside it.

Hope this helps.

Title: Two-column presentation in HTML/CSS

Body:
Add display:inline-block; box-sizing:border-box; in both the divs and it will work.

display:inline-block;

This will keep the elements inline and box-sizing:border-box; will keep the element's width to your defined width by including any padding or border inside it.

Hope this helps.


问:
mySQL error datetime value error for str_to_date?
This error comes from this code which i can't figure out whats wrong;

#1411 - Incorrect datetime value: '11:00 PM' for function str_to_date

```<code>CREATE TABLE OWNS (
STUDNO       NUMERIC(9) NOT NULL,
ENAME         CHAR(30) NOT NULL,
TYPE          CHAR(15) NOT NULL,
OTIME         TIME,
ODATE         DATE,
ODRTN         VARCHAR(7) NOT NULL,
CONSTRAINT OWNS_FOREIGN_KEY FOREIGN KEY (STUDNO) REFERENCES STUD(STUDNO));

INSERT INTO OWNS (STUDNO, ENAME, TYPE, OTIME,ODATE, ODRTN)
VALUES(123456789,'The Lion King','Anti', str_to_date('11:00 PM', '%l:%i
%p'), STR_TO_DATE('16-jan-2011', '%d-%b-%y'), 3)
</code>```

Appreciate the help thanks!!!

答:
```<code>INSERT INTO OWNS (STUDNO, ENAME, TYPE, OTIME,ODATE, ODRTN)
VALUES(1234456789,'The Lion King','Anti', str_to_date('11:00 PM', '%l:%i
%p'), STR_TO_DATE("16-jan-2011", "%d-%b-%Y"), 3)
</code>```

Body:
This error comes from this code which i can't figure out whats wrong;

#1411 - Incorrect datetime value: '11:00 PM' for function str_to_date

CREATE TABLE OWNS (
STUDNO       NUMERIC(9) NOT NULL,
ENAME         CHAR(30) NOT NULL,
TYPE          CHAR(15) NOT NULL,
OTIME         TIME,
ODATE         DATE,
ODRTN         VARCHAR(7) NOT NULL,
CONSTRAINT OWNS_FOREIGN_KEY FOREIGN KEY (STUDNO) REFERENCES STUD(STUDNO));

INSERT INTO OWNS (STUDNO, ENAME, TYPE, OTIME,ODATE, ODRTN)
VALUES(123456789,'The Lion King','Anti', str_to_date('11:00 PM', '%l:%i
%p'), STR_TO_DATE('16-jan-2011', '%d-%b-%y'), 3)

Appreciate the help thanks!!!


问:
How to make HTML text hidden until clicked on
I'm trying to learn how to make HTML text toggle with jQuery, which is pretty easy in itself, but I want the text to be hidden automatically until it is clicked on with a button. I've looked it up and I can't find how to do this. I figured it should be easy, and I have this part

```<code><h4 id="text1">This is some toggleable text</h4>

$(document).ready(function(){
    $("#button1").click(function(){
      $("#text1").toggle();
    });
});
</code>```

Which works fine as a regular toggle, but this leaves the text there until first clicked on.

Codepen: https://codepen.io/anon/pen/bYYeEB

答:
```<code>$(document).ready(
  function(){
    $("#button1").click(toggle);
  }
);

function toggle() {
  $("#text1").toggle();
}

toggle();
</code>```

Calling toggle at the bottom will auto hide the element. This still isn't the greatest since the element will show until this code runs.

But you can always change the HTML to read like this:

```<code><h4 id="text1" style="display:none">This is some toggleable text</h4>
</code>```

Then you don't need to call toggle the first time.

Body:
I'm trying to learn how to make HTML text toggle with jQuery, which is pretty easy in itself, but I want the text to be hidden automatically until it is clicked on with a button. I've looked it up and I can't find how to do this. I figured it should be easy, and I have this part

This is some toggleable text

$(document).ready(function(){
    $("#button1").click(function(){
      $("#text1").toggle();
    });
});

Which works fine as a regular toggle, but this leaves the text there until first clicked on.

Codepen: https://codepen.io/anon/pen/bYYeEB

Body:
$(document).ready(
  function(){
    $("#button1").click(toggle);
  }
);

function toggle() {
  $("#text1").toggle();
}

toggle();

Calling toggle at the bottom will auto hide the element. This still isn't the greatest since the element will show until this code runs.

But you can always change the HTML to read like this:

<h4 id="text1" style="display:none">This is some toggleable text</h4>

Then you don't need to call toggle the first time.


问:
Custom adatper getView returns null pointer
In my app I have a listview with a custom adapter which is reloaded after a message was send. The app chrashes at some of the installations. I have in the app console the stack traces. Here the code:

```<code>class IconicAdapter extends ArrayAdapter<Integer> {
        Activity context;

        IconicAdapter(Activity context) {
            super(context, R.layout.message_layout, listItems);

            this.context = context;
        }

        public View getView(int position, View convertView, ViewGroup parent) {

                //you can access layout inflater by accessing hosting activity
                convertView = getActivity().getLayoutInflater().inflate(R.layout.message_layout, parent, false);

            JSONObject json_data = null;
            try {
                json_data = jArray.getJSONObject(position);
            } catch (JSONException e) {
            }

            try {
                tv = (TextView) convertView.findViewById(R.id.username);
                tv.setText(json_data.getString("username"));
</code>```

Here stack trace:

```<code>java.lang.NullPointerException:
  at com.testing.gold.CommunityFragment$IconicAdapter.getView (CommunityFragment.java:945)
  at android.widget.HeaderViewListAdapter.getView (HeaderViewListAdapter.java:232)
</code>```

The line 945: tv.setText(json_data.getString("username"));

答:
```<code>class IconicAdapter extends ArrayAdapter<Integer> {
   Activity context;

   IconicAdapter(Activity context) {
    super(context, R.layout.activity_main, new Integer[]{1, 2});
    this.context = context;
}

public View getView(int position, View convertView, ViewGroup parent) {

    convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main, null);
    JSONObject json_data = null;
    try {
        json_data = jArray.getJSONObject(position);
        tv = (TextView) convertView.findViewById(R.id.username);
        tv.setText(json_data.getString("username"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return convertView;
}
</code>```

<p>}</p>

Body:
In my app I have a listview with a custom adapter which is reloaded after a message was send. The app chrashes at some of the installations. I have in the app console the stack traces. Here the code:

class IconicAdapter extends ArrayAdapter<Integer> {
        Activity context;

        IconicAdapter(Activity context) {
            super(context, R.layout.message_layout, listItems);

            this.context = context;
        }

        public View getView(int position, View convertView, ViewGroup parent) {

                //you can access layout inflater by accessing hosting activity
                convertView = getActivity().getLayoutInflater().inflate(R.layout.message_layout, parent, false);

            JSONObject json_data = null;
            try {
                json_data = jArray.getJSONObject(position);
            } catch (JSONException e) {
            }

            try {
                tv = (TextView) convertView.findViewById(R.id.username);
                tv.setText(json_data.getString("username"));

Here stack trace:

java.lang.NullPointerException:
  at com.testing.gold.CommunityFragment$IconicAdapter.getView (CommunityFragment.java:945)
  at android.widget.HeaderViewListAdapter.getView (HeaderViewListAdapter.java:232)

The line 945: tv.setText(json_data.getString("username"));

Body:
class IconicAdapter extends ArrayAdapter<Integer> {
   Activity context;

   IconicAdapter(Activity context) {
    super(context, R.layout.activity_main, new Integer[]{1, 2});
    this.context = context;
}

public View getView(int position, View convertView, ViewGroup parent) {

    convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main, null);
    JSONObject json_data = null;
    try {
        json_data = jArray.getJSONObject(position);
        tv = (TextView) convertView.findViewById(R.id.username);
        tv.setText(json_data.getString("username"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return convertView;
}

}


问:
from client implementation perspective, can I compare Java Callable to Angular Observable (RxJS)
Before someone think to downvote or even close my question I would like to highligh that I am not asking which is better (cetainly a non-sense question especially when we think one is focused to server and other to browser side).

From http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/ we see this simple example:

```<code>ExecutorService executor = Executors.newFixedThreadPool(1);
Future<Integer> future = executor.submit(task);

System.out.println("future done? " + future.isDone()); // prints future done? false

Integer result = future.get();

System.out.println("future done? " + future.isDone()); // prints future done? true
System.out.print("result: " + result); //result: 123
</code>```

Well, adding the idea that I can control when call future.get() is pretty the same idea happening with Observable in practical terms. I mean, for instance, I can call a rest service using callable and then get the result after some time without blocking my code and control the maximun time (seconds) I will accept this lazy beaviour.

I read carefully Difference between Java 8 streams and RxJava observables and it is clear that Java streams are quite different from Angular observables but I am wondering if I got correct the idea of Java callable and ExecutorService.

答:
I am not a Java person, but for me Callables seems to be the counterpart of Promises in Javascript.

In very short and rough comparison, the main difference are:

Promises and Callables are pull-based, while Observables are push-based,

Promises and Callables emit data only once, then complete, Observables emits multiple times

Well, adding the idea that I can control when call future.get() is pretty the same idea happening with Observable in practical terms.

No, as a consumer, controlling when to call get is the same as to control when to call then on a Promise. You cannot control when an observable will emit as a consumer.

But ofc, RxJS differs in a lot of other ways, but these are the main reasons.

Body:
Before someone think to downvote or even close my question I would like to highligh that I am not asking which is better (cetainly a non-sense question especially when we think one is focused to server and other to browser side).

From http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/ we see this simple example:

ExecutorService executor = Executors.newFixedThreadPool(1);
Future<Integer> future = executor.submit(task);

System.out.println("future done? " + future.isDone()); // prints future done? false

Integer result = future.get();

System.out.println("future done? " + future.isDone()); // prints future done? true
System.out.print("result: " + result); //result: 123

Well, adding the idea that I can control when call future.get() is pretty the same idea happening with Observable in practical terms. I mean, for instance, I can call a rest service using callable and then get the result after some time without blocking my code and control the maximun time (seconds) I will accept this lazy beaviour.

I read carefully Difference between Java 8 streams and RxJava observables and it is clear that Java streams are quite different from Angular observables but I am wondering if I got correct the idea of Java callable and ExecutorService.


问:
Lower trailing parts of letters "g" and "y" etc hidden/cut off/overwritten in ggplot labels
The bottom parts of the "y"'s and "g"'s are cut off in this map.  See "dryland" and "irrigated" under soy.

What setting controls this?  Here is my theme_map function

```<code>theme_map <- function (base_size = 12, base_family = "") {
  theme_gray(base_size = base_size, base_family = base_family) %+replace%
    theme(
      axis.line=element_blank(),
      axis.text.x=element_blank(),
      axis.text.y=element_blank(),
      axis.ticks=element_blank(),
      axis.ticks.length=unit(0.3, "lines"),
      axis.ticks.margin=unit(0.5, "lines"),
      axis.title.x=element_blank(),
      axis.title.y=element_blank(),
      legend.background=element_rect(fill="white", colour=NA),
      legend.key=element_rect(colour="white"),
      legend.key.size=unit(1.2, "lines"),
      legend.position="right",
      legend.text=element_text(size=rel(0.8)),
      legend.title=element_text(size=rel(0.8), face="bold", hjust=0),
      panel.background=element_blank(),
      panel.border=element_blank(),
      panel.grid.major=element_blank(),
      panel.grid.minor=element_blank(),
      panel.spacing=unit(0, "lines"),
      plot.background=element_blank(),
      plot.margin=unit(c(1, 1, 0.5, 0.5), "lines"),
      plot.title=element_text(size=rel(1.2)),
      strip.background=element_rect(fill="white", colour="white"),
      strip.text.x=element_text(size=rel(.8)),
      strip.text.y=element_text(size=rel(0.8), angle=-90)
    )
}
</code>```

I am just dipping my toe into ggplot2 after spending a long time as a curmudgeonly devotee of base graphics.  I found that theme_map function on the internet somewhere, so I don't understand it yet.  Can someone please tell me which of those settings I'd need to tweak to solve my problem?

Here's my code for generating (one of) those maps, but I'm assuming that the relevant part is in the theme_map function

```<code>mapcorn <- ggplot(USA_fort_premade) +
    aes(long,lat,group=group) +
    geom_polygon(aes(x=long,y=lat, group=group, fill=yield.mean),
                 data=REAP_fort_corn)+
    geom_path(color="grey", lwd = .1) +
    coord_fixed(1.3) +
    facet_wrap( ~ irr) +
    scale_fill_gradient2(low = rgb(.9, .4, 0), mid = rgb(.9, .9, 0),
                         high = rgb(0,.8,0), midpoint = mean(REAP_fort_corn$yield.mean, na.rm = TRUE),
                         space = "Lab", name = "bu/ac",
                         na.value = "grey50", guide = "colourbar") +
    theme_map() +ggtitle("Corn")
</code>```

Apologies for not reproducible, but the data is huge and this should be a fairly simple question.  A hard one to google however if you don't know the terms.

答: If those are the facet strip labels, try strip.text.x=element_text(margin=margin(b=5)), where b is the bottom margin in points. Set it to whatever value is large enough to get the complete text to appear. You can adjust the top, right, bottom, and left margins with margin=margin(t=5, r=2, b=7, l=2), or whatever values work for your plot.

Body:
The bottom parts of the "y"'s and "g"'s are cut off in this map.  See "dryland" and "irrigated" under soy.

What setting controls this?  Here is my theme_map function

theme_map <- function (base_size = 12, base_family = "") {
  theme_gray(base_size = base_size, base_family = base_family) %+replace%
    theme(
      axis.line=element_blank(),
      axis.text.x=element_blank(),
      axis.text.y=element_blank(),
      axis.ticks=element_blank(),
      axis.ticks.length=unit(0.3, "lines"),
      axis.ticks.margin=unit(0.5, "lines"),
      axis.title.x=element_blank(),
      axis.title.y=element_blank(),
      legend.background=element_rect(fill="white", colour=NA),
      legend.key=element_rect(colour="white"),
      legend.key.size=unit(1.2, "lines"),
      legend.position="right",
      legend.text=element_text(size=rel(0.8)),
      legend.title=element_text(size=rel(0.8), face="bold", hjust=0),
      panel.background=element_blank(),
      panel.border=element_blank(),
      panel.grid.major=element_blank(),
      panel.grid.minor=element_blank(),
      panel.spacing=unit(0, "lines"),
      plot.background=element_blank(),
      plot.margin=unit(c(1, 1, 0.5, 0.5), "lines"),
      plot.title=element_text(size=rel(1.2)),
      strip.background=element_rect(fill="white", colour="white"),
      strip.text.x=element_text(size=rel(.8)),
      strip.text.y=element_text(size=rel(0.8), angle=-90)
    )
}

I am just dipping my toe into ggplot2 after spending a long time as a curmudgeonly devotee of base graphics.  I found that theme_map function on the internet somewhere, so I don't understand it yet.  Can someone please tell me which of those settings I'd need to tweak to solve my problem?

Here's my code for generating (one of) those maps, but I'm assuming that the relevant part is in the theme_map function

mapcorn <- ggplot(USA_fort_premade) +
    aes(long,lat,group=group) +
    geom_polygon(aes(x=long,y=lat, group=group, fill=yield.mean),
                 data=REAP_fort_corn)+
    geom_path(color="grey", lwd = .1) +
    coord_fixed(1.3) +
    facet_wrap( ~ irr) +
    scale_fill_gradient2(low = rgb(.9, .4, 0), mid = rgb(.9, .9, 0),
                         high = rgb(0,.8,0), midpoint = mean(REAP_fort_corn$yield.mean, na.rm = TRUE),
                         space = "Lab", name = "bu/ac",
                         na.value = "grey50", guide = "colourbar") +
    theme_map() +ggtitle("Corn")

Apologies for not reproducible, but the data is huge and this should be a fairly simple question.  A hard one to google however if you don't know the terms.


问:
PHP download file?
I am trying to create a download thing for a file in PHP. It will download from the server to the local computer.

Here is the code that I have for now:

```<code>// connect and login to FTP server
$ftp_server = "files.000webhost.com";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, "jonasvdr", "*******");

$local_file = "image";
$server_file = "https://jonasvdr.000webhostapp.com/uploads/NewlogoNoBackGround.png";

// download server file
if (ftp_get($ftp_conn, $local_file, $server_file, FTP_ASCII)) {
    echo "Successfully written to $local_file.";
} else {
    echo "Error downloading $server_file.";
}

// close connection
ftp_close($ftp_conn);
</code>```

The error that I am getting is this:

Warning: ftp_get(): Can't open https://jonasvdr.000webhostapp.com/uploads/NewlogoNoBackGround.png: No such file or directory in /storage/ssd5/555/3642555/public_html/download.php on line 11

I've tried to just put uploads/NewlogoNoBackGround.png instead of the whole URL but got the same result.

This PHP page is in the main root directory, and in that directory is a map called uploads. That is where the file's in. How can I get that file then?

答:
It looks like you are trying to access the file through its URL, not its filepath. Try:

```<code>$server_file = '/uploads/NewlogoBackGround.png';
</code>```

Or, alternatively:

```<code>$server_file = $_SERVER['DOCUMENT_ROOT'].'/uploads/NewlogoBackground.png';
</code>```

Depending on where exactly your file is and what file structure you have.

Title: PHP download file?

Body:
I am trying to create a download thing for a file in PHP. It will download from the server to the local computer.

Here is the code that I have for now:

// connect and login to FTP server
$ftp_server = "files.000webhost.com";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, "jonasvdr", "*******");

$local_file = "image";
$server_file = "https://jonasvdr.000webhostapp.com/uploads/NewlogoNoBackGround.png";

// download server file
if (ftp_get($ftp_conn, $local_file, $server_file, FTP_ASCII)) {
    echo "Successfully written to $local_file.";
} else {
    echo "Error downloading $server_file.";
}

// close connection
ftp_close($ftp_conn);

The error that I am getting is this:

Warning: ftp_get(): Can't open https://jonasvdr.000webhostapp.com/uploads/NewlogoNoBackGround.png: No such file or directory in /storage/ssd5/555/3642555/public_html/download.php on line 11

I've tried to just put uploads/NewlogoNoBackGround.png instead of the whole URL but got the same result.

This PHP page is in the main root directory, and in that directory is a map called uploads. That is where the file's in. How can I get that file then?

Body:
It looks like you are trying to access the file through its URL, not its filepath. Try:

$server_file = '/uploads/NewlogoBackGround.png';

Or, alternatively:

$server_file = $_SERVER['DOCUMENT_ROOT'].'/uploads/NewlogoBackground.png';

Depending on where exactly your file is and what file structure you have.


问:
python3: pretty-print alternatives to "pprint.pformat" and "json.dumps"
I want to pretty-print python objects in a way that differs somewhat from how json.dumps and pprint.pformat do the formatting. I'm wondering if anyone knows any existing modules that I can use to pretty-print my code as follows:

Suppose I have the following python dictionary:

```<code>mydict = { 'a': 'letter a',
           'b': [ 'b', 'b', 'b', 'b' ],
           'c': [ 'c' ],
           'd': [ 'dddd', 'dddd', 'dddd', 'dddd', 'dddd',
                  'dddd', 'dddd', 'dddd', 'dddd', 'dddd',
                  'dddd' ]
         }
</code>```

I would like mydict pretty-printed in much the same way as I wrote it above, i.e. ...

```<code>{ 'a': 'letter a',
  'b': [ 'b', 'b', 'b', 'b' ],
  'c': [ 'c' ],
  'd': [ 'dddd', 'dddd', 'dddd', 'dddd', 'dddd',
         'dddd', 'dddd', 'dddd', 'dddd', 'dddd',
         'dddd' ]
}
</code>```

In other words, for lists and other similar items, I'd like each item to be listed across the page until it reaches some maximum specified width, and then for it to wrap onto a new line that is left-aligned with the data in the line above.

I have been trying different combinations of parameters for json.dumps and pprint.pformat, but I haven't figured out how to obtain this long-line behavior.

I'm sure I could write something like this myself, but instead, I'm hoping that there are one or more existing modules that I can use in order to pretty-print in this way.

Does anyone know of something out there in the wild which already is able to pretty-print in this manner?

Thank you very much.

答:
I found that I can do this with the code formatting that comes with the yapf package: https://github.com/google/yapf

Given the mydict item, above, I can do this ...

```<code>import yapf
style = { 'COLUMN_LIMIT': 50, 'ALLOW_SPLIT_BEFORE_DICT_VALUE': False }
text, flag = yapf.yapflib.yapf_api.FormatCode(str(mydict),
                                              style_config=style)
print(text)
</code>```

... and I get the following output ...

```<code>{
    'a': 'letter a',
    'b': ['b', 'b', 'b', 'b'],
    'c': ['c'],
    'd': [
        'dddd', 'dddd', 'dddd', 'dddd', 'dddd',
        'dddd', 'dddd', 'dddd', 'dddd', 'dddd',
        'dddd'
    ]
}
</code>```

There are ways to control the indentation and other code-formatting policies.

It will be easy to encapsulate this into my own pretty-print function.

Body:
I want to pretty-print python objects in a way that differs somewhat from how json.dumps and pprint.pformat do the formatting. I'm wondering if anyone knows any existing modules that I can use to pretty-print my code as follows:

Suppose I have the following python dictionary:

mydict = { 'a': 'letter a',
           'b': [ 'b', 'b', 'b', 'b' ],
           'c': [ 'c' ],
           'd': [ 'dddd', 'dddd', 'dddd', 'dddd', 'dddd',
                  'dddd', 'dddd', 'dddd', 'dddd', 'dddd',
                  'dddd' ]
         }

I would like mydict pretty-printed in much the same way as I wrote it above, i.e. ...

{ 'a': 'letter a',
  'b': [ 'b', 'b', 'b', 'b' ],
  'c': [ 'c' ],
  'd': [ 'dddd', 'dddd', 'dddd', 'dddd', 'dddd',
         'dddd', 'dddd', 'dddd', 'dddd', 'dddd',
         'dddd' ]
}

In other words, for lists and other similar items, I'd like each item to be listed across the page until it reaches some maximum specified width, and then for it to wrap onto a new line that is left-aligned with the data in the line above.

I have been trying different combinations of parameters for json.dumps and pprint.pformat, but I haven't figured out how to obtain this long-line behavior.

I'm sure I could write something like this myself, but instead, I'm hoping that there are one or more existing modules that I can use in order to pretty-print in this way.

Does anyone know of something out there in the wild which already is able to pretty-print in this manner?

Thank you very much.

Body:
I found that I can do this with the code formatting that comes with the yapf package: https://github.com/google/yapf

Given the mydict item, above, I can do this ...

import yapf
style = { 'COLUMN_LIMIT': 50, 'ALLOW_SPLIT_BEFORE_DICT_VALUE': False }
text, flag = yapf.yapflib.yapf_api.FormatCode(str(mydict),
                                              style_config=style)
print(text)

... and I get the following output ...

{
    'a': 'letter a',
    'b': ['b', 'b', 'b', 'b'],
    'c': ['c'],
    'd': [
        'dddd', 'dddd', 'dddd', 'dddd', 'dddd',
        'dddd', 'dddd', 'dddd', 'dddd', 'dddd',
        'dddd'
    ]
}

There are ways to control the indentation and other code-formatting policies.

It will be easy to encapsulate this into my own pretty-print function.


问:
How do I get the selected row data from a data grid view using SelectedRows?
I have a table that I am displaying in a data grid view control. The user selects a single row from the control and presses a button. I need to retrieve the cells from that row and store them as strings.

Exactly how do I get the data using the SelectedRow method? I've been working on this for several hours and I'm at the end of my rope. Here's an example of something I've tried:

```<code>DataGridViewCellCollection selRowData = dataGridView1.SelectedRows[0].Cells;
</code>```

If I try to access selRowData[x], the return value does not contain my data.

答:
Perhaps this is a more suitable solution use the cell values of the row clicked:</p>

```<code>private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
  if (e.RowIndex > -1)
  {
    var val = this.dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
  }
}
</code>```

Body:
I have a table that I am displaying in a data grid view control. The user selects a single row from the control and presses a button. I need to retrieve the cells from that row and store them as strings.

Exactly how do I get the data using the SelectedRow method? I've been working on this for several hours and I'm at the end of my rope. Here's an example of something I've tried:

DataGridViewCellCollection selRowData = dataGridView1.SelectedRows[0].Cells;

If I try to access selRowData[x], the return value does not contain my data.

Body:
Perhaps this is a more suitable solution use the cell values of the row clicked:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
  if (e.RowIndex > -1)
  {
    var val = this.dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
  }
}


问:
JavaScript variable changing between two values on a regular basis
I want a variable's value regularly changing between 0 and 1.  If I have a variable whose value is 0 (counter = 0), how can I increase it by 1 (counter = 1) after a few seconds, then decrease it back to 0 ( counter = 0) after another few seconds? An endless loop basically is what I want.

I'm assuming this will require setTimeout or setInterval, but I've absolutely no idea how I'd go about this. I'm very unfamiliar with the syntax; I'm very much a newbie. Does anyone have any pointers?

Thanks!

答:
setInterval is what you want, as documented in W3C, you should pass a function and a time interval in milliseconds on how often to execute the code.

```<code>var counter = 0;

setInterval(function(){

  counter = 1 - counter;

  //Do what you want with the result...
  //alert(counter);

}, 1000);
</code>```

https://codepen.io/paulodiogo/pen/xPPOKa?editors=1010

Not using global variable...
https://codepen.io/paulodiogo/pen/KyyMXZ

Body:
setInterval is what you want, as documented in W3C, you should pass a function and a time interval in milliseconds on how often to execute the code.

var counter = 0;

setInterval(function(){

  counter = 1 - counter;

  //Do what you want with the result...
  //alert(counter);

}, 1000);

https://codepen.io/paulodiogo/pen/xPPOKa?editors=1010

Not using global variable...
https://codepen.io/paulodiogo/pen/KyyMXZ