问:
Assigning several colors to nodes on the same network graph in R
I think this is really basic, but we can't seem to find an answer to this question. We are building a network analysis graph, and would like to color each node based on attributes. We are able to do two colors, but need to do more than that. We are not using iGraph, although most searches we are finding give this example. Here is a look at our code for the different groups and colors:

```<code>#### Nodes Attributes ####################################################

nodeColors<-ifelse(nodeInfo$Section=="1","hotpink","dodgerblue")
#nodeColors<-(nodeInfo$Section)
## We can easily give two colors but we need four colors.
##########################################################################
##########################################################################
#### Visualisation    ####################################################

library(sna)
gplot(relations,gmode="graph",displaylabels=TRUE,vertex.col=nodeColors, mode =
"fruchtermanreingold")
</code>```

What we want to do is something like this:

We have 4 different groups assigned based on orientation groups:

```<code>nodeColors<-nodeInfo$Orientation=="1 2 3 4","red","blue","yellow","green")
</code>```

Thoughts? What are we doing wrong?

答:
What are we doing wrong?

Noone can say, since you did not show a reproducible (=copy-paste-run'able) example of what you actually did.

However, I guess that dplyr's case_when will make your life easier:

```<code>(x <- c(1:4, 1))
# [1] 1 2 3 4 1
dplyr::case_when(
  x==1~"red",
  x==2~"orange",
  x==3~"blue",
  TRUE~"lightgray"
)
# [1] "red"       "orange"    "blue"      "lightgray" "red"
</code>```

You may need install.packages("dplyr") beforehand. x is nodeInfo$Orientation in your question. You can assign the result of case_when to your variable nodeColors using <-. See ?dplyr::case_when for more info on that function.

Body:
I think this is really basic, but we can't seem to find an answer to this question. We are building a network analysis graph, and would like to color each node based on attributes. We are able to do two colors, but need to do more than that. We are not using iGraph, although most searches we are finding give this example. Here is a look at our code for the different groups and colors:

#### Nodes Attributes ####################################################

nodeColors<-ifelse(nodeInfo$Section=="1","hotpink","dodgerblue")
#nodeColors<-(nodeInfo$Section)
## We can easily give two colors but we need four colors.
##########################################################################
##########################################################################
#### Visualisation    ####################################################

library(sna)
gplot(relations,gmode="graph",displaylabels=TRUE,vertex.col=nodeColors, mode =
"fruchtermanreingold")

What we want to do is something like this:

We have 4 different groups assigned based on orientation groups:

nodeColors<-nodeInfo$Orientation=="1 2 3 4","red","blue","yellow","green")

Thoughts? What are we doing wrong?

Body:
What are we doing wrong?

Noone can say, since you did not show a reproducible (=copy-paste-run'able) example of what you actually did.

However, I guess that dplyr's case_when will make your life easier:

(x <- c(1:4, 1))
# [1] 1 2 3 4 1
dplyr::case_when(
  x==1~"red",
  x==2~"orange",
  x==3~"blue",
  TRUE~"lightgray"
)
# [1] "red"       "orange"    "blue"      "lightgray" "red"

You may need install.packages("dplyr") beforehand. x is nodeInfo$Orientation in your question. You can assign the result of case_when to your variable nodeColors using <-. See ?dplyr::case_when for more info on that function.


来源: stackexchange

问:
SQL Implementation with Sliding-Window functions or Recursive CTEs
I have a problem that it's very easy to be solved in C# code for example, but I have no idea how to write in a SQL query with Recursive CTE-s or Sliding-Windows functions.

Here is the situation: let's say I have a table with 3 columns (ID, Date, Amount), and here is some data:

```<code>ID  Date         Amount
-----------------------
1   01.01.2016    -500
2   01.02.2016    1000
3   01.03.2016    -200
4   01.04.2016     300
5   01.05.2016     500
6   01.06.2016    1000
7   01.07.2016    -100
8   01.08.2016     200
</code>```

The result I want to get from the table is this (ID, Amount .... Order By Date):

```<code>ID  Amount
-----------------------
2    300
4    300
5    500
6    900
8    200
</code>```

The idea is to distribute the amounts into installments, for each client separately, but the thing is when negative amount comes into play you need to remove amount from the last installment. I don't know how clear I am, so here is an example:

Let's say I have 3 Invoices for one client with amounts 500, 200, -300.

If i start distribute these Invoices, first i distribute the amount 500, then 200. But when i come to the third one -300, then i need to remove from the last Invoice. In other words 200 - 300 = -100, so the amount from second Invoice will disappear, but there are still -100 that needs to be substracted from first Invoice. So 500 - 100 = 400. The result i need is result with one row (first invoice with amount 400)

Another example when the first invoice is with negative amount (-500, 300, 500).
In this case, the first (-500) invoice will make the second disappear and another 200 will be substracted from the third. So the result will be: Third Invoice with amount 300.

This is something like Stack implementation in programming language, but i need to make it with sliding-window functions in SQL Server.

I need an implementation with Sliding Function or Recursive CTEs.
Not with cycles ...

Thanks.

答:
Ok, think this is what you want. there are two recursive queries. One for upward propagation and the second one for the downward propagation.

```<code>with your_data_rn as
(
   select *, row_number() over (order by date) rn
   from your_data
), rcte_up(id, date, ammount, rn, running) as
(
   select *, ammount as running
   from your_data_rn
   union all
   select d.*,
          d.ammount + rcte_up.running
   from your_data_rn d
   join rcte_up on rcte_up.running < 0 and  d.rn = rcte_up.rn - 1
), data2 as
(
   select id, date, min(running) ammount,
          row_number() over (order by date) rn
   from rcte_up
   group by id, date, rn
   having min(running) > 0 or rn = 1
), rcte_down(id, date, ammount, rn, running) as
(
   select *, ammount as running
   from data2
   union all
   select  d.*, d.ammount + rcte_down.running
   from data2 d
   join rcte_down on rcte_down.running < 0 and  d.rn = rcte_down.rn + 1
)
select id, date, min(running) ammount
from rcte_down
group by id, date
having min(running) > 0
</code>```

demo

I can imagine that you use just the upward propagation and the downward propagation of the first row is done in some procedural language. Downward propagation is one scan through few first rows, therefore, the recursive query may be a hammer on a mosquito.

ContentLicense: CC BY-SA 3.0

Body:
I have a problem that it's very easy to be solved in C# code for example, but I have no idea how to write in a SQL query with Recursive CTE-s or Sliding-Windows functions.

Here is the situation: let's say I have a table with 3 columns (ID, Date, Amount), and here is some data:

ID  Date         Amount
-----------------------
1   01.01.2016    -500
2   01.02.2016    1000
3   01.03.2016    -200
4   01.04.2016     300
5   01.05.2016     500
6   01.06.2016    1000
7   01.07.2016    -100
8   01.08.2016     200

The result I want to get from the table is this (ID, Amount .... Order By Date):

ID  Amount
-----------------------
2    300
4    300
5    500
6    900
8    200

The idea is to distribute the amounts into installments, for each client separately, but the thing is when negative amount comes into play you need to remove amount from the last installment. I don't know how clear I am, so here is an example:

Let's say I have 3 Invoices for one client with amounts 500, 200, -300.

If i start distribute these Invoices, first i distribute the amount 500, then 200. But when i come to the third one -300, then i need to remove from the last Invoice. In other words 200 - 300 = -100, so the amount from second Invoice will disappear, but there are still -100 that needs to be substracted from first Invoice. So 500 - 100 = 400. The result i need is result with one row (first invoice with amount 400)

Another example when the first invoice is with negative amount (-500, 300, 500).
In this case, the first (-500) invoice will make the second disappear and another 200 will be substracted from the third. So the result will be: Third Invoice with amount 300.

This is something like Stack implementation in programming language, but i need to make it with sliding-window functions in SQL Server.

I need an implementation with Sliding Function or Recursive CTEs.
Not with cycles ...

Thanks.

Body:
Ok, think this is what you want. there are two recursive queries. One for upward propagation and the second one for the downward propagation.

with your_data_rn as
(
   select *, row_number() over (order by date) rn
   from your_data
), rcte_up(id, date, ammount, rn, running) as
(
   select *, ammount as running
   from your_data_rn
   union all
   select d.*,
          d.ammount + rcte_up.running
   from your_data_rn d
   join rcte_up on rcte_up.running < 0 and  d.rn = rcte_up.rn - 1
), data2 as
(
   select id, date, min(running) ammount,
          row_number() over (order by date) rn
   from rcte_up
   group by id, date, rn
   having min(running) > 0 or rn = 1
), rcte_down(id, date, ammount, rn, running) as
(
   select *, ammount as running
   from data2
   union all
   select  d.*, d.ammount + rcte_down.running
   from data2 d
   join rcte_down on rcte_down.running < 0 and  d.rn = rcte_down.rn + 1
)
select id, date, min(running) ammount
from rcte_down
group by id, date
having min(running) > 0

demo

I can imagine that you use just the upward propagation and the downward propagation of the first row is done in some procedural language. Downward propagation is one scan through few first rows, therefore, the recursive query may be a hammer on a mosquito.


问:
how to avoid "Not Responding"

Possible Duplicate:

  Keep app responsive during long task

how to avoid "Not Responding", when processing large query or long process looping?

thx

答: Execute it in separate thread. (see TThread class)</p>

ContentLicense: CC BY-SA 2.5

Title: how to avoid "Not Responding"


问:
How can I achieve a similar full screen column effect as shown in scabal.com?
I am trying to make two columns in bootstrap with 100% height and 50% width where the left column will have a video playing and the video should be responsive to the column.

In scabal.com if you scroll down you can see the similar effect I am looking for.

How do I achieve that?
I have tried a lot of things to no luck. I gave 100% height to the section with h-100, column as well as row but the desired result is not being achieved. I managed to keep a video inside my left column col-lg-6 but the video isn't responsive and doesn't scale up to 100% height.

Please help.

Code is given below

```<code><section id="product-types-women" class="h-100">
    <div class="container-fluid">
        <div class="row">

            <div class="col-lg-6" data-aos="fade-left">

                       <div class="video-wrapper">
                        <video poster="poster.png" autoplay="true" loop class="h-100">
                            <source src="Assets/videos/hero.mp4" type="video/mp4">
                            <source src="Assets/videos/hero.webm" type="video/webm">
                        </video>
                    </div>

            </div>

            <div class="col-lg-6">
                <h1 class="text-center">Designer Boutique For Women</h1>
                <p class="lead text-center">Your own personalized boutique at your doorstep, Call our expert designer home for all your tailoring needs.</p>
                <a href="#" class="btn btn-lg btn-primary">Click Here</a>
            </div>

        </div><!--row-->
    </div><!--container fluid-->
</section><!--product types women-->
</code>```

css part -

```<code>#product-types-women .row{
display: flex;
align-items: center;
}
#product-types-women .col-lg-6{
padding: 0;
flex-basis: 100%;
text-align: center;
}

#product-types-women .col-lg-6 video{
width: 100%;
height: 100%;
}
</code>```

I simply want that video to the left column to increase its height to 100% and cover it like the text to the right
Looking for a response. Thank you so much.

答:
Fixed it with a simple property called -     object-fit: fill; on the video.
The CSS looks like this :

```<code>#product-types-women .col-lg-6{
padding: 0;
flex-basis: 100%;
text-align: center;
height: 100vh;
}

#product-types-women .col-lg-6 video{
width: 100%;
display: block;
height: 100%;
object-fit: fill;
}
</code>```

Final Result :

Thank you all.

Body:
I am trying to make two columns in bootstrap with 100% height and 50% width where the left column will have a video playing and the video should be responsive to the column.

In scabal.com if you scroll down you can see the similar effect I am looking for.

How do I achieve that?
I have tried a lot of things to no luck. I gave 100% height to the section with h-100, column as well as row but the desired result is not being achieved. I managed to keep a video inside my left column col-lg-6 but the video isn't responsive and doesn't scale up to 100% height.

Please help.

Code is given below

                        <video poster="poster.png" autoplay="true" loop class="h-100">
                            <source src="Assets/videos/hero.mp4" type="video/mp4">
                            <source src="Assets/videos/hero.webm" type="video/webm">
                        </video>

Designer Boutique For Women

Your own personalized boutique at your doorstep, Call our expert designer home for all your tailoring needs.

                Click Here

css part -

#product-types-women .row{
display: flex;
align-items: center;
}
#product-types-women .col-lg-6{
padding: 0;
flex-basis: 100%;
text-align: center;
}

#product-types-women .col-lg-6 video{
width: 100%;
height: 100%;
}

I simply want that video to the left column to increase its height to 100% and cover it like the text to the right
Looking for a response. Thank you so much.

Body:
Fixed it with a simple property called -     object-fit: fill; on the video.
The CSS looks like this :

#product-types-women .col-lg-6{
padding: 0;
flex-basis: 100%;
text-align: center;
height: 100vh;
}

#product-types-women .col-lg-6 video{
width: 100%;
display: block;
height: 100%;
object-fit: fill;
}

Final Result :

Thank you all.


问:
How to send a message inside a netty decoder to the next handler/decoder in the pipeline?
My channel pipeline contains several decoders, all of them operating on TextWebSocketFrame messages. Now my problem is, that I have to choose the right decoder base on some content of the message.

Essentially, I have to parse a certain field in the message and then decide if I want to proceed handling the message or pass the message to the next encoder/handler.

Most people suggest to use a single decoder to decode all messages in such a case, but my problem is that some decoders are added dynamically and it would be a mess to put all logic in a single decoder.

Currently the code looks like this:

```<code>@Override
protected void decode(ChannelHandlerContext ctx, TextWebSocketFrame msg, List<Object> out) throws Exception {
    String messageAsJson = msg.text();
    JsonObject jsonObject = JSON_PARSER.fromJson(messageAsJson, JsonObject.class);

    JsonObject messageHeader = jsonObject.getAsJsonObject(MESSAGE_HEADER_FIELD);
    String serviceAsString = messageHeader.get(MESSAGE_SERVICE_FIELD).getAsString();
    String inboundTypeAsString = messageHeader.get(MESSAGE_TYPE_FIELD).getAsString();

    Service service = JSON_PARSER.fromJson(serviceAsString, Service.class);
    InboundType inboundType = JSON_PARSER.fromJson(inboundTypeAsString, InboundType.class);

    if (service == Service.STREAMING) {
        out.add(decodeQuotesMessage(inboundType, messageAsJson));
    } else {

    }
}
</code>```

So basically I'd need some logic in the else branch to pass the message to the next handler in the pipeline.

I am aware, that this approach is not the most efficient one but the architecture of my service has a slow path (running on a different thread pool), including this logic and a fast path. I can accept some slow code at this place.

答:
In general, you need something like this:

```<code>if (service == Service.STREAMING) {
    ctx.pipeline().addLast(new StreamingHandler());
} else {
    ctx.pipeline().addLast(new OtherHandler());
}
out.add(decodeQuotesMessage(inboundType, messageAsJson));
ctx.pipeline().remove(this);
</code>```

Logic behind is next:

You decoded header and you know now what flow you need to follow;

You add specific handler to the pipeline according to your header;

You add decoded message to 'out' list and thus you say "send this decoded message to next handler in pipeline, that would be handler defined in step 2 in case current handler is last in pipeline";

You remove the current handler from the pipeline to avoid handlers duplication in case your protocol will send the same header again and again. However, this is step is specific to your protocol and may be not necessary.

This is just the general approach, however, it really depends on your protocol flow.

ContentLicense: CC BY-SA 4.0

Body:
My channel pipeline contains several decoders, all of them operating on TextWebSocketFrame messages. Now my problem is, that I have to choose the right decoder base on some content of the message.

Essentially, I have to parse a certain field in the message and then decide if I want to proceed handling the message or pass the message to the next encoder/handler.

Most people suggest to use a single decoder to decode all messages in such a case, but my problem is that some decoders are added dynamically and it would be a mess to put all logic in a single decoder.

Currently the code looks like this:

@Override
protected void decode(ChannelHandlerContext ctx, TextWebSocketFrame msg, List<Object> out) throws Exception {
    String messageAsJson = msg.text();
    JsonObject jsonObject = JSON_PARSER.fromJson(messageAsJson, JsonObject.class);

    JsonObject messageHeader = jsonObject.getAsJsonObject(MESSAGE_HEADER_FIELD);
    String serviceAsString = messageHeader.get(MESSAGE_SERVICE_FIELD).getAsString();
    String inboundTypeAsString = messageHeader.get(MESSAGE_TYPE_FIELD).getAsString();

    Service service = JSON_PARSER.fromJson(serviceAsString, Service.class);
    InboundType inboundType = JSON_PARSER.fromJson(inboundTypeAsString, InboundType.class);

    if (service == Service.STREAMING) {
        out.add(decodeQuotesMessage(inboundType, messageAsJson));
    } else {

    }
}

So basically I'd need some logic in the else branch to pass the message to the next handler in the pipeline.

I am aware, that this approach is not the most efficient one but the architecture of my service has a slow path (running on a different thread pool), including this logic and a fast path. I can accept some slow code at this place.

Body:
In general, you need something like this:

if (service == Service.STREAMING) {
    ctx.pipeline().addLast(new StreamingHandler());
} else {
    ctx.pipeline().addLast(new OtherHandler());
}
out.add(decodeQuotesMessage(inboundType, messageAsJson));
ctx.pipeline().remove(this);

Logic behind is next:

You decoded header and you know now what flow you need to follow;

You add specific handler to the pipeline according to your header;

You add decoded message to 'out' list and thus you say "send this decoded message to next handler in pipeline, that would be handler defined in step 2 in case current handler is last in pipeline";

You remove the current handler from the pipeline to avoid handlers duplication in case your protocol will send the same header again and again. However, this is step is specific to your protocol and may be not necessary.

This is just the general approach, however, it really depends on your protocol flow.


问:
random timer in settimeout (in for loop) is not accurate

     for (var i = 0; i <= 10; i++) { setTimeout(function(ind) { return function() {
       let start = Date.now()

        $('.output').append(
          "
THIS IS THE BOX NUMBER"+ind+"
"
         ).hide().fadeIn(1000);

        // fadeout / remove existing notify box  (3 seconds) and call another box
        setTimeout(function(){
         $('.notify_box').fadeOut("slow")
        }, 2000);

       console.log(Date.now() - start)
     }; }(i), Math.round(Math.random() * (5000 - 3000)) + 3000 *i);  } ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  .notify_box {
   background:  #9782AF;
   color: #ffffff;
   padding: 8px;
   border-radius: 20px;
   width: 30%;
   position: fixed;
      margin: 0 10px 10px 0;
  }</code>```

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

<p>here is my jsfiddle: https://jsfiddle.net/gsfe6vm9/</p>

<p>in line 15, the timber seems not to be accurate. I set it to randomly loop for 3 to 5 seconds, but sometimes it pop-ups 1 or 2 seconds.</p>

<p>How can I also console.log the time it pops-up? line 14 seems to be incorrect.</p>

<p>Here's the code I used:</p>

```for (var i = 0; i <= 10; i++) {
    setTimeout(function (ind) {
        return function () {
            let start = Date.now()

                $('.output').append(
                    "
THIS IS THE BOX NUMBER" + ind + "
").hide().fadeIn(1000);

            // fadeout / remove existing notify box  (3 seconds) and call another box
            setTimeout(function () {
                $('.notify_box').fadeOut("slow")
            }, 2000);

            console.log(Date.now() - start)
        };
    }(i), Math.round(Math.random() * (5000 - 3000)) + 3000 * i);
}
```

答:
I hope with this knowledge you can solve your problem.

for(var i = 1; i < 4; i++) {
    setTimeout(function() {
        console.log(i + " second(s) elapsed");
    }, i * 1000);
}```
</div>
</div>
</p>

<p>The code above is likely intended to output the following messages, with a second of delay between each message:</p>

```1 second(s) elapsed
2 second(s) elapsed
3 second(s) elapsed
```

<p>But the code actually outputs the following:</p>

```4 second(s) elapsed
4 second(s) elapsed
4 second(s) elapsed
```

<p>The problem is that console.log(i + " second(s) elapsed"); is in the callback of an asynchronous function. By the time it runs, the for-loop will have already terminated and the variable <code>i</code> will be equal to <code>4</code>.  </p>

<p>There are various workarounds to this problem, but the most common one is to wrap the call to setTimeout in a closure, which will create a new scope with a different i in each iteration:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>for(var i = 1; i <= 3; i++) {
    (function (i) {
       setTimeout(function() {
           console.log(i + " second(s) elapsed");
       }, i * 1000);
    })(i);
}</code>```

If you are using ECMAScript6 or later, then a more elegant solution is to use let instead of var, since let creates a new scope for i in each iteration:

for(let i = 1; i <= 3; i++) {
    setTimeout(function() {
        console.log(i + " second(s) elapsed");
    }, i * 1000);
}```

Read more at hack.guides()

Body:
     for (var i = 0; i <= 10; i++) { setTimeout(function(ind) { return function() {
       let start = Date.now()

        $('.output').append(
          "
THIS IS THE BOX NUMBER"+ind+"
"
         ).hide().fadeIn(1000);

        // fadeout / remove existing notify box  (3 seconds) and call another box
        setTimeout(function(){
         $('.notify_box').fadeOut("slow")
        }, 2000);

       console.log(Date.now() - start)
     }; }(i), Math.round(Math.random() * (5000 - 3000)) + 3000 *i);  }

  .notify_box {
   background:  #9782AF;
   color: #ffffff;
   padding: 8px;
   border-radius: 20px;
   width: 30%;
   position: fixed;
      margin: 0 10px 10px 0;
  }

here is my jsfiddle: https://jsfiddle.net/gsfe6vm9/

in line 15, the timber seems not to be accurate. I set it to randomly loop for 3 to 5 seconds, but sometimes it pop-ups 1 or 2 seconds.

How can I also console.log the time it pops-up? line 14 seems to be incorrect.

Here's the code I used:

for (var i = 0; i <= 10; i++) {
    setTimeout(function (ind) {
        return function () {
            let start = Date.now()

                $('.output').append(
                    "
THIS IS THE BOX NUMBER" + ind + "
").hide().fadeIn(1000);

            // fadeout / remove existing notify box  (3 seconds) and call another box
            setTimeout(function () {
                $('.notify_box').fadeOut("slow")
            }, 2000);

            console.log(Date.now() - start)
        };
    }(i), Math.round(Math.random() * (5000 - 3000)) + 3000 * i);
}

Body:
I hope with this knowledge you can solve your problem.

for(var i = 1; i < 4; i++) {
    setTimeout(function() {
        console.log(i + " second(s) elapsed");
    }, i * 1000);
}

The code above is likely intended to output the following messages, with a second of delay between each message:

1 second(s) elapsed
2 second(s) elapsed
3 second(s) elapsed

But the code actually outputs the following:

4 second(s) elapsed
4 second(s) elapsed
4 second(s) elapsed

The problem is that console.log(i + " second(s) elapsed"); is in the callback of an asynchronous function. By the time it runs, the for-loop will have already terminated and the variable i will be equal to 4.

There are various workarounds to this problem, but the most common one is to wrap the call to setTimeout in a closure, which will create a new scope with a different i in each iteration:

for(var i = 1; i <= 3; i++) {
    (function (i) {
       setTimeout(function() {
           console.log(i + " second(s) elapsed");
       }, i * 1000);
    })(i);
}

If you are using ECMAScript6 or later, then a more elegant solution is to use let instead of var, since let creates a new scope for i in each iteration:

for(let i = 1; i <= 3; i++) {
    setTimeout(function() {
        console.log(i + " second(s) elapsed");
    }, i * 1000);
}

Read more at hack.guides()


问:
Fail to change windows size and buffer under C with Winapi
I've rewritten my question to simplify it:

instead of calling system("mode con cols=80 lines=25"); I try to do it myself with WinApi calls.

Best code I get is this:

```<code>void screensizexy(int x, int y)
{
SMALL_RECT console_size2;
console_size2.Right = x;
console_size2.Bottom = y;
console_size2.Left = 1;
console_size2.Top = 1;
COORD console_size;
console_size.X = x;
console_size.Y = y;
SetConsoleScreenBufferSize(hStdout, console_size);
SetConsoleWindowInfo(hStdout, TRUE, &console_size2);
SetConsoleScreenBufferSize(hStdout, console_size);
SetConsoleWindowInfo(hStdout, TRUE, &console_size2);
}
</code>```

First of all, why do I have to call SetConsoleScreenBufferSize & SetConsoleWindowInfo twice?

Second, if I leave ".Left = 0" and ".Top = 0"  my code fails. Why?

Original Question:

I have a problem with changing windows size and buffer in a C console app. I can't figure what is wrong. I need help.

I did the following to change buffer and windows size, it worked when called from out of console, but failed when called from inside the console:

```<code>hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
COORD console_size;
console_size.X = 100;
console_size.Y = 50;
SetConsoleScreenBufferSize(hStdout, console_size);
SMALL_RECT console_size2;
console_size2.Right = 100;
console_size2.Bottom = 50;
console_size2.Left = 1;
console_size2.Top = 1;
SetConsoleWindowInfo(hStdout, TRUE, &console_size2);
</code>```

If I tried to do it without scrolling, (when I get .Left and .Top = 0) it failed.

Then I tried to get other way around, but still failed. It became worse.

In the new code, if I call this program from windows (not from a console), it failed too.

This is what I do for a big fail:

```<code>HANDLE hStdout, hStdin;

int main()
{
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
hStdin = GetStdHandle(STD_INPUT_HANDLE);
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hStdout, &csbiInfo); //here I store original stuff

// here is the beginning of my program that changes console screen buffer and window size
CONSOLE_SCREEN_BUFFER_INFO console_size;
GetConsoleScreenBufferInfo(hStdout, &console_size);
console_size.dwSize.X = 100;
console_size.dwSize.Y = 50;
console_size.srWindow.Right = 100;
console_size.srWindow.Bottom = 50;
console_size.srWindow.Left = 0;
console_size.srWindow.Top = 0;
SetConsoleScreenBufferSize(hStdout, console_size.dwSize);
SetConsoleWindowInfo(hStdout, TRUE, &console_size.srWindow);

// I fail here, so i added a code to see what are current values.

CONSOLE_SCREEN_BUFFER_INFO csbiInfo2;
HANDLE hConsoleOut = GetStdHandle( STD_OUTPUT_HANDLE );
GetConsoleScreenBufferInfo( hConsoleOut, &csbiInfo2 );
printf("dwCursorPosition.X = %i\n",csbiInfo2.dwCursorPosition.X);
printf("dwCursorPosition.Y = %i\n",csbiInfo2.dwCursorPosition.Y);
printf("dwSize.X = %i\n",csbiInfo2.dwSize.X);
printf("dwSize.Y = %i\n",csbiInfo2.dwSize.Y);
printf("wAttributes = %i\n", csbiInfo2.wAttributes);
printf("srWindow = %i\n", csbiInfo2.srWindow);
printf("srWindow.Top = %i\n", csbiInfo2.srWindow.Top);
printf("srWindow.Bottom = %i\n", csbiInfo2.srWindow.Bottom);
printf("srWindow.Left = %i\n", csbiInfo2.srWindow.Left);
printf("srWindow.Right = %i\n", csbiInfo2.srWindow.Right);
printf("dwMaximumWindowSize = %i\n", csbiInfo2.dwMaximumWindowSize);
printf("\n");
getch();

// Here, my program does its functions.
// stuff
// stuf

// now, at the end, I want to get back to original window size and buffer.

SetConsoleTextAttribute(hStdout, csbiInfo.wAttributes); // Restore the original text colors.
SetConsoleScreenBufferSize(hStdout, csbiInfo.dwSize); //restore buffer size
SetConsoleWindowInfo(hStdout, TRUE, &csbiInfo.srWindow); //restore window size
return 0;
</code>```

}

答:
I figured out the problem: Buffer cannot be smaller than window size. If you change buffer first, you cant go smaller than old window size. If you change window first, you cant go larger than old buffer size.</p>

```<code>    void newbufwinxy(int x, int y)
{
SMALL_RECT console_size2;
console_size2.Right = x;
console_size2.Bottom = y;
console_size2.Left = 1;
console_size2.Top = 1;
COORD console_size;
console_size.X = x;
console_size.Y = y;
CONSOLE_SCREEN_BUFFER_INFO screencsbi;
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &screencsbi);
//if new buffer is larger than old buffer size or at least window, go ahead
if (console_size.X >= screencsbi.dwSize.X && (console_size.Y >= screencsbi.dwSize.Y||console_size.Y >= screencsbi.srWindow.Bottom-1))
{
    SetConsoleScreenBufferSize(hStdout, console_size);
    SetConsoleWindowInfo(hStdout, TRUE, &console_size2);
}
//if new window is larger in widght but smaller in height, do a temporary shrink
else if (console_size2.Right >= screencsbi.srWindow.Right-1 && console_size2.Bottom <= screencsbi.srWindow.Bottom-1)
{
    console_size2.Right = 20; //temporarily shrink window width...
    SetConsoleWindowInfo(hStdout, TRUE, &console_size2);
    SetConsoleScreenBufferSize(hStdout, console_size);
    console_size2.Right = x;
    SetConsoleWindowInfo(hStdout, TRUE, &console_size2);
}
//if new buffer is smaller than old window, change window first
else if (console_size.X <= screencsbi.dwSize.X && !(console_size2.Bottom >= screencsbi.dwSize.Y))
{
    SetConsoleWindowInfo(hStdout, TRUE, &console_size2);
    SetConsoleScreenBufferSize(hStdout, console_size);
}
else
{
    printf("\nold _values_ >> new _values_ \n");
    printf("dwSize.X = %i >> ",screencsbi.dwSize.X);
    printf("dwSize.X = %i\n",console_size.X);
    printf("dwSize.Y = %i >> ",screencsbi.dwSize.Y);
    printf("dwSize.Y = %i\n",console_size.Y);
    printf("srWindow.Bottom = %i >> ", screencsbi.srWindow.Bottom);
    printf("srWindow.Bottom = %i\n", console_size2.Bottom);
    printf("srWindow.Right = %i >> ", screencsbi.srWindow.Right);
    printf("srWindow.Right = %i\n", console_size2.Right);
    printf("SetConsoleWindowInfo, SetConsoleScreenBufferSize\n");
    printf("Error. Cannot recognise console windows or buffer size!\n");
    printf("\nProgram encountered errors and shall exit now.");
    printf("\nPress any key to continue...");
    getch();
    ExitProcess(1);
}
}
</code>```

Body:
I've rewritten my question to simplify it:

instead of calling system("mode con cols=80 lines=25"); I try to do it myself with WinApi calls.

Best code I get is this:

void screensizexy(int x, int y)
{
SMALL_RECT console_size2;
console_size2.Right = x;
console_size2.Bottom = y;
console_size2.Left = 1;
console_size2.Top = 1;
COORD console_size;
console_size.X = x;
console_size.Y = y;
SetConsoleScreenBufferSize(hStdout, console_size);
SetConsoleWindowInfo(hStdout, TRUE, &console_size2);
SetConsoleScreenBufferSize(hStdout, console_size);
SetConsoleWindowInfo(hStdout, TRUE, &console_size2);
}

First of all, why do I have to call SetConsoleScreenBufferSize & SetConsoleWindowInfo twice?

Second, if I leave ".Left = 0" and ".Top = 0"  my code fails. Why?

Original Question:

I have a problem with changing windows size and buffer in a C console app. I can't figure what is wrong. I need help.

I did the following to change buffer and windows size, it worked when called from out of console, but failed when called from inside the console:

hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
COORD console_size;
console_size.X = 100;
console_size.Y = 50;
SetConsoleScreenBufferSize(hStdout, console_size);
SMALL_RECT console_size2;
console_size2.Right = 100;
console_size2.Bottom = 50;
console_size2.Left = 1;
console_size2.Top = 1;
SetConsoleWindowInfo(hStdout, TRUE, &console_size2);

If I tried to do it without scrolling, (when I get .Left and .Top = 0) it failed.

Then I tried to get other way around, but still failed. It became worse.

In the new code, if I call this program from windows (not from a console), it failed too.

This is what I do for a big fail:

HANDLE hStdout, hStdin;

int main()
{
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
hStdin = GetStdHandle(STD_INPUT_HANDLE);
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hStdout, &csbiInfo); //here I store original stuff

// here is the beginning of my program that changes console screen buffer and window size
CONSOLE_SCREEN_BUFFER_INFO console_size;
GetConsoleScreenBufferInfo(hStdout, &console_size);
console_size.dwSize.X = 100;
console_size.dwSize.Y = 50;
console_size.srWindow.Right = 100;
console_size.srWindow.Bottom = 50;
console_size.srWindow.Left = 0;
console_size.srWindow.Top = 0;
SetConsoleScreenBufferSize(hStdout, console_size.dwSize);
SetConsoleWindowInfo(hStdout, TRUE, &console_size.srWindow);

// I fail here, so i added a code to see what are current values.

CONSOLE_SCREEN_BUFFER_INFO csbiInfo2;
HANDLE hConsoleOut = GetStdHandle( STD_OUTPUT_HANDLE );
GetConsoleScreenBufferInfo( hConsoleOut, &csbiInfo2 );
printf("dwCursorPosition.X = %i\n",csbiInfo2.dwCursorPosition.X);
printf("dwCursorPosition.Y = %i\n",csbiInfo2.dwCursorPosition.Y);
printf("dwSize.X = %i\n",csbiInfo2.dwSize.X);
printf("dwSize.Y = %i\n",csbiInfo2.dwSize.Y);
printf("wAttributes = %i\n", csbiInfo2.wAttributes);
printf("srWindow = %i\n", csbiInfo2.srWindow);
printf("srWindow.Top = %i\n", csbiInfo2.srWindow.Top);
printf("srWindow.Bottom = %i\n", csbiInfo2.srWindow.Bottom);
printf("srWindow.Left = %i\n", csbiInfo2.srWindow.Left);
printf("srWindow.Right = %i\n", csbiInfo2.srWindow.Right);
printf("dwMaximumWindowSize = %i\n", csbiInfo2.dwMaximumWindowSize);
printf("\n");
getch();

// Here, my program does its functions.
// stuff
// stuf

// now, at the end, I want to get back to original window size and buffer.

SetConsoleTextAttribute(hStdout, csbiInfo.wAttributes); // Restore the original text colors.
SetConsoleScreenBufferSize(hStdout, csbiInfo.dwSize); //restore buffer size
SetConsoleWindowInfo(hStdout, TRUE, &csbiInfo.srWindow); //restore window size
return 0;

}

Body:
I figured out the problem: Buffer cannot be smaller than window size. If you change buffer first, you cant go smaller than old window size. If you change window first, you cant go larger than old buffer size.

    void newbufwinxy(int x, int y)
{
SMALL_RECT console_size2;
console_size2.Right = x;
console_size2.Bottom = y;
console_size2.Left = 1;
console_size2.Top = 1;
COORD console_size;
console_size.X = x;
console_size.Y = y;
CONSOLE_SCREEN_BUFFER_INFO screencsbi;
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &screencsbi);
//if new buffer is larger than old buffer size or at least window, go ahead
if (console_size.X >= screencsbi.dwSize.X && (console_size.Y >= screencsbi.dwSize.Y||console_size.Y >= screencsbi.srWindow.Bottom-1))
{
    SetConsoleScreenBufferSize(hStdout, console_size);
    SetConsoleWindowInfo(hStdout, TRUE, &console_size2);
}
//if new window is larger in widght but smaller in height, do a temporary shrink
else if (console_size2.Right >= screencsbi.srWindow.Right-1 && console_size2.Bottom <= screencsbi.srWindow.Bottom-1)
{
    console_size2.Right = 20; //temporarily shrink window width...
    SetConsoleWindowInfo(hStdout, TRUE, &console_size2);
    SetConsoleScreenBufferSize(hStdout, console_size);
    console_size2.Right = x;
    SetConsoleWindowInfo(hStdout, TRUE, &console_size2);
}
//if new buffer is smaller than old window, change window first
else if (console_size.X <= screencsbi.dwSize.X && !(console_size2.Bottom >= screencsbi.dwSize.Y))
{
    SetConsoleWindowInfo(hStdout, TRUE, &console_size2);
    SetConsoleScreenBufferSize(hStdout, console_size);
}
else
{
    printf("\nold _values_ >> new _values_ \n");
    printf("dwSize.X = %i >> ",screencsbi.dwSize.X);
    printf("dwSize.X = %i\n",console_size.X);
    printf("dwSize.Y = %i >> ",screencsbi.dwSize.Y);
    printf("dwSize.Y = %i\n",console_size.Y);
    printf("srWindow.Bottom = %i >> ", screencsbi.srWindow.Bottom);
    printf("srWindow.Bottom = %i\n", console_size2.Bottom);
    printf("srWindow.Right = %i >> ", screencsbi.srWindow.Right);
    printf("srWindow.Right = %i\n", console_size2.Right);
    printf("SetConsoleWindowInfo, SetConsoleScreenBufferSize\n");
    printf("Error. Cannot recognise console windows or buffer size!\n");
    printf("\nProgram encountered errors and shall exit now.");
    printf("\nPress any key to continue...");
    getch();
    ExitProcess(1);
}
}


问:
Swift: How to Convert Text-to-Speech Generated Audio to .mp3?
I have converted text to speech using the AVSpeechSynthesizer. When clicked on Play, converted speech plays. I don't know the extension of this audio file.
 My goal is to convert this created audio file to .mp3. I have searched in Google but I didn't find anything. Any help is appreciated.

My code is here: Convert text to speech

```<code>text = UserDefaults.standard.string(forKey: "TextString")!
voice = selectCountryDic["Clanguage"]!
let speechText = AVSpeechUtterance(string:text)
speechText.voice = AVSpeechSynthesisVoice(language:voice)

let synthesizer = AVSpeechSynthesizer()
synthesizer.speak(speechText)
</code>```

答:
2021-02-20 Update:

This is possible now. Please see the thread: AVSpeechSynthesizer output as file?

2017 Answer (outdated):

A simple strategy would be saving your output from AVSpeechSynthesizer to a directory first, then changing its format.

But, as far as I know, AVSpeechSynthesizer does not let you save your outputs.
I would suggest you check the following post: Save audio stream to mp3 file (iOS)

 Quoting from IanStallings:

Unfortunately no, there is no public API available to capture the speaker output, and looking over the docs for AVSpeechSynthesizer and related classes I don't see a way to capture any audio from it. You may want to look at 3rd party libraries to help with this.

And another one: AVSpeechSynthesizer output as file?

Again, quoting from Bhumit Mehta:

As of now AVSpeechSynthesizer does not support this. There is no way to get the audio file using AVSpeechSynthesizer. I tried this a few weeks ago for one of my apps and found out that it is not possible, Also nothing has changed for AVSpeechSynthesizer in iOS 8.

Body:
I have converted text to speech using the AVSpeechSynthesizer. When clicked on Play, converted speech plays. I don't know the extension of this audio file.
 My goal is to convert this created audio file to .mp3. I have searched in Google but I didn't find anything. Any help is appreciated.

My code is here: Convert text to speech

text = UserDefaults.standard.string(forKey: "TextString")!
voice = selectCountryDic["Clanguage"]!
let speechText = AVSpeechUtterance(string:text)
speechText.voice = AVSpeechSynthesisVoice(language:voice)

let synthesizer = AVSpeechSynthesizer()
synthesizer.speak(speechText)


问:
Smooch - How to access conversations with free plan and Web-Messenger widget
Just created a new account and integration with Web messenger widget on smooch.io. (So no direct API or similar, just the widget)

I can see messages coming in through the logs tab, like this:

logs of incoming messages

But maybe I am dumb or blind, but I can't figure out how or where to respond to these conversations...

Thanks for any input.

答:
You need to integrate with a system in order to intercept these messages. You can view available systems here: https://app.smooch.io/integrations

My company integrated the web messenger with slack. Every time someone writes via the web messenger, it shows up in slack.


问:
Gettext blog posts different languages
I've been looking already over a month for a universal solution and hadn't come up with any.

I need to have my website international everywhere, not just UI. I also need to have my blog posts multilingual, but they are dynamic (created via CMS).

There are two problems:

I can use GNU Gettext for UI's localization but barely can imagine to use it for blog posts (except using some scary things, like parsing and editing .po files through PHP, then compiling it to .mo with unreliable scripts, then using some tricks to avoid Gettext cache...). So I've come up with an idea to make some database-based localization for dynamic content.

But it means that I need to use two different localization systems: GNU Gettext and database-based. It's ridiculous. So I need to make all localization database-based.

Am I right? Are there smarter solutions? Would appreciate a lot any advice.

答:
Do it the other way round.

Extract the translatable strings from your database into a .pot file, for example 'database.pot'.  When you extract the messages from your php sources, do it (more or less) like this:

```<code>xgettext *.php database.pot
</code>```

You can always use .po or .pot files as input to xgettext.

Then, use your regular translation workflow, and once you have to translated .po files, parse the translations out of the files, and write them back into the database.

Title: Gettext blog posts different languages

Body:
Do it the other way round.

Extract the translatable strings from your database into a .pot file, for example 'database.pot'.  When you extract the messages from your php sources, do it (more or less) like this:

xgettext *.php database.pot

You can always use .po or .pot files as input to xgettext.

Then, use your regular translation workflow, and once you have to translated .po files, parse the translations out of the files, and write them back into the database.


问:
Words in a list with consecutively repeated letters
Right now I have a list of for example

```<code>data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']
</code>```

I want to remove the words with the repeated letters, in which I want to remove the words

```<code>'aa','aac','bbb','bcca','ffffff'
</code>```

Maybe import re?

答:
The original version of this question wanted to drop words that consist entirely of repetitions of a single character. An efficient way to do this is to use sets. We convert each word to a set, and if it consists of only a single character the length of that set will be 1. If that's the case, we can drop that word, unless the original word consisted of a single character.

```<code>data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']
newdata = [s for s in data if len(s) == 1 or len(set(s)) != 1]
print(newdata)
</code>```

output

```<code>['dog', 'cat', 'a', 'aac', 'bcca']
</code>```

Here's code for the new version of your question, where you want to drop words that contain any repeated characters. This one's simpler, because we don't need to make a special test for one-character words..

```<code>data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']
newdata = [s for s in data if len(set(s)) == len(s)]
print(newdata)
</code>```

output

```<code>['dog', 'cat', 'a']
</code>```

If the repetitions have to be consecutive, we can handle that using groupby.

```<code>from itertools import groupby

data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff', 'abab', 'wow']
newdata = [s for s in data if max(len(list(g)) for _, g in groupby(s)) == 1]
print(newdata)
</code>```

output

```<code>['dog', 'cat', 'a', 'abab', 'wow']
</code>```

Body:
Right now I have a list of for example

data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']

I want to remove the words with the repeated letters, in which I want to remove the words

'aa','aac','bbb','bcca','ffffff'

Maybe import re?

Body:
The original version of this question wanted to drop words that consist entirely of repetitions of a single character. An efficient way to do this is to use sets. We convert each word to a set, and if it consists of only a single character the length of that set will be 1. If that's the case, we can drop that word, unless the original word consisted of a single character.

data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']
newdata = [s for s in data if len(s) == 1 or len(set(s)) != 1]
print(newdata)

output

['dog', 'cat', 'a', 'aac', 'bcca']

Here's code for the new version of your question, where you want to drop words that contain any repeated characters. This one's simpler, because we don't need to make a special test for one-character words..

data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']
newdata = [s for s in data if len(set(s)) == len(s)]
print(newdata)

output

['dog', 'cat', 'a']

If the repetitions have to be consecutive, we can handle that using groupby.

from itertools import groupby

data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff', 'abab', 'wow']
newdata = [s for s in data if max(len(list(g)) for _, g in groupby(s)) == 1]
print(newdata)

output

['dog', 'cat', 'a', 'abab', 'wow']


问:
w2ui grid reorderRows to server
I need to send the new row order to the server after re-ordering rows in a w2ui grid, but no event seems to be triggered when dropping a row in a new position.

Any idea of how to trigger an "onRowDrop" event?

Thanks

答:
I found an undocumented "reorderRow" event type in version 1.5.rc1 that goes along with the "onReorderRow" event in the grid's events.

So problem is solved.

Title: w2ui grid reorderRows to server


问:
Print more than 20 posts from Tumblr API
Good afternoon,

I'm very new to Python, but I'm trying to write a code which will allow me to download all of the posts (including the "notes")
from a specified Tumblr account to my computer.

Given my inexperience with coding, I was trying to find a pre-made script which would allow me to do this. I found several brilliant scripts on GitHub, but none of them actually return the notes from Tumblr posts (as far as I can see, although please do correct me if anyone knows of one that does!).

Therefore, I tried to write my own script. I've had some success with the code below. It prints the most recent 20 posts from the given Tumblr (albeit in a rather ugly format -- essentially hundreds of lines of texts all printed into one line of a notepad file):

```<code>#This script prints all the posts (including tags, comments) and also the
#first 20notes from all the Tumblr blogs.

import pytumblr

# Authenticate via API Key
client = pytumblr.TumblrRestClient('myapikey')

#offset = 0

# Make the request
client.posts('staff', limit=2000, offset=0, reblog_info=True, notes_info=True,
filter='html')
#print out into a .txt file
with open('out.txt', 'w') as f:
print >> f, client.posts('staff', limit=2000, offset=0, reblog_info=True,
notes_info=True, filter='html')
</code>```

However, I want the script to continuously print posts until it reaches the end of the specified blog.

I searched this site and found a very similar question (Getting only 20 posts returned through PyTumblr), which has been answered by the stackoverflow user poke. However, I can't seem to actually implement poke's solution so that it works for my data. Indeed, when I run the following script, no output at all is produced.

```<code>import pytumblr

# Authenticate via API Key
client = pytumblr.TumblrRestClient('myapikey')
blog = ('staff')
def getAllPosts (client, blog):
offset = 0
while True:
    posts = client.posts(blog, limit=20, offset=offset, reblog_info=True, notes_info=True)
    if not posts:
        return

    for post in posts:
        yield post

    offset += 20
</code>```

I should note that there are several posts on this site (e.g.Getting more than 50 notes with Tumblr API) about Tumblr notes, most of them asking how to download more than 50 notes per posts. I'm perfectly happy with just 50 notes per post, it is the number of posts that I would like to increase.

Also, I've tagged this post as Python, however, if there is a better way to get the data I require using another programming language, that would be more than okay.

Thank you very much in advance for your time!

答:
tl;dr If you'd like to just see the answer, it's at the bottom after the heading A Corrected Version

The second code snippet is a generator that yields posts one by one, so you have to use it as part of something like a loop and then do something with the output. Here's your code with some additional code that iterates over the generator and prints out the data it gets back.

```<code>import pytumblr

def getAllPosts (client, blog):
    offset = 0
    while True:
        posts = client.posts(blog, limit=20, offset=offset, reblog_info=True, notes_info=True)
        if not posts:
            return

        for post in posts:
            yield post

        offset += 20

# Authenticate via API Key
client = pytumblr.TumblrRestClient('myapikey')
blog = ('staff')

# use the generator getAllPosts
for post in getAllPosts(client, blog):
    print(post)
</code>```

However, that code has a couple bugs in it. getAllPosts won't yield just each post, it will also return other things because it will iterate over the API response, as you can see from this example I ran in my ipython shell.

```<code>In [7]: yielder = getAllPosts(client, 'staff')

In [8]: next(yielder)
Out[8]: 'blog'

In [9]: next(yielder)
Out[9]: 'posts'

In [10]: next(yielder)
Out[10]: 'total_posts'

In [11]: next(yielder)
Out[11]: 'supply_logging_positions'

In [12]: next(yielder)
Out[12]: 'blog'

In [13]: next(yielder)
Out[13]: 'posts'

In [14]: next(yielder)
Out[14]: 'total_posts'
</code>```

This happens because the posts object in getAllPosts is a dictionary that contains much more than just each post from the staff blog - it also has items like how many posts the blog contains, the blog's description, when it was last updated, etc. The code as-is could potentially result in an infinite loop because the following conditional:

```<code>if not posts:
    return
</code>```

Would never be true because of the response structure, because an empty Tumblr API response from pytumblr looks like this:

```<code>{'blog': {'ask': False,
  'ask_anon': False,
  'ask_page_title': 'Ask me anything',
  'can_send_fan_mail': False,
  'can_subscribe': False,
  'description': '',
  'followed': False,
  'is_adult': False,
  'is_blocked_from_primary': False,
  'is_nsfw': False,
  'is_optout_ads': False,
  'name': 'asdfasdf',
  'posts': 0,
  'reply_conditions': '3',
  'share_likes': False,
  'subscribed': False,
  'title': 'Untitled',
  'total_posts': 0,
  'updated': 0,
  'url': 'https://asdfasdf.tumblr.com/'},
 'posts': [],
 'supply_logging_positions': [],
 'total_posts': 0}
</code>```

if not posts would be checked against that structure, rather than the posts field (which is an empty list here), so the condition would never fail because the response dictionary isn't empty (see: Truth Value Testing in Python).

A Corrected Version

Here's code (mostly tested/verified) that fixes the loop from your getAllPosts implementation, and then uses the function to retrieve posts and dumps them to a file with the name (BLOG_NAME)-posts.txt.

```<code>import pytumblr

def get_all_posts(client, blog):
    offset = 0
    while True:
        response = client.posts(blog, limit=20, offset=offset, reblog_info=True, notes_info=True)

        # Get the 'posts' field of the response
        posts = response['posts']

        if not posts: return

        for post in posts:
            yield post

        # move to the next offset
        offset += 20

client = pytumblr.TumblrRestClient('secrety-secret')
blog = 'staff'

# use our function
with open('{}-posts.txt'.format(blog), 'w') as out_file:
    for post in get_all_posts(client, blog):
        print >>out_file, post
        # if you're in python 3.x, use the following
        # print(post, file=out_file)
</code>```

This will just be a straight text dump of the API's post responses, so if you need to make it look nicer or anything, that's up to you.

Body:
Good afternoon,

I'm very new to Python, but I'm trying to write a code which will allow me to download all of the posts (including the "notes")
from a specified Tumblr account to my computer.

Given my inexperience with coding, I was trying to find a pre-made script which would allow me to do this. I found several brilliant scripts on GitHub, but none of them actually return the notes from Tumblr posts (as far as I can see, although please do correct me if anyone knows of one that does!).

Therefore, I tried to write my own script. I've had some success with the code below. It prints the most recent 20 posts from the given Tumblr (albeit in a rather ugly format -- essentially hundreds of lines of texts all printed into one line of a notepad file):

#This script prints all the posts (including tags, comments) and also the
#first 20notes from all the Tumblr blogs.

import pytumblr

# Authenticate via API Key
client = pytumblr.TumblrRestClient('myapikey')

#offset = 0

# Make the request
client.posts('staff', limit=2000, offset=0, reblog_info=True, notes_info=True,
filter='html')
#print out into a .txt file
with open('out.txt', 'w') as f:
print >> f, client.posts('staff', limit=2000, offset=0, reblog_info=True,
notes_info=True, filter='html')

However, I want the script to continuously print posts until it reaches the end of the specified blog.

I searched this site and found a very similar question (Getting only 20 posts returned through PyTumblr), which has been answered by the stackoverflow user poke. However, I can't seem to actually implement poke's solution so that it works for my data. Indeed, when I run the following script, no output at all is produced.

import pytumblr

# Authenticate via API Key
client = pytumblr.TumblrRestClient('myapikey')
blog = ('staff')
def getAllPosts (client, blog):
offset = 0
while True:
    posts = client.posts(blog, limit=20, offset=offset, reblog_info=True, notes_info=True)
    if not posts:
        return

    for post in posts:
        yield post

    offset += 20

I should note that there are several posts on this site (e.g.Getting more than 50 notes with Tumblr API) about Tumblr notes, most of them asking how to download more than 50 notes per posts. I'm perfectly happy with just 50 notes per post, it is the number of posts that I would like to increase.

Also, I've tagged this post as Python, however, if there is a better way to get the data I require using another programming language, that would be more than okay.

Thank you very much in advance for your time!

Body:
tl;dr If you'd like to just see the answer, it's at the bottom after the heading A Corrected Version

The second code snippet is a generator that yields posts one by one, so you have to use it as part of something like a loop and then do something with the output. Here's your code with some additional code that iterates over the generator and prints out the data it gets back.

import pytumblr

def getAllPosts (client, blog):
    offset = 0
    while True:
        posts = client.posts(blog, limit=20, offset=offset, reblog_info=True, notes_info=True)
        if not posts:
            return

        for post in posts:
            yield post

        offset += 20

# Authenticate via API Key
client = pytumblr.TumblrRestClient('myapikey')
blog = ('staff')

# use the generator getAllPosts
for post in getAllPosts(client, blog):
    print(post)

However, that code has a couple bugs in it. getAllPosts won't yield just each post, it will also return other things because it will iterate over the API response, as you can see from this example I ran in my ipython shell.

In [7]: yielder = getAllPosts(client, 'staff')

In [8]: next(yielder)
Out[8]: 'blog'

In [9]: next(yielder)
Out[9]: 'posts'

In [10]: next(yielder)
Out[10]: 'total_posts'

In [11]: next(yielder)
Out[11]: 'supply_logging_positions'

In [12]: next(yielder)
Out[12]: 'blog'

In [13]: next(yielder)
Out[13]: 'posts'

In [14]: next(yielder)
Out[14]: 'total_posts'

This happens because the posts object in getAllPosts is a dictionary that contains much more than just each post from the staff blog - it also has items like how many posts the blog contains, the blog's description, when it was last updated, etc. The code as-is could potentially result in an infinite loop because the following conditional:

if not posts:
    return

Would never be true because of the response structure, because an empty Tumblr API response from pytumblr looks like this:

{'blog': {'ask': False,
  'ask_anon': False,
  'ask_page_title': 'Ask me anything',
  'can_send_fan_mail': False,
  'can_subscribe': False,
  'description': '',
  'followed': False,
  'is_adult': False,
  'is_blocked_from_primary': False,
  'is_nsfw': False,
  'is_optout_ads': False,
  'name': 'asdfasdf',
  'posts': 0,
  'reply_conditions': '3',
  'share_likes': False,
  'subscribed': False,
  'title': 'Untitled',
  'total_posts': 0,
  'updated': 0,
  'url': 'https://asdfasdf.tumblr.com/'},
 'posts': [],
 'supply_logging_positions': [],
 'total_posts': 0}

if not posts would be checked against that structure, rather than the posts field (which is an empty list here), so the condition would never fail because the response dictionary isn't empty (see: Truth Value Testing in Python).

A Corrected Version

Here's code (mostly tested/verified) that fixes the loop from your getAllPosts implementation, and then uses the function to retrieve posts and dumps them to a file with the name (BLOG_NAME)-posts.txt.

import pytumblr

def get_all_posts(client, blog):
    offset = 0
    while True:
        response = client.posts(blog, limit=20, offset=offset, reblog_info=True, notes_info=True)

        # Get the 'posts' field of the response
        posts = response['posts']

        if not posts: return

        for post in posts:
            yield post

        # move to the next offset
        offset += 20

client = pytumblr.TumblrRestClient('secrety-secret')
blog = 'staff'

# use our function
with open('{}-posts.txt'.format(blog), 'w') as out_file:
    for post in get_all_posts(client, blog):
        print >>out_file, post
        # if you're in python 3.x, use the following
        # print(post, file=out_file)

This will just be a straight text dump of the API's post responses, so if you need to make it look nicer or anything, that's up to you.


问:
Abstract class --> get a new instace of current derived class
Is it possible to get a new instance of the current derived class that is calling a function of the base abstract class? For example:

```<code>class Bar1 : Foo
{

}
class Bar2 : Foo
{

}

abstract class Foo
{
    public Foo CreateAnotherInstance()
    {
        return new Bar1/Bar2();   // depending on the calling derived class
    }
}
</code>```

Should lead to:

```<code>Bar1 bar1 = new Bar1();
Bar2 bar2 = new Bar2();
Foo bar1_2 = bar1.CreateAnotherInstance();  // Should be a new Bar1 instance
Foo bar2_2 = bar1.CreateAnotherInstance();  // Should be a new Bar2 instance
</code>```

The only way i've found is to create the instance is an abstract method, where the instance is created in each derived class like:

```<code>class Bar1 : Foo
{
    public override Foo CreateAnotherInstance()
    {
        return new Bar1();
    }
}

class Bar2 : Foo
{
    public override Foo CreateAnotherInstance()
    {
        return new Bar2();
    }
}

abstract class Foo
{
    public abstract Foo CreateAnotherInstance();
}
</code>```

But in this way, i have to create the method for each derived class.

Is there a simpler solution for this problem available?

答:
Whilst Activator.CreateInstance is a good way to do this, I'm not sure this is a method that belongs in the base abstract class, or indeed any of these classes. Doesn't this break polymorphism? Or at least the Liskov substitution principle?

In any case, as an alternative, how about just creating a simple method that will work for any type, not just the ones above. e.g.

```<code>public static T CreateNew<T>(params object[] parms)
{
  return (T) Activator.CreateInstance(typeof(T), parms);
}
</code>```

This also allows you to pass in the constructor parameters if there are any.

Body:
Is it possible to get a new instance of the current derived class that is calling a function of the base abstract class? For example:

class Bar1 : Foo
{

}
class Bar2 : Foo
{

}

abstract class Foo
{
    public Foo CreateAnotherInstance()
    {
        return new Bar1/Bar2();   // depending on the calling derived class
    }
}

Should lead to:

Bar1 bar1 = new Bar1();
Bar2 bar2 = new Bar2();
Foo bar1_2 = bar1.CreateAnotherInstance();  // Should be a new Bar1 instance
Foo bar2_2 = bar1.CreateAnotherInstance();  // Should be a new Bar2 instance

The only way i've found is to create the instance is an abstract method, where the instance is created in each derived class like:

class Bar1 : Foo
{
    public override Foo CreateAnotherInstance()
    {
        return new Bar1();
    }
}

class Bar2 : Foo
{
    public override Foo CreateAnotherInstance()
    {
        return new Bar2();
    }
}

abstract class Foo
{
    public abstract Foo CreateAnotherInstance();
}

But in this way, i have to create the method for each derived class.

Is there a simpler solution for this problem available?

Body:
Whilst Activator.CreateInstance is a good way to do this, I'm not sure this is a method that belongs in the base abstract class, or indeed any of these classes. Doesn't this break polymorphism? Or at least the Liskov substitution principle?

In any case, as an alternative, how about just creating a simple method that will work for any type, not just the ones above. e.g.

public static T CreateNew<T>(params object[] parms)
{
  return (T) Activator.CreateInstance(typeof(T), parms);
}

This also allows you to pass in the constructor parameters if there are any.


问:
Password Masking(not duplicate)
Compiler-Code::Blocks
Operating System(OS)-Windows

I wrote a very simple password masking program unlike the complicated ones on the internet.When i build and run my code it displays "Enter password" but does not allow me to input anything.

By password masking i mean that when i enter password then it is displayed as ****
while being input just as it happens in E-mail.(one * for each character)

```<code>#include <iostream>
#include <string>
#include <conio.h>

using namespace std;

int main()
{
    string pass;

    cout << "Enter password";

    for (int i=0; i<100; i++)
    {
        char ch = getch();

        if (ch == 13)
            break;

        if (ch == 8)
        {
            if (pass.size())
            {
                cout << "\b \b";
                pass.pop_back();
            }
        }
        else
        {
            cout << "*";
            pass += ch;
        }
    }

    cout <<  "pass = " << pass << '\n';
}
</code>```

答:
Duh. I found  the simplest solution ever.
settings>compiler>reset defaults
:|</p>

Title: Password Masking(not duplicate)

Body:
Compiler-Code::Blocks
Operating System(OS)-Windows

I wrote a very simple password masking program unlike the complicated ones on the internet.When i build and run my code it displays "Enter password" but does not allow me to input anything.

By password masking i mean that when i enter password then it is displayed as ****
while being input just as it happens in E-mail.(one * for each character)

#include <iostream>
#include <string>
#include <conio.h>

using namespace std;

int main()
{
    string pass;

    cout << "Enter password";

    for (int i=0; i<100; i++)
    {
        char ch = getch();

        if (ch == 13)
            break;

        if (ch == 8)
        {
            if (pass.size())
            {
                cout << "\b \b";
                pass.pop_back();
            }
        }
        else
        {
            cout << "*";
            pass += ch;
        }
    }

    cout <<  "pass = " << pass << '\n';
}


Title: PYSPARK- find top n records for every month using core spark api's

Body:
My sorted RDD with count close to 50 k is as per below
format of rdd : (date, (customer_id, subtotal)) data as per below.
How can i extract top 5 customers for each date in the above RDD using
core Spark.
any pointers on implementing rank in core spark would also help.``

for i in orderItemsJoinSortMap.take(10): print(i)

('2013-07', (5293, 2781.73))
('2013-07', (4257, 2059.75))
('2013-07', (32, 2009.75))
('2013-07', (5182, 1949.8200000000002))
('2013-07', (1478, 1784.7600000000002))
('2013-07', (1175, 1699.91))
('2013-07', (9807, 1664.9))
('2013-07', (1780, 1651.8500000000001))
('2013-07', (11941, 1649.8000000000002))
('2013-07', (2071, 1629.8400000000001))

Body:
You can use window functions in the spark sql module, there several enumerating functions in the module.

First you'll need to convert your RDD to a dataframe:

from pyspark.sql.types import StructType, StructField, IntegerType, DoubleType, StringType
schema = StructType([
    StructField("date", StringType()),
    StructField("col", StructType([
        StructField("customer_id", IntegerType()),
        StructField("subtotal", DoubleType())
    ]))])
my_rdd = sc.parallelize([('2013-07', (5293, 2781.73)),('2013-07', (4257, 2059.75)),('2013-07', (32, 2009.75)),
                         ('2013-07', (5182, 1949.8200000000002)),('2013-07', (1478, 1784.7600000000002)),
                         ('2013-07', (1175, 1699.91)),('2013-07', (9807, 1664.9)),('2013-07', (1780, 1651.8500000000001)),
                         ('2013-07', (11941, 1649.8000000000002)),('2013-07', (2071, 1629.8400000000001))])
df = my_rdd.toDF(schema)
df.printSchema()

    root
     |-- date: string (nullable = true)
     |-- col: struct (nullable = true)
     |    |-- customer_id: integer (nullable = true)
     |    |-- subtotal: double (nullable = true)

Now we can define our window frame and apply the window function:

import pyspark.sql.functions as psf
from pyspark.sql import Window
w = Window.partitionBy("date").orderBy(psf.desc("col.subtotal"))
df = df.withColumn("rn", psf.row_number().over(w))
df.show()

    +-------+--------------------+---+
    |   date|                 col| rn|
    +-------+--------------------+---+
    |2013-07|      [5293,2781.73]|  1|
    |2013-07|      [4257,2059.75]|  2|
    |2013-07|        [32,2009.75]|  3|
    |2013-07|[5182,1949.820000...|  4|
    |2013-07|[1478,1784.760000...|  5|
    |2013-07|      [1175,1699.91]|  6|
    |2013-07|       [9807,1664.9]|  7|
    |2013-07|[1780,1651.850000...|  8|
    |2013-07|[11941,1649.80000...|  9|
    |2013-07|[2071,1629.840000...| 10|
    +-------+--------------------+---+

And finally you can filter on the top 5 customers for each date:

df.filter("rn >= 5")


问:
unable to get data from js file
this is the code which fetch data from database AJAX i ha dcheck the table names and syntax but there is some problem i am unable to get the data .

file name :: ajax_check_uname.php

```<code><?php

    $dbhandle = mysql_connect('localhost', 'root', 'root') or die("Opps some thing went wrong");
    mysql_select_db('db_new', $dbhandle) or die("Opps some thing went wrong");

    if(isset($_POST['uname']))//If a name has been submitted
    {
    $uname= mysql_real_escape_string($_POST['uname']);//Some clean up :)

    $check_for_uname = mysql_query("SELECT uname FROM `db_new`.`operators` WHERE uname='$uname'");
    //Query to check if uname is available or not

    if(mysql_num_rows($check_for_uname))
    {
    echo '1';//If there is a  record match in the Database - Not Available
    }
    else
    {
    echo '0';//No Record Found - uname is available
    }

    }

    mysql_close($dbhandle);
    ?>
</code>```

this is the script code where i will call to the above file for data verification.

```<code><script type="text/javascript">
    $(document).ready(function()    //When the dom is ready
    {
    $("#uname").change(function()
    { //if theres a change in the uname textbox

    var uname = $("#uname").val();    //Get the value in the uname textbox
    //var re = ^([\w-]+(?:\.[\w-]+)*)\$;
    if(uname) //if the length greater than 5 characters
    {
    $("#availability_status").html('<img src="/ahs/images/loader.gif" align="absmiddle"> Checking availability...');
    //Add a loading image in the span id="availability_status"

    $.ajax({  //Make the Ajax Request
        type: "POST",
        url: "/abc/app/views/ControlPanelViews/forms/ajax_check_uname.php",  //file name
        data: "uname="+ uname,  //data
        //data: {uname: value},
        success: function(server_response){

       $("#availability_status").ajaxComplete(function(event, request){

        if(server_response == '0')  //if ajax_check_username.php return value "0"
        {
        $("#availability_status").html('<img src="/abc/images/available.png" align="absmiddle"> <font color="Green"> Available </font>  ');
        //add this image to the span with id "availability_status"
        }
        else  if(server_response == '1')    //if it returns "1"
        {
         $("#availability_status").html('<img src="/abc/images/not_available.png" align="absmiddle"> <font color="red">Not Available </font>');
        }
       });
       }
      });
    }

    else
    {

    $("#availability_status").html('<label></label>');
    //if in case the uname is less than or equal 6 characters only
    }

    return false;
    });

    });
</script>
</code>```

the below is the HTML form code for displaying the data.

HTML FORM :

```<code><div class="form-group">
<label class="control-label col-md-3">Username</label>
<div class="col-md-9">
<input type="text" name="uname" id="uname" class="form-control" placeholder="name" type="text">
<span id="availability_status"></span>
</div></div>
</code>```

答:
```<code><script type="text/javascript">
    $(document).ready(function()    //When the dom is ready
    {
    $("#uname").change(function()
    { //if theres a change in the uname textbox

    var uname = $("#uname").val();    //Get the value in the uname textbox
    //var re = ^([\w-]+(?:\.[\w-]+)*)\$;
    if(uname) //if the length greater than 5 characters
    {
    $("#availability_status").html('<img src="/ahs/images/loader.gif" align="absmiddle"> Checking availability...');
    //Add a loading image in the span id="availability_status"

    $.ajax({  //Make the Ajax Request
        type: "POST",
        url: "/abc/app/views/ControlPanelViews/forms/ajax_check_uname.php",  //file name
        data: {uname: uname},  //data
        success: function(server_response){

       $("#availability_status").ajaxComplete(function(event, request){

        if(server_response == '0')  //if ajax_check_username.php return value "0"
        {
        $("#availability_status").html('<img src="/abc/images/available.png" align="absmiddle"> <font color="Green"> Available </font>  ');
        //add this image to the span with id "availability_status"
        }
        else  if(server_response == '1')    //if it returns "1"
        {
         $("#availability_status").html('<img src="/abc/images/not_available.png" align="absmiddle"> <font color="red">Not Available </font>');
        }
       });
       }
      });
    }

    else
    {

    $("#availability_status").html('<label></label>');
    //if in case the uname is less than or equal 6 characters only
    }

    return false;
    });

    });
</script>
</code>```

Title: unable to get data from js file

Body:
this is the code which fetch data from database AJAX i ha dcheck the table names and syntax but there is some problem i am unable to get the data .

file name :: ajax_check_uname.php

<?php

    $dbhandle = mysql_connect('localhost', 'root', 'root') or die("Opps some thing went wrong");
    mysql_select_db('db_new', $dbhandle) or die("Opps some thing went wrong");

    if(isset($_POST['uname']))//If a name has been submitted
    {
    $uname= mysql_real_escape_string($_POST['uname']);//Some clean up :)

    $check_for_uname = mysql_query("SELECT uname FROM `db_new`.`operators` WHERE uname='$uname'");
    //Query to check if uname is available or not

    if(mysql_num_rows($check_for_uname))
    {
    echo '1';//If there is a  record match in the Database - Not Available
    }
    else
    {
    echo '0';//No Record Found - uname is available
    }

    }

    mysql_close($dbhandle);
    ?>

this is the script code where i will call to the above file for data verification.

the below is the HTML form code for displaying the data.

HTML FORM :

Username

<input type="text" name="uname" id="uname" class="form-control" placeholder="name" type="text">

Body:
<script type="text/javascript">
    $(document).ready(function()    //When the dom is ready
    {
    $("#uname").change(function()
    { //if theres a change in the uname textbox

    var uname = $("#uname").val();    //Get the value in the uname textbox
    //var re = ^([\w-]+(?:\.[\w-]+)*)\$;
    if(uname) //if the length greater than 5 characters
    {
    $("#availability_status").html('<img src="/ahs/images/loader.gif" align="absmiddle">&nbsp;Checking availability...');
    //Add a loading image in the span id="availability_status"

    $.ajax({  //Make the Ajax Request
        type: "POST",
        url: "/abc/app/views/ControlPanelViews/forms/ajax_check_uname.php",  //file name
        data: {uname: uname},  //data
        success: function(server_response){

       $("#availability_status").ajaxComplete(function(event, request){

        if(server_response == '0')  //if ajax_check_username.php return value "0"
        {
        $("#availability_status").html('<img src="/abc/images/available.png" align="absmiddle"> <font color="Green"> Available </font>  ');
        //add this image to the span with id "availability_status"
        }
        else  if(server_response == '1')    //if it returns "1"
        {
         $("#availability_status").html('<img src="/abc/images/not_available.png" align="absmiddle"> <font color="red">Not Available </font>');
        }
       });
       }
      });
    }

    else
    {

    $("#availability_status").html('<label></label>');
    //if in case the uname is less than or equal 6 characters only
    }

    return false;
    });

    });
</script>


问:
IE Box shadow showing 1px border like effect
i have applied box shadow to the mark tag to give extra space on right and left , except IE all other browsers looks fine.But in IE it shows a 1px border like effect . is there any solution for this?

mark {
    font-size: 24px ;
    background-color: rgba(0,0,0,0.5);
    line-height: 48px;
    max-width:350px;
    color: #fff;
    -webkit-box-shadow: rgba(0,0,0,0.5) -15px 0 0 0, rgba(0,0,0,0.5) 15px 0 0 0;
    -moz-box-shadow: rgba(0,0,0,0.5) -15px 0 0 0, rgba(0,0,0,0.5) 15px 0 0 0;
    box-shadow: rgba(0,0,0,0.5) -15px 0 0 0, rgba(0,0,0,0.5) 15px 0 0 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><mark>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</mark></code>```

答:
```<code><style>
  mark {
    font-size: 24px ;
    line-height: 48px;
    max-width:350px;
    color: #fff;
    background-color: rgb(68,68,68); /* Needed for IEs */
    -moz-box-shadow: 5px 5px 5px rgba(68,68,68,0.6);
    -webkit-box-shadow: 5px 5px 5px rgba(68,68,68,0.6);
    box-shadow: 5px 5px 5px rgba(68,68,68,0.6);
    filter: progid:DXImageTransform.Microsoft.Blur(PixelRadius=3,MakeShadow=true,ShadowOpacity=0.30);
    -ms-filter: "progid:DXImageTransform.Microsoft.Blur(PixelRadius=3,MakeShadow=true,ShadowOpacity=0.30)";
    zoom: 1;
   }
</style>

<mark>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</mark>
</code>```

Body:
i have applied box shadow to the mark tag to give extra space on right and left , except IE all other browsers looks fine.But in IE it shows a 1px border like effect . is there any solution for this?

mark {
    font-size: 24px ;
    background-color: rgba(0,0,0,0.5);
    line-height: 48px;
    max-width:350px;
    color: #fff;
    -webkit-box-shadow: rgba(0,0,0,0.5) -15px 0 0 0, rgba(0,0,0,0.5) 15px 0 0 0;
    -moz-box-shadow: rgba(0,0,0,0.5) -15px 0 0 0, rgba(0,0,0,0.5) 15px 0 0 0;
    box-shadow: rgba(0,0,0,0.5) -15px 0 0 0, rgba(0,0,0,0.5) 15px 0 0 0;
}

Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum


问:
How to make JavaScript and Python work together?
I want to make a two way communication model for JavaScript and Python.
I want JavaScript to process a data and send it to Python and then Python processes it and sends it back to JavaScript. I don't have a clue how this can be achieved and how the communication between the two languages will be made.

Consider the example:

Read the comments for clarity of the model!

var files = [];
const div_files = document.getElementById("files");
const div_results = document.getElementById("results");

function fetchNames() {
  div_files.innerHTML = ""; // clears the file div
  div_results.innerHTML = ""; // clears the results div

  var checkbox_elements = document.getElementsByClassName('filename');

  Array.from(checkbox_elements).forEach(function(k) {
    if (k.checked) {

      files.push(k.value);
      div_files.innerHTML += k.value + '
';
    }

  });

  // the files array should now be shared with python

  //console.log(files);

  // JavaScript SHOULD WAIT while PYTHON processes the data and shares the cal_array with JS

  // when the cal_array is available with JS only then it shall start processing the code mentioned below

  var cal_array = [
    [2231, 11640, 104621],
    [2231, 11640, 104621],
    [9, 494, 3339]
  ];
  Array.from(cal_array).forEach(function(k) {
    div_results.innerHTML += k + '
';
  })

};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <input type="checkbox" class="filename" value="./first.html">First File<br>
  <input type="checkbox" class="filename" value="./second.html">Second File<br>
  <input type="checkbox" class="filename" value="./third.html">Third File<br>
  <br>
  <input type="button" value="Submit" onclick="fetchNames()">
</form>
<br>
The selected file(s) are:
<div id="files"></div>
<br> The result shows the number of lines, words, and characters of the respective files mentioned above:
<div id="results"></div></code>```

The Python Script is as follows:

import os

files = ['./first.html','./second.html','./firstfile.txt'] #this array should be passed into python by the JS script
cal_array = [] #this array should be shared with JS after data has been entered into it
def calculation(): # this function calculates the number of lines, words and characters of the selected file(s)
    for val in files:
        file_details = []
        fname=(val)
        infile=open(fname, 'r')
        lines=0
        words=0
        characters=0
        for line in infile:
            line = line.strip(os.linesep)
            wordslist=line.split()
            lines=lines+1
            words=words+len(wordslist)
            characters=characters+ len(line)
        file_details.append(lines)
        file_details.append(words)
        file_details.append(characters)
        cal_array.append(file_details)

calculation()

print(cal_array)

# some code here to share cal_array with javascript```

I'm a noob in Python, but I want to know how to make the two languages interact with each other? I'll really appreciate any help!

答:
There are a lot of ways to do this and this is quite a broad question. Since JavaScript exists in the browser and python is run on your computer, you must set up some sort of webserver for the two to talk together. The most common and easy way is to go via the normal HTTP request response method. The most straightforward combination is Flask on the python site and AJAX on the JavasScript side. However, there are a hundred other ways to do this. I would suggest to read up on:

REST APIs:
https://www.codecademy.com/courses/javascript-beginner-en-EID4t/0/4

Ajax (JavaScript)
https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp

Flask (Python) http://flask.pocoo.org/

Body:
I want to make a two way communication model for JavaScript and Python.
I want JavaScript to process a data and send it to Python and then Python processes it and sends it back to JavaScript. I don't have a clue how this can be achieved and how the communication between the two languages will be made.

Consider the example:

Read the comments for clarity of the model!

var files = [];
const div_files = document.getElementById("files");
const div_results = document.getElementById("results");

function fetchNames() {
  div_files.innerHTML = ""; // clears the file div
  div_results.innerHTML = ""; // clears the results div

  var checkbox_elements = document.getElementsByClassName('filename');

  Array.from(checkbox_elements).forEach(function(k) {
    if (k.checked) {

      files.push(k.value);
      div_files.innerHTML += k.value + '
';
    }

  });

  // the files array should now be shared with python

  //console.log(files);

  // JavaScript SHOULD WAIT while PYTHON processes the data and shares the cal_array with JS

  // when the cal_array is available with JS only then it shall start processing the code mentioned below

  var cal_array = [
    [2231, 11640, 104621],
    [2231, 11640, 104621],
    [9, 494, 3339]
  ];
  Array.from(cal_array).forEach(function(k) {
    div_results.innerHTML += k + '
';
  })

};

<form>
  <input type="checkbox" class="filename" value="./first.html">First File

  <input type="checkbox" class="filename" value="./second.html">Second File

  <input type="checkbox" class="filename" value="./third.html">Third File

  <input type="button" value="Submit" onclick="fetchNames()">
</form>

The selected file(s) are:

 The result shows the number of lines, words, and characters of the respective files mentioned above:

The Python Script is as follows:

import os

files = ['./first.html','./second.html','./firstfile.txt'] #this array should be passed into python by the JS script
cal_array = [] #this array should be shared with JS after data has been entered into it
def calculation(): # this function calculates the number of lines, words and characters of the selected file(s)
    for val in files:
        file_details = []
        fname=(val)
        infile=open(fname, 'r')
        lines=0
        words=0
        characters=0
        for line in infile:
            line = line.strip(os.linesep)
            wordslist=line.split()
            lines=lines+1
            words=words+len(wordslist)
            characters=characters+ len(line)
        file_details.append(lines)
        file_details.append(words)
        file_details.append(characters)
        cal_array.append(file_details)

calculation()

print(cal_array)

# some code here to share cal_array with javascript

I'm a noob in Python, but I want to know how to make the two languages interact with each other? I'll really appreciate any help!


问:
ASP .Net WebAPI does not work with Owin when hosted using XSP/Mono
I am trying to run a project (refer solution here) using mono which has ASP .net Web API and Owin components. The project gets built successfully. However when I hit the endpoint http://127.0.0.1:6666/customers I get below error.

```<code>System.Web.HttpException
The resource cannot be found.

Description: HTTP 404.The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is  temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Details: Requested URL: /customers

Exception stack trace:
at System.Web.StaticFileHandler.ProcessRequest (System.Web.HttpContext context) [0x000a1] in /builddir/build/BUILD/mono-4.4.0/mcs/class/System.Web/System.Web/StaticFileHandler.cs:77
at System.Web.DefaultHttpHandler.BeginProcessRequest  (System.Web.HttpContext context, System.AsyncCallback callback, System.Object state) [0x00098] in /builddir/build/BUILD/mono-4.4.0/mcs/class/System.Web/System.Web/DefaultHttpHandler.cs:101
at System.Web.HttpApplication+<Pipeline>c__Iterator1.MoveNext () [0x00d9c] in /builddir/build/BUILD/mono-4.4.0/mcs/class/System.Web/System.Web/HttpApplication.cs:1335
at System.Web.HttpApplication.Tick () [0x00000] in /builddir/build/BUILD/mono-4.4.0/mcs/class/System.Web/System.Web/HttpApplication.cs:927
</code>```

However, CustomersController.Get() endpoint was called correctly which means that the framework was able to go to the correct controller. But something BAD happens past the endpoint.

Note: Worth mentioning that normal ASP .Net Web API project (without OWin) works fine. Issue is only when upon OWin integration.

I am using:

Mono JIT compiler version 4.4.0

  Monodevelop 5.10

  Refer packages.config for versions of Nuget packages

  Here is the WebApiConfig.cs

  Here is the CustomerController.cs

  Here is the Web.config

If you want to give a try please refer/pull the code and import it in monodevelop.

I tried running this solution in windows and it worked fine there.

I am not able to figure out the cause for this behavior. If anyone can provide me with some pointers to fix this it would be very helpful.

答:
If you absolutely need to run your app on XSP then I don’t have a solution for you, sorry. I started reading Mono’s source code of System.Web.HttpApplication to try to understand why the request would be processed by the static file handler but this is an impossible task without stepping over with a debugger.

But if you just need to run your Web API application on Mono, there’s a very simple solution. Since you have converted your app to OWIN, you can use OwinHost.exe (from the OwinHost NuGet package) instead of xsp4.exe to host your app. This worked fine for me with Mono 5.4.1.7 / OwinHost 3.1.0 / Microsoft.AspNet.WebApi 5.2.3 on OS X 10.11.6.

Excerpt from the OwinHost documentation:

Launching OwinHost:

  Self-hosting an OWIN application with OwinHost is as simple as running OwinHost.exe from your Web application's project directory. Project directory is defined here as the parent directory of ./bin which contains the application's assemblies as well as the selected server assembly. By default, when running OwinHost.exe with no additional parameters, the host will attempt to locate and load the application's startup class and the OWIN HttpListener server. After constructing the OWIN pipeline with the help of the startup class, it will then begin listening on port 5000. All of these default behaviors can be easily changed using parameters to OwinHost.exe, as described below.

OwinHost Parameters:

  There are a variety of ways to customize the default behavior of OwinHost. For example, to select an alternate OWIN-compatible server, run the following:

OwinHost.exe -s <Custom.Server.Assembly>

The full list of options can be seen by running:

OwinHost.exe /?

Body:
I am trying to run a project (refer solution here) using mono which has ASP .net Web API and Owin components. The project gets built successfully. However when I hit the endpoint http://127.0.0.1:6666/customers I get below error.

System.Web.HttpException
The resource cannot be found.

Description: HTTP 404.The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is  temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Details: Requested URL: /customers

Exception stack trace:
at System.Web.StaticFileHandler.ProcessRequest (System.Web.HttpContext context) [0x000a1] in /builddir/build/BUILD/mono-4.4.0/mcs/class/System.Web/System.Web/StaticFileHandler.cs:77
at System.Web.DefaultHttpHandler.BeginProcessRequest  (System.Web.HttpContext context, System.AsyncCallback callback, System.Object state) [0x00098] in /builddir/build/BUILD/mono-4.4.0/mcs/class/System.Web/System.Web/DefaultHttpHandler.cs:101
at System.Web.HttpApplication+<Pipeline>c__Iterator1.MoveNext () [0x00d9c] in /builddir/build/BUILD/mono-4.4.0/mcs/class/System.Web/System.Web/HttpApplication.cs:1335
at System.Web.HttpApplication.Tick () [0x00000] in /builddir/build/BUILD/mono-4.4.0/mcs/class/System.Web/System.Web/HttpApplication.cs:927

However, CustomersController.Get() endpoint was called correctly which means that the framework was able to go to the correct controller. But something BAD happens past the endpoint.

Note: Worth mentioning that normal ASP .Net Web API project (without OWin) works fine. Issue is only when upon OWin integration.

I am using:

Mono JIT compiler version 4.4.0

  Monodevelop 5.10

  Refer packages.config for versions of Nuget packages

  Here is the WebApiConfig.cs

  Here is the CustomerController.cs

  Here is the Web.config

If you want to give a try please refer/pull the code and import it in monodevelop.

I tried running this solution in windows and it worked fine there.

I am not able to figure out the cause for this behavior. If anyone can provide me with some pointers to fix this it would be very helpful.


问:
Angular4 routing is not working in IE while its working fine in Mozilla and chrome
Hi I have created a angular4 app with tomcat server and all my routes are working fine in chrome and Mozilla while the same routes are not working on IE11.

Things i have tried

1.changes in polyfills.ts for IE browser

useHash: true

but these changes not worked for me.

basically i want to handle the reload button functionality with the routes which is working fine for mozilla and chrome but not working in IE11.

答:
I resolved it by adding an extra path,appended with my war name. I had one path 'index.html', mapped to first route, but for IE it required path : 'myApp/index.html', where myApp is my tomcat war name.

for chrome :

path: 'index.html', redirectTo: '/abc/admin'

for IE :

path: 'myapp/index.html', redirectTo: '/abc/admin'


问:
HL7 parser/writer for PHP
I've been reading HL7 files with a home grown script, but am looking for something a little more robust.  I've checked out the Net_HL7 Pear module, but there is no documentation and it looks like no updates since 2009.

Is there anything new on the market (commercial or open source) available for working with HL7 via PHP?

答: I know this is an old thread, but if someone is still looking for a HL7 package for PHP, here is one I've developed recently - https://github.com/senaranya/HL7</p>

Title: HL7 parser/writer for PHP


问:
Converting {integer} to f32 in Rust
I want to convert a value from {integer} to f32:

```<code>struct Vector3 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

for x in -5..5 {
    for y in -5..5 {
        for z in -5..5 {
            let foo: Vector3 = Vector3 { x: x, y: y, z: z };
            // do stuff with foo
        }
    }
}
</code>```

The compiler chokes on this with a type mismatch error (expecting f32 but getting {integer}). Unfortunately I can not simply change Vector3. I'm feeding a C-API with this.

Is there any easy and concise way I can convert x, y and z from {integer} to f32?

I guess there is no builtin conversion from i32 or {integer} to f32 because it could be lossy in certain situations. However, in my case the range I'm using is so small that this wouldn't be an issue. So I would like to tell the compiler to convert the value anyways.

Interestingly, the following works:

```<code>for x in -5..5 {
    let tmp: i32 = x;
    let foo: f32 = tmp as f32;
}
</code>```

I'm using a lot more that just one foo and one x so this turns hideous really fast.

Also, this works:

```<code>for x in -5i32..5i32 {
    let foo: f32 = x as f32;
    // do stuff with foo here
}
</code>```

But with my usecase this turns into:

```<code>for x in -5i32..5i32 {
    for y in -5i32..5i32 {
        for z in -5i32..5i32 {
            let foo: Vector3 = Vector3 {
                x: x as f32,
                y: y as f32,
                z: z as f32,
            };
            // do stuff with foo
        }
    }
}
</code>```

Which I think is pretty unreadable and an unreasonable amount of cruft for a simple conversion.

What am I missing here?

答:
From<i16> is implemented for f32.

So it should be possible to

```<code>for x in -5..5 {
    for y in -5..5 {
        for z in -5..5 {
            let foo: Vector3 = Vector3 {
                 x: f32::from(x),
                 y: f32::from(y),
                 z: f32::from(z),
            };
            // do stuff with foo
        }
    }
}
</code>```

Of course if your iteration uses values bigger than i16 (i32 or i64) this is no longer possible in a safe way and you have to try another way.

Title: Converting {integer} to f32 in Rust

Body:
I want to convert a value from {integer} to f32:

struct Vector3 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

for x in -5..5 {
    for y in -5..5 {
        for z in -5..5 {
            let foo: Vector3 = Vector3 { x: x, y: y, z: z };
            // do stuff with foo
        }
    }
}

The compiler chokes on this with a type mismatch error (expecting f32 but getting {integer}). Unfortunately I can not simply change Vector3. I'm feeding a C-API with this.

Is there any easy and concise way I can convert x, y and z from {integer} to f32?

I guess there is no builtin conversion from i32 or {integer} to f32 because it could be lossy in certain situations. However, in my case the range I'm using is so small that this wouldn't be an issue. So I would like to tell the compiler to convert the value anyways.

Interestingly, the following works:

for x in -5..5 {
    let tmp: i32 = x;
    let foo: f32 = tmp as f32;
}

I'm using a lot more that just one foo and one x so this turns hideous really fast.

Also, this works:

for x in -5i32..5i32 {
    let foo: f32 = x as f32;
    // do stuff with foo here
}

But with my usecase this turns into:

for x in -5i32..5i32 {
    for y in -5i32..5i32 {
        for z in -5i32..5i32 {
            let foo: Vector3 = Vector3 {
                x: x as f32,
                y: y as f32,
                z: z as f32,
            };
            // do stuff with foo
        }
    }
}

Which I think is pretty unreadable and an unreasonable amount of cruft for a simple conversion.

What am I missing here?

Body:
From<i16> is implemented for f32.

So it should be possible to

for x in -5..5 {
    for y in -5..5 {
        for z in -5..5 {
            let foo: Vector3 = Vector3 {
                 x: f32::from(x),
                 y: f32::from(y),
                 z: f32::from(z),
            };
            // do stuff with foo
        }
    }
}

Of course if your iteration uses values bigger than i16 (i32 or i64) this is no longer possible in a safe way and you have to try another way.


问:
Sweetalert2 redirection
I'm struggling with this for a few hours already and I think that the solution is very simple. First a bit of background.

So, I have a php page where I can enter a number in a texfield. If the number entered is higher than the credit the user has, then I have to show an error message. When the user clicks on the button to send the form, I go to makeTransfer.php and I do several checks in here. If, as I said, the user has not credit enough I want to show him an error message using SweetAlert2 and then redirect him to the previous page (let's call it cashier). At the moment, I can show the alert but I'm unable to redirect him :(.

Here is the code:

```<code>echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("WOW!","Message!","error");';
echo '});</script>';
</code>```

Any help, please? I just want to show the alert, and as soon as the user clicks on Accept button, redirects him to cashier.php

Thanks in advance!

答:
```<code>swal({
  title: 'WOW',
  text: "Message",
  type: 'error',
}).then(function (result) {
  if (result.value) {
    window.location = "/cashier.php";
  }
})
</code>```

Title: Sweetalert2 redirection

Body:
I'm struggling with this for a few hours already and I think that the solution is very simple. First a bit of background.

So, I have a php page where I can enter a number in a texfield. If the number entered is higher than the credit the user has, then I have to show an error message. When the user clicks on the button to send the form, I go to makeTransfer.php and I do several checks in here. If, as I said, the user has not credit enough I want to show him an error message using SweetAlert2 and then redirect him to the previous page (let's call it cashier). At the moment, I can show the alert but I'm unable to redirect him :(.

Here is the code:

echo '';

Any help, please? I just want to show the alert, and as soon as the user clicks on Accept button, redirects him to cashier.php

Thanks in advance!